@bivelio/savings-layer 0.4.26 → 0.4.28
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 +113 -12
- package/dist/adapters/ai-sdk.js +73 -73
- package/dist/adapters/anthropic-sdk.js +67 -66
- package/dist/adapters/langchain.js +60 -58
- package/dist/adapters/mastra.js +65 -65
- package/dist/gateway/bin.js +537 -530
- package/dist/index.d.ts +256 -6
- package/dist/index.js +1293 -1192
- package/package.json +4 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var go="2026-09-27",Zt={"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,286 +20,320 @@ 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
|
-
""&&c!=="-"&&c!=="."&&c!=="_")continue;let u=i.slice(a.length+1);if(!(/^\d/.test(u)&&!/^\d{4}/.test(u)))return t[a]}}function
|
|
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}},rd={"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
|
+
od={"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}}]},id=Object.fromEntries(Object.keys(Zt).map(t=>[t,[{...rd[t],
|
|
26
|
+
precio:Zt[t]},...od[t]??[]]]));var sd=864e13;function qs(t){let e=t instanceof Date?t.getTime():t,n=typeof e=="number"&&Number.isFinite(e)&&Math.abs(e)<=sd?e:Date.now();return new Date(n).toISOString().slice(0,10)}function Vs(t,e){
|
|
27
|
+
for(let n of id[t]??[])if(!(n.vigenteDesde!==void 0&&e<n.vigenteDesde)&&!(n.vigenteHasta!==void 0&&e>=n.vigenteHasta))return n.precio}function bo(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 vo(t){return Object.keys(t).sort((e,n)=>n.length-e.length)}var ad=["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"],ho={...Zt,...Object.
|
|
30
|
+
fromEntries(ad.map(t=>[t,null]))},cd=vo(ho);function Ln(t,e){let n=St(t);return n===void 0?void 0:Vs(n,qs(e))}var ud=Object.fromEntries(Object.keys(ho).map(t=>[t,ho[t]===null?null:t]));function St(t){
|
|
31
|
+
return bo(ud,cd,t)??void 0}var ld=/^\d{4}-?\d{2}-?\d{2}$/;function We(t,e){let n=St(t);if(n===void 0)return;let r=t.lastIndexOf("/"),o=r>=0?t.slice(r+1):t;if(!(n!==t&&n!==o&&!ld.test(o.slice(n.length+
|
|
32
|
+
1))))return Vs(n,qs(e))}var Me="0.4.28",jn="x-bvsala-version";var dd=0;function Yt(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else {let r=++dd,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 Xh=["exact","task_equivalent","not_verified","bounded_degradation","rejected"];function tg(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 yo=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))}},Tt=new yo;var ko=class{estimators=new Map;modelToTokenizer=new Map;fallbackId;constructor(e=Tt){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)}},xo=new ko;var wo=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}},Nn={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 So(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 wo(o,i)),r=true;for(let s of Nn[o]??
|
|
41
|
+
[])t.mapModel(s,o),t.mapModel(`openai/${s}`,o);}}return r}var pg=Nn,fg=So;var Hs=2592e6,Ws=.95,Js=8,Ct=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 h=this.actualInput/this.sentInputLocal,m=Math.max(0,this.actualInput-this.repairInput-this.discoveryInput);this.baselineInput=m+Math.round(h*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=
|
|
50
|
+
repairOutput-this.discoveryOutput):this.baselineOutput,i=e.cachedInputPer1k??e.inputPer1k,s=Math.min(this.providerCachedInput,this.actualInput),a=h=>Math.max(0,h-s)/1e3*e.inputPer1k+s/1e3*i,c=n?null:this.
|
|
51
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,
|
|
53
|
-
|
|
52
|
+
0?"reference":"estimated");let d=a(this.actualInput)+this.actualOutput/1e3*e.outputPer1k+this.extraCostUsd+this.cacheWritePremiumUsd+u,p=l===0?0:1-d/l;return {baselineEstimate:Us(l),actual:Us(d),netSavings:pd(
|
|
53
|
+
p),basis:r}}};function Us(t){return Math.round(t*1e10)/1e10}function pd(t){return Math.round(t*1e6)/1e6}var fd=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]),md=new TextEncoder;function Re(t,e){return t>>>e|t<<32-e}function Ks(t){let e=md.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
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
|
|
60
|
-
|
|
61
|
-
s[4]=s[4]+
|
|
62
|
-
|
|
63
|
-
normalize("NFC"),e=e.replace(
|
|
64
|
-
he(s)||he(s)&&!he(i)&&!
|
|
65
|
-
return
|
|
66
|
-
return t}function
|
|
59
|
+
64;b++){let y=a[b-15],k=a[b-2],T=Re(y,7)^Re(y,18)^y>>>3,w=Re(k,17)^Re(k,19)^k>>>10;a[b]=a[b-16]+T+a[b-7]+w|0;}let l=s[0],d=s[1],p=s[2],h=s[3],m=s[4],g=s[5],f=s[6],v=s[7];for(let b=0;b<64;b++){let y=Re(
|
|
60
|
+
m,6)^Re(m,11)^Re(m,25),k=m&g^~m&f,T=v+y+k+fd[b]+a[b]|0,w=Re(l,2)^Re(l,13)^Re(l,22),S=l&d^l&p^d&p,x=w+S|0;v=f,f=g,g=m,m=h+T|0,h=p,p=d,d=l,l=T+x|0;}s[0]=s[0]+l|0,s[1]=s[1]+d|0,s[2]=s[2]+p|0,s[3]=s[3]+h|0,
|
|
61
|
+
s[4]=s[4]+m|0,s[5]=s[5]+g|0,s[6]=s[6]+f|0,s[7]=s[7]+v|0;}let c="";for(let u=0;u<8;u++)c+=(s[u]>>>0).toString(16).padStart(8,"0");return c}var hd=/\s+/g,gd=[[/′′/g,'"'],[/[‘’‚‛′´`]/g,"'"],[/[“”„‟″«»]/g,'"'],[/[‐-―−]/g,"-"],[/⁄/g,"/"],[/…/g,""]],bd=/[¿?¡!;.,:'"·•]/g,vd=/([a-z])\p{M}+/gu,yd=/(^|\s)\p{M}+/gu,
|
|
62
|
+
To=/\p{L}/u;function he(t){return t>="0"&&t<="9"}function $n(t){let e=t.normalize("NFKC").toLowerCase();for(let[n,r]of gd)e=e.replace(n,r);return e=e.normalize("NFD").replace(vd,"$1").replace(yd,"$1").
|
|
63
|
+
normalize("NFC"),e=e.replace(bd,(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)&&!To.test(i)?n:"";case ":":return he(i)&&he(s)?n:"";case "'":case '"':return To.test(i)&&To.test(s)||he(i)||he(s)?n:"";default:return he(i)||he(s)?n:""}}),e.replace(hd," ").trim()}function te(t){
|
|
65
|
+
return Ks(t)}function ye(t){return JSON.stringify(Co(t))}function Co(t){if(Array.isArray(t))return t.map(Co);if(t&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=Co(t[n]);return e}
|
|
66
|
+
return t}function Eo(t){return t.replace(/[-_]?\d{4,}.*$/,"").replace(/[-_](mini|nano|small|large|latest)$/i,"")}function Po(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:
|
|
68
|
+
`),r=t.messages.filter(i=>i.role!=="system").map(i=>`${i.role}:${$n(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:Eo(t.model),messages:t.messages,normalizedText:r,
|
|
70
|
+
systemPromptHash:te(n),toolsetHash:te(ye(o)),structuredDataHash:t.structuredData!==void 0?te(ye(t.structuredData)):"none",schemaVersion:t.response?.version??t.response?.contractId??"none",contractId:t.
|
|
71
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
|
|
72
|
+
"und",knowledgeEpoch:e.knowledgeEpoch??"none",freshnessBucket:e.freshnessBucket??"any",safetyPolicyVersion:e.safetyPolicyVersion??"none",tokenizer:t.tokenizer,original:t}}var Gs="n2";function Ro(t,e={}){let n=e.servedModel??t.model,r=ye({tenant:t.tenantId,scope:t.authorizationScope,principal:t.principal,text:t.normalizedText,modelFamily:n===t.model?t.modelFamily:Eo(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:${Gs}:${te(r)}`}function Zs(t,e={}){let n=ye({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:${Gs}:${te(n)}`}var kd=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"),xd=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(b=>b.risk==="write"||b.risk==="destructive"),o=t.freshnessBucket==="live"||t.freshnessBucket==="hour"||
|
|
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 Bn(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"||kd.test(n),i=xd.test(n),s=(t.temperature??0)>.3&&t.seed==null,a=t.messages.
|
|
88
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)"),
|
|
92
|
-
personalized request with no principal (context.sessionId) \u2192 exact cache off");let
|
|
90
|
+
ed)");let p=o&&(t.freshnessBucket==null||t.freshnessBucket==="any"),h=t.freshnessBucket==="live",m=i&&t.principal==null,g=!s&&!p&&!h&&!m&&!r;r&&e.push("write/destructive tools \u2192 exact cache off (side \
|
|
91
|
+
effects must execute)"),h&&e.push("freshnessBucket=live \u2192 exact cache off (answer must be current)"),p&&e.push("freshness-sensitive without a freshness bucket \u2192 exact cache off"),m&&e.push("\
|
|
92
|
+
personalized request with no principal (context.sessionId) \u2192 exact cache off");let f=!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&&!
|
|
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 v=!r&&!o&&!i&&!s&&t.freshnessBucket!=="day";return {allowExactCache:g,allowSemanticCache:f,allowElision:v,
|
|
95
|
+
allowSingleflight:!r&&!m,allowCompression:true,requiresFreshData:o,hasSideEffects:r,isPersonalized:i,isAgentic:l,maxCacheAgeMs:t.freshnessBucket==="hour"?36e5:t.freshnessBucket==="day"?864e5:null,reasons:e}}var Fn=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),Ys(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:Ys(n),expiresAtMs:r!=null?this.now()+r:null});}async delete(e){this.store.delete(e);}get size(){return this.store.size}};function Ys(t){
|
|
98
|
+
try{return structuredClone(t)}catch{return t}}var zn=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
|
-
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
|
|
102
|
-
return t<=0||e>=t*n?false:
|
|
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(
|
|
104
|
-
erroneas[r];return {n:e,e:n}}};function
|
|
105
|
-
let r=[];for(let o of [1,1/4,1/16,1/64,1/256]){let i=
|
|
106
|
-
o[c],i[c],n,r))break;a={indice:c,retenidas:o[c],erroneas:i[c]};}return a}var
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
100
|
+
waiters.get(e)??1)+1),n}get activeKeys(){return this.inflight.size}};function en(t){return !Number.isFinite(t)||t<0?-1:t>=1?1e3:Math.floor(t*1e3+1e-9)}var tn=t=>t/1e3;function wd(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 _o(t,e,n,r){
|
|
102
|
+
return t<=0||e>=t*n?false:wd(t,e,n)<=r}function Un(t,e){return Math.ceil(Math.log(e)/Math.log1p(-t))}function qn(t,e){return 6*t/(Math.PI*Math.PI*(e+1)*(e+1))}var Je=class{total=new Uint32Array(1001);erroneas=new Uint32Array(
|
|
103
|
+
1001);n=0;anotar(e,n){this.total[e]++,n||this.erroneas[e]++,this.n++;}copiarDe(e){this.total.set(e.total),this.erroneas.set(e.erroneas),this.n=e.n;}acumulados(){let e=new Uint32Array(1002),n=new Uint32Array(
|
|
104
|
+
1002);for(let r=1e3;r>=0;r--)e[r]=e[r+1]+this.total[r],n[r]=n[r+1]+this.erroneas[r];return {n:e,e:n}}};function Sd(t,e,n){let{n:r,e:o}=t.acumulados(),i=null;for(let s=1e3;s>=0;s--)_o(r[s],o[s],e,n)&&(i=
|
|
105
|
+
s);if(i==null)return null;for(;i<1e3&&t.total[i]===0;)i++;return i}function Ao(t,e,n){let r=[];for(let o of [1,1/4,1/16,1/64,1/256]){let i=Sd(t,e,n*o);i!=null&&r.push(i);}return r}function Oo(t,e,n,r){let{
|
|
106
|
+
n:o,e:i}=t.acumulados(),s=[...new Set(e)].sort((c,u)=>u-c),a=null;for(let c of s){if(!_o(o[c],i[c],n,r))break;a={indice:c,retenidas:o[c],erroneas:i[c]};}return a}var Xt=class t{constructor(e,n){this.delta=
|
|
107
|
+
e;this.alfa=n;this.primeraMirada=2*Un(e,qn(n,0));}delta;alfa;seleccion=new Je;retenida=new Je;etiquetas=0;miradas=0;candidatoPrevio=null;certificado=null;primeraMirada;etiquetasDeLaMirada(e){return Do(
|
|
108
|
+
this.primeraMirada,e)}exportar(){return {labeled:this.etiquetas,looks:this.miradas,previousCandidate:this.candidatoPrevio,certified:this.certificado?{floorIndex:this.certificado.indice,heldOut:this.certificado.
|
|
109
|
+
retenidas,wrong:this.certificado.erroneas}:null,selection:Qs(this.seleccion),heldOut:Qs(this.retenida)}}static restaurar(e,n,r,o){let i=new t(e,n),s=f=>{throw new we(`importCalibration: ${o}: ${f}`)};
|
|
110
|
+
(r===null||typeof r!="object"||Array.isArray(r))&&s("not an object");let a=r,c=a.labeled;Qt(c)||s("`labeled` must be a non-negative integer");let u=c,l=Xs(a.selection,`${o}.selection`),d=Xs(a.heldOut,
|
|
111
|
+
`${o}.heldOut`);(l.n!==Math.ceil(u/2)||d.n!==Math.floor(u/2))&&s(`the two halves hold ${l.n} and ${d.n} labels, but ${u} labels split by arrival order give ${Math.ceil(u/2)} and ${Math.floor(u/2)}`);let p=Td(
|
|
112
|
+
i.primeraMirada,u);a.looks!==p&&s(`\`looks\` is ${String(a.looks)}, but ${u} labels have already spent ${p} tests of the confidence budget; a state cannot start that spending over`);let h=a.previousCandidate;
|
|
113
|
+
h!==null&&!Io(h)&&s("`previousCandidate` must be null or a grid index");let m=a.certified,g=null;if(m!==null){(m===void 0||typeof m!="object"||Array.isArray(m))&&s("`certified` must be null or an obje\
|
|
114
|
+
ct");let f=m;Io(f.floorIndex)||s("`certified.floorIndex` must be a grid index"),(!Qt(f.heldOut)||!Qt(f.wrong))&&s("`certified.heldOut` and `certified.wrong` must be non-negative integers"),g={indice:f.
|
|
115
|
+
floorIndex,retenidas:f.heldOut,erroneas:f.wrong},p===0&&s("a floor is certified but no test has run yet"),h!==g.indice&&s("`previousCandidate` must be the certified floor");let v=p-1,b=Do(i.primeraMirada,
|
|
116
|
+
v),y=Math.floor(b/2);(g.retenidas>y||g.erroneas>g.retenidas)&&s("the certificate counts more held-out labels than there were when it was issued"),_o(g.retenidas,g.erroneas,e,qn(n,v))||s("the certifica\
|
|
117
|
+
te does not pass the test it claims to have passed");let{n:k,e:T}=d.acumulados(),w=k[g.indice]-g.retenidas,S=T[g.indice]-g.erroneas;(w<0||S<0||S>w||w>d.n-y)&&s("the held-out labels at the floor do not\
|
|
118
|
+
extend the ones the certificate counted");}else p===0&&h!==null&&s("`previousCandidate` is set but no test has run yet");return i.seleccion.copiarDe(l),i.retenida.copiarDe(d),i.etiquetas=u,i.miradas=p,
|
|
119
|
+
i.candidatoPrevio=h,i.certificado=g,i}anotar(e,n){let r=en(e);r<0||((this.etiquetas%2===0?this.seleccion:this.retenida).anotar(r,n),this.etiquetas++,this.etiquetas>=this.etiquetasDeLaMirada(this.miradas)&&
|
|
120
|
+
this.mirar());}mirar(){let e=qn(this.alfa,this.miradas);this.miradas++;let n=Ao(this.seleccion,this.delta,e),r=this.candidatoPrevio==null?n:[...n,this.candidatoPrevio],o=Oo(this.retenida,r,this.delta,e);
|
|
121
|
+
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,retenidas:this.
|
|
122
|
+
retenida.n,retenidasEnSuelo:this.certificado?.retenidas??0,erroneasEnSuelo:this.certificado?.erroneas??0,miradas:this.miradas,minimasParaLaSiguiente:Un(this.delta,qn(this.alfa,this.miradas)),etiquetasParaLaSiguiente:this.
|
|
123
|
+
etiquetasDeLaMirada(this.miradas)}}},we=class extends Error{constructor(e){super(`[bvsala] ${e}`),this.name="CalibrationStateError";}},ea="bvsala.semantic-calibration",Vn=1,ta=["single_shot","agentic"];
|
|
124
|
+
function na(t,e){let n={};for(let r of ta){let o=e.get(r);o&&(n[r]=o.exportar());}return {format:ea,version:Vn,embedder:t.embedder,verifier:t.verifier,judge:t.judge,config:{maxErrorRate:t.maxErrorRate,confidence:t.
|
|
125
|
+
confidence,similarityThreshold:t.similarityThreshold,grid:1e3},segments:n}}function ra(t,e){let n=l=>{throw new we(`importCalibration: ${l}`)};(t===null||typeof t!="object"||Array.isArray(t))&&n("the \
|
|
126
|
+
state must be an object");let r=t;r.format!==ea&&n(`not a semantic calibration state (format ${JSON.stringify(r.format)})`);let o=r.version;typeof o=="number"&&o>Vn&&n(`this state was exported by a ne\
|
|
127
|
+
wer SDK (version ${o}); this one reads version ${Vn}`),o!==Vn&&n(`unknown state version ${JSON.stringify(o)}`);let i=r.config??{},s=[],a=(l,d,p)=>{d!==p&&s.push(`${l}: ${JSON.stringify(d)} in the stat\
|
|
128
|
+
e, ${JSON.stringify(p)} here`);};a("embedder",r.embedder,e.embedder),a("verifier",r.verifier,e.verifier),a("judge",r.judge,e.judge),a("maxErrorRate",i.maxErrorRate,e.maxErrorRate),a("confidence",i.confidence,
|
|
129
|
+
e.confidence),a("similarityThreshold",i.similarityThreshold,e.similarityThreshold),a("grid",i.grid,1e3),s.length>0&&n(`the state was recorded under a different setup (${s.join("; ")}). A floor certifi\
|
|
130
|
+
ed under one setup says nothing about another: start a new calibration instead`);let c=r.segments;(c===null||typeof c!="object"||Array.isArray(c))&&n("`segments` must be an object");let u=new Map;for(let[
|
|
131
|
+
l,d]of Object.entries(c))ta.includes(l)||n(`unknown segment ${JSON.stringify(l)}`),u.set(l,Xt.restaurar(e.maxErrorRate,1-e.confidence,d,`segments.${l}`));return u}function Do(t,e){return Math.ceil(t*1.5**
|
|
132
|
+
e)}function Td(t,e){let n=0;for(;Do(t,n)<=e;)n++;return n}function Qt(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=4294967295}function Io(t){return typeof t=="number"&&Number.isInteger(
|
|
133
|
+
t)&&t>=0&&t<=1e3}function Qs(t){let e=[];for(let n=0;n<=1e3;n++)t.total[n]>0&&e.push([n,t.total[n],t.erroneas[n]]);return e}function Xs(t,e){let n=i=>{throw new we(`importCalibration: ${e}: ${i}`)};Array.
|
|
134
|
+
isArray(t)||n("must be an array of [gridIndex, labels, wrong]");let r=new Je,o=-1;for(let i of t){(!Array.isArray(i)||i.length!==3)&&n("each entry must be [gridIndex, labels, wrong]");let[s,a,c]=i;(!Io(
|
|
135
|
+
s)||s<=o)&&n("grid indices must be increasing integers in [0, 1000]"),(!Qt(a)||a===0)&&n("label counts must be positive integers"),(!Qt(c)||c>a)&&n("wrong counts must be integers between 0 and the lab\
|
|
136
|
+
el count"),r.total[s]=a,r.erroneas[s]=c,r.n+=a,o=s;}return r.n>4294967295&&n("too many labels"),r}function Hn(t){let{maxErrorRate:e}=t,n=t.confidence??.95,r=t.auditRate??.05;if(!(e>0&&e<=.5))throw new RangeError(
|
|
137
|
+
`calibration.maxErrorRate 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\
|
|
138
|
+
.auditRate must be in [0, 1); got ${r}`);return {maxErrorRate:e,confidence:n,auditRate:r}}function oa(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>>>
|
|
139
|
+
7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}function Mo(t,e){let n=o=>o!==null&&typeof o=="object";if(n(t.data)&&n(e.data))return Wn(t.data)===Wn(e.data);let r=o=>o.trim().replace(/\s+/g," ");return r(t.text)===r(e.text)}function Wn(t){if(Array.
|
|
140
|
+
isArray(t))return `[${t.map(Wn).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)}:${Wn(e[n])}`).join(",")}}`}return JSON.
|
|
141
|
+
stringify(t)??"null"}function jg(t,e){let{maxErrorRate:n,confidence:r}=Hn(e),o=1-r,i=new Je,s=new Je,a=oa(1592642065),c=0;for(let l of t){let d=en(l.score),p=a()<.5;d<0||((p?i:s).anotar(d,l.correct),c++);}
|
|
142
|
+
let u=Oo(s,Ao(i,n,o),n,o);return {maxErrorRate:n,confidence:r,floor:u?tn(u.indice):null,labeled:c,heldOut:s.n,heldOutAtFloor:u?.retenidas??0,wrongHeldOutAtFloor:u?.erroneas??0,minHeldOutToCertify:Un(n,
|
|
143
|
+
o)}}function Cd(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 Ed(t){return t.toLowerCase().normalize("NFKC").split(/[^\p{L}\p{N}]+/u).filter(
|
|
144
|
+
Boolean)}function Pd(t){let e=new Array(256).fill(0),n=Ed(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+
|
|
145
|
+
1]}`;r.set(a,(r.get(a)??0)+1);}}for(let[i,s]of r){let a=Cd(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++)
|
|
146
|
+
e[i]/=o;return e}function ia(t){return Pd(t)}var sa=.72;function Rd(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 Dd=new Set(
|
|
122
147
|
["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\
|
|
123
|
-
\xFAn","ninguna","ninguno","nada","nadie","sense","mai","tampoc","cap","gens","ningu","ning\xFA","res"]),
|
|
148
|
+
\xFAn","ninguna","ninguno","nada","nadie","sense","mai","tampoc","cap","gens","ningu","ning\xFA","res"]),Id=new Set(["the","a","an","of","to","in","on","for","and","or","is","are","was","were","what",
|
|
124
149
|
"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",
|
|
125
150
|
"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\
|
|
126
151
|
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",
|
|
127
152
|
"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",
|
|
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
|
|
129
|
-
match(/\d[\d.,:/-]*/g)??[]).map(e=>e.replace(/[.,:/-]+$/,""))}function
|
|
130
|
-
return false;n.set(r,o-1);}return true}function
|
|
131
|
-
function
|
|
132
|
-
`).map(e=>{let n=
|
|
133
|
-
r[o].rol||!
|
|
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
|
|
135
|
-
let n=e.embed==null;if(this.embebedorPropio=n,this.embed=e.embed??
|
|
136
|
-
e.acceptThreshold!=null,this.
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
e.
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
null
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
153
|
+
"aquests","aquestes","aquell","aquella","que","quin","quina","qui","com","quan","on","dona","vull","necessito","pots","podries","sisplau","gracies","meu","meva","seu","seva","hi"]);function nn(t){return (t.
|
|
154
|
+
match(/\d[\d.,:/-]*/g)??[]).map(e=>e.replace(/[.,:/-]+$/,""))}function Lo(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)
|
|
155
|
+
return false;n.set(r,o-1);}return true}function rn(t){return t.split(/\s+/).filter(Boolean)}function on(t){return t.filter(e=>Dd.has(e.replace(/'/g,""))||e.endsWith("n't")).length}var _d=/^(system|user|assistant|tool):/;
|
|
156
|
+
function aa(t){return t.split(`
|
|
157
|
+
`).map(e=>{let n=_d.exec(e);return n?{rol:n[1],texto:e.slice(n[0].length)}:{rol:"",texto:e}})}function Ad(t,e){let n=aa(t),r=aa(e);if(n.length!==r.length)return false;for(let o=0;o<n.length;o++)if(n[o].rol!==
|
|
158
|
+
r[o].rol||!Od(n[o].texto,r[o].texto))return false;return true}function Od(t,e){if(!Lo(nn(t),nn(e)))return false;let n=rn(t),r=rn(e);if(on(n)!==on(r))return false;let o=u=>u.length>1&&!Id.has(u)&&!/^\d/.test(u),i=new Set(
|
|
159
|
+
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 Md="lexical-256-v1",Ld="same-answer-v1",ca=class{records=[];embed;verify;similarityThreshold;acceptThreshold;ttlMs;maxRecords;now;embebedorPropio;calibracion;estados=new Map;nombres;pendientes=new Set;aceptacionExplicita;constructor(e={}){
|
|
160
|
+
let n=e.embed==null;if(this.embebedorPropio=n,this.embed=e.embed??ia,this.verify=e.verify,this.similarityThreshold=e.similarityThreshold??(n?sa:.9),this.acceptThreshold=e.acceptThreshold??.85,this.aceptacionExplicita=
|
|
161
|
+
e.acceptThreshold!=null,this.nombres={...e.embedderId!=null?{embedder:e.embedderId}:{},...e.verifierId!=null?{verifier:e.verifierId}:{},...e.calibration?.judgeId!=null?{judge:e.calibration.judgeId}:{}},
|
|
162
|
+
this.ttlMs=e.ttlMs,this.maxRecords=e.maxRecords??5e3,this.now=e.now??(()=>Date.now()),e.calibration){let r=Hn(e.calibration);this.calibracion={...r,judge:e.calibration.judge??Mo,perRecordFloors:e.calibration.
|
|
163
|
+
perRecordFloors??true,random:e.calibration.random??Math.random};}}get calibrated(){return this.calibracion!=null}async find(e){return this.calibracion?(await this.lookup(e)).hit:this.mejorCandidata(e,true)}async mejorCandidata(e,n){
|
|
164
|
+
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.authorizationScope!==e.authorizationScope||i.principal!==
|
|
165
|
+
e.principal||i.knowledgeEpoch!==e.knowledgeEpoch||i.contractId!==e.contractId||i.model!==e.model||i.systemPromptHash!==e.systemPromptHash||i.structuredDataHash!==e.structuredDataHash||i.locale!==e.locale||
|
|
166
|
+
i.schemaVersion!==e.schemaVersion||i.safetyPolicyVersion!==e.safetyPolicyVersion||i.toolsetHash!==e.toolsetHash||i.temperature!==e.temperature||i.seed!==e.seed||this.ttlMs!=null&&this.now()-i.storedAtMs>
|
|
167
|
+
this.ttlMs)continue;let s=Rd(r,i.embedding);if(s<this.similarityThreshold||!Ad(e.normalizedText,i.query))continue;let a=this.verify?await this.verify(e.normalizedText,i.query):s,c=Math.min(s,a);n&&c<this.
|
|
168
|
+
acceptThreshold||(!o||c>o.confidence)&&(o={record:i,similarity:s,verifierScore:a,confidence:c,ageMs:this.now()-i.storedAtMs,similarityFloor:this.similarityThreshold,acceptFloor:this.acceptThreshold,embedder:this.
|
|
169
|
+
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(e,true),probe:null};let o=n.agentic?"a\
|
|
170
|
+
gentic":"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=p=>({hit:null,probe:{reason:p,score:c,segment:o,record:i.record}});
|
|
171
|
+
if(a==null)return u("calibrating");if(en(c)<a||this.aceptacionExplicita&&c<this.acceptThreshold)return u("below_floor");if(r.perRecordFloors&&i.record.failedAtScore!=null&&c<=i.record.failedAtScore)return u(
|
|
172
|
+
"record_floor");if(r.auditRate>0&&r.random()<r.auditRate)return u("audit");let l=tn(a),d=s.resumen();return {hit:{...i,acceptFloor:this.aceptacionExplicita?Math.max(l,this.acceptThreshold):l,calibration:{
|
|
173
|
+
maxErrorRate:r.maxErrorRate,confidence:r.confidence,floor:l,heldOutAtFloor:d.retenidasEnSuelo,wrongHeldOutAtFloor:d.erroneasEnSuelo,labeled:d.etiquetas,segment:o}},probe:null}}observe(e,n){let r=this.
|
|
174
|
+
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.judge(e.record.answer,n)===!0;}catch{
|
|
175
|
+
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(){for(;this.pendientes.size>
|
|
176
|
+
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.maxErrorRate,confidence:n.
|
|
177
|
+
confidence,floor:r.suelo==null?null:tn(r.suelo),labeled:r.etiquetas,heldOut:r.retenidas,heldOutAtFloor:r.retenidasEnSuelo,wrongHeldOutAtFloor:r.erroneasEnSuelo,minHeldOutToCertify:r.minimasParaLaSiguiente,
|
|
178
|
+
nextTestAt:r.etiquetasParaLaSiguiente}}exportCalibration(){return na(this.identidad("exportCalibration"),this.estados)}importCalibration(e){let n=this.identidad("importCalibration"),r=e;if(typeof e=="\
|
|
179
|
+
string")try{r=JSON.parse(e);}catch{throw new we("importCalibration: the state is a string but not JSON")}let o=ra(r,n);for(let[i]of o){let s=this.estados.get(i);if(s&&s.resumen().etiquetas>0)throw new we(
|
|
180
|
+
`importCalibration: this cache has already recorded ${s.resumen().etiquetas} labels in the ${i} segment; import right after constructing it`)}for(let[i,s]of o)this.estados.set(i,s);}identidad(e){let n=this.
|
|
181
|
+
calibracion;if(!n)throw new we(`${e}: this cache runs without \`calibration\``);let r=(a,c)=>{throw new we(`${e}: pass \`${a}\` naming your ${c}, so that a saved calibration is only ever restored unde\
|
|
182
|
+
r the same one`)},o=this.embebedorPropio?`built_in:${Md}`:`custom:${this.nombres.embedder??r("embedderId","embed function")}`,i=this.verify==null?null:`custom:${this.nombres.verifier??r("verifierId","\
|
|
183
|
+
verifier")}`,s=n.judge===Mo?`built_in:${Ld}`:`custom:${this.nombres.judge??r("calibration.judgeId","judge")}`;return {embedder:o,verifier:i,judge:s,maxErrorRate:n.maxErrorRate,confidence:n.confidence,similarityThreshold:this.
|
|
184
|
+
similarityThreshold}}estadoDe(e){let n=this.estados.get(e);if(!n){let r=this.calibracion;n=new Xt(r.maxErrorRate,1-r.confidence),this.estados.set(e,n);}return n}async store(e,n){let r=await this.embed(
|
|
185
|
+
e.normalizedText);this.records.length>=this.maxRecords&&this.records.shift(),this.records.push({embedding:r,query:e.normalizedText,answer:n,tenantId:e.tenantId,authorizationScope:e.authorizationScope,
|
|
186
|
+
principal:e.principal,knowledgeEpoch:e.knowledgeEpoch,contractId:e.contractId,model:e.model,systemPromptHash:e.systemPromptHash,structuredDataHash:e.structuredDataHash,locale:e.locale,schemaVersion:e.
|
|
187
|
+
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.records.length-
|
|
188
|
+
1;r>=0;r--)this.records[r].knowledgeEpoch===e&&(this.records.splice(r,1),n++);return n}get size(){return this.records.length}};var ua=class{entradas=new Map;maxEntries;now;constructor(e={}){this.maxEntries=Math.max(1,e.maxEntries??1024),this.now=e.now??(()=>Date.now());}async get(e){let n=this.entradas.get(e);return n?this.now()>
|
|
189
|
+
n.vence?(this.entradas.delete(e),null):n.valor:null}async set(e,n,r){if(this.entradas.delete(e),this.entradas.size>=this.maxEntries){let o=this.entradas.keys().next().value;o!==void 0&&this.entradas.delete(
|
|
190
|
+
o);}this.entradas.set(e,{valor:n,vence:this.now()+r});}get size(){return this.entradas.size}};var jo=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}},
|
|
191
|
+
jd={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]??Nd(t.normalizedText))?.trim();if(!n)return null;
|
|
192
|
+
let r=Bd(n);return r===null||!Number.isFinite(r)?null:{text:$d(r),data:{value:r},resolver:"arithmetic"}}};function Nd(t){return /^[0-9+\-*/%.()\s]+$/.test(t.trim())&&/[+\-*/%]/.test(t)?t.trim():null}function $d(t){
|
|
193
|
+
return Number.isInteger(t)?String(t):String(Math.round(t*1e9)/1e9)}function Bd(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
194
|
"*":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
195
|
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&&
|
|
162
196
|
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),
|
|
163
|
-
s=true;}for(;r.length;){let a=r.pop();if(a==="("||!i(a))return null}return n.length===1?n[0]:null}function
|
|
164
|
-
|
|
197
|
+
s=true;}for(;r.length;){let a=r.pop();if(a==="("||!i(a))return null}return n.length===1?n[0]:null}function la(){return new jo().register(jd)}var Fd=/\b(compare|versus|\bvs\b|difference between|both|and then|after that|which is (?:better|cheaper|faster)|compar[ae]|diferencia entre)\b/i,da=/\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,
|
|
198
|
+
zd=/\b(summarize|rewrite|translate|classify|extract|reformat|fix|convert|the following|below|above|this text|resume|reescribe|traduce|clasifica)\b/i,Jn=class{classifier;maxRounds;constructor(e={}){this.
|
|
165
199
|
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.
|
|
166
|
-
test(r))return
|
|
167
|
-
.8,"self-contained transformation",0);let i=this.classifier?.classify(r);return i&&i.confidence>=.75?
|
|
168
|
-
e"?
|
|
169
|
-
d question",Math.min(this.maxRounds,2)):
|
|
170
|
-
"SINGLE_RETRIEVAL"?1:t==="MULTI_HOP_RETRIEVAL"?Math.min(e,2):0}function
|
|
171
|
-
us-4-5-20251101","claude-sonnet-4-5-20250929","claude-haiku-4-5-20251001"],
|
|
172
|
-
name:"tool_search_tool_bm25"},regex:{type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"}},
|
|
173
|
-
function
|
|
200
|
+
test(r))return Le("TOOL_ACTION",.9,"imperative + write tool available",0);if(n==="off")return Le("NO_RETRIEVAL",1,"retrieval disabled by caller",0);if(zd.test(r)&&!da.test(r))return Le("NO_RETRIEVAL",
|
|
201
|
+
.8,"self-contained transformation",0);let i=this.classifier?.classify(r);return i&&i.confidence>=.75?Le(i.executionClass,i.confidence,"local classifier",qd(i.executionClass,this.maxRounds)):n==="singl\
|
|
202
|
+
e"?Le("SINGLE_RETRIEVAL",.7,"caller hint: single",1):n==="multi"?Le("MULTI_HOP_RETRIEVAL",.7,"caller hint: multi",Math.min(this.maxRounds,2)):Fd.test(r)?Le("MULTI_HOP_RETRIEVAL",.7,"comparison/compoun\
|
|
203
|
+
d question",Math.min(this.maxRounds,2)):da.test(r)?Le("SINGLE_RETRIEVAL",.65,"single factual lookup",1):Le("NO_RETRIEVAL",.5,"no retrieval signal (conservative default)",0)}};function qd(t,e){return t===
|
|
204
|
+
"SINGLE_RETRIEVAL"?1:t==="MULTI_HOP_RETRIEVAL"?Math.min(e,2):0}function Le(t,e,n,r){return {executionClass:t,confidence:e,reason:n,rounds:r}}var Vd=["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\
|
|
205
|
+
us-4-5-20251101","claude-sonnet-4-5-20250929","claude-haiku-4-5-20251001"],pa={herramientas:10,tokensDeEsquemas:1e4},fa=5,Ud={regex:200,bm25:500},ma=1e4,Kn={bm25:{type:"tool_search_tool_bm25_20251119",
|
|
206
|
+
name:"tool_search_tool_bm25"},regex:{type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"}},Hd="bvsala_contract";function ha(t){let e=t.lastIndexOf("/");return (e>=0?t.slice(e+1):t).toLowerCase()}
|
|
207
|
+
function No(t){let e=r=>r.replace(/-\d{8}$/,""),n=e(ha(t));return Vd.some(r=>e(r)===n)}function $o(t){let e={modo:"off",siempreCargadas:[],variante:"bm25"};if(t===void 0)return e;let n=r=>r==="off"||r===
|
|
174
208
|
"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
|
|
176
|
-
let{opciones:e}=t,n=e.variante,r=(
|
|
209
|
+
r=>typeof r=="string"))]:[],variante:t.variant==="regex"?"regex":"bm25"}}function sn(t){return !t.some(e=>Array.isArray(e.intents)&&e.intents.length>0)&&!t.some(e=>typeof e.risk=="string")}function ga(t){
|
|
210
|
+
let{opciones:e}=t,n=e.variante,r=(y,k={})=>({aplicar:false,razon:y,variante:n,siempreCargadas:[],diferidas:0,tokensDiferidos:0,...k});if(e.modo==="off")return r("toolSearch is off");if(t.herramientas.length===
|
|
177
211
|
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(!
|
|
212
|
+
Responses and Agents APIs, not for Chat Completions, which is what the OpenAI-compatible adapter speaks");if(!No(t.modelo))return r(`${ha(t.modelo)} is not in the provider's tool search model compatib\
|
|
179
213
|
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=
|
|
181
|
-
return r(`one of your tools is already named \`${o.name}\``);let i=new Set(t.herramientas.map(
|
|
182
|
-
id)),u=c.reduce((
|
|
183
|
-
`${c.length} tools to defer, over the provider's limit of ${
|
|
214
|
+
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=Kn[n];if(t.herramientas.some(y=>y.id===o.name))
|
|
215
|
+
return r(`one of your tools is already named \`${o.name}\``);let i=new Set(t.herramientas.map(y=>y.id)),s=e.siempreCargadas.filter(y=>i.has(y)&&y!==Hd),a=new Set(s),c=t.herramientas.filter(y=>!a.has(y.
|
|
216
|
+
id)),u=c.reduce((y,k)=>y+k.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>ma)return r(
|
|
217
|
+
`${c.length} tools to defer, over the provider's limit of ${ma}`,l);if(e.modo==="always")return {aplicar:true,variante:n,...l,razon:`toolSearch "always": ${c.length} tool(s) deferred behind the provider'\
|
|
184
218
|
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((
|
|
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
|
|
187
|
-
1e3,
|
|
188
|
-
return
|
|
219
|
+
the search blocks. Use toolSearch "always" if yours does`,l);let d=t.herramientas.reduce((y,k)=>y+k.tokens,0);if(t.herramientas.length<pa.herramientas&&d<=pa.tokensDeEsquemas)return r(`${t.herramientas.
|
|
220
|
+
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 p=t.precio.inputPer1k/
|
|
221
|
+
1e3,h=t.precio.outputPer1k/1e3,m=Math.min(1,Math.max(0,t.lecturaDeCache)),g=c.map(y=>y.tokens).sort((y,k)=>k-y).slice(0,fa).reduce((y,k)=>y+k,0),f=m*p*u,v=p*g+h*Ud[n],b={ahorroDelPrefijo:f,costeDeUnaBusqueda:v};
|
|
222
|
+
return f<v?r(`deferring ${u} tokens of definitions saves ${f.toFixed(6)} per request even with a warm prompt cache, less than one worst-case search costs (${v.toFixed(6)}: the ${fa} largest definition\
|
|
189
223
|
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 (${
|
|
191
|
-
the layer credits nothing for it`}}function
|
|
192
|
-
this.maxTools=e.maxTools??8,this.scoreIntentMatch=e.scoreIntentMatch??
|
|
224
|
+
definitions out of the cached prefix): it pays even if every request searches once with a warm cache (${f.toFixed(6)} saved vs ${v.toFixed(6)} worst-case search). The provider's counter measures it; \
|
|
225
|
+
the layer credits nothing for it`}}function ba(t,e,n){return n||sn(t)?[...t]:t.filter(r=>e||r.risk==="read")}var Bo=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});}},Gn=class{maxTools;scoreIntentMatch;learningTurns;freezer;constructor(e={}){
|
|
226
|
+
this.maxTools=e.maxTools??8,this.scoreIntentMatch=e.scoreIntentMatch??Wd,this.learningTurns=e.learningTurns??16,this.freezer=e.freezer??new Bo;}passthrough(e){if(!e||e.length===0)return {tools:[],droppedIds:[],
|
|
193
227
|
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
228
|
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(
|
|
196
|
-
/${n.length}, capped at maxTools=${this.maxTools}). Declare ToolDescriptor.intents/risk to enable pruning`}}let i=r==="TOOL_ACTION",s=n.filter(
|
|
197
|
-
|
|
198
|
-
0).sort((
|
|
199
|
-
if(o!==void 0){let
|
|
200
|
-
tools:
|
|
201
|
-
x cache survives`,setIsStable:true}}let b=[...new Set([...
|
|
202
|
-
map(
|
|
203
|
-
isArray(e.intents)?e.intents:[]){let i
|
|
229
|
+
reason:"no tools provided",setIsStable:true};if(sn(n)){let f=this.passthrough(n);return {...f,reason:`catalogue declares no \`intents\` and no \`risk\`: nothing to select on, passed through (${f.tools.length}\
|
|
230
|
+
/${n.length}, capped at maxTools=${this.maxTools}). Declare ToolDescriptor.intents/risk to enable pruning`}}let i=r==="TOOL_ACTION",s=n.filter(f=>i||f.risk==="read"),a=f=>i&&f.risk!=="read",c=s.filter(
|
|
231
|
+
f=>!a(f)),u=s.filter(f=>a(f)),l=u.map(f=>({tool:f,score:this.scoreIntentMatch(e,f)})).sort((f,v)=>v.score-f.score).map(f=>f.tool),d=c.map(f=>({tool:f,score:this.scoreIntentMatch(e,f)})).filter(f=>f.score>
|
|
232
|
+
0).sort((f,v)=>v.score-f.score).map(f=>f.tool),h=[...l.slice(0,this.maxTools),...d.slice(0,Math.max(0,this.maxTools-u.length))].map(f=>({tool:f})).map(f=>f.tool).sort((f,v)=>f.id<v.id?-1:f.id>v.id?1:0);
|
|
233
|
+
if(o!==void 0){let f=this.freezer.read(o),v=(f?.turns??0)+1;if(f&&v>this.learningTurns){let y=new Set(f.ids),k=n.filter(w=>y.has(w.id));this.freezer.record(o,f.ids,v);let T=new Set(k.map(w=>w.id));return {
|
|
234
|
+
tools:k,droppedIds:n.filter(w=>!T.has(w.id)).map(w=>w.id),reason:`frozen tool set after ${this.learningTurns} turns (${k.length}/${n.length}): it no longer depends on this request's text, so the prefi\
|
|
235
|
+
x cache survives`,setIsStable:true}}let b=[...new Set([...f?.ids??[],...h.map(y=>y.id)])].sort().slice(0,this.maxTools);this.freezer.record(o,b,v);}let m=new Set(h.map(f=>f.id)),g=n.filter(f=>!m.has(f.id)).
|
|
236
|
+
map(f=>f.id);return {tools:h,droppedIds:g,reason:`selected ${h.length}/${n.length} by intent match (writes ${i?"allowed":"blocked"})`,setIsStable:g.length===0}}};function Wd(t,e){let n=$n(t),r=0;for(let o of Array.
|
|
237
|
+
isArray(e.intents)?e.intents:[]){let i=$n(o);i&&(n.includes(i)?r+=2:i.split(/\s+/).some(s=>s.length>3&&n.includes(s))&&(r+=1));}return r}function Jd(t){let e=new Set,n=[];for(let r of t){let o=r.hash??Gd(r.text);e.has(o)||(e.add(o),n.push(r));}return n}function Kd(t,e={maxDocuments:5}){let n=e.minDocuments??1,r=[...t].sort((s,a)=>(a.score??
|
|
204
238
|
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(
|
|
205
|
-
s);else break}return i}async function
|
|
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=
|
|
207
|
-
(r=await e.reranker.rerank(t.query,r));let i=
|
|
208
|
-
...t.userPreferences},decisions:[...t.decisions],openItems:[...t.openItems],evidenceRefs:[...t.evidenceRefs]};for(let[r,o]of Object.entries(e.set??{}))r==="userPreferences"&&
|
|
209
|
-
o):n.confirmedFacts[r]=o;for(let[r,o]of Object.entries(e.append??{})){let i=
|
|
210
|
-
|
|
211
|
-
${r}`});let o=t.history.slice(-e);return n.push(...o,t.current),n}function
|
|
239
|
+
s);else break}return i}async function va(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};
|
|
240
|
+
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=Jd(r),e.reranker&&
|
|
241
|
+
(r=await e.reranker.rerank(t.query,r));let i=Kd(r,{maxDocuments:t.maxDocuments});return {docs:i,rounds:n,retrievedCount:o,keptCount:i.length}}function Gd(t){return t.trim().replace(/\s+/g," ").toLowerCase()}function d0(){return {goals:[],confirmedFacts:{},userPreferences:{},decisions:[],openItems:[],evidenceRefs:[]}}function p0(t,e){let n={goals:[...t.goals],confirmedFacts:{...t.confirmedFacts},userPreferences:{
|
|
242
|
+
...t.userPreferences},decisions:[...t.decisions],openItems:[...t.openItems],evidenceRefs:[...t.evidenceRefs]};for(let[r,o]of Object.entries(e.set??{}))r==="userPreferences"&&Xd(o)?Object.assign(n.userPreferences,
|
|
243
|
+
o):n.confirmedFacts[r]=o;for(let[r,o]of Object.entries(e.append??{})){let i=Yd(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],
|
|
244
|
+
Qd(n,r);return n}function f0(t){let e=t.rawTurns??3,n=[],r=Zd(t.state);r&&n.push({role:"system",content:`Conversation state:
|
|
245
|
+
${r}`});let o=t.history.slice(-e);return n.push(...o,t.current),n}function Zd(t){let e=[];return t.goals.length&&e.push(`goals: ${t.goals.join("; ")}`),Object.keys(t.confirmedFacts).length&&e.push(`fa\
|
|
212
246
|
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(
|
|
213
247
|
"; ")}`),t.openItems.length&&e.push(`open: ${t.openItems.join("; ")}`),e.join(`
|
|
214
|
-
`)}function
|
|
215
|
-
for(let n of ["goals","decisions","openItems","evidenceRefs"]){let r=t[n].indexOf(e);r>=0&&t[n].splice(r,1);}}function
|
|
216
|
-
`).filter(c=>c.trim().length>0).map(c=>({indent:
|
|
217
|
-
c[2],n),d=Number(c[1]),
|
|
218
|
-
match(/^\[(\d+)\]:\s*(.*)$/);if(u){let l=u[2];return Number(u[1])===0||l.trim()===""?[]:
|
|
219
|
-
function
|
|
248
|
+
`)}function Yd(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 Qd(t,e){
|
|
249
|
+
for(let n of ["goals","decisions","openItems","evidenceRefs"]){let r=t[n].indexOf(e);r>=0&&t[n].splice(r,1);}}function Xd(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var ya={format:"json-compact",supports(){return true},encode(t){return JSON.stringify(t)},instruction(){return ""}};function ka(t,e={}){let n=e.delimiter??",",r=e.indent??" ",i=t.split(`
|
|
250
|
+
`).filter(c=>c.trim().length>0).map(c=>({indent:ep(c,r),content:c.slice(xa(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=Et(
|
|
251
|
+
c[2],n),d=Number(c[1]),p=[];for(let h=0,m=1;h<d&&m<i.length;h++,m++){let g=i[m];if(g.indent!==1)break;let f=Et(g.content,n),v={};l.forEach((b,y)=>{v[b]=an(f[y]??"null");}),p.push(v);}return p}let u=s.content.
|
|
252
|
+
match(/^\[(\d+)\]:\s*(.*)$/);if(u){let l=u[2];return Number(u[1])===0||l.trim()===""?[]:Et(l,n).map(an)}}let[a]=wa(i,0,0,n);return a}function xa(t,e){let n=0;for(;t.startsWith(e,n);)n+=e.length;return n}
|
|
253
|
+
function ep(t,e){return xa(t,e)/e.length}function wa(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=tp(s.content,r);if(!a){i++;continue}let{key:c,
|
|
220
254
|
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
|
|
222
|
-
i]}function
|
|
223
|
-
let i=Number(r[2]),s=r[3];return i===0||s.trim()===""?{key:
|
|
224
|
-
o[1]),s=o[2];return s===""?{key:i,kind:{type:"object"}}:{key:i,kind:{type:"scalar",value:
|
|
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
|
|
226
|
-
'"'):t==="null"?null:t==="true"?true:t==="false"?false:/^-?\d+$/.test(t)||/^-?\d*\.\d+$/.test(t)?Number(t):t}function
|
|
227
|
-
'"'):e}function
|
|
228
|
-
`)}function
|
|
229
|
-
e))
|
|
230
|
-
join(o);r.push(`${s}${a}[${e.length}]: ${d}`);return}let c=
|
|
231
|
-
return}r.push(`${s}${a}[${e.length}]:`);let u=n+1,l=i.repeat(u);for(let d of e)if(
|
|
232
|
-
r.push(`${l}${i}${g}`);}}function
|
|
233
|
-
o))return null;let i=Object.keys(o);if(i.slice().sort().join("\0")!==r)return null;for(let s of i)if(!
|
|
255
|
+
i<t.length;d++,i++){let p=t[i];if(p.indent!==n+1)break;let h=Et(p.content,r),m={};u.columns.forEach((g,f)=>{m[g]=an(h[f]??"null");}),l.push(m);}o[c]=l;}else {let[l,d]=wa(t,i+1,n+1,r);o[c]=l,i=d;}}return [o,
|
|
256
|
+
i]}function tp(t,e){let n=t.match(/^([^[:]+)\[(\d+)\]\{(.*)\}:\s*$/);if(n)return {key:Zn(n[1]),kind:{type:"table",count:Number(n[2]),columns:Et(n[3],e)}};let r=t.match(/^([^[:]+)\[(\d+)\]:\s*(.*)$/);if(r){
|
|
257
|
+
let i=Number(r[2]),s=r[3];return i===0||s.trim()===""?{key:Zn(r[1]),kind:{type:"emptyArray"}}:{key:Zn(r[1]),kind:{type:"inlineArray",values:Et(s,e).map(an)}}}let o=t.match(/^([^:]+):\s*(.*)$/);if(o){let i=Zn(
|
|
258
|
+
o[1]),s=o[2];return s===""?{key:i,kind:{type:"object"}}:{key:i,kind:{type:"scalar",value:an(s)}}}return null}function Et(t,e){let n=[],r="",o=false;for(let i=0;i<t.length;i++){let s=t[i];o?s==='"'?t[i+1]===
|
|
259
|
+
'"'?(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 an(t){return t.startsWith('"')&&t.endsWith('"')&&t.length>=2?t.slice(1,-1).replace(/""/g,
|
|
260
|
+
'"'):t==="null"?null:t==="true"?true:t==="false"?false:/^-?\d+$/.test(t)||/^-?\d*\.\d+$/.test(t)?Number(t):t}function Zn(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/""/g,
|
|
261
|
+
'"'):e}function np(t,e={}){let n=e.delimiter??",",r=e.indent??" ",o=[];return qo(null,t,0,o,n,r),o.join(`
|
|
262
|
+
`)}function qo(t,e,n,r,o,i){let s=i.repeat(n),a=t===null?"":`${op(t)}`;if(Array.isArray(e)){rp(a,e,n,r,o,i);return}if(zo(e)){t!==null&&r.push(`${s}${a}:`);let c=t===null?n:n+1;for(let[u,l]of Object.entries(
|
|
263
|
+
e))qo(u,l,c,r,o,i);return}r.push(`${s}${a}: ${Yn(e,o)}`);}function rp(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(Fo)){let d=e.map(p=>Yn(p,o)).
|
|
264
|
+
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 p of e){let h=c.map(m=>Yn(p[m],o)).join(o);r.push(`${d}${h}`);}
|
|
265
|
+
return}r.push(`${s}${a}[${e.length}]:`);let u=n+1,l=i.repeat(u);for(let d of e)if(Fo(d))r.push(`${l}- ${Yn(d,o)}`);else {let p=[];qo(null,d,0,p,o,i);let[h,...m]=p;r.push(`${l}- ${h??""}`);for(let g of m)
|
|
266
|
+
r.push(`${l}${i}${g}`);}}function Qn(t){if(t.length===0)return null;let e=t[0];if(!zo(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(!zo(
|
|
267
|
+
o))return null;let i=Object.keys(o);if(i.slice().sort().join("\0")!==r)return null;for(let s of i)if(!Fo(o[s]))return null}return n}function op(t){return /^[A-Za-z_][A-Za-z0-9_]*$/.test(t)?t:Sa(t)}function Yn(t,e){
|
|
234
268
|
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(`
|
|
235
|
-
`)||n.includes('"')||n!==n.trim()||/^(true|false|null)$/.test(n)||/^-?\d/.test(n)?
|
|
236
|
-
"number"||typeof t=="boolean"}function
|
|
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
|
|
238
|
-
encode(e){return
|
|
239
|
-
`)},instruction(){return "Data is CSV: first line is the header row; each subsequent line is one record."}};function
|
|
240
|
-
'""')}"`:e}var
|
|
269
|
+
`)||n.includes('"')||n!==n.trim()||/^(true|false|null)$/.test(n)||/^-?\d/.test(n)?Sa(n):n}function Sa(t){return `"${t.replace(/"/g,'""')}"`}function Fo(t){return t===null||typeof t=="string"||typeof t==
|
|
270
|
+
"number"||typeof t=="boolean"}function zo(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var ip="Data is the compact encoder: `key[N]{c1,c2}:` declares an N-row table with columns c1,c2; ea\
|
|
271
|
+
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 sp(t={}){return {format:"compact-rows",supports(){return true},
|
|
272
|
+
encode(e){return np(e,t)},instruction(){return ip},decode(e){return ka(e,t)}}}var Ta=sp();var Ea={format:"csv",supports(t){return Array.isArray(t)&&Qn(t)!==null},encode(t){let e=t,n=Qn(e),r=n.map(Ca).join(","),o=e.map(i=>n.map(s=>Ca(i[s])).join(","));return [r,...o].join(`
|
|
273
|
+
`)},instruction(){return "Data is CSV: first line is the header row; each subsequent line is one record."}};function Ca(t){if(t==null)return "";let e=String(t);return /[",\n]/.test(e)?`"${e.replace(/"/g,
|
|
274
|
+
'""')}"`:e}var Xn=class{tokenizer;serializers;minSavingsTokens;minSavingsRatio;qualityPenalty;constructor(e){this.tokenizer=e.tokenizer,this.serializers=e.serializers??[ya,Ta,Ea],this.minSavingsTokens=e.minimumSavingsTokens??
|
|
241
275
|
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"&&!
|
|
243
|
-
o.push({format:u.format,encoded:l,instruction:d,payloadTokens:
|
|
244
|
-
return u?
|
|
276
|
+
e))continue;let l=u.encode(e);if(u.format!=="json-compact"&&!ap(u,l,e))continue;let d=u.instruction(e),p=this.tokenizer.count(l,r),h=d?this.tokenizer.count(d,r):0,m=this.qualityPenalty(n.model??"",u.format);
|
|
277
|
+
o.push({format:u.format,encoded:l,instruction:d,payloadTokens:p,instructionTokens:h,penalty:m,total:p+h+m});}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];
|
|
278
|
+
return u?Pa(u,s,"json baseline unavailable"):{chosen:"json-compact",encoded:JSON.stringify(e),instruction:"",candidateTokens:s,instructionOverheadTokens:0,reason:"no serializer supported payload; defa\
|
|
245
279
|
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
|
|
247
|
-
n)}catch{return false}}function
|
|
248
|
-
length)return false;for(let s=0;s<t.length;s++)if(!
|
|
249
|
-
call(e,s)||!
|
|
250
|
-
string":return "string";case "number":return "number";case "boolean":return "boolean";default:return}}function
|
|
251
|
-
e.type??
|
|
252
|
-
message:"expected boolean"});break;case "null":t!==null&&r.push({path:n,message:"expected null"});break;}}function
|
|
280
|
+
d>=this.minSavingsRatio&&u.total<a.total&&(a=u,c=`${u.format} saved ${l} tokens (${(d*100).toFixed(1)}%) vs json`);}return Pa(a,s,c)}};function ap(t,e,n){if(!t.decode)return false;try{return Vo(t.decode(e),
|
|
281
|
+
n)}catch{return false}}function Vo(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.
|
|
282
|
+
length)return false;for(let s=0;s<t.length;s++)if(!Vo(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.
|
|
283
|
+
call(e,s)||!Vo(t[s],e[s]))return false;return true}function Pa(t,e,n){return {chosen:t.format,encoded:t.encoded,instruction:t.instruction,candidateTokens:e,instructionOverheadTokens:t.instructionTokens,reason:n}}function pe(t,e,n="$"){let r=[];return Uo(t,e,n,r),{valid:r.length===0,errors:r}}function cp(t){if(Array.isArray(t))return "array";if(t===null)return "null";switch(typeof t){case "object":return "object";case "\
|
|
284
|
+
string":return "string";case "number":return "number";case "boolean":return "boolean";default:return}}function Uo(t,e,n,r){switch(e.enum&&!e.enum.some(i=>fp(i,t))&&r.push({path:n,message:"value not in enum"}),
|
|
285
|
+
e.type??cp(t)){case "object":up(t,e,n,r);break;case "array":lp(t,e,n,r);break;case "string":dp(t,e,n,r);break;case "number":case "integer":pp(t,e,n,r);break;case "boolean":typeof t!="boolean"&&r.push({path:n,
|
|
286
|
+
message:"expected boolean"});break;case "null":t!==null&&r.push({path:n,message:"expected null"});break;}}function up(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t)){r.push({path:n,
|
|
253
287
|
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(
|
|
254
288
|
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&&
|
|
255
|
-
|
|
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)=>
|
|
289
|
+
Uo(o[i],s,`${n}.${i}`,r);}function lp(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\
|
|
290
|
+
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)=>Uo(o,e.items,`${n}[${i}]`,r));}function dp(t,e,n,r){if(typeof t!=
|
|
257
291
|
"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.
|
|
258
292
|
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\
|
|
259
|
-
sion: ${e.pattern}`});}o&&!o.test(t)&&r.push({path:n,message:"string does not match pattern"});}}function
|
|
293
|
+
sion: ${e.pattern}`});}o&&!o.test(t)&&r.push({path:n,message:"string does not match pattern"});}}function pp(t,e,n,r){if(typeof t!="number"||Number.isNaN(t)){r.push({path:n,message:"expected number"});return}
|
|
260
294
|
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.
|
|
261
|
-
minimum&&r.push({path:n,message:`number below minimum ${e.minimum}`});}function
|
|
262
|
-
e,n,r),r}};function
|
|
263
|
-
.${r}`,n);}t.type==="array"&&(t.maxItems==null&&n.push(`${e}: array should set maxItems to bound output`),t.items&&
|
|
264
|
-
tring should set maxLength or use an enum`);}function
|
|
265
|
-
ate + repair"}}function
|
|
266
|
-
return r<n?{compress:false,reason:`net saving ${r} < ${n} min`}:{compress:true,reason:`net saving ${r} tokens`}}function
|
|
295
|
+
minimum&&r.push({path:n,message:`number below minimum ${e.minimum}`});}function fp(t,e){return t===e?true:typeof t!=typeof e?false:t&&e&&typeof t=="object"?JSON.stringify(t)===JSON.stringify(e):false}var er=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 Ho(
|
|
296
|
+
e,n,r),r}};function Ho(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??{}))Ho(o,`${e}\
|
|
297
|
+
.${r}`,n);}t.type==="array"&&(t.maxItems==null&&n.push(`${e}: array should set maxItems to bound output`),t.items&&Ho(t.items,`${e}[]`,n)),t.type==="string"&&t.maxLength==null&&!t.enum&&n.push(`${e}: s\
|
|
298
|
+
tring should set maxLength or use an enum`);}function Ra(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\
|
|
299
|
+
ate + repair"}}function j0(t=()=>true){return {id:"provider-native",supports:t}}function Wo(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;
|
|
300
|
+
return r<n?{compress:false,reason:`net saving ${r} < ${n} min`}:{compress:true,reason:`net saving ${r} tokens`}}function V0(t){return {async compress(e){let n=e.protectedSpans??[],r=e.text,o=[];n.forEach((c,u)=>{
|
|
267
301
|
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
302
|
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
|
|
270
|
-
compressedTokens:0,protectedSpans:(t.protectedSpans??[]).length,fidelityPassed:true,skipped:true,reason:"no compressor configured (noop)"}}};function
|
|
303
|
+
originalTokens,protectedSpans:n.length,fidelityPassed:false,skipped:true,reason:"protected span lost during compression; fell back to original"}}}}var U0={async compress(t){return {compressed:t.text,originalTokens:0,
|
|
304
|
+
compressedTokens:0,protectedSpans:(t.protectedSpans??[]).length,fidelityPassed:true,skipped:true,reason:"no compressor configured (noop)"}}};function Da(t,e){let n=s=>s.toLowerCase().replace(/[.,;:!¡?¿()[\]{}"«»…]/g,
|
|
271
305
|
" ").replace(/\s+/g," ").trim(),o=n((s=>{let a=new Set,c=[];for(let u of s.split(`
|
|
272
306
|
`)){let l=u.trim();l&&a.has(l)||(l&&a.add(l),c.push(u));}return c.join(`
|
|
273
|
-
`)})(t)),i=n(e);return !(!
|
|
274
|
-
let e=t.replace(
|
|
307
|
+
`)})(t)),i=n(e);return !(!Lo(nn(o),nn(i))||on(rn(o))!==on(rn(i)))}var Jo=["ansi","carriage-return","json","repeated-lines"],mp=256,hp=/\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)|[ -/]+[0-~]|[@-_])/g;function gp(t){if(!t.includes("\x1B"))return null;
|
|
308
|
+
let e=t.replace(hp,"");return e.length<t.length?e:null}function bp(t){let e="";for(let n of t.split("\r"))e=n+e.slice(n.length);return e}function vp(t){if(!t.includes("\r")||t.includes(`\r
|
|
275
309
|
`))return null;let e=t.split(`
|
|
276
|
-
`).map(n=>n.includes("\r")?
|
|
277
|
-
`);return e.length<t.length?e:null}var
|
|
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}
|
|
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
|
|
280
|
-
[previous line repeated ${t} more times]`,
|
|
281
|
-
`)){let r=
|
|
282
|
-
`)}function
|
|
283
|
-
`);if(e.length<
|
|
310
|
+
`).map(n=>n.includes("\r")?bp(n):n).join(`
|
|
311
|
+
`);return e.length<t.length?e:null}var yp=t=>t===32||t===9||t===10||t===13;function kp(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=[],
|
|
312
|
+
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}yp(u)&&(c>i&&o.push(e.slice(i,c)),i=c+1);}i<e.length&&o.push(e.slice(i));let a=o.
|
|
313
|
+
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 Aa=/^\[previous line repeated (\d+) more times\]$/,xp=t=>`\
|
|
314
|
+
[previous line repeated ${t} more times]`,Ia=3;function wp(t){let e=[];for(let n of t.split(`
|
|
315
|
+
`)){let r=Aa.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(`
|
|
316
|
+
`)}function Sp(t){let e=t.split(`
|
|
317
|
+
`);if(e.length<Ia||e.some(i=>Aa.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=xp(c);if(c+1>=Ia&&c*(s.length+1)>u.length+1)n.push(
|
|
284
318
|
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
|
|
286
|
-
o=t,i=[];for(let a of
|
|
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
|
|
288
|
-
applied:[],originalChars:t.length,compactChars:t.length,reason:e}}var
|
|
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=>
|
|
319
|
+
`);return wp(o)!==t?null:o.length<t.length?o:null}var Tp={ansi:gp,"carriage-return":vp,json:kp,"repeated-lines":Sp};function Oa(t,e={}){let n=new Set(e.transforms??Jo),r=Math.max(1,e.minSavedChars??256),
|
|
320
|
+
o=t,i=[];for(let a of Jo){if(!n.has(a))continue;let c=Tp[a](o);c!=null&&c.length<o.length&&(o=c,i.push(a));}let s=t.length-o.length;return i.length===0?_a(t,"nothing to compact"):s<r?_a(t,`compaction w\
|
|
321
|
+
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 _a(t,e){return {text:t,changed:false,
|
|
322
|
+
applied:[],originalChars:t.length,compactChars:t.length,reason:e}}var Cp=new Set(["path","paths","file","files","filepath","filename","absolutepath","relativepath","targetfile","notebookpath"]);function Ep(t){
|
|
323
|
+
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=>Cp.has(n.toLowerCase().replace(/[_-]/g,"")))}function Ma(t,e={}){let n=new Map,
|
|
290
324
|
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&&
|
|
292
|
-
argumentos)){i.vistasDeFichero+=1;return}let l=
|
|
293
|
-
`),o=
|
|
294
|
-
options.data??
|
|
325
|
+
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&&Ep(c?.
|
|
326
|
+
argumentos)){i.vistasDeFichero+=1;return}let l=Oa(s.content,e);l.changed&&i.compactados.push({indice:a,texto:l.text,aplicadas:l.applied,enLaCola:a>r});}),i}var La=new WeakSet;function ja(t){La.add(t);}function Ko(t){return typeof t=="object"&&t!==null&&La.has(t)}var Go=class{id="mock";options;constructor(e={}){this.options=e,ja(this);}async generate(e,n){let r=e.messages.map(c=>c.content).join(`
|
|
327
|
+
`),o=Tt.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+=Tt.count(c);}let i,s=false;if(e.schema){let c=this.
|
|
328
|
+
options.data??tr(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,Tt.count(i));return {text:i,usage:{
|
|
295
329
|
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.
|
|
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
|
|
297
|
-
enum[0];switch(t.type){case "object":{let e={};for(let n of t.required??[]){let r=t.properties?.[n];e[n]=r?
|
|
298
|
-
array":return t.items?[
|
|
299
|
-
t)}function
|
|
300
|
-
Number(e[2]);return n>5||n===5&&r>=6}function
|
|
301
|
-
return
|
|
302
|
-
|
|
330
|
+
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 tr(t){if(t.enum&&t.enum.length>0)return t.
|
|
331
|
+
enum[0];switch(t.type){case "object":{let e={};for(let n of t.required??[]){let r=t.properties?.[n];e[n]=r?tr(r):null;}for(let[n,r]of Object.entries(t.properties??{}))n in e||(e[n]=tr(r));return e}case "\
|
|
332
|
+
array":return t.items?[tr(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 X0(t){return new Go(
|
|
333
|
+
t)}function Zo(t){let e=t.toLowerCase(),n=e.lastIndexOf("/");return n>=0?e.slice(n+1):e}function Na(t){let e=/^gpt-(\d+)(?:\.(\d+))?(?![\d.])/.exec(t);if(!e)return false;let n=Number(e[1]),r=e[2]===void 0?0:
|
|
334
|
+
Number(e[2]);return n>5||n===5&&r>=6}function Ke(t){let e=Zo(t);return e.startsWith("gpt-")||e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4")?Na(e)?1.25:1:e.startsWith("gemini")?1:1.25}function cn(t){
|
|
335
|
+
return Na(Zo(t))?1.25:1}function Yo(t){let e=t.toLowerCase();return e.startsWith("claude")||e.startsWith("anthropic/")||Zo(e).startsWith("claude")?2:Ke(t)}var Pp="https://developers.openai.com/api/docs/pricing",Rp="https://ai.google.dev/gemini-api/docs/pricing",Qo="2026-09-27",$=t=>({...t,fuente:Pp,consultado:Qo}),De=t=>({...t,fuente:Rp,consultado:Qo}),
|
|
336
|
+
Dp="https://platform.claude.com/docs/en/about-claude/pricing",ne=t=>({...t,fuente:Dp,consultado:Qo}),Ip={openai:{flex:{"gpt-5":$({inputPer1k:625e-6,cachedInputPer1k:625e-7,outputPer1k:.005}),"gpt-5-mi\
|
|
303
337
|
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
338
|
"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
339
|
"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,
|
|
@@ -327,208 +361,246 @@ outputPer1k:.00225}),"gpt-5.4-nano":$({inputPer1k:1e-4,cachedInputPer1k:1e-5,out
|
|
|
327
361
|
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
362
|
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
363
|
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":
|
|
331
|
-
cacheWritePer1k:.00625,outputPer1k:.025}),"claude-fable-5":
|
|
332
|
-
cacheWritePer1k:.00625,outputPer1k:.025}),"claude-opus-5-5":
|
|
333
|
-
cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-8":
|
|
334
|
-
cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-6":
|
|
335
|
-
cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4":
|
|
336
|
-
cacheWritePer1k:.00125,outputPer1k:.005}),"claude-sonnet-4-6":
|
|
337
|
-
cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-sonnet-4":
|
|
338
|
-
cacheWritePer1k:625e-6,outputPer1k:.0025}),"claude-3-5-haiku":
|
|
339
|
-
outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.5-flash":
|
|
340
|
-
cachedInputPer1k:2e-5}),"gemini-3.1-pro-preview":
|
|
341
|
-
outputPer1k:.009,cachedInputPer1k:4e-4}}}),"gemini-2.5-pro":
|
|
342
|
-
inputPer1k:.00125,outputPer1k:.0075,cachedInputPer1k:25e-5}}}),"gemini-2.5-flash":
|
|
343
|
-
cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.6-flash":
|
|
344
|
-
outputPer1k:75e-5,cachedInputPer1k:125e-7}),"gemini-3-flash-preview":
|
|
345
|
-
t}function
|
|
346
|
-
opic":/^(gpt-|o[1-9](-|$))/.test(o)?"openai":o.startsWith("gemini")?"google":o.startsWith("claude-")?"anthropic":null}function
|
|
347
|
-
if(
|
|
348
|
-
inputPer1k*
|
|
349
|
-
null?{servido:t,factor:null,conDescuento:false}:{servido:t,factor:e,conDescuento:e<1}}var
|
|
350
|
-
"number"&&Number.isFinite(t);function
|
|
351
|
-
standard-rate-tier"};let n=t.uso;if(n.complete===false||!
|
|
352
|
-
return {ok:false,motivo:"incomplete-usage"};let r=
|
|
353
|
-
motivo:"no-tier-price"};let s=Math.max(0,n.inputTokens),a=
|
|
354
|
-
u?Math.min(Math.max(0,n.cacheWriteInputTokens??0),s-l):0,
|
|
355
|
-
outputPer1k},g={input:i.inputPer1k,"cached input":i.cachedInputPer1k,"cache write":i.cacheWritePer1k,output:i.outputPer1k},
|
|
356
|
-
{tokens:l,posibles:["cached input"]},{tokens:d,posibles:["cache write"]},{tokens:
|
|
357
|
-
b.inputPer1k,"cache write":b.inputPer1k*a,output:b.outputPer1k}:void 0,
|
|
358
|
-
|
|
359
|
-
void 0&&
|
|
360
|
-
std-j.aplicado;
|
|
364
|
+
{inputPer1k:.01,outputPer1k:.04})}},anthropic:{batch:{"claude-fable-5-1":ne({inputPer1k:.005,cachedInputPer1k:125e-6,cacheWritePer1k:.00625,outputPer1k:.025}),"claude-mythos-5-1":ne({inputPer1k:.005,cachedInputPer1k:125e-6,
|
|
365
|
+
cacheWritePer1k:.00625,outputPer1k:.025}),"claude-fable-5":ne({inputPer1k:.005,cachedInputPer1k:5e-4,cacheWritePer1k:.00625,outputPer1k:.025}),"claude-mythos-5":ne({inputPer1k:.005,cachedInputPer1k:5e-4,
|
|
366
|
+
cacheWritePer1k:.00625,outputPer1k:.025}),"claude-opus-5-5":ne({inputPer1k:.002,cachedInputPer1k:1e-4,cacheWritePer1k:.0025,outputPer1k:.01}),"claude-opus-5":ne({inputPer1k:.0025,cachedInputPer1k:25e-5,
|
|
367
|
+
cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-8":ne({inputPer1k:.0025,cachedInputPer1k:25e-5,cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-7":ne({inputPer1k:.0025,cachedInputPer1k:25e-5,
|
|
368
|
+
cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-6":ne({inputPer1k:.0025,cachedInputPer1k:25e-5,cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-5":ne({inputPer1k:.0025,cachedInputPer1k:25e-5,
|
|
369
|
+
cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4":ne({inputPer1k:.0075,cachedInputPer1k:75e-5,cacheWritePer1k:.009375,outputPer1k:.0375}),"claude-sonnet-5":ne({inputPer1k:.001,cachedInputPer1k:1e-4,
|
|
370
|
+
cacheWritePer1k:.00125,outputPer1k:.005}),"claude-sonnet-4-6":ne({inputPer1k:.0015,cachedInputPer1k:15e-5,cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-sonnet-4-5":ne({inputPer1k:.0015,cachedInputPer1k:15e-5,
|
|
371
|
+
cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-sonnet-4":ne({inputPer1k:.0015,cachedInputPer1k:15e-5,cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-haiku-4-5":ne({inputPer1k:5e-4,cachedInputPer1k:5e-5,
|
|
372
|
+
cacheWritePer1k:625e-6,outputPer1k:.0025}),"claude-3-5-haiku":ne({inputPer1k:4e-4,cachedInputPer1k:4e-5,cacheWritePer1k:5e-4,outputPer1k:.002})}},google:{flex:{"gemini-3.7-flash":De({inputPer1k:375e-6,
|
|
373
|
+
outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.5-flash":De({inputPer1k:75e-5,outputPer1k:.0045,cachedInputPer1k:8e-5}),"gemini-3.5-flash-lite":De({inputPer1k:15e-5,outputPer1k:.00125,
|
|
374
|
+
cachedInputPer1k:2e-5}),"gemini-3.1-pro-preview":De({inputPer1k:.001,outputPer1k:.006,cachedInputPer1k:2e-4,largo:{estandar:{inputPer1k:.004,outputPer1k:.018,cachedInputPer1k:4e-4},tier:{inputPer1k:.002,
|
|
375
|
+
outputPer1k:.009,cachedInputPer1k:4e-4}}}),"gemini-2.5-pro":De({inputPer1k:625e-6,outputPer1k:.005,cachedInputPer1k:125e-6,largo:{estandar:{inputPer1k:.0025,outputPer1k:.015,cachedInputPer1k:25e-5},tier:{
|
|
376
|
+
inputPer1k:.00125,outputPer1k:.0075,cachedInputPer1k:25e-5}}}),"gemini-2.5-flash":De({inputPer1k:15e-5,outputPer1k:.00125,cachedInputPer1k:3e-5}),"gemini-3.8-flash":De({inputPer1k:375e-6,outputPer1k:.001875,
|
|
377
|
+
cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.6-flash":De({inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.1-flash-lite":De({inputPer1k:125e-6,
|
|
378
|
+
outputPer1k:75e-5,cachedInputPer1k:125e-7}),"gemini-3-flash-preview":De({inputPer1k:25e-5,outputPer1k:.0015,cachedInputPer1k:5e-5})}}};function Ge(t){let e=t.lastIndexOf("/");return e>=0?t.slice(e+1):
|
|
379
|
+
t}function un(t){let e=t.toLowerCase(),n=e.indexOf("/"),r=n>0?e.slice(0,n):"",o=Ge(e);return r==="openai"||r==="azure-openai"?"openai":r==="google"||r==="google-vertex"?"google":r==="anthropic"?"anthr\
|
|
380
|
+
opic":/^(gpt-|o[1-9](-|$))/.test(o)?"openai":o.startsWith("gemini")?"google":o.startsWith("claude-")?"anthropic":null}function _p(t){return Date.parse(`${t}T23:59:59.999Z`)}function ln(t,e,n,r=Date.now()){
|
|
381
|
+
if(We(n)===void 0)return;let o=St(n);if(o===void 0)return;let i=Ip[t]?.[e],s=i?i[o]:void 0;if(s&&!(s.vigenteHasta&&r>_p(s.vigenteHasta)))return s}function nr(t){let e=We(t);if(e)return {...e,cacheWritePer1k:e.
|
|
382
|
+
inputPer1k*Ke(Ge(t))}}var $a={flex:.5,default:1,auto:1,priority:1,fast:1,scale:1,standard:1,batch:.5},Ba=Math.min(...Object.values($a).filter(t=>t<1)),Pt="flex";function Xo(t){if(t==null||t==="")return null;let e=$a[t];return e==
|
|
383
|
+
null?{servido:t,factor:null,conDescuento:false}:{servido:t,factor:e,conDescuento:e<1}}var rr=1e10;function ei(t){let e=Math.floor(t*rr)/rr;return e>t&&(e=(Math.floor(t*rr)-1)/rr),e<=0?0:e}var or=t=>typeof t==
|
|
384
|
+
"number"&&Number.isFinite(t);function ir(t){let e=Xo(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:"\
|
|
385
|
+
standard-rate-tier"};let n=t.uso;if(n.complete===false||!or(n.inputTokens)||!or(n.outputTokens)||n.cachedInputTokens!=null&&!or(n.cachedInputTokens)||n.cacheWriteInputTokens!=null&&!or(n.cacheWriteInputTokens))
|
|
386
|
+
return {ok:false,motivo:"incomplete-usage"};let r=nr(t.modelo);if(!r)return {ok:false,motivo:"no-standard-price"};let o=t.origen??un(t.modelo),i=o?ln(o,e.servido,t.modelo,t.ahoraMs):void 0;if(!i)return {ok:false,
|
|
387
|
+
motivo:"no-tier-price"};let s=Math.max(0,n.inputTokens),a=Ke(Ge(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&&
|
|
388
|
+
u?Math.min(Math.max(0,n.cacheWriteInputTokens??0),s-l):0,p=s-l-d,h=Math.max(0,n.outputTokens),m={input:r.inputPer1k,"cached input":r.cachedInputPer1k??r.inputPer1k,"cache write":r.cacheWritePer1k,output:r.
|
|
389
|
+
outputPer1k},g={input:i.inputPer1k,"cached input":i.cachedInputPer1k,"cache write":i.cacheWritePer1k,output:i.outputPer1k},f=[{tokens:p,posibles:["input",...c?[]:["cached input"],...u?[]:["cache write"]]},
|
|
390
|
+
{tokens:l,posibles:["cached input"]},{tokens:d,posibles:["cache write"]},{tokens:h,posibles:["output"]}],v=p>0&&f[0].posibles.length>1,b=t.precioDelCliente,y=b?{input:b.inputPer1k,"cached input":b.cachedInputPer1k??
|
|
391
|
+
b.inputPer1k,"cache write":b.inputPer1k*a,output:b.outputPer1k}:void 0,k=(j,B)=>{let V=B?y[j]:m[j],z=g[j];return z===void 0?{std:V,aplicado:V}:B?{std:V,aplicado:m[j]>0?V*(z/m[j]):V}:{std:V,aplicado:z}},
|
|
392
|
+
T=new Set,w=j=>{let B=0,V=0;for(let z of f){if(z.tokens<=0)continue;let ee=z.posibles[0],L=k(ee,j);for(let ae of z.posibles.slice(1)){let ce=k(ae,j);ce.std-ce.aplicado<L.std-L.aplicado&&(ee=ae,L=ce);}g[ee]===
|
|
393
|
+
void 0&&z.posibles.length===1&&T.add(ee),B+=z.tokens/1e3*L.std,V+=z.tokens/1e3*L.aplicado;}return {std:B,aplicado:V}},S=w(false),x=S.std-S.aplicado,C=S.std,_=S.aplicado,R=x,E=false;if(b){let j=w(true);C=j.std;let B=j.
|
|
394
|
+
std-j.aplicado;E=B>x,R=Math.min(B,x),_=E?j.std-R:j.aplicado;}if(!(R>0))return {ok:false,motivo:"no-difference"};let D=ei(R);if(D<=0)return {ok:false,motivo:"no-difference"};let I=[];if(t.origen===null?I.push("\
|
|
361
395
|
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"+(
|
|
363
|
-
t the difference between the two published rate cards":"")),
|
|
364
|
-
its prompt cache, so those tokens are priced at the smallest per-token difference they could have had`);}
|
|
365
|
-
e tokens add nothing`);let
|
|
396
|
+
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"+(E?", capped a\
|
|
397
|
+
t the difference between the two published rate cards":"")),v){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}\
|
|
398
|
+
its prompt cache, so those tokens are priced at the smallest per-token difference they could have had`);}T.size>0&&I.push(`the provider publishes no ${[...T].join(" or ")} price for this tier, so thos\
|
|
399
|
+
e tokens add nothing`);let M=I.length===0;return {ok:true,importe:D,basis:M?"measured":"estimated",costeEstandar:C,costeAplicado:_,factorEfectivo:_/C,motivoBasis:M?`the provider's own usage for this call\
|
|
366
400
|
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
|
|
401
|
+
led at the batch rate card)":""):`estimated: ${I.join("; ")}`,consultado:i.consultado}}function Fa(t,e,n){let r=e??un(t);return r!==null&&ln(r,"batch",t,n)!==void 0}var Ap="slower and variable: OpenAI\
|
|
368
402
|
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\
|
|
369
|
-
short the request returns 429 and is not charged. Do not put a deferrable request on a user-facing path.",
|
|
403
|
+
short the request returns 429 and is not charged. Do not put a deferrable request on a user-facing path.",Op='slower and variable: Google targets minutes for the Flex tier ("Minutes (1\u201315 min target)\
|
|
370
404
|
", 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\
|
|
371
|
-
he server side. Do not put a deferrable request on a user-facing path.',
|
|
405
|
+
he server side. Do not put a deferrable request on a user-facing path.',Mp="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\
|
|
372
406
|
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\
|
|
373
|
-
n a user-facing path.",
|
|
407
|
+
n a user-facing path.",Lp="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.",za="this provider\
|
|
374
408
|
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 \
|
|
375
|
-
request/response call (with the built-in Anthropic and OpenAI providers, layer.batches.submit() sends such requests there)";function
|
|
376
|
-
google"?
|
|
377
|
-
st on a user-facing path.`}var
|
|
378
|
-
return {minimumCacheTokens:
|
|
379
|
-
0),n),o=Math.min(Math.max(0,t.uso.cacheWriteInputTokens??0),n-r),i=n-r-o;if(n<
|
|
380
|
-
cacheWritePer1k,a=i/1e3*t.fila.inputPer1k;return {importe:
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
409
|
+
request/response call (with the built-in Anthropic and OpenAI providers, layer.batches.submit() sends such requests there)";function qa(t,e=null){return t==null||t===""?Lp:t===Pt?e==="openai"?Ap:e==="\
|
|
410
|
+
google"?Op:Mp:`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\
|
|
411
|
+
st on a user-facing path.`}var Va=1024;function lt(t,e){return e==="openai"&&un(Ge(t))==="openai"&&Ke(Ge(t))>1}function ti(t){let e=We(t);if(!e||!(e.inputPer1k>0))return null;let n=(e.cachedInputPer1k??e.inputPer1k)/e.inputPer1k;
|
|
412
|
+
return {minimumCacheTokens:Va,cacheReadMultiplier:n,cacheWriteMultiplier:Ke(Ge(t))}}function Ua(t){let e=t.consultado??go,n=Math.max(0,t.uso.inputTokens),r=Math.min(Math.max(0,t.uso.cachedInputTokens??
|
|
413
|
+
0),n),o=Math.min(Math.max(0,t.uso.cacheWriteInputTokens??0),n-r),i=n-r-o;if(n<Va||i<=0)return {importe:0,costeEstandar:0,costeAplicado:0,tokensOrdinarios:Math.max(0,i),consultado:e};let s=i/1e3*t.fila.
|
|
414
|
+
cacheWritePer1k,a=i/1e3*t.fila.inputPer1k;return {importe:ei(s-a),costeEstandar:s,costeAplicado:a,tokensOrdinarios:i,consultado:e}}var Ha=new Set;function U(t,e){Ha.has(t)||(Ha.add(t),console.warn(e));}var jp={"api.anthropic.com":"anthropic","api.openai.com":"openai","generativelanguage.googleapis.com":"google"};function dn(t){if(typeof t!="string")return null;try{let e=new URL(t);return e.protocol!==
|
|
415
|
+
"https:"||e.port!==""?null:jp[e.hostname.toLowerCase()]??null}catch{return null}}function sr(t){return dn(t)!==null?"oficial":"no-oficial"}var Wa=Symbol.for("@bivelio/savings-layer:provider-origin");function pn(t){return {esquemaEnFormatoNativo:false,esquemaEstricto:false,esquemaPorPrompt:false,piezasDelAdaptador:t}}var Np=2;function Rt(t){return Np*(t??[]).filter(e=>e.parameters==null).length}var ar=new WeakMap;
|
|
416
|
+
function Dt(t,e){return ar.set(t,e),t}function cr(t){return typeof t=="object"&&t!==null?ar.get(t):void 0}var Ja=new WeakMap;function Ka(t,e){Ja.set(t,e);}function dt(t){return typeof t=="object"&&t!==
|
|
417
|
+
null?Ja.get(t):void 0}var Ga=new WeakMap;function ur(t,e){Ga.set(t,e);}function Za(t){if(typeof t!="object"||t===null)return;let e=Ga.get(t);if(e!==void 0)return e;try{let n=t[Wa];if(typeof n!="functio\
|
|
418
|
+
n")return;let r=n.call(t);return r==="oficial"||r==="no-oficial"?r:void 0}catch{return}}function Ya(t,e){let n=ar.get(t);return n&&ar.set(e,n),e}var Qa=new WeakMap;function Xa(t,e){Qa.set(t,e);}function ni(t){
|
|
419
|
+
return typeof t=="object"&&t!==null?Qa.get(t):void 0}var ec=new WeakSet;function tc(t){typeof t=="object"&&t!==null&&ec.add(t);}function nc(t){return ec.has(t)}var rc=new WeakMap;function lr(t,e){rc.set(t,e);}function oc(t){return typeof t=="object"&&t!==null?rc.get(t):void 0}function dr(t){try{let e=new URL(t);return e.username="",e.password="",e.search="",e.
|
|
420
|
+
hash="",e.toString().replace(/\/+$/,"")}catch{return t.replace(/\/+$/,"")}}function pr(t){if(!t.startsWith("/")||t.startsWith("//")||/^\/*[a-z][a-z0-9+.-]*:/i.test(t))throw new Error(`[bvsala] interna\
|
|
421
|
+
l: a batch request path must be relative to the provider base (got "${t}")`);return t}var ri=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(
|
|
385
422
|
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,
|
|
386
423
|
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(
|
|
387
424
|
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.
|
|
388
425
|
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),
|
|
389
426
|
i=e.slice(r+1),i.charCodeAt(0)===32&&(i=i.slice(1))),o){case "data":this.datos+=i+`
|
|
390
427
|
`;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":
|
|
391
|
-
this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};async function*
|
|
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
|
|
393
|
-
map(String):[];if(o.some(s=>!i.includes(s)))return false;for(let s of Object.values(n))if(!
|
|
394
|
-
isArray(i)&&i.some(s=>!
|
|
395
|
-
test(t)?false:/invalid parameter|not supported|unsupported|unrecognized request argument|unknown parameter/i.test(t)}function
|
|
428
|
+
this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};async function*fr(t){let e=new ri;if(typeof t=="string"){yield*e.push(t),yield*e.
|
|
429
|
+
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 Ze(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.
|
|
430
|
+
map(String):[];if(o.some(s=>!i.includes(s)))return false;for(let s of Object.values(n))if(!Ze(s))return false}if(e.items!==void 0&&!Ze(e.items))return false;for(let o of ["anyOf","oneOf","allOf"]){let i=e[o];if(Array.
|
|
431
|
+
isArray(i)&&i.some(s=>!Ze(s)))return false}let r=e.$defs??e.definitions;return !(r&&typeof r=="object"&&Object.values(r).some(o=>!Ze(o)))}function $p(t){return !/response_format/i.test(t)||/invalid schema/i.
|
|
432
|
+
test(t)?false:/invalid parameter|not supported|unsupported|unrecognized request argument|unknown parameter/i.test(t)}function Bp(t){return `Respond with a single JSON object and nothing else: no prose, no\
|
|
396
433
|
explanation, no markdown code fences. The object must validate against this JSON Schema:
|
|
397
|
-
`+JSON.stringify(t)}var
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
this.opts
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
n.
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
if(
|
|
451
|
-
|
|
452
|
-
|
|
434
|
+
`+JSON.stringify(t)}var Fp=/(^|\.)api\.openai\.com$|\.openai\.azure\.com$/i;function oi(t,e,n){return e??qp(n)?t.replace(/^[^/]+\//,""):t}function zp(t){let e=dn(t);return e==="openai"||e==="google"?e:
|
|
435
|
+
null}var ic="x-gemini-service-tier";function sc(t,e){try{let n=t.headers?.get?.(e);return typeof n=="string"&&n.trim()!==""?n.trim():void 0}catch{return}}function ii(t,e,n){if(e.explicitCacheWrites!==
|
|
436
|
+
true||!lt(t,n))return null;let r=e.stablePrefixMessages;if(r==null||!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==="u\
|
|
437
|
+
ser"||o.role==="tool")&&typeof o.content=="string"&&o.content!==""?{puntos:1,indice:r-1}:{puntos:0,indice:-1}}function qp(t){try{return Fp.test(new URL(t).hostname)}catch{return false}}var ac=class{id;opts;fetchImpl;sinResponseFormat=new Set;streamOptionsRejected=false;origen;constructor(e){
|
|
438
|
+
this.opts=e,this.id=`openai-compatible:${e.baseUrl}`,this.fetchImpl=e.fetchImpl??fetch,this.origen=zp(e.baseUrl),Ka(this,this.origen),ur(this,sr(e.baseUrl));let n=(o,i)=>o.schema!=null&&!this.sinResponseFormat.
|
|
439
|
+
has(i),r=o=>oi(o,this.opts.stripProviderPrefix,this.opts.baseUrl);lr(this,{protocolo:"openai",origen:this.origen,endpoint:dr(e.baseUrl),cuerpo:o=>{let i=r(o.model);return this.construirCuerpo(i,o,n(o,
|
|
440
|
+
i))},leer:(o,i)=>{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(/\/$/,"")}${pr(o)}`,{method:i.method,headers:{...i.json!==
|
|
441
|
+
void 0?{"content-type":"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.
|
|
442
|
+
form}:{},...i.signal?{signal:i.signal}:{}})});}async generate(e,n){let r=oi(e.model,this.opts.stripProviderPrefix,this.opts.baseUrl),o=n?.signal,i=e.schema!=null&&!this.sinResponseFormat.has(r),s=await this.
|
|
443
|
+
enviar(r,e,i,void 0,o);if(!s.ok&&s.status===400&&i){let a=await hr(s);if(!$p(a))throw new Error(`provider ${s.status}: ${a}`);this.sinResponseFormat.add(r),U(`sin-response-format:${r}`,`[bvsala] Model\
|
|
444
|
+
"${r}" rejects \`response_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\
|
|
445
|
+
there). The schema 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 \
|
|
446
|
+
guarantee, use a model 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 hr(s);throw new Error(`provider ${s.status}: ${a}`)}return this.leer(
|
|
447
|
+
s,e,i,r)}async*generateStream(e,n={}){if(e.schema!=null||e.deferrable===true){let S=await this.generate(e);S.text!==""&&(yield {type:"text",delta:S.text}),yield {type:"done",response:S};return}let r=oi(e.
|
|
448
|
+
model,this.opts.stripProviderPrefix,this.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===
|
|
449
|
+
422)){let S=await hr(s);if(s.status!==422&&!/stream_options|include_usage/i.test(S))throw new Error(`provider ${s.status}: ${S}`);if(this.opts.requireUsage)throw new Error(`provider ${s.status}: this \
|
|
450
|
+
endpoint rejects stream_options, so a streamed answer would carry no usage and requireUsage is set. ${S}`);s=await this.enviar(r,e,false,{includeUsage:false,...o?{signal:o}:{}}),s.ok&&(this.streamOptionsRejected=
|
|
451
|
+
true,U(`sin-stream-options:${this.opts.baseUrl}`,"[bvsala] This endpoint rejects `stream_options`, so streamed answers from it carry no usage: they are reported as `unmeasured` and never billed. Use `ge\
|
|
452
|
+
nerate()` for a measured figure, or an endpoint that reports usage when streaming."));}if(!s.ok)throw new Error(`provider ${s.status}: ${await hr(s)}`);if((s.headers.get("content-type")??"").includes("\
|
|
453
|
+
application/json")){let S=await this.leer(s,e,false,r);S.text!==""&&(yield {type:"text",delta:S.text}),yield {type:"done",response:S};return}let a=s.body,c=a&&typeof a.getReader=="function"?a:await s.text(),
|
|
454
|
+
u="",l=new Map,d,p,h,m=false;for await(let S of fr(c)){if(S.data==="[DONE]")break;let x;try{x=JSON.parse(S.data);}catch{continue}if(x===null||typeof x!="object")continue;if(x.error!=null){let R=x.error,E=typeof R.
|
|
455
|
+
message=="string"?R.message:JSON.stringify(x.error);throw new Error(`provider stream error: ${E}`)}let C=x.choices?.[0],_=C?.delta;(mr(_?.reasoning_content)||mr(_?.reasoning))&&(m=true),typeof _?.content==
|
|
456
|
+
"string"&&_.content!==""&&(u+=_.content,yield {type:"text",delta:_.content});for(let R of _?.tool_calls??[]){let E=typeof R.index=="number"?R.index:0,D=l.get(E)??{args:""};!D.id&&typeof R.id=="string"&&
|
|
457
|
+
R.id!==""&&(D.id=R.id);let I=R.function?.name;!D.name&&typeof I=="string"&&I!==""&&(D.name=I),typeof R.function?.arguments=="string"&&(D.args+=R.function.arguments),l.set(E,D);}C?.finish_reason!=null&&
|
|
458
|
+
(d=C.finish_reason),x.usage!=null&&typeof x.usage=="object"&&(p=x.usage),typeof x.service_tier=="string"&&x.service_tier!==""&&(h=x.service_tier);}if(d===void 0)throw new Error("provider stream ended b\
|
|
459
|
+
efore completion (no finish_reason)");let g=typeof p?.prompt_tokens!="number",f=typeof p?.completion_tokens!="number";if(this.opts.requireUsage&&(g||f))throw new Error(lc(p?.prompt_tokens,p?.completion_tokens));
|
|
460
|
+
let v=cc(p,m),b=uc(p),y={inputTokens:p?.prompt_tokens??0,outputTokens:p?.completion_tokens??0,...p?.prompt_tokens_details?.cached_tokens!=null?{cachedInputTokens:p.prompt_tokens_details.cached_tokens}:
|
|
461
|
+
{},...b!==void 0?{cacheWriteInputTokens:b}:{},...v!==void 0?{reasoningTokens:v}:{},...g||f?{complete:false}:{}},k=[...l.entries()].sort((S,x)=>S[0]-x[0]).map(([,S])=>({...S.id?{id:S.id}:{},name:S.name??"",
|
|
462
|
+
arguments:S.args})).filter(S=>S.name!==""),T=h?"cuerpo":void 0;!h&&this.origen==="google"&&(h=sc(s,ic),h&&(T="cabecera"));let w=ii(r,e,this.origen);yield {type:"done",response:Dt({text:u,...k.length>0?
|
|
463
|
+
{toolCalls:k}:{},finishReason:d,...h?{servedServiceTier:h}:{},usage:y,structuredNatively:false,raw:p??null},{...pn(Rt(e.tools)),origen:this.origen,...T?{tierLeidoDe:T}:{},...w?{cacheExplicita:{puntos:w.puntos}}:
|
|
464
|
+
{}})};}async enviar(e,n,r,o,i){let s=this.construirCuerpo(e,n,r,o);return await this.fetchImpl(`${this.opts.baseUrl.replace(/\/$/,"")}/chat/completions`,{method:"POST",headers:{"content-type":"applicat\
|
|
465
|
+
ion/json",...this.opts.apiKey?{authorization:`Bearer ${this.opts.apiKey}`}:{},...this.opts.headers},body:JSON.stringify(s),...o?.signal?{signal:o.signal}:!o&&i?{signal:i}:{}})}construirCuerpo(e,n,r,o){
|
|
466
|
+
let i=n.messages.map(c=>c.role==="tool"?{role:"tool",content:c.content,tool_call_id:c.toolCallId??c.metadata?.tool_call_id,...c.name?{name:c.name}:{}}:c.role==="assistant"&&c.toolCalls&&c.toolCalls.length>
|
|
467
|
+
0?{role:"assistant",content:c.content||null,tool_calls:c.toolCalls.map((u,l)=>({id:u.id??`call_${l}`,type:"function",function:{name:u.name,arguments:u.arguments}}))}:{role:c.role,content:c.content}),s=ii(
|
|
468
|
+
e,n,this.origen);if(s?.puntos===1){let c=i[s.indice];c.content=[{type:"text",text:c.content,prompt_cache_breakpoint:{mode:"explicit"}}];}n.schema&&!r&&i.push({role:"system",content:Bp(n.schema)});let a={
|
|
469
|
+
model:e,messages:i};if(n.maxOutputTokens!=null&&(a.max_tokens=n.maxOutputTokens),n.temperature!=null&&(a.temperature=n.temperature),n.seed!=null&&(a.seed=n.seed),n.promptCacheKey!=null&&(a.prompt_cache_key=
|
|
470
|
+
n.promptCacheKey),n.deferrable===true&&(a.service_tier=Pt),s&&(a.prompt_cache_options={mode:"explicit"}),n.schema&&r){let c=Ze(n.schema);c||U("strict-incompatible","[bvsala] The response contract does n\
|
|
471
|
+
ot meet OpenAI's `strict` mode (in strict, `required` must list ALL the keys in `properties`, and every object needs `additionalProperties: false`). The schema is sent with `strict: false`: the model \
|
|
472
|
+
is still guided and the layer still validates, but the guarantee comes from the layer, not the provider. To recover it, make every key in the contract required."),a.response_format={type:"json_schema",
|
|
473
|
+
json_schema:{name:"bvsala_contract",schema:n.schema,strict:c}};}return n.tools&&n.tools.length>0&&(a.tools=n.tools.map(c=>({type:"function",function:{name:c.id,...c.description?{description:c.description}:
|
|
474
|
+
{},parameters:c.parameters??{type:"object",properties:{}}}}))),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,
|
|
475
|
+
e,n,r,o,this.opts.requireUsage===true)}leerJson(e,n,r,o,i,s){let a=e.choices?.[0]?.message,c=a?.content??"",u=(a?.tool_calls??[]).map(T=>({...T.id?{id:T.id}:{},name:T.function?.name??"",arguments:T.function?.
|
|
476
|
+
arguments??""})).filter(T=>T.name!==""),l=e.usage??{},d=l.prompt_tokens??0,p=l.completion_tokens??0,h=typeof l.prompt_tokens!="number",m=typeof l.completion_tokens!="number";if(s&&(h||m))throw new Error(
|
|
477
|
+
lc(l.prompt_tokens,l.completion_tokens));let g=e.choices?.[0]?.finish_reason,f=typeof e.service_tier=="string"&&e.service_tier!==""?e.service_tier:void 0,v=f?"cuerpo":void 0;!f&&this.origen==="google"&&
|
|
478
|
+
n&&(f=sc(n,ic),f&&(v="cabecera"));let b=uc(l),y=ii(i,r,this.origen),k=cc(l,mr(a?.reasoning_content)||mr(a?.reasoning));return Dt({text:c,...u.length>0?{toolCalls:u}:{},...g?{finishReason:g}:{},...f?{servedServiceTier:f}:
|
|
479
|
+
{},...r.deferrable===true?{requestedServiceTier:Pt}:{},usage:{inputTokens:d,outputTokens:p,...l.prompt_tokens_details?.cached_tokens!=null?{cachedInputTokens:l.prompt_tokens_details.cached_tokens}:{},...b!==
|
|
480
|
+
void 0?{cacheWriteInputTokens:b}:{},...k!==void 0?{reasoningTokens:k}:{},...h||m?{complete:false}:{}},structuredNatively:r.schema!=null&&o,raw:e},{esquemaEnFormatoNativo:r.schema!=null&&o,esquemaEstricto:r.
|
|
481
|
+
schema!=null&&o&&Ze(r.schema),esquemaPorPrompt:r.schema!=null&&!o,piezasDelAdaptador:Rt(r.tools),origen:this.origen,...v?{tierLeidoDe:v}:{},...y?{cacheExplicita:{puntos:y.puntos}}:{}})}};function cc(t,e){
|
|
482
|
+
let n=t?.completion_tokens_details?.reasoning_tokens;if(!(typeof n!="number"||!Number.isInteger(n)||n<0)&&!(n===0&&e))return n}function uc(t){let e=t?.prompt_tokens_details?.cache_write_tokens;return typeof e==
|
|
483
|
+
"number"&&Number.isInteger(e)&&e>=0?e:void 0}function mr(t){return typeof t=="string"&&t!==""}function lc(t,e){return `provider returned incomplete usage (prompt=${t??"absent"}, completion=${e??"absent"}\
|
|
484
|
+
); cannot measure cost. For gateways/streaming, ensure usage reporting is enabled.`}async function hr(t){try{return (await t.text()).slice(0,500)}catch{return "<no body>"}}function dc(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:
|
|
485
|
+
`+JSON.stringify(t)}function pc(t){let e=[];for(let n of t){if(n.type!=="server_tool_use")continue;let r=n.id,o=n.name;if(typeof r!="string"||typeof o!="string"||!o.startsWith("tool_search_tool"))continue;let i=t.find(u=>u.
|
|
486
|
+
type==="tool_search_tool_result"&&u.tool_use_id===r),s=i?.content;if(!i||!s||s.type!=="tool_search_tool_search_result"||!Array.isArray(s.tool_references)||s.tool_references.length===0)continue;let a=[],
|
|
487
|
+
c=true;for(let u of s.tool_references){if(typeof u?.tool_name!="string"){c=false;break}a.includes(u.tool_name)||a.push(u.tool_name);}c&&e.push({busqueda:o,id:r,uso:n,resultado:i,herramientas:a});}return e}var Vp={
|
|
488
|
+
bytes:4*1024*1024,porEntrada:64*1024,claves:4096},gr=class{constructor(e=Vp){this.topes=e;}topes;entradas=new Map;bytes=0;recordar(e,n){if(e.length===0||n.length===0)return;let r=JSON.parse(JSON.stringify(
|
|
489
|
+
n)),o=JSON.stringify(r).length;if(o>this.topes.porEntrada)return;let i={pares:r,bytes:o};for(let s of new Set(e))this.quitar(s),this.entradas.set(s,i),this.bytes+=o;for(;this.entradas.size>0&&(this.bytes>
|
|
490
|
+
this.topes.bytes||this.entradas.size>this.topes.claves);){let s=this.entradas.keys().next().value;this.quitar(s);}}para(e){let n;for(let r of e){let o=this.entradas.get(r);o&&(this.entradas.delete(r),this.
|
|
491
|
+
entradas.set(r,o),n??=o);}return n?JSON.parse(JSON.stringify(n.pares)):void 0}get tamano(){return this.entradas.size}quitar(e){let n=this.entradas.get(e);n&&(this.entradas.delete(e),this.bytes-=n.bytes);}};var It=t=>typeof t=="number"&&Number.isFinite(t)&&t>0?t:0;function fc(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){
|
|
492
|
+
if(n===null||typeof n!="object")continue;let r=n;if(r.type!=="compaction")continue;e.iteraciones++,e.input+=It(r.input_tokens),e.output+=It(r.output_tokens),e.cacheRead+=It(r.cache_read_input_tokens);
|
|
493
|
+
let o=r.cache_creation,i=It(o?.ephemeral_5m_input_tokens),s=It(o?.ephemeral_1h_input_tokens),a=typeof r.cache_creation_input_tokens=="number"?It(r.cache_creation_input_tokens):i+s;e.cacheWrite+=a,e.cacheWrite1h+=
|
|
494
|
+
Math.min(s,a);}return e.iteraciones>0?e:null}function si(t,e,n){let r=t??{},o=fc(r.iterations),i=mc(r.cache_read_input_tokens,o?.cacheRead),s=mc(r.cache_creation_input_tokens,o?.cacheWrite),a=r.cache_creation?.ephemeral_1h_input_tokens,c=typeof a==
|
|
453
495
|
"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",
|
|
455
|
-
|
|
456
|
-
function
|
|
457
|
-
{},...n,...r?{cache_creation:r}:{}}}function
|
|
458
|
-
tool_calls";case "refusal":return "content_filter";default:return t}}var
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
`
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
r
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
"
|
|
478
|
-
{}}
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
0
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
496
|
+
"number",p=typeof e!="number";return {usage:{inputTokens:u,outputTokens:l,...i!=null?{cachedInputTokens:i}:{},...s!=null?{cacheWriteInputTokens:s}:{},...c!==void 0?{cacheWrite1hInputTokens:c}:{},...n||
|
|
497
|
+
p||o?{}:{reasoningTokens:0},...d||p?{complete:false}:{}},entradaAusente:d,salidaAusente:p}}function mc(t,e){return e?(t??0)+e:t}function ai(t){let e=t?.service_tier;return typeof e=="string"&&e!==""?e:void 0}
|
|
498
|
+
function ci(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??
|
|
499
|
+
{},...n,...r?{cache_creation:r}:{}}}function ui(t){return t==="thinking"||t==="redacted_thinking"}function li(t){switch(t){case "end_turn":return "stop";case "max_tokens":return "length";case "tool_use":return "\
|
|
500
|
+
tool_calls";case "refusal":return "content_filter";default:return t}}var br=4,Ye="bvsala_contract",Up={"sin-ids":'[bvsala] A tool conversation reached the Anthropic adapter without its call ids. To send it the way the Messages API expects (`tool_use` blocks in the assi\
|
|
501
|
+
stant turn, `tool_result` blocks in the next user turn), each entry of the assistant turn\'s `toolCalls` needs its `id`, and each `role: "tool"` message the `toolCallId` of the call it answers: the sam\
|
|
502
|
+
e ids that came back in `result.toolCalls`. Without them the exchange is sent as plain text, as in earlier versions: the model reads the results but not its own calls.',"sin-pareja":'[bvsala] A tool e\
|
|
503
|
+
xchange sent to the Anthropic adapter does not pair up. The Messages API wants one result for every call, right after the assistant turn that made them, and each call\'s `arguments` must be a JSON obje\
|
|
504
|
+
ct. This exchange has a call without its result, a result for a call that turn did not make, a repeated id, or arguments that are not a JSON object, so it is sent as plain text, as in earlier versions\
|
|
505
|
+
. Answer every call of a turn with one `role: "tool"` message carrying its `toolCallId`, before the next user or assistant message.',"no-disponibles":"[bvsala] A tool exchange names a tool this reques\
|
|
506
|
+
t does not make available to the model: it is missing from `tools` (not passed, or left out by the layer's tool selection), or it is deferred behind tool search and this adapter no longer holds the se\
|
|
507
|
+
arch that loaded it. The Messages API does not document a `tool_use` block for such a tool as valid, so that exchange is sent as plain text, as in earlier versions. Pass the tool in `tools` on every t\
|
|
508
|
+
urn of the conversation to keep the native tool loop."},hc=class{id;opts;fetchImpl;busquedas=new gr;constructor(e={}){this.opts=e,this.id=`anthropic:${e.baseUrl??"https://api.anthropic.com/v1"}`,this.
|
|
509
|
+
fetchImpl=e.fetchImpl??fetch,Xa(this,vr(e.baseUrl)?"oficial":"compatible"),ur(this,sr(e.baseUrl??"https://api.anthropic.com/v1"));let n=this.opts.baseUrl??"https://api.anthropic.com/v1";lr(this,{protocolo:"\
|
|
510
|
+
anthropic",origen:Yp(n),endpoint:dr(n),cuerpo:r=>this.construirCuerpo(r).body,leer:(r,o)=>this.leerMensaje(r,o,false,false,false,false),solicitar:(r,o)=>{let i=`${n.replace(/\/$/,"")}${pr(r)}`;return this.fetchImpl(
|
|
511
|
+
i,{method:o.method,headers:{...o.json!==void 0?{"content-type":"application/json"}:{},"anthropic-version":this.opts.apiVersion??"2023-06-01",...this.opts.apiKey?{"x-api-key":this.opts.apiKey}:{},...this.
|
|
512
|
+
opts.headers},...o.json!==void 0?{body:JSON.stringify(o.json)}:{},...o.signal?{signal:o.signal}:{}})}});}modeloEnElCable(e){return this.opts.stripProviderPrefix??vr(this.opts.baseUrl)?e.replace(/^[^/]+\//,
|
|
513
|
+
""):e}async generate(e,n){let r=this.construirCuerpo(e),o=await this.enviar(r.body,n?.signal);if(!o.ok)throw new Error(`provider ${o.status}: ${await yc(o)}`);return this.leer(o,e,r.contratoNativo,r.turnoAnadido,
|
|
514
|
+
r.esquemaPorPrompt,r.reenviadas)}async*generateStream(e,n={}){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};
|
|
515
|
+
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(`provider ${i.status}: ${await yc(i)}`);if((i.headers.get("content-type")??"").includes(
|
|
516
|
+
"application/json")){let x=await this.leer(i,e,r.contratoNativo,r.turnoAnadido,r.esquemaPorPrompt,r.reenviadas);x.text!==""&&(yield {type:"text",delta:x.text}),yield {type:"done",response:x};return}let s=i.
|
|
517
|
+
body,a=s&&typeof s.getReader=="function"?s:await i.text(),c="",u=new Map,l,d,p=false,h=false,m,g=false,f,v;for await(let x of fr(a)){let C;try{C=JSON.parse(x.data);}catch{continue}if(C===null||typeof C!="object")
|
|
518
|
+
continue;let _=x.event!=="message"?x.event:C.type??x.event;if(_==="message_start")l=C.message?.usage??l,typeof C.message?.id=="string"&&C.message.id!==""&&(f=C.message.id),v=C.message?.diagnostics;else if(_===
|
|
519
|
+
"content_block_start"){let R=C.content_block;ui(R?.type)&&(g=true),typeof C.index=="number"&&R&&u.set(C.index,{tipo:R.type??"",...typeof R.id=="string"?{id:R.id}:{},...typeof R.name=="string"?{name:R.name}:
|
|
520
|
+
{},json:"",...R.content!==void 0?{content:R.content}:{},...e.toolSearch&&(R.type==="server_tool_use"||R.type==="tool_search_tool_result")?{crudo:R}:{}});}else if(_==="content_block_delta"){let R=C.delta;
|
|
521
|
+
if(R?.type==="text_delta"&&typeof R.text=="string"&&R.text!=="")c+=R.text,yield {type:"text",delta:R.text};else if(R?.type==="input_json_delta"&&typeof R.partial_json=="string"){let E=typeof C.index=="\
|
|
522
|
+
number"?u.get(C.index):void 0;E&&(E.json+=R.partial_json);}}else if(_==="message_delta")p=true,m=C.delta?.stop_reason??m,C.usage&&(d=ci(d,C.usage));else if(_==="message_stop"){h=true;break}else if(_==="err\
|
|
523
|
+
or")throw new Error(`provider stream error: ${C.error?.type}: ${C.error?.message}`)}if(!h&&!p)throw new Error("provider stream ended before completion (no message_delta)");let b=ci(l,d),k=(p?si(b,d?.output_tokens,
|
|
524
|
+
g):void 0)?.usage??{inputTokens:0,outputTokens:0,complete:false};if(this.opts.requireUsage&&k.complete===false)throw new Error(vc(p?b.input_tokens:void 0,p?d?.output_tokens:void 0));let T=[...u.entries()].sort(
|
|
525
|
+
(x,C)=>x[0]-C[0]).map(([,x])=>x).filter(x=>x.tipo==="tool_use"&&x.name!==Ye).map(x=>({...x.id?{id:x.id}:{},name:x.name??"",arguments:Zp(x.json)})).filter(x=>x.name!==""),w=ai(b),S=e.toolSearch?bc([...u.
|
|
526
|
+
entries()].sort((x,C)=>x[0]-C[0]).map(([,x])=>({type:x.tipo,name:x.name,content:x.content})),r.reenviadas):void 0;if(e.toolSearch){let x=[];for(let[,C]of [...u.entries()].sort((_,R)=>_[0]-R[0]))if(C.tipo===
|
|
527
|
+
"tool_use")x.push({type:"tool_use",id:C.id,name:C.name});else if(C.tipo==="tool_search_tool_result"&&C.crudo)x.push(C.crudo);else if(C.tipo==="server_tool_use"&&C.crudo){let _=C.json===""?C.crudo.input??
|
|
528
|
+
{}:Gp(C.json);_!==void 0&&x.push({...C.crudo,input:_});}this.recordarBusquedas(x);}yield {type:"done",response:Dt({text:c,...T.length>0?{toolCalls:T}:{},...m?{finishReason:li(m)}:{},...w?{servedServiceTier:w}:
|
|
529
|
+
{},...S?{toolSearch:S}:{},...f?{providerMessageId:f}:{},...this.diagnosticoDe(e,v),usage:k,structuredNatively:false,raw:{usage:b,stop_reason:m}},pn((r.turnoAnadido?1:0)+Rt(e.tools)))};}async enviar(e,n){let r=(this.
|
|
530
|
+
opts.baseUrl??"https://api.anthropic.com/v1").replace(/\/$/,"");return await this.fetchImpl(`${r}/messages`,{method:"POST",headers:{"content-type":"application/json","anthropic-version":this.opts.apiVersion??
|
|
531
|
+
"2023-06-01",...this.opts.apiKey?{"x-api-key":this.opts.apiKey}:{},...this.opts.headers},body:JSON.stringify(e),...n?{signal:n}:{}})}construirCuerpo(e){let n=this.reenvioDeBusquedas(e),{system:r,messages:o,
|
|
532
|
+
finDelPrefijo:i,prefijoEnSystem:s,turnoAnadido:a}=Hp(e,n?.anteponer,m=>this.avisar(`anthropic-herramientas-${m}`,Up[m]));if(o.length===0)throw new Error("anthropic: the request has no user/assistant m\
|
|
533
|
+
essage. The Messages API needs at least one, and system prompts travel in the `system` field \u2014 they do not count.");let c=(e.tools??[]).map(m=>({name:m.id,...m.description?{description:m.description}:
|
|
534
|
+
{},input_schema:m.parameters??{type:"object",properties:{}}}));if(e.toolSearch&&c.length>0){let m=new Set(e.toolSearch.alwaysLoaded);for(let g of c)m.has(g.name)||(g.defer_loading=true);c.unshift({...Kn[e.
|
|
535
|
+
toolSearch.variant]});}let u=false,l=false,d=false;if(e.schema){let m=c.length>0,g=c.some(v=>v.name===Ye),f=Ze(e.schema);g?(r.push({type:"text",text:dc(e.schema)}),l=true,U("anthropic-contrato-nombre-ocupado",`[b\
|
|
536
|
+
vsala] One of your tools is already named \`${Ye}\`, 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 t\
|
|
537
|
+
ext instead, which is measurably more expensive on this API. Rename that tool to get the cheaper path.`)):(!f&&!m&&U("anthropic-strict-incompatible","[bvsala] The response contract does not meet `stri\
|
|
538
|
+
ct` mode (in strict, `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 la\
|
|
539
|
+
yer still validates, but the guarantee comes from the layer, not the provider."),u=f&&!m,c.push({name:Ye,description:m?"Return the final answer in the required shape. Use the other tools first if you \
|
|
540
|
+
need data; call this one instead of writing the answer as text.":"Return the final answer in the required shape.",input_schema:e.schema,...u?{strict:true}:{}}),m&&(d=this.opts.forceAnswerThroughTool!==false,
|
|
541
|
+
U("anthropic-contrato-con-herramientas","[bvsala] This request carries BOTH your tools and an output contract. On Anthropic's Messages API a specific shape is only GUARANTEED by forcing that exact too\
|
|
542
|
+
l, and forcing ours would leave the model unable to call yours. The contract travels as one extra tool"+(d?' and the request is sent with `tool_choice: {type: "any"}`, so the model must answer through\
|
|
543
|
+
SOME tool \u2014 yours or the contract \u2014 and can no longer reply in prose. Your tool turn is untouched. The guarantee is still the layer\'s, not the provider\'s (`constraints.backend: "none"`), because the \
|
|
544
|
+
model may pick one of your tools and defer the final answer to the next turn.':", not forced (`forceAnswerThroughTool: false`). The guarantee is the layer's, not the provider's (`constraints.backend: \
|
|
545
|
+
\"none\"`), and if the model answers in prose the layer pays a second full call to repair it \u2014 on this API that second call re-pays the whole tool-use overhead.")+" Dropping either the tools or t\
|
|
546
|
+
he contract from this request is what makes the guarantee free.")));}let p={model:this.modeloEnElCable(e.model),max_tokens:e.maxOutputTokens??this.opts.defaultMaxOutputTokens??4096,messages:o};r.length>
|
|
547
|
+
0&&(p.system=r),e.temperature!=null&&(p.temperature=e.temperature),c.length>0&&(p.tools=c),u?p.tool_choice={type:"tool",name:Ye}:d&&(p.tool_choice={type:"any"}),e.deferrable===true&&U("anthropic-sin-tie\
|
|
548
|
+
r-diferible","[bvsala] This request was declared deferrable, but the Anthropic Messages API has NO cheaper synchronous tier: its `service_tier` chooses between priority capacity (more expensive) and s\
|
|
549
|
+
tandard, not a flex. The request 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/respon\
|
|
550
|
+
se call: send such requests with layer.batches.submit() instead.");let h=this.marcarCache(e,r,o,i,s);return e.cacheDiagnostics&&vr(this.opts.baseUrl)&&(p.diagnostics={previous_message_id:e.cacheDiagnostics.
|
|
551
|
+
previousMessageId}),this.opts.automaticCache===true&&e.cachePlacement==null&&e.stablePrefixMessages!=null&&h<Math.min(this.opts.maxCacheBreakpoints??br,br)&&(p.cache_control={type:"ephemeral"}),{body:p,
|
|
552
|
+
contratoNativo:u,turnoAnadido:a,esquemaPorPrompt:l,reenviadas:n}}reenvioDeBusquedas(e){if(!e.toolSearch||!e.tools||e.tools.length===0)return;let n=new Set(e.tools.map(a=>a.id)),r=Kn[e.toolSearch.variant].
|
|
553
|
+
name,o=new Set,i=this.busquedas,s={resultados:0,herramientas:[],anteponer(a){let c=(a.toolCalls??[]).map(d=>d.id).filter(d=>typeof d=="string"&&d!=="");if(c.length===0)return;let u=i.para(c);if(!u)return;
|
|
554
|
+
let l=[];for(let d of u)if(!(d.busqueda!==r||o.has(d.id))&&d.herramientas.every(p=>n.has(p))){o.add(d.id),l.push(d.uso,d.resultado),s.resultados+=1;for(let p of d.herramientas)s.herramientas.includes(
|
|
555
|
+
p)||s.herramientas.push(p);}return l.length>0?l:void 0}};return s}recordarBusquedas(e){let n=e.filter(r=>r.type==="tool_use"&&r.name!==Ye).map(r=>r.id).filter(r=>typeof r=="string"&&r!=="");n.length!==
|
|
556
|
+
0&&this.busquedas.recordar(n,pc(e));}avisar(e,n){nc(this)||U(e,n);}marcarCache(e,n,r,o,i){if(e.promptCacheKey!=null,e.stablePrefixMessages==null)return 0;let s=Math.min(this.opts.maxCacheBreakpoints??br,
|
|
557
|
+
br);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.length-1],d=l?.content[l.content.
|
|
558
|
+
length-1];if(e.cachePlacement?.tail===true&&s>0&&d&&(d.cache_control=c(),s-=1),s>0&&o){let p=r[o.mensaje]?.content[o.bloque];p&&p.cache_control==null&&(p.cache_control=c(),s-=1);}return a-s}async leer(e,n,r,o,i,s){
|
|
559
|
+
let a=await e.json();return this.leerMensaje(a,n,r,o,i,this.opts.requireUsage===true,s)}diagnosticoDe(e,n){if(e.cacheDiagnostics?.previousMessageId==null||!vr(this.opts.baseUrl))return {};if(n===void 0)return {};
|
|
560
|
+
if(n===null)return {cacheDiagnostics:{missReason:"none"}};if(typeof n!="object")return {};let r=n.cache_miss_reason;if(r===null)return {cacheDiagnostics:{missReason:"pending"}};if(r===void 0||typeof r!="\
|
|
561
|
+
object")return {};let o=r.type,i=r.cache_missed_input_tokens;return typeof o!="string"||o===""?{}:{cacheDiagnostics:{missReason:o,...typeof i=="number"&&Number.isFinite(i)&&i>=0?{missedInputTokens:i}:{}}}}leerMensaje(e,n,r,o,i,s,a){
|
|
562
|
+
let c=e.content??[],u=c.some(k=>ui(k.type)),l=c.filter(k=>k.type==="text").map(k=>k.text??"").join(""),d=c.filter(k=>k.type==="tool_use"&&k.name!==Ye).map(k=>({...k.id?{id:k.id}:{},name:k.name??"",arguments:JSON.
|
|
563
|
+
stringify(k.input??{})})).filter(k=>k.name!==""),p=c.find(k=>k.type==="tool_use"&&k.name===Ye),h=p?JSON.stringify(p.input??{}):l,m=e.usage,{usage:g,entradaAusente:f,salidaAusente:v}=si(m,m?.output_tokens,
|
|
564
|
+
u);if(s&&(f||v))throw new Error(vc(m?.input_tokens,m?.output_tokens));let b=ai(m),y=n.toolSearch?bc(c,a):void 0;return n.toolSearch&&this.recordarBusquedas(c),Dt({text:h,...d.length>0?{toolCalls:d}:{},
|
|
565
|
+
...e.stop_reason?{finishReason:li(e.stop_reason)}:{},...b?{servedServiceTier:b}:{},usage:g,structuredNatively:n.schema!=null&&r,...y?{toolSearch:y}:{},...typeof e.id=="string"&&e.id!==""?{providerMessageId:e.
|
|
566
|
+
id}:{},...this.diagnosticoDe(n,e.diagnostics),raw:e},{...pn((o?1:0)+Rt(n.tools)),esquemaPorPrompt:i})}};function Hp(t,e,n){let r=[],o=[],i=t.stablePrefixMessages??0,s,a=0,c=true,u=Kp(t),l=new Set,d=t.messages,
|
|
567
|
+
p=g=>{if(g>=i)return;let f=o.length-1;s={mensaje:f,bloque:o[f].content.length-1};},h=(g,f)=>{g.content!==""&&(o.push({role:g.role==="assistant"?"assistant":"user",content:[{type:"text",text:g.content}]}),
|
|
568
|
+
p(f));};for(let g=0;g<d.length;g++){let f=d[g];if(f.role==="system"&&c){r.push({type:"text",text:f.content}),g<i&&(a=r.length);continue}if(c=false,f.role!=="assistant"){f.role==="tool"&&n(f.toolCallId?"si\
|
|
569
|
+
n-pareja":"sin-ids"),h(f,g);continue}let v=e?e(f):void 0;v&&u.cargar(v);let b=f.content!==""?[{type:"text",text:f.content}]:[],y=f.toolCalls??[],k=g+1;if(y.length>0){for(;k<d.length&&d[k].role==="tool";)
|
|
570
|
+
k+=1;let w=Wp(y,d.slice(g+1,k),u,l);if("llamadas"in w){o.push({role:"assistant",content:[...v??[],...b,...w.llamadas]}),p(g);let S={role:"user",content:[]};o.push(S),w.resultados.forEach((x,C)=>{S.content.
|
|
571
|
+
push(x),p(g+1+C);}),g=k-1;continue}n(w.motivo);}let T=v?[...v,...b]:b;T.length>0&&(o.push({role:"assistant",content:T}),p(g));for(let w=g+1;w<k;w++)h(d[w],w);g=k-1;}let m=false;return o.length>0&&o[0].role===
|
|
572
|
+
"assistant"&&(o.unshift({role:"user",content:[{type:"text",text:"(continue)"}]}),s&&(s={mensaje:s.mensaje+1,bloque:s.bloque}),m=true),{system:r,messages:o,finDelPrefijo:s,prefijoEnSystem:a,turnoAnadido:m}}
|
|
573
|
+
function Wp(t,e,n,r){if(t.some(c=>!c.id)||e.some(c=>!c.toolCallId))return {motivo:"sin-ids"};let o=t.map(c=>gc(c.id)),i=new Set(o);if(i.size!==o.length||o.some(c=>r.has(c)))return {motivo:"sin-pareja"};
|
|
574
|
+
let s=e.map(c=>gc(c.toolCallId));if(s.length!==o.length||new Set(s).size!==s.length||s.some(c=>!i.has(c)))return {motivo:"sin-pareja"};let a=t.map(c=>Jp(c.arguments));if(a.some(c=>c===void 0))return {motivo:"\
|
|
575
|
+
sin-pareja"};if(t.some(c=>!n.tiene(c.name)))return {motivo:"no-disponibles"};for(let c of o)r.add(c);return {llamadas:t.map((c,u)=>({type:"tool_use",id:o[u],name:c.name,input:a[u]})),resultados:e.map((c,u)=>({
|
|
576
|
+
type:"tool_result",tool_use_id:s[u],...c.content!==""?{content:c.content}:{},...c.isError===true?{is_error:true}:{}}))}}function gc(t){return t.replace(/[^a-zA-Z0-9_-]/g,"_")}function Jp(t){let e=n=>typeof n==
|
|
577
|
+
"object"&&n!==null&&!Array.isArray(n);if(e(t))return t;if(typeof t=="string"){if(t.trim()==="")return {};try{let n=JSON.parse(t);return e(n)?n:void 0}catch{return}}}function Kp(t){let e=new Set((t.tools??
|
|
578
|
+
[]).map(r=>r.id));if(!t.toolSearch)return {tiene:r=>e.has(r),cargar:()=>{}};let n=new Set(t.toolSearch.alwaysLoaded.filter(r=>e.has(r)));return {tiene:r=>n.has(r),cargar(r){for(let o of r){if(o.type!=="\
|
|
579
|
+
tool_search_tool_result")continue;let i=o.content?.tool_references;if(Array.isArray(i))for(let s of i)typeof s?.tool_name=="string"&&e.has(s.tool_name)&&n.add(s.tool_name);}}}}function vr(t){try{return /(^|\.)api\.anthropic\.com$/i.
|
|
580
|
+
test(new URL(t??"https://api.anthropic.com/v1").hostname)}catch{return false}}function bc(t,e){let n=0,r=0,o=[];for(let i of t)if(i.type==="server_tool_use"&&typeof i.name=="string"&&i.name.startsWith("to\
|
|
581
|
+
ol_search_tool"))n+=1;else if(i.type==="tool_search_tool_result"){let s=i.content;if(s&&s.type==="tool_search_tool_result_error")r+=1;else if(s&&Array.isArray(s.tool_references))for(let a of s.tool_references)
|
|
582
|
+
typeof a?.tool_name=="string"&&!o.includes(a.tool_name)&&o.push(a.tool_name);}return {searches:n,loaded:o,errors:r,...e&&e.resultados>0?{resent:{results:e.resultados,tools:[...e.herramientas]}}:{}}}function Gp(t){
|
|
583
|
+
try{return JSON.parse(t)}catch{return}}function Zp(t){try{return JSON.stringify(JSON.parse(t===""?"{}":t))}catch{return t}}function vc(t,e){return `provider returned incomplete usage (input=${t??"absen\
|
|
584
|
+
t"}, output=${e??"absent"}); cannot measure cost.`}async function yc(t){try{return (await t.text()).slice(0,500)}catch{return "<no body>"}}function Yp(t){return dn(t)==="anthropic"?"anthropic":null}var fn=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.
|
|
585
|
+
now()-this.start}all(){return this.events}};var Qe=class extends Error{status;constructor(e,n){super(e),this.name="LicenseError",n&&(this.status=n);}};function di(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function yr(t,e=""){if(typeof t!="number"){let n=e&&
|
|
586
|
+
`"${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 Se(t,e,n=""){
|
|
587
|
+
let r=di(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):
|
|
588
|
+
new TypeError(u)}return t}function pi(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 xc(t,e){Se(t,void 0,"digestInt\
|
|
589
|
+
o() output");let n=e.outputLen;if(t.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function mn(...t){for(let e=0;e<t.length;e++)t[e].fill(0);}function kr(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var wc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Qp=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function xr(t){if(Se(t),wc)return t.toHex();
|
|
590
|
+
let e="";for(let n=0;n<t.length;n++)e+=Qp[t[n]];return e}var je={_0:48,_9:57,A:65,F:70,a:97,f:102};function kc(t){if(t>=je._0&&t<=je._9)return t-je._0;if(t>=je.A&&t<=je.F)return t-(je.A-10);if(t>=je.a&&
|
|
591
|
+
t<=je.f)return t-(je.a-10)}function hn(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(wc)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?
|
|
592
|
+
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=kc(t.charCodeAt(
|
|
593
|
+
i)),a=kc(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 fi(...t){let e=0;for(let r=0;r<t.length;r++){let o=t[r];Se(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 Sc(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 Tc(t=32){
|
|
594
|
+
yr(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(
|
|
595
|
+
`"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}var Cc=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});var wr=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=
|
|
596
|
+
new Uint8Array(e),this.view=kr(this.buffer);}update(e){pi(this),Se(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=kr(e);for(;o<=i-s;s+=
|
|
597
|
+
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){pi(this),
|
|
598
|
+
xc(e,this),this.finished=true;let{buffer:n,view:r,blockLen:o,isLE:i}=this,{pos:s}=this;n[s++]=128,mn(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(
|
|
599
|
+
o-8,BigInt(this.length*8),i),this.process(r,0);let a=kr(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
600
|
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
|
|
530
|
-
o=new Uint32Array(n);for(let i=0;i<n;i++){let{h:s,l:a}=
|
|
531
|
-
n+r+o+(t/2**32|0)|0,
|
|
601
|
+
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 re=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Sr=BigInt(4294967295),Ec=BigInt(32);function Xp(t,e=false){return e?{h:Number(t&Sr),l:Number(t>>Ec&Sr)}:{h:Number(t>>Ec&Sr)|0,l:Number(t&Sr)|0}}function Pc(t,e=false){let n=t.length,r=new Uint32Array(n),
|
|
602
|
+
o=new Uint32Array(n);for(let i=0;i<n;i++){let{h:s,l:a}=Xp(t[i],e);[r[i],o[i]]=[s,a];}return [r,o]}var mi=(t,e,n)=>t>>>n,hi=(t,e,n)=>t<<32-n|e>>>n,pt=(t,e,n)=>t>>>n|e<<32-n,ft=(t,e,n)=>t<<32-n|e>>>n,gn=(t,e,n)=>t<<64-n|e>>>n-32,bn=(t,e,n)=>t>>>n-32|e<<64-n;function Ie(t,e,n,r){let o=(e>>>0)+(r>>>0);return {h:t+n+(o/2**32|0)|0,l:o|0}}var Rc=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Dc=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Ic=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),_c=(t,e,n,r,o)=>e+
|
|
603
|
+
n+r+o+(t/2**32|0)|0,Ac=(t,e,n,r,o)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(o>>>0),Oc=(t,e,n,r,o,i)=>e+n+r+o+i+(t/2**32|0)|0;var Mc=Pc(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242",
|
|
532
604
|
"0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc6\
|
|
533
605
|
8b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","\
|
|
534
606
|
0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3\
|
|
@@ -536,158 +608,158 @@ c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a6
|
|
|
536
608
|
x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5d\
|
|
537
609
|
efb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0x\
|
|
538
610
|
eada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c1\
|
|
539
|
-
00d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),
|
|
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:
|
|
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=
|
|
542
|
-
16;
|
|
543
|
-
|
|
544
|
-
Gh:g,Gl:
|
|
545
|
-
|
|
546
|
-
let
|
|
547
|
-
0),{h:d,l:
|
|
548
|
-
|
|
549
|
-
0;Dh=
|
|
550
|
-
xpected boolean, got type="+typeof t)}return t}function
|
|
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
|
|
552
|
-
function
|
|
553
|
-
return
|
|
554
|
-
"expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function
|
|
611
|
+
00d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),tf=Mc[0],nf=Mc[1],Xe=new Uint32Array(80),et=new Uint32Array(80),gi=class extends wr{constructor(e){
|
|
612
|
+
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:p,Gh:h,Gl:m,Hh:g,Hl:f}=this;return [e,n,r,o,i,s,a,c,u,l,d,p,h,m,g,f]}set(e,n,r,o,i,s,a,c,u,l,d,p,h,m,g,f){this.Ah=
|
|
613
|
+
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=p|0,this.Gh=h|0,this.Gl=m|0,this.Hh=g|0,this.Hl=f|0;}process(e,n){for(let y=0;y<
|
|
614
|
+
16;y++,n+=4)Xe[y]=e.getUint32(n),et[y]=e.getUint32(n+=4);for(let y=16;y<80;y++){let k=Xe[y-15]|0,T=et[y-15]|0,w=pt(k,T,1)^pt(k,T,8)^mi(k,T,7),S=ft(k,T,1)^ft(k,T,8)^hi(k,T,7),x=Xe[y-2]|0,C=et[y-2]|0,_=pt(
|
|
615
|
+
x,C,19)^gn(x,C,61)^mi(x,C,6),R=ft(x,C,19)^bn(x,C,61)^hi(x,C,6),E=Ic(S,R,et[y-7],et[y-16]),D=_c(E,w,_,Xe[y-7],Xe[y-16]);Xe[y]=D|0,et[y]=E|0;}let{Ah:r,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:u,Dl:l,Eh:d,El:p,Fh:h,Fl:m,
|
|
616
|
+
Gh:g,Gl:f,Hh:v,Hl:b}=this;for(let y=0;y<80;y++){let k=pt(d,p,14)^pt(d,p,18)^gn(d,p,41),T=ft(d,p,14)^ft(d,p,18)^bn(d,p,41),w=d&h^~d&g,S=p&m^~p&f,x=Ac(b,T,S,nf[y],et[y]),C=Oc(x,v,k,w,tf[y],Xe[y]),_=x|0,
|
|
617
|
+
R=pt(r,o,28)^gn(r,o,34)^gn(r,o,39),E=ft(r,o,28)^bn(r,o,34)^bn(r,o,39),D=r&i^r&a^i&a,I=o&s^o&c^s&c;v=g|0,b=f|0,g=h|0,f=m|0,h=d|0,m=p|0,{h:d,l:p}=Ie(u|0,l|0,C|0,_|0),u=a|0,l=c|0,a=i|0,c=s|0,i=r|0,s=o|0;
|
|
618
|
+
let M=Rc(_,E,I);r=Dc(M,C,R,D),o=M|0;}(({h:r,l:o}=Ie(this.Ah|0,this.Al|0,r|0,o|0))),{h:i,l:s}=Ie(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Ie(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=Ie(this.Dh|0,this.Dl|0,u|0,l|
|
|
619
|
+
0),{h:d,l:p}=Ie(this.Eh|0,this.El|0,d|0,p|0),{h,l:m}=Ie(this.Fh|0,this.Fl|0,h|0,m|0),{h:g,l:f}=Ie(this.Gh|0,this.Gl|0,g|0,f|0),{h:v,l:b}=Ie(this.Hh|0,this.Hl|0,v|0,b|0),this.set(r,o,i,s,a,c,u,l,d,p,h,
|
|
620
|
+
m,g,f,v,b);}roundClean(){mn(Xe,et);}destroy(){this.destroyed=true,mn(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}},bi=class extends gi{Ah=re[0]|0;Al=re[1]|0;Bh=re[2]|0;Bl=re[3]|0;Ch=re[4]|0;Cl=re[5]|
|
|
621
|
+
0;Dh=re[6]|0;Dl=re[7]|0;Eh=re[8]|0;El=re[9]|0;Fh=re[10]|0;Fl=re[11]|0;Gh=re[12]|0;Gl=re[13]|0;Hh=re[14]|0;Hl=re[15]|0;constructor(){super(64);}};var Tr=Sc(()=>new bi,Cc(3));var G=(t,e,n)=>Se(t,e,n),yi=yr,ki=xr,_e=(...t)=>fi(...t),Lc=t=>hn(t),Pr=di,jc=t=>Tc(t),Er=BigInt(0),vi=BigInt(1);function _t(t,e=""){if(typeof t!="boolean"){let n=e&&`"${e}" `;throw new TypeError(n+"e\
|
|
622
|
+
xpected boolean, got type="+typeof t)}return t}function rf(t){if(typeof t=="bigint"){if(!Cr(t))throw new RangeError("positive bigint expected, got "+t)}else yi(t);return t}function Ne(t,e=""){if(typeof t!=
|
|
623
|
+
"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 Nc(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?Er:BigInt("0x"+t)}function xi(t){return Nc(xr(t))}function $e(t){return Nc(xr(vn(Se(t)).reverse()))}
|
|
624
|
+
function wi(t,e){if(yr(e),e===0)throw new RangeError("zero length");t=rf(t);let n=t.toString(16);if(n.length>e*2)throw new RangeError("number too large");return hn(n.padStart(e*2,"0"))}function $c(t,e){
|
|
625
|
+
return wi(t,e).reverse()}function Bc(t,e){if(t=G(t),e=G(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 vn(t){return Uint8Array.from(G(t))}var Cr=t=>typeof t=="bigint"&&Er<=t;function of(t,e,n){return Cr(t)&&Cr(e)&&Cr(n)&&e<=t&&t<n}function Si(t,e,n,r){if(!of(e,n,r))throw new RangeError(
|
|
626
|
+
"expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function Ti(t){if(t<Er)throw new Error("expected non-negative bigint, got "+t);let e;for(e=0;t>Er;t>>=vi,e+=1);return e}var Fc=t=>(vi<<BigInt(t))-vi;function mt(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
627
|
`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
|
|
557
|
-
odulus, got "+e);let n=t%e;return n>=
|
|
558
|
-
o number");if(e<=
|
|
559
|
-
"invert: does not exist");return J(o,e)}function
|
|
560
|
-
e),o}function
|
|
561
|
-
e.ONE)),o=n(e,r),i=n(e,e.neg(r)),s=(t+
|
|
562
|
-
eql(u.sqr(d),c),
|
|
563
|
-
1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return
|
|
564
|
-
"Cannot find square root");let d=n,
|
|
565
|
-
"Cannot find square root");let
|
|
566
|
-
t,e)&
|
|
567
|
-
reduce((r,o)=>(r[o]="function",r),e);if(
|
|
568
|
-
id field: expected ORDER > 1, got "+t.ORDER);return t}function
|
|
569
|
-
i=e;for(;n>
|
|
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
|
|
571
|
-
let n=
|
|
572
|
-
|
|
628
|
+
entries(i).forEach(([a,c])=>r(a,c,s));o(e,false),o(n,true);}var Ci=()=>{throw new Error("not implemented")};var oe=BigInt(0),Q=BigInt(1),ht=BigInt(2),Uc=BigInt(3),Hc=BigInt(4),Wc=BigInt(5),sf=BigInt(7),Jc=BigInt(8),af=BigInt(9),Kc=BigInt(16);function J(t,e){if(e<=oe)throw new Error("mod: expected positive m\
|
|
629
|
+
odulus, got "+e);let n=t%e;return n>=oe?n:e+n}function Te(t,e,n){if(e<oe)throw new Error("pow2: expected non-negative exponent, got "+e);let r=t;for(;e-- >oe;)r*=r,r%=n;return r}function zc(t,e){if(t===oe)throw new Error("invert: expected non-zer\
|
|
630
|
+
o number");if(e<=oe)throw new Error("invert: expected positive modulus, got "+e);let n=J(t,e),r=e,o=oe,s=Q;for(;n!==oe;){let u=r/n,l=r-n*u,d=o-s*u;r=n,n=l,o=s,s=d;}if(r!==Q)throw new Error(
|
|
631
|
+
"invert: does not exist");return J(o,e)}function Ei(t,e,n){let r=t;if(!r.eql(r.sqr(e),n))throw new Error("Cannot find square root")}function Gc(t,e){let n=t,r=(n.ORDER+Q)/Hc,o=n.pow(e,r);return Ei(n,o,
|
|
632
|
+
e),o}function cf(t,e){let n=t,r=(n.ORDER-Wc)/Jc,o=n.mul(e,ht),i=n.pow(o,r),s=n.mul(e,i),a=n.mul(n.mul(s,ht),i),c=n.mul(s,n.sub(a,n.ONE));return Ei(n,c,e),c}function uf(t){let e=_r(t),n=Zc(t),r=n(e,e.neg(
|
|
633
|
+
e.ONE)),o=n(e,r),i=n(e,e.neg(r)),s=(t+sf)/Kc;return((a,c)=>{let u=a,l=u.pow(c,s),d=u.mul(l,r),p=u.mul(l,o),h=u.mul(l,i),m=u.eql(u.sqr(d),c),g=u.eql(u.sqr(p),c);l=u.cmov(l,d,m),d=u.cmov(h,p,g);let f=u.
|
|
634
|
+
eql(u.sqr(d),c),v=u.cmov(l,d,f);return Ei(u,v,c),v})}function Zc(t){if(t<Uc)throw new Error("sqrt is not defined for small field");let e=t-Q,n=0;for(;e%ht===oe;)e/=ht,n++;let r=ht,o=_r(t);for(;qc(o,r)===
|
|
635
|
+
1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Gc;let i=o.pow(r,e),s=(e+Q)/ht;return function(c,u){let l=c;if(l.is0(u))return u;if(qc(l,u)!==1)throw new Error(
|
|
636
|
+
"Cannot find square root");let d=n,p=l.mul(l.ONE,i),h=l.pow(u,e),m=l.pow(u,s);for(;!l.eql(h,l.ONE);){if(l.is0(h))return l.ZERO;let g=1,f=l.sqr(h);for(;!l.eql(f,l.ONE);)if(g++,f=l.sqr(f),g===d)throw new Error(
|
|
637
|
+
"Cannot find square root");let v=Q<<BigInt(d-g-1),b=l.pow(p,v);d=g,p=l.sqr(b),h=l.mul(h,p),m=l.mul(m,b);}return m}}function lf(t){return t%Hc===Uc?Gc:t%Jc===Wc?cf:t%Kc===af?uf(t):Zc(t)}var Be=(t,e)=>(J(
|
|
638
|
+
t,e)&Q)===Q,df=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Yc(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},n=df.
|
|
639
|
+
reduce((r,o)=>(r[o]="function",r),e);if(mt(t,n),Ne(t.BYTES,"BYTES"),Ne(t.BITS,"BITS"),t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=Q)throw new Error("inval\
|
|
640
|
+
id field: expected ORDER > 1, got "+t.ORDER);return t}function pf(t,e,n){let r=t;if(n<oe)throw new Error("invalid exponent, negatives unsupported");if(n===oe)return r.ONE;if(n===Q)return e;let o=r.ONE,
|
|
641
|
+
i=e;for(;n>oe;)n&Q&&(o=r.mul(o,i)),i=r.sqr(i),n>>=Q;return o}function Ir(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(
|
|
642
|
+
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 qc(t,e){let n=t,r=(n.ORDER-Q)/ht,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 ff(t,e){if(e!==void 0&&yi(e),t<=oe)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);
|
|
643
|
+
let n=Ti(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 Vc=new WeakMap,
|
|
644
|
+
Dr=class{ORDER;BITS;BYTES;isLE;ZERO=oe;ONE=Q;_lengths;_mod;constructor(e,n={}){if(e<=Q)throw new Error("invalid field: expected ORDER > 1, got "+e);let r;this.isLE=false,n!=null&&typeof n=="object"&&(typeof n.
|
|
573
645
|
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.
|
|
574
|
-
freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:i}=
|
|
646
|
+
freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:i}=ff(e,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2\
|
|
575
647
|
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
|
|
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
|
|
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
|
|
579
|
-
isLE
|
|
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
|
|
581
|
-
|
|
582
|
-
freeze(
|
|
583
|
-
throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function
|
|
584
|
-
shiftBy:s}}function
|
|
585
|
-
isNeg:
|
|
586
|
-
e.ZERO,this.Fn=e.Fn,this.bits=n;}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>
|
|
648
|
+
"+typeof e);return oe<=e&&e<this.ORDER}is0(e){return e===oe}isValidNot0(e){return !this.is0(e)&&this.isValid(e)}isOdd(e){return (e&Q)===Q}neg(e){return J(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return J(
|
|
649
|
+
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 pf(this,e,n)}div(e,n){return J(e*zc(n,this.ORDER),this.ORDER)}sqrN(e){
|
|
650
|
+
return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return zc(e,this.ORDER)}sqrt(e){let n=Vc.get(this);return n||Vc.set(this,n=lf(this.ORDER)),n(this,e)}toBytes(e){return this.
|
|
651
|
+
isLE?$c(e,this.BYTES):wi(e,this.BYTES)}fromBytes(e,n=false){G(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\
|
|
652
|
+
: 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?$e(e):
|
|
653
|
+
xi(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 Ir(this,e)}cmov(e,n,r){return _t(r,"condition"),r?n:e}};Object.
|
|
654
|
+
freeze(Dr.prototype);function _r(t,e={}){return new Dr(t,e)}var Ar=BigInt(0),Ii=BigInt(1);function Qc(t,e){let n=e.negate();return t?n:e}function Mr(t,e){let n=Ir(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function nu(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)
|
|
655
|
+
throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Pi(t,e){nu(t,e);let n=Math.ceil(e/t)+1,r=2**(t-1),o=2**t,i=Fc(t),s=BigInt(t);return {windows:n,windowSize:r,mask:i,maxNumber:o,
|
|
656
|
+
shiftBy:s}}function Xc(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+=Ii);let u=e*r,l=u+Math.abs(a)-1,d=a===0,p=a<0,h=e%2!==0;return {nextN:c,offset:l,isZero:d,
|
|
657
|
+
isNeg:p,isNegF:h,offsetF:u}}var Ri=new WeakMap,ru=new WeakMap;function Di(t){return ru.get(t)||1}function eu(t){if(t!==Ar)throw new Error("invalid wNAF")}var Or=class{BASE;ZERO;Fn;bits;constructor(e,n){this.BASE=e.BASE,this.ZERO=
|
|
658
|
+
e.ZERO,this.Fn=e.Fn,this.bits=n;}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>Ar;)n&Ii&&(r=r.add(o)),o=o.double(),n>>=Ii;return r}precomputeWindow(e,n){let{windows:r,windowSize:o}=Pi(n,this.bits),i=[],
|
|
587
659
|
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=
|
|
589
|
-
ZERO){let i=
|
|
590
|
-
get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),
|
|
591
|
-
e);return i===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),n,o)}createCache(e,n){
|
|
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>
|
|
593
|
-
let o=
|
|
594
|
-
freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:i}}function
|
|
595
|
-
let n=e,r=
|
|
596
|
-
sqrt(o.div(g,
|
|
597
|
-
b,c),
|
|
598
|
-
this.X=d("x",
|
|
599
|
-
x:
|
|
600
|
-
o.ORDER;
|
|
601
|
-
"bad point: x=0 and x_0=1");return
|
|
602
|
-
return
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
let{a:
|
|
606
|
-
Y:
|
|
607
|
-
this.add(
|
|
608
|
-
if(!i.isValid(
|
|
609
|
-
return
|
|
610
|
-
was invalid");return {x,y:
|
|
611
|
-
return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let
|
|
612
|
-
this.ep=e;}static fromBytes(e){
|
|
613
|
-
return this.ep.toAffine(e)}toHex(){return
|
|
660
|
+
s=Pi(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:u,isZero:l,isNeg:d,isNegF:p,offsetF:h}=Xc(r,a,s);r=c,l?i=i.add(Qc(p,n[h])):o=o.add(Qc(d,n[u]));}return eu(r),{p:o,f:i}}wNAFUnsafe(e,n,r,o=this.
|
|
661
|
+
ZERO){let i=Pi(e,this.bits);for(let s=0;s<i.windows&&r!==Ar;s++){let{nextN:a,offset:c,isZero:u,isNeg:l}=Xc(r,s,i);if(r=a,!u){let d=n[c];o=o.add(l?d.negate():d);}}return eu(r),o}getPrecomputes(e,n,r){let o=Ri.
|
|
662
|
+
get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),Ri.set(n,o))),o}cached(e,n,r){let o=Di(e);return this.wNAF(o,this.getPrecomputes(o,e,r),n)}unsafe(e,n,r,o){let i=Di(
|
|
663
|
+
e);return i===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),n,o)}createCache(e,n){nu(n,this.bits),ru.set(e,n),Ri.delete(e);}hasCache(e){return Di(e)!==1}};function tu(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Yc(e),e}else return _r(t,{isLE:n})}function ou(t,e,n={},r){if(r===void 0&&(r=t==="edwar\
|
|
664
|
+
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>Ar))throw new Error(`CURVE.${c} must be positive bigint`)}
|
|
665
|
+
let o=tu(e.p,n.Fp,r),i=tu(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.
|
|
666
|
+
freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:i}}function iu(t,e){return function(r){let o=t(r);return {secretKey:o,publicKey:e(o)}}}var tt=BigInt(0),X=BigInt(1),_i=BigInt(2),mf=BigInt(8);function hf(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 su(t,e={}){
|
|
667
|
+
let n=e,r=ou("edwards",t,n,n.FpFnLE),{Fp:o,Fn:i}=r,s=r.CURVE,{h:a}=s;mt(n,{},{uvRatio:"function"});let c=_i<<BigInt(i.BYTES*8)-X,u=g=>o.create(g),l=n.uvRatio===void 0?(g,f)=>{try{return {isValid:!0,value:o.
|
|
668
|
+
sqrt(o.div(g,f))}}catch{return {isValid:false,value:tt}}}:n.uvRatio;if(!hf(o,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function d(g,f,v=false){let b=v?X:tt;return Si("coordinate "+g,f,
|
|
669
|
+
b,c),f}function p(g){if(!(g instanceof h))throw new Error("EdwardsPoint expected")}class h{static BASE=new h(s.Gx,s.Gy,X,u(s.Gx*s.Gy));static ZERO=new h(tt,X,X,tt);static Fp=o;static Fn=i;X;Y;Z;T;constructor(f,v,b,y){
|
|
670
|
+
this.X=d("x",f),this.Y=d("y",v),this.Z=d("z",b,true),this.T=d("t",y),Object.freeze(this);}static CURVE(){return s}static fromAffine(f){if(f instanceof h)throw new Error("extended point not allowed");let{
|
|
671
|
+
x:v,y:b}=f||{};return d("x",v),d("y",b),new h(v,b,X,u(v*b))}static fromBytes(f,v=false){let b=o.BYTES,{a:y,d:k}=s;f=vn(G(f,b,"point")),_t(v,"zip215");let T=vn(f),w=f[b-1];T[b-1]=w&-129;let S=$e(T),x=v?c:
|
|
672
|
+
o.ORDER;Si("point.y",S,tt,x);let C=u(S*S),_=u(C-X),R=u(k*C-y),{isValid:E,value:D}=l(_,R);if(!E)throw new Error("bad point: invalid y coordinate");let I=(D&X)===X,M=(w&128)!==0;if(!v&&D===tt&&M)throw new Error(
|
|
673
|
+
"bad point: x=0 and x_0=1");return M!==I&&(D=u(-D)),h.fromAffine({x:D,y:S})}static fromHex(f,v=false){return h.fromBytes(Lc(f),v)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(f=8,v=true){
|
|
674
|
+
return m.createCache(this,f),v||this.multiply(_i),this}assertValidity(){let f=this,{a:v,d:b}=s;if(f.is0())throw new Error("bad point: ZERO");let{X:y,Y:k,Z:T,T:w}=f,S=u(y*y),x=u(k*k),C=u(T*T),_=u(C*C),
|
|
675
|
+
R=u(S*v),E=u(C*u(R+x)),D=u(_+u(b*u(S*x)));if(E!==D)throw new Error("bad point: equation left != right (1)");let I=u(y*k),M=u(T*w);if(I!==M)throw new Error("bad point: equation left != right (2)")}equals(f){
|
|
676
|
+
p(f);let{X:v,Y:b,Z:y}=this,{X:k,Y:T,Z:w}=f,S=u(v*w),x=u(k*y),C=u(b*w),_=u(T*y);return S===x&&C===_}is0(){return this.equals(h.ZERO)}negate(){return new h(u(-this.X),this.Y,this.Z,u(-this.T))}double(){
|
|
677
|
+
let{a:f}=s,{X:v,Y:b,Z:y}=this,k=u(v*v),T=u(b*b),w=u(_i*u(y*y)),S=u(f*k),x=v+b,C=u(u(x*x)-k-T),_=S+T,R=_-w,E=S-T,D=u(C*R),I=u(_*E),M=u(C*E),j=u(R*_);return new h(D,I,j,M)}add(f){p(f);let{a:v,d:b}=s,{X:y,
|
|
678
|
+
Y:k,Z:T,T:w}=this,{X:S,Y:x,Z:C,T:_}=f,R=u(y*S),E=u(k*x),D=u(w*b*_),I=u(T*C),M=u((y+k)*(S+x)-R-E),j=I-D,B=I+D,V=u(E-v*R),z=u(M*j),ee=u(B*V),L=u(M*V),ae=u(j*B);return new h(z,ee,ae,L)}subtract(f){return p(
|
|
679
|
+
f),this.add(f.negate())}multiply(f){if(!i.isValidNot0(f))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:v,f:b}=m.cached(this,f,y=>Mr(h,y));return Mr(h,[v,b])[0]}multiplyUnsafe(f){
|
|
680
|
+
if(!i.isValid(f))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return f===tt?h.ZERO:this.is0()||f===X?this:m.unsafe(this,f,v=>Mr(h,v))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){
|
|
681
|
+
return m.unsafe(this,s.n).is0()}toAffine(f){let v=this,b=f,{X:y,Y:k,Z:T}=v,w=v.is0();b==null&&(b=w?mf:o.inv(T));let S=u(y*b),x=u(k*b),C=o.mul(T,b);if(w)return {x:tt,y:X};if(C!==X)throw new Error("invZ \
|
|
682
|
+
was invalid");return {x:S,y:x}}clearCofactor(){return a===X?this:this.multiplyUnsafe(a)}toBytes(){let{x:f,y:v}=this.toAffine(),b=o.toBytes(v);return b[b.length-1]|=f&X?128:0,b}toHex(){return ki(this.toBytes())}toString(){
|
|
683
|
+
return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let m=new Or(h,i.BITS);return i.BITS>=8&&h.BASE.precompute(8),Object.freeze(h.prototype),Object.freeze(h),h}var Lr=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){
|
|
684
|
+
this.ep=e;}static fromBytes(e){Ci();}static fromHex(e){Ci();}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity();}toAffine(e){
|
|
685
|
+
return this.ep.toAffine(e)}toHex(){return ki(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){
|
|
614
686
|
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.
|
|
615
|
-
ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,n){return this.ep.precompute(e,n),this}};function
|
|
616
|
-
equired');let r=e,o=n;
|
|
617
|
-
outputLen,l=2*a.BYTES;if(u!==void 0&&(
|
|
618
|
-
|
|
619
|
-
let
|
|
620
|
-
|
|
621
|
-
"context"),!!i)))}function
|
|
622
|
-
if(!c.isValid(
|
|
623
|
-
!!
|
|
624
|
-
|
|
625
|
-
is0()}let
|
|
626
|
-
try{return !!t.fromBytes(
|
|
627
|
-
|
|
628
|
-
|
|
687
|
+
ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,n){return this.ep.precompute(e,n),this}};function au(t,e,n={}){if(typeof e!="function")throw new Error('"hash" function param is r\
|
|
688
|
+
equired');let r=e,o=n;mt(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.
|
|
689
|
+
outputLen,l=2*a.BYTES;if(u!==void 0&&(Ne(u,"hash.outputLen"),u!==l))throw new Error(`hash.outputLen must be ${l}, got ${u}`);let d=o.randomBytes===void 0?jc:o.randomBytes,p=o.adjustScalarBytes===void 0?
|
|
690
|
+
E=>E:o.adjustScalarBytes,h=o.domain===void 0?(E,D,I)=>{if(_t(I,"phflag"),D.length||I)throw new Error("Contexts/pre-hash are not supported");return E}:o.domain;function m(E){return c.create($e(E))}function g(E){
|
|
691
|
+
let D=S.secretKey;G(E,S.secretKey,"secretKey");let I=G(r(E),2*D,"hashedSecretKey"),M=p(I.slice(0,D)),j=I.slice(D,2*D),B=m(M);return {head:M,prefix:j,scalar:B}}function f(E){let{head:D,prefix:I,scalar:M}=g(
|
|
692
|
+
E),j=s.multiply(M),B=j.toBytes();return {head:D,prefix:I,scalar:M,point:j,pointBytes:B}}function v(E){return f(E).pointBytes}function b(E=Uint8Array.of(),...D){let I=_e(...D);return m(r(h(I,G(E,void 0,
|
|
693
|
+
"context"),!!i)))}function y(E,D,I={}){E=G(E,void 0,"message"),i&&(E=i(E));let{prefix:M,scalar:j,pointBytes:B}=f(D),V=b(I.context,M,E),z=s.multiply(V).toBytes(),ee=b(I.context,z,B,E),L=c.create(V+ee*j);
|
|
694
|
+
if(!c.isValid(L))throw new Error("sign failed: invalid s");let ae=_e(z,c.toBytes(L));return G(ae,S.signature,"result")}let k={zip215:o.zip215};function T(E,D,I,M=k){let{context:j}=M,B=M.zip215===void 0?
|
|
695
|
+
!!k.zip215:M.zip215,V=S.signature;E=G(E,V,"signature"),D=G(D,void 0,"message"),I=G(I,S.publicKey,"publicKey"),B!==void 0&&_t(B,"zip215"),i&&(D=i(D));let z=V/2,ee=E.subarray(0,z),L=$e(E.subarray(z,V)),
|
|
696
|
+
ae,ce,Z;try{ae=t.fromBytes(I,B),ce=t.fromBytes(ee,B),Z=s.multiplyUnsafe(L);}catch{return false}if(!B&&ae.isSmallOrder())return false;let Ut=b(j,ee,I,D);return ce.add(ae.multiplyUnsafe(Ut)).subtract(Z).clearCofactor().
|
|
697
|
+
is0()}let w=a.BYTES,S={secretKey:w,publicKey:w,signature:2*w,seed:w};function x(E){return E=E===void 0?d(S.seed):E,G(E,S.seed,"seed")}function C(E){return Pr(E)&&E.length===S.secretKey}function _(E,D){
|
|
698
|
+
try{return !!t.fromBytes(E,D===void 0?k.zip215:D)}catch{return false}}let R={getExtendedPublicKey:f,randomSecretKey:x,isValidSecretKey:C,isValidPublicKey:_,toMontgomery(E){let{y:D}=t.fromBytes(E),I=S.publicKey,
|
|
699
|
+
M=I===32;if(!M&&I!==57)throw new Error("only defined for 25519 and 448");let j=M?a.div(X+D,X-D):a.div(D-X,D+X);return a.toBytes(j)},toMontgomerySecret(E){let D=S.secretKey;G(E,D);let I=r(E.subarray(0,
|
|
700
|
+
D));return p(I).subarray(0,D)}};return Object.freeze(S),Object.freeze(R),Object.freeze({keygen:iu(x,v),getPublicKey:v,sign:y,verify:T,utils:R,Point:t,lengths:S})}var vf=BigInt(0),Fe=BigInt(1),uu=BigInt(2);var yf=BigInt(5),kf=BigInt(8),At=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),ji={p:At,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:kf,
|
|
629
701
|
a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6d\
|
|
630
|
-
c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function
|
|
631
|
-
i*t%i,c=
|
|
632
|
-
return t[0]&=248,t[31]&=127,t[31]|=64,t}var
|
|
633
|
-
s=J(t*r*i,n),a=J(e*s*s,n),c=s,u=J(s*
|
|
634
|
-
"1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var
|
|
635
|
-
fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),
|
|
636
|
-
|
|
637
|
-
oint expected")}init(e){return new t(e)}static fromBytes(e){
|
|
638
|
-
let a=i(s*s),c=i(
|
|
639
|
-
"invalid ristretto255 encoding 2");return new t(new
|
|
640
|
-
u=s(c*c),{value:l}=
|
|
641
|
-
g)}equals(e){this.assertSame(e);let{X:n,Y:r}=this.ep,{X:o,Y:i}=e.ep,s=u=>
|
|
642
|
-
|
|
702
|
+
c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function xf(t){let e=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),i=At,a=t*t%
|
|
703
|
+
i*t%i,c=Te(a,uu,i)*a%i,u=Te(c,Fe,i)*t%i,l=Te(u,yf,i)*u%i,d=Te(l,e,i)*l%i,p=Te(d,n,i)*d%i,h=Te(p,r,i)*p%i,m=Te(h,o,i)*h%i,g=Te(m,o,i)*h%i,f=Te(g,e,i)*l%i;return {pow_p_5_8:Te(f,uu,i)*t%i,b2:a}}function wf(t){
|
|
704
|
+
return t[0]&=248,t[31]&=127,t[31]|=64,t}var Oi=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Ni(t,e){let n=At,r=J(e*e*e,n),o=J(r*r*e,n),i=xf(t*o).pow_p_5_8,
|
|
705
|
+
s=J(t*r*i,n),a=J(e*s*s,n),c=s,u=J(s*Oi,n),l=a===t,d=a===J(-t,n),p=a===J(-t*Oi,n);return l&&(s=c),(d||p)&&(s=u),Be(s,n)&&(s=J(-s,n)),{isValid:l||d,value:s}}var rt=su(ji,{uvRatio:Ni}),nt=rt.Fp,pu=rt.Fn;function Sf(t){return au(rt,Tr,Object.assign({adjustScalarBytes:wf,zip215:true},t))}var fu=Sf({});var Mi=Oi;BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");var Cf=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt(
|
|
706
|
+
"1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var lu=t=>Ni(Fe,t),Rf=BigInt("0x7\
|
|
707
|
+
fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Li=t=>nt.create($e(t)&Rf);var ot=class t extends Lr{static BASE=new t(
|
|
708
|
+
rt.BASE);static ZERO=new t(rt.ZERO);static Fp=nt;static Fn=pu;constructor(e){super(e);}static fromAffine(e){return new t(rt.fromAffine(e))}assertSame(e){if(!(e instanceof t))throw new Error("RistrettoP\
|
|
709
|
+
oint expected")}init(e){return new t(e)}static fromBytes(e){Se(e,32);let{a:n,d:r}=ji,o=At,i=k=>nt.create(k),s=Li(e);if(!Bc(nt.toBytes(s),e)||Be(s,o))throw new Error("invalid ristretto255 encoding 1");
|
|
710
|
+
let a=i(s*s),c=i(Fe+n*a),u=i(Fe-n*a),l=i(c*c),d=i(u*u),p=i(n*r*l-d),{isValid:h,value:m}=lu(i(p*d)),g=i(m*u),f=i(m*g*p),v=i((s+s)*g);Be(v,o)&&(v=i(-v));let b=i(c*f),y=i(v*b);if(!h||Be(y,o)||b===vf)throw new Error(
|
|
711
|
+
"invalid ristretto255 encoding 2");return new t(new rt(v,b,Fe,y))}static fromHex(e){return t.fromBytes(hn(e))}toBytes(){let{X:e,Y:n,Z:r,T:o}=this.ep,i=At,s=f=>nt.create(f),a=s(s(r+n)*s(r-n)),c=s(e*n),
|
|
712
|
+
u=s(c*c),{value:l}=lu(s(a*u)),d=s(l*a),p=s(l*c),h=s(d*p*o),m;if(Be(o*h,i)){let f=s(n*Mi),v=s(e*Mi);e=f,n=v,m=s(d*Cf);}else m=p;Be(e*h,i)&&(n=s(-n));let g=s((r-n)*m);return Be(g,i)&&(g=s(-g)),nt.toBytes(
|
|
713
|
+
g)}equals(e){this.assertSame(e);let{X:n,Y:r}=this.ep,{X:o,Y:i}=e.ep,s=u=>nt.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(ot.BASE);Object.freeze(
|
|
714
|
+
ot.ZERO);Object.freeze(ot.prototype);Object.freeze(ot);var mu=`-----BEGIN PUBLIC KEY-----
|
|
643
715
|
MCowBQYDK2VwAyEAWBiklf0kmDIVmM7nMiCxwiEAkwQIiqWGuRiRDJonsFY=
|
|
644
|
-
-----END PUBLIC KEY-----`;function
|
|
645
|
-
length%4?"=".repeat(4-e.length%4):"";return
|
|
646
|
-
function
|
|
647
|
-
function
|
|
648
|
-
oken"};let n=t.split("."),r=n[0],o=n[1],i=n[2],s;try{s=JSON.parse(
|
|
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=
|
|
650
|
-
return {ok:false,reason:"invalid public key"}}let u=false;try{u=
|
|
651
|
-
{ok:false,reason:"bad signature"}}function
|
|
652
|
-
n.payloadBytes))}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function
|
|
653
|
-
active":e<=r?"grace":"expired"}function
|
|
654
|
-
{reason:i.reason}:{}};let s=i.payload,a=n.nowSeconds??Math.floor(Date.now()/1e3),c=
|
|
655
|
-
if(o.header?.typ!==
|
|
716
|
+
-----END PUBLIC KEY-----`;function hu(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 $i(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.
|
|
717
|
+
length%4?"=".repeat(4-e.length%4):"";return hu(e+n)}function If(t){let e=t.replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=hu(e);return n.subarray(n.length-32)}var _f=new TextEncoder,gu=new TextDecoder;
|
|
718
|
+
function Af(t){return typeof t=="object"&&t!==null&&"keys"in t}function Ot(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 Of=/^[A-Za-z0-9_-]+$/;
|
|
719
|
+
function bu(t){let e=t.split(".");return e.length===3&&e.every(n=>Of.test(n))}function Bi(t){return t===""?"empty":bu(t)?"token":"malformed"}function Fi(t,e){if(!bu(t))return {ok:false,reason:"malformed t\
|
|
720
|
+
oken"};let n=t.split("."),r=n[0],o=n[1],i=n[2],s;try{s=JSON.parse(gu.decode($i(r)));}catch{return {ok:false,reason:"header is not valid JSON"}}let a;if(Af(e)){let l=typeof s.kid=="string"?s.kid:e.defaultKid,
|
|
721
|
+
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=If(a),c.length!==32)return {ok:!1,reason:"invalid public key"}}catch{
|
|
722
|
+
return {ok:false,reason:"invalid public key"}}let u=false;try{u=fu.verify($i(i),_f.encode(`${r}.${o}`),c);}catch{return {ok:false,reason:"signature verification error"}}return u?{ok:true,header:s,payloadBytes:$i(o)}:
|
|
723
|
+
{ok:false,reason:"bad signature"}}function Mt(t,e){let n=Fi(t,e);if(!n.ok||!n.payloadBytes)return {signatureValid:false,...n.reason?{reason:n.reason}:{}};try{return {signatureValid:!0,payload:JSON.parse(gu.decode(
|
|
724
|
+
n.payloadBytes))}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function zi(t,e,n){if(n?.has(t.jti))return "revoked";let r=t.expires_at+t.grace_days*86400;return e<=t.expires_at?"\
|
|
725
|
+
active":e<=r?"grace":"expired"}function Av(t,e,n={}){let r=Ot(t);if(Bi(r)==="empty")return {status:"none",reason:"empty"};let i=Mt(r,e);if(!i.signatureValid||!i.payload)return {status:"invalid",...i.reason?
|
|
726
|
+
{reason:i.reason}:{}};let s=i.payload,a=n.nowSeconds??Math.floor(Date.now()/1e3),c=zi(s,a,n.revoked);return c==="revoked"?{status:c,payload:s,reason:"license revoked"}:{status:c,payload:s}}var vu="BVSALA-REVOC",Mf=300,Lf=new TextDecoder;function yu(t,e,n={}){let r=u=>({ok:false,seq:-1,asOf:0,revoked:new Set,reason:u}),o=Fi(t,e);if(!o.ok||!o.payloadBytes)return r(o.reason??"bad signature");
|
|
727
|
+
if(o.header?.typ!==vu)return r(`unexpected token type "${String(o.header?.typ??"")}" (want ${vu})`);let i;try{i=JSON.parse(Lf.decode(o.payloadBytes));}catch{return r("payload is not valid JSON")}if(typeof i.
|
|
656
728
|
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.
|
|
657
|
-
nowSeconds??Math.floor(Date.now()/1e3),c=n.maxSkewSeconds??
|
|
729
|
+
nowSeconds??Math.floor(Date.now()/1e3),c=n.maxSkewSeconds??Mf;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 Lt=class{_seq=-1;_asOf=0;_lastContactAt=0;set=new Set;get seq(){
|
|
658
730
|
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.
|
|
659
731
|
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&&
|
|
660
|
-
(this._asOf=e.asOf),r||o}};function
|
|
661
|
-
c?.features??[]),l=()=>{if(s==="empty")return "none";if(!c)return "invalid";let
|
|
662
|
-
86400,
|
|
663
|
-
|
|
732
|
+
(this._asOf=e.asOf),r||o}};function jr(t,e,n){let r=()=>Math.floor((n.now?n.now():Date.now())/1e3),o=n.startedAt??r(),i=Ot(t),s=Bi(i),a=s==="token"?Mt(i,e):{signatureValid:false,reason:s},c=a.signatureValid?a.payload:void 0,u=new Set(
|
|
733
|
+
c?.features??[]),l=()=>{if(s==="empty")return "none";if(!c)return "invalid";let p=zi(c,r(),n.revocation.snapshot());if(n.maxStalenessSeconds!=null&&(p==="active"||p==="grace")){let h=c.expires_at+c.grace_days*
|
|
734
|
+
86400,m=Math.min(o,h),g=Math.max(n.revocation.lastContactAt,m);if(r()-g>n.maxStalenessSeconds)return "stale"}return p},d=()=>{let p=l();return p==="active"||p==="grace"};return {isEntitled:p=>d()&&u.has(
|
|
735
|
+
p),isActive:()=>d(),status:l,reason:()=>c?void 0:a.reason,refreshAfter:()=>{if(c)return Math.min(c.expires_at,r()+86400)}}}function ku(t,e,n){return jr(t,e,{revocation:new Lt,...n?{now:n}:{}})}var jt={pollIntervalSeconds:900,floorSeconds:300,maxIntervalSeconds:3600,jitterRatio:.1,maxSkewSeconds:300,requestTimeoutMs:3e4},xu=3,jf=12;function Nf(t){let e=t.random??Math.random,n;if(t.consecutiveFailures>
|
|
664
736
|
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:
|
|
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
|
|
737
|
+
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 $f=10,Nr=class{constructor(e){this.opts=e;}opts;timer=null;controller=null;consecutiveFailures=0;stopped=false;started=false;warnedNoFetch=false;lastEtag=null;consecutive304=0;now(){
|
|
666
738
|
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();
|
|
667
739
|
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.
|
|
668
|
-
onEvent?.({type:"no-fetch"});return}let n=new AbortController;this.controller=n;let r=this.opts.requestTimeoutMs??
|
|
740
|
+
onEvent?.({type:"no-fetch"});return}let n=new AbortController;this.controller=n;let r=this.opts.requestTimeoutMs??jt.requestTimeoutMs,o=setTimeout(()=>n.abort(),r);o.unref?.();let i={accept:"applicati\
|
|
669
741
|
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.
|
|
670
|
-
now()),this.opts.onEvent?.({type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304
|
|
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=
|
|
672
|
-
publicKeyPem,{minSeq:this.opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??
|
|
742
|
+
now()),this.opts.onEvent?.({type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=$f&&(this.consecutive304=0,this.lastEtag=null);return}if(this.consecutive304=0,!s.
|
|
743
|
+
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=yu(c.list,this.opts.
|
|
744
|
+
publicKeyPem,{minSeq:this.opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??jt.maxSkewSeconds});if(!u.ok){let d=u.reason??"rejected";this.opts.onEvent?.({type:"rejected",
|
|
673
745
|
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\
|
|
674
746
|
. 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
747
|
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()||
|
|
677
|
-
if(n<
|
|
748
|
+
return !!(this.opts.silenceWarnings??this.opts.silenciarAvisos)}avisar(e,n){this.callado()||U(`poller:${this.opts.url}:${e}`,n);}avisarFalloDeRed(e){if(this.callado())return;let n=this.consecutiveFailures;
|
|
749
|
+
if(n<xu||(n-xu)%jf!==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\
|
|
678
750
|
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(){
|
|
679
|
-
if(this.stopped)return;let e=
|
|
680
|
-
opts.pollIntervalSeconds??
|
|
751
|
+
if(this.stopped)return;let e=Nf({refreshAfter:this.opts.getRefreshAfter?.(),nowSeconds:this.now(),consecutiveFailures:this.consecutiveFailures,floorSeconds:this.opts.floorSeconds??jt.floorSeconds,pollIntervalSeconds:this.
|
|
752
|
+
opts.pollIntervalSeconds??jt.pollIntervalSeconds,maxIntervalSeconds:this.opts.maxIntervalSeconds??jt.maxIntervalSeconds,jitterRatio:this.opts.jitterRatio??jt.jitterRatio,...this.opts.random?{random:this.
|
|
681
753
|
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.
|
|
682
|
-
controller?.abort();}};var
|
|
754
|
+
controller?.abort();}};var kn=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=
|
|
683
755
|
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.
|
|
684
756
|
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.
|
|
685
757
|
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??
|
|
686
758
|
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.
|
|
687
759
|
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.
|
|
688
760
|
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\
|
|
689
|
-
er ${this.options.serviceAccountKey}`,[
|
|
690
|
-
`the server responded ${o.status}`)):o.status===401||o.status===403?(
|
|
761
|
+
er ${this.options.serviceAccountKey}`,[jn]:`${this.options.surface??"sdk"}/${Me}`},body:JSON.stringify(r)});o.ok?this.fallosSeguidos=0:o.status>=500?(this.fallosSeguidos++,this.requeue(n),this.avisarDeFallo(
|
|
762
|
+
`the server responded ${o.status}`)):o.status===401||o.status===403?(U(`metering-auth-${o.status}`,`[bv-sala] usage reporting is being rejected with HTTP ${o.status} at ${this.options.url}. Check 'ser\
|
|
691
763
|
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?.(
|
|
692
764
|
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.
|
|
693
765
|
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||
|
|
@@ -699,193 +771,207 @@ tokens.compressedInput,baselineOutputTokens:n.tokens.baselineOutput,actualOutput
|
|
|
699
771
|
eliminatedInputFloorCost!==void 0&&Number.isFinite(n.cost.eliminatedInputFloorCost)&&n.cost.eliminatedInputFloorCost>0&&n.tokens.eliminatedInput>0?{eliminatedInputFloorCost:n.cost.eliminatedInputFloorCost}:
|
|
700
772
|
{},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}$/.
|
|
701
773
|
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.
|
|
702
|
-
attribution.sessionId}:{},...n.attribution?.agentId?{agentId:n.attribution.agentId}:{}}}};function
|
|
703
|
-
]";return new RegExp(`-${e}{8,10}-${e}{5}$`).test(t)}function
|
|
704
|
-
t.NETLIFY)}async function
|
|
705
|
-
if(t.KUBERNETES_SERVICE_HOST||
|
|
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
|
|
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
|
|
708
|
-
return false;for(let e of
|
|
774
|
+
attribution.sessionId}:{},...n.attribution?.agentId?{agentId:n.attribution.agentId}:{}}}};function $r(){return globalThis.process}function Bf(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\
|
|
775
|
+
]";return new RegExp(`-${e}{8,10}-${e}{5}$`).test(t)}function Ff(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??
|
|
776
|
+
t.NETLIFY)}async function zf(){if($r()?.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 qf(t,e=zf){
|
|
777
|
+
if(t.KUBERNETES_SERVICE_HOST||Ff(t))return;let n=t.HOSTNAME??t.COMPUTERNAME??await e();if(!(!n||Bf(n)))return n}async function Vf(){let t=$r();if(!t||!t.env)return;let e=t.env,n=await qf(e),r=[t.platform,
|
|
778
|
+
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 Uf=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTI\
|
|
779
|
+
ONS","GITLAB_CI","CIRCLECI","TRAVIS","JENKINS_URL","BUILDKITE","TF_BUILD","TEAMCITY_VERSION","BITBUCKET_BUILD_NUMBER","CODEBUILD_BUILD_ID","HEROKU_TEST_RUN_ID","DRONE"];function qi(){let t=$r()?.env;if(!t)
|
|
780
|
+
return false;for(let e of Uf){let n=t[e];if(n&&n!=="false"&&n!=="0")return true}return false}async function Hf(t,e){let n=globalThis.crypto,r=new TextEncoder;if(n?.subtle)try{let s=await n.subtle.importKey("raw",
|
|
709
781
|
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
|
|
711
|
-
if(!r)return;let o=await
|
|
712
|
-
new
|
|
713
|
-
ted before any provider request was sent"),this.name="StreamAbortedError",this.requestSent=e;}},
|
|
714
|
-
job=n,this.notSubmitted=r;}};var
|
|
782
|
+
|${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 Vi(t){let n=$r()?.env?.BVSALA_SEAT_ID;if(n&&Wf.test(n))return n;let r=await Vf();
|
|
783
|
+
if(!r)return;let o=await Hf(t,r);if(o)return `m-${o.slice(0,32)}`}var Wf=/^[A-Za-z0-9._:/-]{1,128}$/;var wu={inputPer1k:5e-4,outputPer1k:.0015,cachedInputPer1k:5e-5};function Su(t){return {exactCache:t.exactCache??new Fn,semanticCache:t.semanticCache,singleflight:t.singleflight??new zn,resolvers:t.resolvers??la(),router:t.router??new Jn,toolSelector:t.toolSelector??
|
|
784
|
+
new Gn,formatSelector:t.formatSelector??new Xn({tokenizer:t.tokenizer}),schemaRegistry:t.schemaRegistry??new er,constraintBackends:t.constraintBackends??[]}}var ke=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\
|
|
785
|
+
ted before any provider request was sent"),this.name="StreamAbortedError",this.requestSent=e;}},Br=class extends Error{job;notSubmitted;constructor(e,n,r,o){super(e,o),this.name="BatchSubmitError",this.
|
|
786
|
+
job=n,this.notSubmitted=r;}};var Jf={"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.\
|
|
715
787
|
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\
|
|
716
788
|
.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,
|
|
717
789
|
"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\
|
|
718
790
|
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,
|
|
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},
|
|
720
|
-
["claude-opus-4-7","claude-opus-4-8"]),
|
|
721
|
-
/^qwq/,/^qwen3/,/^glm-(4\.[5-9]|[5-9])/,/magistral/];function
|
|
722
|
-
return "unclassified-model";let o=
|
|
791
|
+
"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},Kf=new Set(
|
|
792
|
+
["claude-opus-4-7","claude-opus-4-8"]),Gf=[/^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($|[-_.])/,
|
|
793
|
+
/^qwq/,/^qwen3/,/^glm-(4\.[5-9]|[5-9])/,/magistral/];function Tu(t){let e=t.lastIndexOf("/"),n=(e>=0?t.slice(e+1):t).toLowerCase();if(Gf.some(i=>i.test(n)))return "reasoning-model";let r=St(t);if(r===void 0)
|
|
794
|
+
return "unclassified-model";let o=Jf[r];if(o===true)return "reasoning-model";if(o!==false)return "unclassified-model";if(Kf.has(r))return "temperature-ignored"}var Ui={minimumCacheTokens:1024,cacheReadMultiplier:.5,cacheWriteMultiplier:1},Cu={minimumCacheTokens:1024,cacheReadMultiplier:.1,cacheWriteMultiplier:1.25},Zf=[["claude-fable-5-1",512],["claude-mytho\
|
|
723
795
|
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",
|
|
724
|
-
4096],["claude-3-5-haiku",2048]];function
|
|
725
|
-
n)),c=a*i*r.cacheReadMultiplier+(1-a)*i*r.cacheWriteMultiplier;return s+c}function
|
|
796
|
+
4096],["claude-3-5-haiku",2048]];function Hi(t){for(let[e,n]of Zf)if(t===e||t.startsWith(`${e}-`))return {...Cu,minimumCacheTokens:n};return Cu}var Wi={minimumCacheTokens:1024,cacheReadMultiplier:.1,cacheWriteMultiplier:1};var Eu={minimumCacheTokens:1024,cacheReadMultiplier:1,cacheWriteMultiplier:1};function Fr(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,
|
|
797
|
+
n)),c=a*i*r.cacheReadMultiplier+(1-a)*i*r.cacheWriteMultiplier;return s+c}function Ji(t){let e=Fr(t.originalTokens,t.stablePrefixTokens,t.prefixHitRate,t.tier),n=Fr(t.compressedTokens,0,0,t.tier)+(t.compressorCostTokens??
|
|
726
798
|
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
799
|
< ${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*
|
|
728
800
|
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\
|
|
729
|
-
es not touch the cache tier";return {comprimir:r>0,costeComprimido:n,costeSinComprimir:e,ganancia:r,razon:a}}function
|
|
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
|
|
731
|
-
totalTokens?null:1)}var
|
|
732
|
-
1)*e}estado(e){return this.estados.get(e)}decidir(e,n){let r=
|
|
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 ${
|
|
801
|
+
es not touch the cache tier";return {comprimir:r>0,costeComprimido:n,costeSinComprimir:e,ganancia:r,razon:a}}function Pu(t){let e=o=>Ji({...t,prefixHitRate:o}).ganancia;if(e(0)<=0||e(1)>0)return null;let n=0,
|
|
802
|
+
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 Yf(t){let e=Pu({originalTokens:t.totalTokens,compressedTokens:t.totalTokens,stablePrefixTokens:t.stablePrefixTokens,tier:t.tier});return e??(Fr(t.totalTokens,t.stablePrefixTokens,0,t.tier)<=t.
|
|
803
|
+
totalTokens?null:1)}var zr=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-
|
|
804
|
+
1)*e}estado(e){return this.estados.get(e)}decidir(e,n){let r=Yf(n),o=this.estados.get(e),i=Qf(o);return n.stablePrefixTokens<=0?{marcar:false,razon:"no stable prefix to cache",umbral:r,observada:i}:r==null?
|
|
805
|
+
{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 ${Nt(i)} did not reach the ${Nt(
|
|
734
806
|
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 \
|
|
735
|
-
is only observable on requests that were marked`,umbral:r,observada:i}:i!=null&&i>r?{marcar:true,razon:`measured hit rate ${
|
|
736
|
-
razon:`prefix-cache marking OFF: measured hit rate ${
|
|
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
|
|
738
|
-
if(!t)return null;let e=t.tokensLeidos+t.tokensEscritos;return e<=0?t.marcadas>0?0:null:t.tokensLeidos/e}function
|
|
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
|
|
740
|
-
return
|
|
741
|
-
""}${t.toolCallId??""}${e}${t.content}`}function
|
|
742
|
-
role==="system";)e+=1;return e}function
|
|
743
|
-
reutilizadas:0,tardias:0}}}var
|
|
744
|
-
2048),this.maxClases=Math.max(1,e.maxClases??256),this.prediccionesMinimas=Math.max(1,e.prediccionesMinimas??8),this.confirmacionMinima=e.confirmacionMinima
|
|
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!==
|
|
746
|
-
1h"]||(this.resolverReutilizada(o,a,c),i={tipo:a.tipo,indice:s,huecoMs:c,...a.posicionDelProveedor!==void 0?{posicionDelProveedor:a.posicionDelProveedor}:
|
|
747
|
-
let n=this.estadoDe(e.clase);this.vencer(n,e.enviada);let r=e.enviada;for(let o of ["S","H","
|
|
748
|
-
break;let s=e.huellas[i],a=e.ultimoMarcado===o,c={clase:e.clase,tipo:o,huella:s,indice:i,
|
|
749
|
-
posicionDelProveedor}:{},...a&&e.ttl?{ttl:e.ttl}:{}
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
5m"]
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
null
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
n,e)
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
807
|
+
is only observable on requests that were marked`,umbral:r,observada:i}:i!=null&&i>r?{marcar:true,razon:`measured hit rate ${Nt(i)} beats the ${Nt(r)} break-even`,umbral:r,observada:i}:(o.apagada=true,{marcar:false,
|
|
808
|
+
razon:`prefix-cache marking OFF: measured hit rate ${Nt(i)} did not reach the ${Nt(r)} break-even, so marking was costing money`,umbral:r,observada:i})}registrar(e,n){let r=this.estados.get(e)??{marcadas:0,
|
|
809
|
+
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 Qf(t){
|
|
810
|
+
if(!t)return null;let e=t.tokensLeidos+t.tokensEscritos;return e<=0?t.marcadas>0?0:null:t.tokensLeidos/e}function Nt(t){return t==null?"n/a":`${(t*100).toFixed(1)}%`}var $t={"5m":3e5,"30m":18e5,"1h":36e5},Ce=["5m","30m","1h"],Iu=20;function Ru(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.
|
|
811
|
+
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 Du(t){
|
|
812
|
+
return Ru(t,0).toString(36)+"."+Ru(t,2654435769).toString(36)}function Xf(t){let e=t.toolCalls?.length?t.toolCalls.map(r=>`${r.id??""}${r.name}${r.arguments}`).join(""):"",n=t.isError===true?"error":
|
|
813
|
+
"";return `${t.role}${t.name??""}${t.toolCallId??""}${e}${t.content}${n}`}function _u(t,e){let n=[Du(`bvsala-prefijo\0${t}`)];for(let r of e)n.push(Du(`${n[n.length-1]}${Xf(r)}`));return n}function es(t){
|
|
814
|
+
let e=0;for(;e<t.length&&t[e].role==="system";)e+=1;return e}function Ki(){return {"5m":0,"30m":0,"1h":0}}function Gi(){return {"5m":{resueltas:0,reutilizadas:0,tardias:0},"30m":{resueltas:0,reutilizadas:0,
|
|
815
|
+
tardias:0},"1h":{resueltas:0,reutilizadas:0,tardias:0}}}var qr=1,Au=1440*6e4;function ts(t){return `bvsala:cache-breakpoints:v${qr}:${t}`}var Ft=class{clases=new Map;porHuella=new Map;maxPorClase;maxClases;prediccionesMinimas;confirmacionMinima;memoria;constructor(e={}){
|
|
816
|
+
this.maxPorClase=Math.max(16,e.maxPorClase??2048),this.maxClases=Math.max(1,e.maxClases??256),this.prediccionesMinimas=Math.max(1,e.prediccionesMinimas??8),this.confirmacionMinima=e.confirmacionMinima??
|
|
817
|
+
.5,this.memoria=Math.max(32,e.memoria??512);}observar(e,n,r){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!==
|
|
818
|
+
e||a.indice!==s)continue;let c=Math.max(0,r-a.escrita);c>$t["1h"]||(this.resolverReutilizada(o,a,c),i={tipo:a.tipo,indice:s,huecoMs:c,...a.posicionDelProveedor!==void 0?{posicionDelProveedor:a.posicionDelProveedor}:
|
|
819
|
+
{},...a.ttl?{ttl:a.ttl}:{},...a.idDelProveedor?{idDelProveedor:a.idDelProveedor}:{}});}return i}registrar(e){let n=this.estadoDe(e.clase);this.vencer(n,e.enviada);let r=e.enviada;for(let o of ["S","H","\
|
|
820
|
+
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)break;let s=e.huellas[i],a=e.ultimoMarcado===o,c={clase:e.clase,tipo:o,huella:s,indice:i,
|
|
821
|
+
escrita:r,contadas:0,descartada:false,...a&&e.posicionDelProveedor!=null&&e.posicionDelProveedor>0?{posicionDelProveedor:e.posicionDelProveedor}:{},...a&&e.ttl?{ttl:e.ttl}:{},...a&&e.idDelProveedor?{idDelProveedor:e.
|
|
822
|
+
idDelProveedor}:{}},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 Ce)n.pendientes[o][l]+=1;}}verificar(e,n,r){if(n.posicionDelProveedor===
|
|
823
|
+
void 0)return;let o=n.ttl??"5m";if(n.huecoMs>$t[o])return;let i=this.estadoDe(e);i.predichas+=1,r>=n.posicionDelProveedor*.98&&(i.confirmadas+=1),i.predichas>=this.prediccionesMinimas&&i.confirmadas/i.
|
|
824
|
+
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"],muestras5m:i["\
|
|
825
|
+
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:Zi(i["5m"]),en30m:Zi(
|
|
826
|
+
i["30m"]),en1h:Zi(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,apagada:r.apagada}}get vivas(){
|
|
827
|
+
return this.porHuella.size}exportarClase(e){let r=this.clases.get(e)??this.estadoVacio(),o=r.cabeza,i=c=>Ce.map(u=>{let l=r.contadores[c][u];return [l.resueltas,l.reutilizadas,l.tardias]}),s=c=>Ce.map(
|
|
828
|
+
u=>r.pendientes[c][u]),a={v:qr,clase:e,c:{S:i("S"),H:i("H"),T:i("T")},p:{S:s("S"),H:s("H"),T:s("T")},e:r.cola.slice(o).map(c=>c.descartada?["",c.tipo,c.indice,c.escrita,c.contadas,1,null,null,null]:[c.
|
|
829
|
+
huella,c.tipo,c.indice,c.escrita,c.contadas,0,c.posicionDelProveedor??null,c.ttl??null,c.idDelProveedor??null]),cur:Ce.map(c=>Math.max(0,r.cursores[c]-o)),pr:r.predichas,co:r.confirmadas,off:r.apagada};
|
|
830
|
+
return JSON.stringify(a)}importarClase(e,n){let r=n;if(typeof n=="string")try{r=JSON.parse(n);}catch{return "invalid"}let o=r;if(o===null||typeof o!="object")return "invalid";if(typeof o.v=="number"&&o.v>
|
|
831
|
+
qr)return "newer";let i=this.leerInstantanea(o,e);if(!i)return "invalid";let s=this.clases.get(e);if(s){for(let a=s.cabeza;a<s.cola.length;a++){let c=s.cola[a];this.porHuella.get(c.huella)===c&&this.porHuella.
|
|
832
|
+
delete(c.huella);}this.clases.delete(e);}this.clases.set(e,i);for(let a of i.cola)a.descartada||this.porHuella.set(a.huella,a);return "loaded"}leerInstantanea(e,n){if(e.v!==qr||e.clase!==n)return null;let r=i=>typeof i==
|
|
833
|
+
"number"&&Number.isInteger(i)&&i>=0,o=this.estadoVacio();for(let i of ["S","H","T"]){let s=e.c?.[i],a=e.p?.[i];if(!Array.isArray(s)||s.length!==3||!Array.isArray(a)||a.length!==3)return null;for(let c=0;c<
|
|
834
|
+
3;c++){let u=s[c];if(!Array.isArray(u)||u.length!==3||!u.every(r))return null;let[l,d,p]=u;if(d>l||p>d||!r(a[c]))return null;let h=Ce[c];o.contadores[i][h]={resueltas:l,reutilizadas:d,tardias:p},o.pendientes[i][h]=
|
|
835
|
+
a[c];}}if(!Array.isArray(e.e)||e.e.length>this.maxPorClase)return null;for(let i of e.e){if(!Array.isArray(i)||i.length!==9)return null;let[s,a,c,u,l,d,p,h,m]=i;if(typeof s!="string"||d===0&&s===""||a!==
|
|
836
|
+
"S"&&a!=="H"&&a!=="T"||!r(c)||c===0||typeof u!="number"||!Number.isFinite(u)||!r(l)||l>7||d!==0&&d!==1||p!==null&&!(typeof p=="number"&&Number.isFinite(p)&&p>0)||h!==null&&h!=="5m"&&h!=="1h"||m!==null&&
|
|
837
|
+
!(typeof m=="string"&&m!==""&&m.length<=256))return null;o.cola.push({clase:n,tipo:a,huella:s,indice:c,escrita:u,contadas:l,descartada:d===1,...p!==null?{posicionDelProveedor:p}:{},...h!==null?{ttl:h}:
|
|
838
|
+
{},...m!==null?{idDelProveedor:m}:{}});}if(!Array.isArray(e.cur)||e.cur.length!==3)return null;for(let i=0;i<3;i++){let s=e.cur[i];if(!r(s)||s>o.cola.length)return null;o.cursores[Ce[i]]=s;}return !r(e.pr)||
|
|
839
|
+
!r(e.co)||e.co>e.pr||typeof e.off!="boolean"?null:(o.predichas=e.pr,o.confirmadas=e.co,o.apagada=e.off,o)}estadoVacio(){return {contadores:{S:Gi(),H:Gi(),T:Gi()},pendientes:{S:Ki(),H:Ki(),T:Ki()},cola:[],
|
|
840
|
+
cabeza:0,cursores:{"5m":0,"30m":0,"1h":0},predichas:0,confirmadas:0,apagada:false}}estadoDe(e){let n=this.clases.get(e);if(n)return this.clases.delete(e),this.clases.set(e,n),n;for(n=this.estadoVacio(),this.
|
|
841
|
+
clases.set(e,n);this.clases.size>this.maxClases;){let[r,o]=this.clases.entries().next().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(
|
|
842
|
+
s.huella);}this.clases.delete(r);}return n}descartar(e){let n=this.clases.get(e.clase);Ce.forEach((r,o)=>{e.contadas&1<<o||(n&&(n.pendientes[e.tipo][r]=Math.max(0,n.pendientes[e.tipo][r]-1)),e.contadas|=
|
|
843
|
+
1<<o);}),e.descartada=true;}resolverReutilizada(e,n,r){Ce.forEach((o,i)=>{if(n.contadas&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+=
|
|
844
|
+
1,r<=$t[o]&&(s.reutilizadas+=1),o==="1h"&&r<=$t["1h"]&&r>$t["5m"]&&(s.tardias+=1),n.contadas|=1<<i;}),this.reducirSiHaceFalta(e.contadores[n.tipo]);}vencer(e,n){for(Ce.forEach((r,o)=>{let i=Math.max(e.cursores[r],
|
|
845
|
+
e.cabeza);for(;i<e.cola.length&&n-e.cola[i].escrita>$t[r];){let s=e.cola[i];!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+=
|
|
846
|
+
1,this.reducirSiHaceFalta(e.contadores[s.tipo])),s.contadas|=1<<o,i+=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),
|
|
847
|
+
e.cabeza+=1;}if(e.cabeza>1024&&e.cabeza*2>e.cola.length){e.cola.splice(0,e.cabeza);for(let r of Ce)e.cursores[r]-=e.cabeza;e.cabeza=0;}}reducirSiHaceFalta(e){for(let n of Ce)e[n].resueltas>=this.memoria&&
|
|
848
|
+
(e[n].resueltas=Math.floor(e[n].resueltas/2),e[n].reutilizadas=Math.floor(e[n].reutilizadas/2),e[n].tardias=Math.floor(e[n].tardias/2));}};function Zi(t){return t.resueltas>0?t.reutilizadas/t.resueltas:
|
|
849
|
+
0}function Yi(t,e){let n=t-e;return n>0?Math.max(0,(t-1)/n):1}function Qi(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(
|
|
850
|
+
0,i-s),Math.min(1,i+s)]}function Xi(t,e,n,r,o){return e+n>=o&&Qi(t,e+n)[0]>r?true:e>=o&&Qi(t,e)[1]<r?false:null}function Ou(t){let e=t.muestrasMinimas??5,n=t.tramo.cacheReadMultiplier,r=t.tramo.cacheWriteMultiplier,
|
|
851
|
+
o=t.primaDeUnaHora!=null&&t.primaDeUnaHora>r?t.primaDeUnaHora:null,i=Yi(r,n),s=o!=null?Yi(o,n):null,a={historial:true,cola:false,ttl:"5m",razon:"",equilibrio:i};if(t.estadistica.apagada)return {...a,razon:`\
|
|
852
|
+
fixed placement: the provider's counter confirmed only ${t.estadistica.confirmadas} of ${t.estadistica.predichas} cache reads the layer predicted for this traffic, so the layer stopped trusting its ow\
|
|
853
|
+
n reuse measurement here`};let c=b=>({en5m:Xi(b.k5m,b.muestras5m,b.pendientes5m,i,e),en1h:s!=null?Xi(b.k1h,b.muestras1h,b.pendientes1h,s,e):null}),u=[],l=t.estadistica.H,d=t.estadistica.T,p=c(l),h=c(d),
|
|
854
|
+
m=b=>`${b.k5m}/${b.muestras5m} in 5 min, ${b.k1h}/${b.muestras1h} in 1 h`,g=true;t.hayHistorial&&(p.en5m===true||p.en1h===true?u.push(`history re-sent (${m(l)}): above break-even, marked`):p.en5m===false?(g=false,
|
|
855
|
+
u.push(`history re-sent only ${m(l)} (break-even ${Bt(i)}): breakpoint moved back to the system header, no write premium on a prefix nobody re-reads`)):u.push(`history: not conclusive yet (${m(l)}), f\
|
|
856
|
+
ixed placement kept`));let f=h.en5m===true||h.en1h===true;u.push(f?`continued ${m(d)}: above break-even, tail marked so the next turn reads this whole prompt`:h.en5m===false?`continued only ${m(d)} (break-ev\
|
|
857
|
+
en ${Bt(i)}): tail not marked`:`tail: not conclusive yet (${m(d)}), not marked`);let v="5m";if(o!=null){let b=f?"T":g&&t.hayHistorial?"H":"S",y=t.estadistica[b],k=b==="T"?h:b==="H"?p:c(y),T=b==="T"?t.
|
|
858
|
+
tokens.T:b==="H"?t.tokens.H:t.tokens.S;if(k.en5m!==true&&k.en1h===true)v="1h",u.push(`1h TTL: re-sent ${m(y)} (1 h break-even ${Bt(s)}), while 5 min does not pay`);else if(k.en5m===true&&y.muestras1h>=e&&T>
|
|
859
|
+
0){let[w]=Qi(y.kTardias,y.muestras1h+y.pendientes1h),S=Math.max(0,T-t.lecturaPrevista()),x=w*(r-n)*T,C=(o-r)*S;x>C&&(v="1h",u.push(`1h TTL: at least ${Bt(w)} of re-sends come after 5 min; re-reading ${T}\
|
|
860
|
+
tokens then beats the extra premium on the ${S} written now`));}}return {historial:g,cola:f,ttl:v,razon:u.join("; "),equilibrio:i}}function Mu(t){let e=t.muestrasMinimas??5,n=Yi(t.tramo.cacheWriteMultiplier,
|
|
861
|
+
t.tramo.cacheReadMultiplier),r=t.estadistica.T,o=t.estadistica.H,i=(a,c,u)=>Xi(a,c,u,n,e)===false;if(t.estadistica.apagada)return {explicita:false,historial:true,razon:`provider default kept: the provider's co\
|
|
862
|
+
unter confirmed only ${t.estadistica.confirmadas} of ${t.estadistica.predichas} predicted cache reads`,equilibrio:n};if(!i(r.k30m,r.muestras30m,r.pendientes30m))return {explicita:false,historial:true,razon:`\
|
|
863
|
+
provider default kept: continued ${r.k30m}/${r.muestras30m} within 30 min, not clearly below the ${Bt(n)} break-even`,equilibrio:n};let s=!t.hayHistorial||!i(o.k30m,o.muestras30m,o.pendientes30m);return {
|
|
864
|
+
explicita:true,historial:s,razon:`explicit mode: continued only ${r.k30m}/${r.muestras30m} within 30 min (break-even ${Bt(n)}), so the question is not written; breakpoint at the ${s?"end of the stable h\
|
|
865
|
+
istory":"system header"}`,equilibrio:n}}function Bt(t){return `${(t*100).toFixed(1)}%`}var Lu=.5;function em(t,e){return e.inputPer1k<=0||e.outputPer1k<=0?null:Math.max(t.inputPer1k/e.inputPer1k,t.outputPer1k/e.outputPer1k)}function tm(t){return 1-t}function nm(t,e=Lu){return e-t}function ju(t,e,n=Lu){
|
|
866
|
+
if(!t||!e)return null;let r=em(t,e);if(r==null||!Number.isFinite(r))return null;let o=tm(r),i=nm(r,n),s=i>0,a=c=>`${(c*100).toFixed(1)}%`;return {r,equilibrio:o,escaladoMaximo:i,viable:s,razon:s?`the c\
|
|
781
867
|
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\
|
|
782
|
-
o escalations it cannot reach the ${a(n)} target, so this pair is not worth the quality risk`}}var
|
|
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
|
|
784
|
-
length||e.localeCompare(n))}function
|
|
785
|
-
for(let n of
|
|
786
|
-
e)}decidir(e,n){let r=this.estados.get(e),o=
|
|
868
|
+
o escalations it cannot reach the ${a(n)} target, so this pair is not worth the quality risk`}}var ns={"gpt-4":"gpt-4o","gpt-4-turbo":"gpt-4o-mini","gpt-4o":"gpt-4o-mini","gpt-4.1":"gpt-4.1-mini","cla\
|
|
869
|
+
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 rm(t){return Object.keys(t).sort((e,n)=>n.length-e.
|
|
870
|
+
length||e.localeCompare(n))}function Nu(t,e=ns){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]??om(o,e);return !i||i===o?null:r+i}function om(t,e){
|
|
871
|
+
for(let n of rm(e))if(t.startsWith(n)&&t.charAt(n.length)==="-"&&/^\d{4}/.test(t.slice(n.length+1)))return e[n]}var Vr=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(
|
|
872
|
+
e)}decidir(e,n){let r=this.estados.get(e),o=im(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\
|
|
787
873
|
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}\
|
|
788
874
|
); 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(
|
|
789
875
|
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)}\
|
|
790
876
|
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,
|
|
791
|
-
n&&(r.escaladas+=1),this.estados.set(e,r);}};function
|
|
792
|
-
for(let r of
|
|
877
|
+
n&&(r.escaladas+=1),this.estados.set(e,r);}};function im(t){return !t||t.enrutadas<=0?null:t.escaladas/t.enrutadas}var sm=["enum","pattern","maximum","minimum","maxLength","minLength","maxItems","minItems"];function am(t){return t?rs(t)?"value-constrained":"structural":"none"}function rs(t,e=0){if(e>12)return false;let n=t;
|
|
878
|
+
for(let r of sm)if(n[r]!==void 0)return true;if(t.properties){for(let r of Object.values(t.properties))if(rs(r,e+1))return true}return !!(t.items&&rs(t.items,e+1))}function $u(t){let e=am(t.schema),n=(t.tools??
|
|
793
879
|
[]).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\
|
|
794
880
|
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\
|
|
795
881
|
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 \
|
|
796
|
-
content has somewhere to fall":"output contract checks shape only: a well-formed answer with wrong content passes"}}function
|
|
882
|
+
content has somewhere to fall":"output contract checks shape only: a well-formed answer with wrong content passes"}}function os(t){let e=[];if(e.push("non-empty"),t.texto.trim()==="")return {acepta:false,
|
|
797
883
|
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 \
|
|
798
884
|
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\
|
|
799
885
|
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,
|
|
800
|
-
motivo:"the cheap model's answer is not valid JSON",comprobaciones:e}}let r=
|
|
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
|
|
802
|
-
JSON.parse(t),r=JSON.parse(e);}catch{return {divergen:false,motivo:"not comparable (at least one answer is not JSON)"}}let o=
|
|
803
|
-
le facts (free prose only)"}:
|
|
804
|
-
of a false valid \u2014 it is a reason to look, never a verdict"}}var
|
|
805
|
-
an")n.push(`b:${t}`);else if(typeof t=="string"){let r=t.trim();r.length>0&&r.length<=
|
|
806
|
-
t")for(let r of Object.keys(t).sort())
|
|
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
|
|
808
|
-
0,t)}function
|
|
809
|
-
"object":t.items?"array":void 0)){case "string":return t.maxLength!=null?{valor:
|
|
810
|
-
{valor:Math.trunc(t.maximum)}:void 0;case "number":return;case "array":{if(t.maxItems==null||!t.items)return;let n=
|
|
811
|
-
ject":{if(t.additionalProperties!==false||!t.properties)return;let n={};for(let[r,o]of Object.entries(t.properties)){let i=
|
|
812
|
-
t);return e?JSON.stringify(e.valor):null}function
|
|
813
|
-
let o=r.minimumSavingsTokens??
|
|
886
|
+
motivo:"the cheap model's answer is not valid JSON",comprobaciones:e}}let r=pe(n,t.schema);return r.valid?{acepta:true,motivo:"the cheap model's answer satisfies the output contract",comprobaciones:e}:{
|
|
887
|
+
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 Bu(t,e){let n,r;try{n=
|
|
888
|
+
JSON.parse(t),r=JSON.parse(e);}catch{return {divergen:false,motivo:"not comparable (at least one answer is not JSON)"}}let o=Ur(n),i=Ur(r);return o.length===0&&i.length===0?{divergen:false,motivo:"no comparab\
|
|
889
|
+
le facts (free prose only)"}:um(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 \
|
|
890
|
+
of a false valid \u2014 it is a reason to look, never a verdict"}}var cm=40;function Ur(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\
|
|
891
|
+
an")n.push(`b:${t}`);else if(typeof t=="string"){let r=t.trim();r.length>0&&r.length<=cm&&n.push(`s:${r.toLowerCase()}`);}else if(Array.isArray(t))for(let r of t)Ur(r,e+1,n);else if(t&&typeof t=="objec\
|
|
892
|
+
t")for(let r of Object.keys(t).sort())Ur(t[r],e+1,n);return n.sort()}function um(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 Fu="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\
|
|
893
|
+
, because a number nobody can check is not a number at all but a promise, and this product exists to stop making those. ";function lm(t){if(t<=0)return "";let e=Fu;for(;e.length<t;)e+=Fu;return e.slice(
|
|
894
|
+
0,t)}function dm(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 is(t){if(t.enum&&t.enum.length>0)return {valor:dm(t.enum)};switch(t.type??(t.properties?
|
|
895
|
+
"object":t.items?"array":void 0)){case "string":return t.maxLength!=null?{valor:lm(t.maxLength)}:void 0;case "boolean":return {valor:false};case "null":return {valor:null};case "integer":return t.maximum!=null?
|
|
896
|
+
{valor:Math.trunc(t.maximum)}:void 0;case "number":return;case "array":{if(t.maxItems==null||!t.items)return;let n=is(t.items);return n?{valor:Array.from({length:t.maxItems},()=>n.valor)}:void 0}case "ob\
|
|
897
|
+
ject":{if(t.additionalProperties!==false||!t.properties)return;let n={};for(let[r,o]of Object.entries(t.properties)){let i=is(o);if(!i)return;n[r]=i.valor;}return {valor:n}}default:return}}function pm(t){let e=is(
|
|
898
|
+
t);return e?JSON.stringify(e.valor):null}function zu(t,e){let n=pm(t);return n===null?null:e(n)}var Hr=16,qu=64,fm=8,mm="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 Vu(t,e,n,r={}){
|
|
899
|
+
let o=r.minimumSavingsTokens??fm,i;try{if(cs(t,0))return {applied:!1,reason:"schema has a pattern; no witness can be synthesised to prove the round trip"};i=ls(t,0);}catch(_){return {applied:false,reason:_ instanceof
|
|
814
900
|
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;
|
|
815
|
-
if(!s)return {applied:false,reason:"nothing to compact"};let a=
|
|
816
|
-
i.compact)),
|
|
817
|
-
|
|
818
|
-
evidencia;if(
|
|
819
|
-
e model, not of the schema: ${
|
|
820
|
-
chmarks/ab-live.ts) and pass it in`};let
|
|
821
|
-
he input win is capped by the size of the schema while the output loss grows with the answer and is billed ${
|
|
822
|
-
n.inputPer1k:
|
|
823
|
-
ut tokens ($${
|
|
824
|
-
1)} input tokens equivalent): the compact contract saves ${
|
|
825
|
-
codedEnumValues:i.coded,schemaTokensOriginal:d,schemaTokensCompact:
|
|
826
|
-
function
|
|
827
|
-
ok:false,reason:"compact witness does not validate against the compact schema"};if(!
|
|
828
|
-
ject"||t.type==null&&t.properties!=null}function
|
|
829
|
-
ng")?null:e}function
|
|
901
|
+
if(!s)return {applied:false,reason:"nothing to compact"};let a=_=>zt(_,s,true),c=_=>zt(_,s,false),u=km(t),l=hm(t,i.compact,s,u);if(!l.ok)return {applied:false,reason:l.reason};let d=e(JSON.stringify(t)),p=e(JSON.stringify(
|
|
902
|
+
i.compact)),h=d-p,m=Number.POSITIVE_INFINITY;for(let _ of u){let R=e(JSON.stringify(_))-e(JSON.stringify(a(_)));R<m&&(m=R);}Number.isFinite(m)||(m=0);let g=_=>_/1e3*n.inputPer1k,f=_=>_/1e3*n.outputPer1k,
|
|
903
|
+
v=g(o),b=n.outputPer1k>0?(o-h)*n.inputPer1k/n.outputPer1k:Number.NEGATIVE_INFINITY,y=Number.isFinite(b)?b.toFixed(1):"any",k=n.inputPer1k>0?`${(n.outputPer1k/n.inputPer1k).toFixed(1)}x`:"more than",T=r.
|
|
904
|
+
evidencia;if(T==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\
|
|
905
|
+
e model, not of the schema: ${mm}. Here the compact contract saves ${h} input tokens and output is billed ${k} input, so it only pays while the output delta stays above ${y} tokens. Measure yours (ben\
|
|
906
|
+
chmarks/ab-live.ts) and pass it in`};let w=T.deltaTokens;if(w<0)return {applied:false,reason:`the measured output delta is ${w} tokens: this model writes MORE from a compact contract (${T.procedencia}). T\
|
|
907
|
+
he input win is capped by the size of the schema while the output loss grows with the answer and is billed ${k} input, so no schema is big enough to buy it back`};let S=g(h)+f(w),x=n.inputPer1k>0?S*1e3/
|
|
908
|
+
n.inputPer1k:h,C=`+${w} tokens (${w>0?"the model wrote LESS":"no measured change"}), ${T.procedencia}`;return S<v?{applied:false,reason:`net saving $${S.toFixed(9)}/request is below the floor of ${o} inp\
|
|
909
|
+
ut tokens ($${v.toFixed(9)}): the compact contract saves ${h} input tokens and the measured output delta is ${C}; break-even at ${y}`}:{applied:true,reason:`net saving $${S.toFixed(9)}/request (${x.toFixed(
|
|
910
|
+
1)} input tokens equivalent): the compact contract saves ${h} input tokens and the measured output delta is ${C}; break-even at ${y}`,plan:{compactSchema:i.compact,expand:c,compact:a,renamedKeys:i.renamed,
|
|
911
|
+
codedEnumValues:i.coded,schemaTokensOriginal:d,schemaTokensCompact:p,modelledShapeSavingTokens:m,measuredOutputDeltaTokens:w,outputDeltaProvenance:T.procedencia,breakEvenOutputDeltaTokens:b,netSavingUsd:S}}}
|
|
912
|
+
function hm(t,e,n,r){for(let o of r){if(!pe(o,t).valid)return {ok:false,reason:"synthesised witness does not satisfy the caller's own schema; nothing can be proven"};let i=zt(o,n,true);if(!pe(i,e).valid)return {
|
|
913
|
+
ok:false,reason:"compact witness does not validate against the compact schema"};if(!us(zt(i,n,false),o))return {ok:false,reason:"round trip is not the identity"}}return {ok:true}}function Uu(t){return t.type==="ob\
|
|
914
|
+
ject"||t.type==null&&t.properties!=null}function Hu(t){return t.type==="array"||t.type==null&&t.items!=null}function gm(t){let e=t.enum;return !e||e.length===0||e.length>qu||!e.every(n=>typeof n=="stri\
|
|
915
|
+
ng")?null:e}function ls(t,e){if(e>Hr)throw new RangeError("schema too deep");let n=gm(t);if(n){if(t.minLength!=null)return {compact:t,renamed:0,coded:0};let r=Wu(n,true);if(!r)return {compact:t,renamed:0,
|
|
830
916
|
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,
|
|
831
|
-
enumBack:i},renamed:0,coded:o}}return
|
|
832
|
-
let r=0,o=0,i=new Map,s=new Map;for(let[
|
|
833
|
-
let c={};for(let[
|
|
834
|
-
|
|
835
|
-
if(!t.items)return {compact:t,renamed:0,coded:0};let n=
|
|
917
|
+
enumBack:i},renamed:0,coded:o}}return Uu(t)?bm(t,e):Hu(t)?vm(t,e):{compact:t,renamed:0,coded:0}}function bm(t,e){let n=Object.entries(t.properties??{});if(n.length===0)return {compact:t,renamed:0,coded:0};
|
|
918
|
+
let r=0,o=0,i=new Map,s=new Map;for(let[p,h]of n){let m=ls(h,e+1);s.set(p,m.compact),m.node&&i.set(p,m.node),r+=m.renamed,o+=m.coded;}let a=null;t.additionalProperties===false&&(a=Wu(n.map(([p])=>p),false));
|
|
919
|
+
let c={};for(let[p]of n)c[a?.get(p)??p]=s.get(p);let u={...t,properties:c};t.required&&(u.required=t.required.map(p=>a?.get(p)??p));let l={};if(a){let p=new Map;for(let[m,g]of a)p.set(g,m);let h=false;for(let[
|
|
920
|
+
m,g]of a)m!==g&&(h=true);if(h){l.keysFwd=a,l.keysBack=p;for(let[m,g]of a)m!==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 vm(t,e){
|
|
921
|
+
if(!t.items)return {compact:t,renamed:0,coded:0};let n=ls(t.items,e+1);return {compact:{...t,items:n.compact},...n.node?{node:{items:n.node}}:{},renamed:n.renamed,coded:n.coded}}function Wu(t,e){let n=[
|
|
836
922
|
...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
|
|
838
|
-
t;if(e.items&&Array.isArray(t))return t.map(i
|
|
839
|
-
u);i[c]=l
|
|
840
|
-
r,0));return n}function
|
|
841
|
-
if(n>
|
|
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?
|
|
923
|
+
!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 zt(t,e,n){let r=n?e.enumFwd:e.enumBack;if(r&&typeof t=="string")return r.get(t)??
|
|
924
|
+
t;if(e.items&&Array.isArray(t))return t.map(i=>zt(i,e.items,n));let o=n?e.keysFwd:e.keysBack;if((o||e.props)&&ym(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(
|
|
925
|
+
u);i[c]=l?zt(a,l,n):a;}return i}return t}function ym(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function km(t){let e=Math.min(qu,Math.max(1,ss(t,0))),n=[];for(let r=0;r<e;r++)n.push(as(t,
|
|
926
|
+
r,0));return n}function ss(t,e){if(e>Hr)return 0;let n=t.enum?.length??0;for(let r of Object.values(t.properties??{}))n=Math.max(n,ss(r,e+1));return t.items&&(n=Math.max(n,ss(t.items,e+1))),n}function as(t,e,n){
|
|
927
|
+
if(n>Hr)return null;if(t.enum&&t.enum.length>0)return t.enum[Math.min(e,t.enum.length-1)];if(Uu(t)){let r={};for(let[o,i]of Object.entries(t.properties??{}))r[o]=as(i,e,n+1);return r}if(Hu(t)){if(t.maxItems===
|
|
928
|
+
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?as(i,e,n+1):null)}switch(t.type){case "string":{if(t.maxLength===0)return "";
|
|
843
929
|
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===
|
|
844
|
-
"integer"?Math.round(r):r}case "boolean":return true;case "null":return null;default:return null}}function
|
|
845
|
-
values(t.properties??{}))if(
|
|
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(!
|
|
847
|
-
return false;for(let s of o)if(!Object.prototype.hasOwnProperty.call(e,s)||!
|
|
848
|
-
enums)",pares:8}},
|
|
930
|
+
"integer"?Math.round(r):r}case "boolean":return true;case "null":return null;default:return null}}function cs(t,e){if(e>Hr)throw new RangeError("schema too deep");if(t.pattern!=null)return true;for(let n of Object.
|
|
931
|
+
values(t.properties??{}))if(cs(n,e+1))return true;return !!(t.items&&cs(t.items,e+1))}function us(t,e){if(t===e)return true;if(t===null||e===null||typeof t!="object"||typeof e!="object")return false;let n=Array.
|
|
932
|
+
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(!us(t[s],e[s]))return false;return true}let o=Object.keys(t),i=Object.keys(e);if(o.length!==i.length)
|
|
933
|
+
return false;for(let s of o)if(!Object.prototype.hasOwnProperty.call(e,s)||!us(t[s],e[s]))return false;return true}var xm="2026-08-14",Ju={"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 \
|
|
934
|
+
enums)",pares:8}},wm=vo(Ju);function Sm(t){return bo(Ju,wm,t)}var Wr=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&&
|
|
849
935
|
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,
|
|
850
|
-
origen:"remembered",procedencia:`measured by the caller on an earlier request for this contract on ${e}`};let i=
|
|
851
|
-
Velio on ${e} (${
|
|
852
|
-
r=
|
|
853
|
-
n)}:${
|
|
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,
|
|
855
|
-
o.set(u,
|
|
856
|
-
get(u);if(l===void 0||s.get(l)===u)continue;let d=
|
|
857
|
-
(r,o)=>n.has(o)?{...r,content:
|
|
858
|
-
o==="google"||o==="google-vertex"?
|
|
936
|
+
origen:"remembered",procedencia:`measured by the caller on an earlier request for this contract on ${e}`};let i=Sm(e);return i?{deltaTokens:i.deltaTokens,origen:"catalogue",procedencia:`measured by Bi\
|
|
937
|
+
Velio on ${e} (${xm}, ${i.pares} paired reps, ${i.contrato}, ${i.salidaDelBrazoA}-token answers) \u2014 NOT measured on YOUR contract`}:null}};var ps="[BiVelio Savings: an older tool result was trimmed here to lower the cost; the most recent results travel in full.]",Tm=new TextEncoder;function Cm(t){return Tm.encode(t).length}function Em(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;
|
|
938
|
+
r=ds(o);}catch{r=n;}return `${t} ${r}`}function ds(t){return t===null||typeof t!="object"?JSON.stringify(t)??"null":Array.isArray(t)?`[${t.map(ds).join(",")}]`:`{${Object.keys(t).sort().map(n=>`${JSON.stringify(
|
|
939
|
+
n)}:${ds(t[n])}`).join(",")}}`}function Ku(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=[],
|
|
940
|
+
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,p=l.toolCallId?e.get(l.toolCallId):void 0,h=Em(d,p);h!==null&&
|
|
941
|
+
o.set(u,h);}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.
|
|
942
|
+
get(u);if(l===void 0||s.get(l)===u)continue;let d=Cm(t[u].content);d<1024||(a.push(u),c+=d);}return {indices:a,bytesOriginales:c}}function Gu(t,e){if(e.length===0)return t;let n=new Set(e);return t.map(
|
|
943
|
+
(r,o)=>n.has(o)?{...r,content:ps}:r)}function Jr(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"?Ui:o==="anthropic"?Hi(i):
|
|
944
|
+
o==="google"||o==="google-vertex"?Wi:/^(gpt-|o[1-9](-|$)|chatgpt)/.test(i)?Ui:i.startsWith("claude")?Hi(i):i.startsWith("gemini")?Wi:Eu}function Zu(t){let e=t.prefix!=null,n=Ji({originalTokens:t.originalTokens,
|
|
859
945
|
compressedTokens:t.compressedTokens,stablePrefixTokens:t.prefix?.stableTokens??0,prefixHitRate:t.prefix?.hitRate??0,tier:t.tier,...t.compressorCostTokens!=null?{compressorCostTokens:t.compressorCostTokens}:
|
|
860
946
|
{}});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.
|
|
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
|
|
947
|
+
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 Qu(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
948
|
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
949
|
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
950
|
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
|
|
866
|
-
0,
|
|
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
|
|
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
|
|
869
|
-
var
|
|
870
|
-
if(t.contadorSimulado)return "simulated-provider";let e=t.usoPrimario;if(!e||e.complete===false||!
|
|
871
|
-
false||!
|
|
872
|
-
return "codebook";if(t.tokensDelSondeo!==0||t.sondeoAplicado)return "tool-discovery";if(t.busquedaNativa===true)return "native-tool-
|
|
873
|
-
|
|
874
|
-
model-served";if(!t.cacheable)return "not-cacheable";let r
|
|
875
|
-
model:t.modeloPedido,inputTokens:e.inputTokens,outputTokens:n?Math.min(e.outputTokens,n.outputTokens):e.outputTokens,...o!==void 0?
|
|
876
|
-
max(0,t.piezasDelAdaptador)+(t.hayEsquema?1:0),...i!==void 0?{reasoningTokens:i}:{},requestFingerprint:t.huella(),textSha256:
|
|
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))
|
|
878
|
-
v===2&&typeof n.inputTokens=="number"&&Number.isInteger(n.inputTokens)&&n.inputTokens>0&&
|
|
879
|
-
n.layerInsertions)&&(o===void 0||
|
|
880
|
-
outputTokens,...r!==void 0?{tierFactor:r}:{},layerInsertions:n.layerInsertions,...o!==void 0?{reasoningTokens:o}:{},requestFingerprint:n.
|
|
881
|
-
"string"?{cacheKey:n.cacheKey}:{}}:"malformed"}function
|
|
882
|
-
-not-reported";if(t.reasoningTokens!==0)return "reasoning-reported"}function
|
|
883
|
-
return {ok:false,reason:"witness"};if(t.model!==e.modeloPedido||e.modeloServido!==e.modeloPedido)return {ok:false,reason:"model-mismatch"};let n=e.
|
|
884
|
-
|
|
885
|
-
isFinite(o)||!(o>0)||!Number.isFinite(r.inputPer1k)||o>r.inputPer1k||typeof r.outputPer1k!="number"||!Number.isFinite(r.outputPer1k)||r.outputPer1k<
|
|
886
|
-
8*t.layerInsertions;if(!(i>0))return {ok:false,reason:"no-credit"};let s=typeof e.topeDeSalida=="number"&&Number.isFinite(e.topeDeSalida)?Math.
|
|
887
|
-
void 0?Math.floor(.95*Math.min(t.outputTokens,s)):0,u=Math.min(1,t.tierFactor??1,e.diferible?
|
|
888
|
-
inputTokens,outputTokens:t.outputTokens,creditedInputTokens:i,creditedOutputTokens:c,cachedInputPer1k:o,outputPer1k:r.outputPer1k,tierFactor:u}}}var
|
|
951
|
+
costeDeDosLlamadas:i,ganancia:s,perdidaSiDegrada:a,razon:u}}function Xu(t){let n=(t.description??(Array.isArray(t.intents)?t.intents.join("; "):"")).trim().split(/\r?\n/,1)[0]??"",r=n.length>Yu?n.slice(
|
|
952
|
+
0,Yu-1).trimEnd()+"\u2026":n;return {id:t.id,intents:t.intents,risk:t.risk,...r?{description:r}:{}}}var Yu=200;function el(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.
|
|
953
|
+
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 tl(t,e){
|
|
954
|
+
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 Rm=2;function fs(t){return te(ye({messages:t.messages,structuredData:t.structuredData??null,tools:t.tools??[],schema:t.response?.schema??null}))}function nl(t){return t.temperature===0}
|
|
955
|
+
var it=t=>typeof t=="number"&&Number.isInteger(t)&&t>=0;function Dm(t,e){if(it(t.reasoningTokens)){if(!e)return t.reasoningTokens;if(it(e.reasoningTokens))return t.reasoningTokens+e.reasoningTokens}}function rl(t){
|
|
956
|
+
if(t.contadorSimulado)return "simulated-provider";if(t.origen==="no-oficial")return "unofficial-origin";let e=t.usoPrimario;if(!e||e.complete===false||!it(e.inputTokens)||e.inputTokens<=0||!it(e.outputTokens))
|
|
957
|
+
return "no-usage";let n=t.usoReparacion;if(n&&(n.complete===false||!it(n.outputTokens)))return "no-usage";if(t.eliminatedInput!==0||t.compressedInput!==0||t.elididoLocal!==0||Math.abs(t.sentLocalSinSondeo-
|
|
958
|
+
t.baselineInput)>Rm)return "layer-changed-request";if(t.codebookAplicado)return "codebook";if(t.tokensDelSondeo!==0||t.sondeoAplicado)return "tool-discovery";if(t.busquedaNativa===true)return "native-tool-s\
|
|
959
|
+
earch";if(t.hayEsquema&&(!t.esquemaNativo||t.esquemaPorPrompt))return "schema-in-prompt";if(t.hayEsquema&&!t.esquemaEnFormatoNativo)return "schema-not-verbatim";if(t.hayEsquema&&!t.esquemaEstricto)return "\
|
|
960
|
+
schema-not-strict";if(t.modeloServido!==t.modeloPedido)return "cheaper-model-served";if(!t.cacheable)return "not-cacheable";let r=Xo(t.tierServido),o=r?.conDescuento&&r.factor!=null&&r.factor>0&&r.factor<
|
|
961
|
+
1?r.factor:void 0,i=Dm(e,n);return {v:2,requestId:t.requestId,at:t.at,model:t.modeloPedido,inputTokens:e.inputTokens,outputTokens:n?Math.min(e.outputTokens,n.outputTokens):e.outputTokens,...o!==void 0?
|
|
962
|
+
{tierFactor:o}:{},layerInsertions:Math.max(0,t.mensajesDeLaCapa)+Math.max(0,t.piezasDelAdaptador)+(t.hayEsquema?1:0),...i!==void 0?{reasoningTokens:i}:{},requestFingerprint:t.huella(),textSha256:te(t.
|
|
963
|
+
textoServido)}}var Kr=t=>typeof t=="string"&&t.length>0;function ol(t){if(t==null||typeof t!="object")return "absent";let e=t.reference;if(e==null)return "absent";if(typeof e!="object"||Array.isArray(e))
|
|
964
|
+
return "malformed";let n=e,r=n.tierFactor,o=n.reasoningTokens;return n.v===2&&typeof n.inputTokens=="number"&&Number.isInteger(n.inputTokens)&&n.inputTokens>0&&it(n.outputTokens)&&typeof n.at=="number"&&
|
|
965
|
+
Number.isFinite(n.at)&&(r===void 0||typeof r=="number"&&r>0&&r<1)&&it(n.layerInsertions)&&(o===void 0||it(o))&&Kr(n.requestId)&&Kr(n.model)&&Kr(n.requestFingerprint)&&Kr(n.textSha256)?{v:2,requestId:n.
|
|
966
|
+
requestId,at:n.at,model:n.model,inputTokens:n.inputTokens,outputTokens:n.outputTokens,...r!==void 0?{tierFactor:r}:{},layerInsertions:n.layerInsertions,...o!==void 0?{reasoningTokens:o}:{},requestFingerprint:n.
|
|
967
|
+
requestFingerprint,textSha256:n.textSha256,...typeof n.cacheKey=="string"?{cacheKey:n.cacheKey}:{}}:"malformed"}function Im(t,e){if(!e.determinista)return "sampled";if(e.salidaDelModelo!==void 0)return e.
|
|
968
|
+
salidaDelModelo;if(t.reasoningTokens===void 0)return "reasoning-not-reported";if(t.reasoningTokens!==0)return "reasoning-reported"}function il(t,e){if(e.textoServidoSha256!==t.textSha256)return {ok:false,reason:"\
|
|
969
|
+
witness"};if(e.claveLeida!==void 0&&t.cacheKey!==e.claveLeida)return {ok:false,reason:"witness"};if(t.model!==e.modeloPedido||e.modeloServido!==e.modeloPedido)return {ok:false,reason:"model-mismatch"};let n=e.
|
|
970
|
+
ahoraMs-t.at;if(!(n>=-3e5&&n<=2592e6))return {ok:false,reason:"expired"};if(e.huella!==t.requestFingerprint)return {ok:false,reason:"different-request"};if(!e.calidadOk)return {ok:false,reason:"quality"};let r=e.precio,
|
|
971
|
+
o=r?.cachedInputPer1k;if(!r||typeof o!="number"||!Number.isFinite(o)||!(o>0)||!Number.isFinite(r.inputPer1k)||o>r.inputPer1k||typeof r.outputPer1k!="number"||!Number.isFinite(r.outputPer1k)||r.outputPer1k<
|
|
972
|
+
0)return {ok:false,reason:"no-cached-price"};let i=t.inputTokens-8*t.layerInsertions;if(!(i>0))return {ok:false,reason:"no-credit"};let s=typeof e.topeDeSalida=="number"&&Number.isFinite(e.topeDeSalida)?Math.
|
|
973
|
+
max(0,e.topeDeSalida):Number.POSITIVE_INFINITY,a=Im(t,e),c=a===void 0?Math.floor(.95*Math.min(t.outputTokens,s)):0,u=Math.min(1,t.tierFactor??1,e.diferible?Ba:1);return {ok:true,...a!==void 0?{outputNotCredited:a}:
|
|
974
|
+
{},credit:{requestId:t.requestId,at:t.at,inputTokens:t.inputTokens,outputTokens:t.outputTokens,creditedInputTokens:i,creditedOutputTokens:c,cachedInputPer1k:o,outputPer1k:r.outputPer1k,tierFactor:u}}}var xn={done:true,value:void 0},wn=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
975
|
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);},
|
|
890
976
|
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.
|
|
891
977
|
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.
|
|
@@ -894,54 +980,54 @@ terminado)return;let r=e.toolCalls?.length??0,o=this.primerEventoAt??(n.vivo&&r>
|
|
|
894
980
|
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(){
|
|
895
981
|
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.
|
|
896
982
|
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)
|
|
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(
|
|
898
|
-
esperas.splice(0);if(n){n.reject(e);for(let o of r)o.resolve(
|
|
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(
|
|
983
|
+
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(xn);}fallarCola(e){this.cerrada=true;let[n,...r]=this.
|
|
984
|
+
esperas.splice(0);if(n){n.reject(e);for(let o of r)o.resolve(xn);}else this.errorPendiente={valor:e};}siguiente(){if(this.consumidorSalio)return Promise.resolve(xn);let e=this.cola.shift();if(e)return Promise.
|
|
985
|
+
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(xn):new Promise((n,r)=>{this.esperas.
|
|
900
986
|
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(),
|
|
901
|
-
this.consumidorSalio=true,this.cola.length=0,Promise.resolve(
|
|
902
|
-
"fail_open"?"fail_open":"provider"}}function
|
|
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
|
|
904
|
-
hechos,n=
|
|
987
|
+
this.consumidorSalio=true,this.cola.length=0,Promise.resolve(xn))}}};function _m(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===
|
|
988
|
+
"fail_open"?"fail_open":"provider"}}function Am(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!==
|
|
989
|
+
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 sl(t){let e=t.
|
|
990
|
+
hechos,n=_m(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,
|
|
905
991
|
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\
|
|
906
992
|
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.
|
|
907
993
|
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){
|
|
908
994
|
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.
|
|
909
|
-
embedder,factGuard:"passed",...i.calibration?{calibration:{...i.calibration}}:{}};}let o=
|
|
995
|
+
embedder,factGuard:"passed",...i.calibration?{calibration:{...i.calibration}}:{}};}let o=Am(t.cascada);return o&&(r.cascade=o),r}function al(t){return {source:"coalesced",sharedFrom:t==null?"provider":t.
|
|
910
996
|
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:
|
|
997
|
+
{cacheMatch:Om(t.cacheMatch)}:{},...t?.cascade?{cascade:{...t.cascade}}:{}}}function Om(t){return t.kind==="semantic"&&t.calibration?{...t,calibration:{...t.calibration}}:{...t}}function Gr(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,
|
|
912
998
|
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==
|
|
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
|
|
914
|
-
n=Math.round(e*100)/100;return n===0?"<0.01%":Number.isInteger(n)?`${n}%`:`${n.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}%`}function
|
|
999
|
+
"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 Mm(t){let e=t*100,
|
|
1000
|
+
n=Math.round(e*100)/100;return n===0?"<0.01%":Number.isInteger(n)?`${n}%`:`${n.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}%`}function cl(t){let e=Mm(t);return `[bvsala] Verification sampling is ON \
|
|
915
1001
|
(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\
|
|
916
1002
|
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\
|
|
917
|
-
your statement or any commission.`}function
|
|
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
|
|
1003
|
+
your statement or any commission.`}function ul(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\
|
|
1004
|
+
\` must be a number from 0 to 1 and \`verification.maxCheckCostUsd\`, when set, a positive number (got sampleRate ${e}); verification sampling is OFF.`}var ll="[bvsala] Verification sampling is set, b\
|
|
919
1005
|
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\
|
|
920
|
-
g/usage` \u2014 or pass `verification.onCheck` to receive them yourself. No request will be sent twice until then.",
|
|
921
|
-
request was not affected.";function
|
|
1006
|
+
g/usage` \u2014 or pass `verification.onCheck` to receive them yourself. No request will be sent twice until then.",dl="[bvsala] verification sampling hit an internal error and skipped a request; your\
|
|
1007
|
+
request was not affected.";function pl(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?
|
|
922
1008
|
{tools:[...t.tools]}:{},...t.response?.schema?{schema:t.response.schema}:{},...t.response?.maxOutputTokens!=null?{maxOutputTokens:t.response.maxOutputTokens}:{},...t.temperature!==void 0?{temperature:t.
|
|
923
|
-
temperature}:{},...t.seed!==void 0?{seed:t.seed}:{}}}function
|
|
1009
|
+
temperature}:{},...t.seed!==void 0?{seed:t.seed}:{}}}function fl(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==="\
|
|
924
1010
|
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===
|
|
925
1011
|
"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>
|
|
926
1012
|
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?
|
|
927
|
-
{estrato:"tokens_compressed"}:{estrato:"unchanged"}}function
|
|
928
|
-
i*1e10)/1e10}var
|
|
1013
|
+
{estrato:"tokens_compressed"}:{estrato:"unchanged"}}function ml(t,e){if(!(e>0))return false;if(e>=1)return true;let n=te(`${t}:verification-sample`);return Number.parseInt(n.slice(0,13),16)/2**52<e}function hl(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(
|
|
1014
|
+
i*1e10)/1e10}var Lm=32,jm=6e5;function Nm(t){return new Date(t).toISOString().slice(0,10)}var Zr=class{tasa;tope;onCheck;waitUntil;provider;precio;contrato;now;sumidero;avisar;enVuelo=new Set;cerrado=false;constructor(e){
|
|
929
1015
|
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,
|
|
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=
|
|
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:
|
|
932
|
-
e),precios:l,estrato:s.estrato};}let c=this.now();this.sumidero.contar?.(
|
|
933
|
-
excluida};return {...n,report:{...o,verification:u}}}catch{return this.avisar("verificacion-fallo-interno",
|
|
1016
|
+
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=ml(o.requestId,this.tasa),s=fl({request:e,result:n,
|
|
1017
|
+
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:pl(
|
|
1018
|
+
e),precios:l,estrato:s.estrato};}let c=this.now();this.sumidero.contar?.(Nm(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.
|
|
1019
|
+
excluida};return {...n,report:{...o,verification:u}}}catch{return this.avisar("verificacion-fallo-interno",dl),n}}cerrar(){this.cerrado=true;let e=[...this.enVuelo];this.enVuelo.clear();for(let n of e)if(!n.
|
|
934
1020
|
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.
|
|
935
1021
|
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??
|
|
936
|
-
0,outputTokens:i.tokens.actualOutput},prices:{inputPer1k:s.inputPer1k,...s.cachedInputPer1k!==void 0?{cachedInputPer1k:s.cachedInputPer1k}:{},outputPer1k:s.outputPer1k}};if(this.enVuelo.size>=
|
|
1022
|
+
0,outputTokens:i.tokens.actualOutput},prices:{inputPer1k:s.inputPer1k,...s.cachedInputPer1k!==void 0?{cachedInputPer1k:s.cachedInputPer1k}:{},outputPer1k:s.outputPer1k}};if(this.enVuelo.size>=Lm){this.
|
|
937
1023
|
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"});},
|
|
939
|
-
{signal:l.abortar.signal}));}catch(
|
|
1024
|
+
try{l.abortar.abort();}catch{}this.resolverVuelo(l,{...a,outcome:"check_failed"});},jm),l.reloj.unref?.(),setTimeout(()=>{if(l.decidido)return;let d;try{d=Promise.resolve(this.provider.generate(o.peticion,
|
|
1025
|
+
{signal:l.abortar.signal}));}catch(p){d=Promise.reject(p);}d.then(p=>{let h;try{h=this.checkDeLaRespuesta(a,o.peticion,p,s);}catch{h={...a,outcome:"check_failed"};}this.resolverVuelo(l,h);},()=>{this.resolverVuelo(
|
|
940
1026
|
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=
|
|
942
|
-
"string"?/^[a-z_]{1,32}$/.test(d)?d:"other":void 0;return {...e,outcome:"paired",naive:{cost
|
|
943
|
-
void 0?{finishReason:
|
|
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
|
|
1027
|
+
0,u=h=>typeof h=="number"&&Number.isSafeInteger(h)&&h>=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,p=typeof d==
|
|
1028
|
+
"string"?/^[a-z_]{1,32}$/.test(d)?d:"other":void 0;return {...e,outcome:"paired",naive:{cost:hl({inputTokens:s,outputTokens:a,cachedInputTokens:l},o),inputTokens:s,cachedInputTokens:l,outputTokens:a,...p!==
|
|
1029
|
+
void 0?{finishReason:p}:{},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.
|
|
1030
|
+
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 ms=true,wl=new WeakSet;function $m(t){typeof t=="object"&&t!==null&&wl.add(t);}function vl(t){return typeof t=="object"&&t!==null&&wl.has(t)}function yl(t,e){switch(t){case "none":return Bm();case "inv\
|
|
945
1031
|
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\
|
|
946
1032
|
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 \
|
|
947
1033
|
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\
|
|
@@ -949,560 +1035,575 @@ status: invalid)":"BiVelio license key is not valid (it does not verify). Check
|
|
|
949
1035
|
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\
|
|
950
1036
|
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\
|
|
951
1037
|
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\
|
|
952
|
-
license is not active. See https://savings.bivelio.com/dashboard/account${t?` (license status: ${t})`:""}`}}function
|
|
1038
|
+
license is not active. See https://savings.bivelio.com/dashboard/account${t?` (license status: ${t})`:""}`}}function Bm(){return "BiVelio license required: none was configured. Pass { licenseKey } \u2014 t\
|
|
953
1039
|
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\
|
|
954
|
-
cense status: none)"}function
|
|
955
|
-
path at all \u2014 pass { licenseKey } instead, from https://savings.bivelio.com/dashboard/install (license status: invalid)"}var
|
|
956
|
-
this.config=e,this.deps=
|
|
957
|
-
exploration!=null?{exploracion:e.modelCascade.exploration}:{});let r=
|
|
958
|
-
contrato:(o,i)=>
|
|
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.
|
|
960
|
-
if(o instanceof
|
|
961
|
-
r,"optimizado")}generateStream(e,n={},r){let o;try{o=new
|
|
962
|
-
try{if(r&&await r,n.abortado)throw new
|
|
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
|
|
964
|
-
throw new
|
|
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(
|
|
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:{
|
|
967
|
-
...i?{standalone:true}:{}}}}motivoDeEntregaEntera(e){return e.response?.schema!=null?"output-contract":e.savings?.deferrable===true?"deferrable":typeof this.config.provider.
|
|
968
|
-
|
|
969
|
-
1),r}async llamarProveedorEnStream(e,n,r){if(r.senal.aborted)throw new
|
|
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
|
|
971
|
-
senal.aborted?new
|
|
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
|
|
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=
|
|
974
|
-
let
|
|
975
|
-
colocacion:null},
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
marcado;
|
|
981
|
-
tools:(o.tools??[]).map(
|
|
982
|
-
|
|
983
|
-
mensajesDePrefijo:s,cacheWriteMultiplier:
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
null:"T",indiceDelUltimo:
|
|
989
|
-
explicita:true,explicitaPorColocador:true,colocacion:{...
|
|
990
|
-
|
|
991
|
-
this.huellaDelPrefijo(n,o.tools,r,
|
|
992
|
-
indiceDelUltimo:
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
/${
|
|
996
|
-
explicita:false,explicitaPorColocador:false,colocacion:
|
|
997
|
-
T,stablePrefixTokens:
|
|
998
|
-
observedHitRate:
|
|
999
|
-
colocacion:{...
|
|
1000
|
-
let
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
apagada&&!
|
|
1004
|
-
{
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
s
|
|
1011
|
-
|
|
1012
|
-
,
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
"
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
which
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
,
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1040
|
+
cense status: none)"}function Fm(){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 \
|
|
1041
|
+
path at all \u2014 pass { licenseKey } instead, from https://savings.bivelio.com/dashboard/install (license status: invalid)"}var Qr=class{deps;config;now;generateId;contratosQueIncumplen;verjaDeCache=new zr;espejoDeCache=new Ft;verjaDeCascada;memoriaDelCodebook=new Wr;referenciasDeLider=new WeakMap;noReproducibles=new WeakSet;comprobador;constructor(e,n={}){
|
|
1042
|
+
this.config=e,e.silenceWarnings===true&&tc(e.provider),this.deps=Su(e),this.now=e.now??(()=>Date.now()),this.generateId=e.generateId??(()=>Yt()),this.contratosQueIncumplen=e.constraintMemory??new Set,this.
|
|
1043
|
+
verjaDeCascada=new Vr(e.modelCascade?.exploration!=null?{exploracion:e.modelCascade.exploration}:{});let r=Gr(e.verification);this.comprobador=r.activo&&n.verificacion?new Zr({ajustes:r,provider:e.provider,
|
|
1044
|
+
precio:o=>this.precioConocido(o),contrato:(o,i)=>zm(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(
|
|
1045
|
+
e,n,r):n}cerrarVerificacion(){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.
|
|
1046
|
+
generateOptimized(e,n);}catch(o){if(o instanceof Qe||this.config.failOpen===false||n.falloDelProveedor||n.llamadas>0||vl(o))throw o;return this.conVerificacion(e,await this.failOpenDirect(e,o),"fail-open")}
|
|
1047
|
+
return this.conVerificacion(e,r,"optimizado")}generateStream(e,n={},r){let o;try{o=new wn(this.now,n?.signal);}catch(i){let s=new wn(this.now);return s.fallar(i),s.handle}return this.ejecutarStream(e,o,
|
|
1048
|
+
r),o.handle}async ejecutarStream(e,n,r){try{if(r&&await r,n.abortado)throw new ke(!1);e=this.conPalancasPorDefecto(e);let o=this.motivoDeEntregaEntera(e);if(o){let a=await this.generate(e);n.completar(
|
|
1049
|
+
a,{vivo:!1,motivo:o});return}this.assertLicensed(),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 Qe||
|
|
1050
|
+
a instanceof ke)throw a;if(n.sumidero.senal.aborted)throw new ke(i.llamadas>0);if(this.config.failOpen===!1||i.falloDelProveedor||i.llamadas>0||vl(a))throw a;let c=this.conVerificacion(e,await this.failOpenDirect(
|
|
1051
|
+
e,a),"fail-open");n.completar(c,{vivo:!1,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(
|
|
1052
|
+
o);}}conPalancasPorDefecto(e){let n=this.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:{
|
|
1053
|
+
...r??{},...o?{deferrable:true}:{},...i?{standalone:true}:{}}}}motivoDeEntregaEntera(e){return e.response?.schema!=null?"output-contract":e.savings?.deferrable===true?"deferrable":typeof this.config.provider.
|
|
1054
|
+
generateStream!="function"?"provider-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.
|
|
1055
|
+
usage.complete===false&&(n.sinContador+=1),r}async llamarProveedorEnStream(e,n,r){if(r.senal.aborted)throw new ke(n.llamadas>0);n.llamadas+=1;let o="",i;try{for await(let s of this.config.provider.generateStream(
|
|
1056
|
+
e,{signal:r.senal})){if(r.senal.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 ke(true):(n.
|
|
1057
|
+
falloDelProveedor=true,s)}if(!i)throw r.senal.aborted?new ke(true):(n.falloDelProveedor=true,new Error(`provider "${this.config.provider.id}" stream ended without a final response`));return r.proveedorTermino(),
|
|
1058
|
+
i.usage.complete===false&&(n.sinContador+=1),i.text!==o&&(this.avisar(`stream-texto-distinto:${this.config.provider.id}`,`[bvsala] provider "${this.config.provider.id}" streamed text that differs from it\
|
|
1059
|
+
s final response; the streamed text is 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=Ya(
|
|
1060
|
+
i,{...i,text:o})),r.sirvioEnVivo=true,i}decidirMarcadoDeCache(e,n,r,o,i,s,a,c=null){let u=e.savings?.standalone===true&<(n,dt(this.config.provider))?ti(n):null,l=u!==null,d={marcar:false,huella:"",claveDeVerja:"",
|
|
1061
|
+
mensajesDePrefijo:0,cacheWriteMultiplier:1,explicita:l,explicitaPorColocador:false,colocacion:null},p=hs(n,this.config.compressionEconomics);if(!p)return a.record("prefix-cache","skipped",{reason:`no cac\
|
|
1062
|
+
he read discount for model "${n}" (unrecognised provider, or a declared tier that does not discount reads): not claiming a cacheable prefix`}),d;if(!o.setIsStable)return a.record("prefix-cache","skipp\
|
|
1063
|
+
ed",{reason:"the tool SET is selected per request; tools render first, so the prefix cannot hit. Pruning wins here (it is a measured saving); pass the tools you want fixed."}),d;if(i)return a.record("\
|
|
1064
|
+
prefix-cache","skipped",{reason:"savings.toolDiscovery is on: which schemas travel is decided by a non-deterministic probe, so the tool block \u2014 which renders first \u2014 varies across requests that would \
|
|
1065
|
+
share a prefix fingerprint. Marking would pay the 1.25x write premium for a prefix that cannot hit. Turn tool discovery off to reclaim the prefix cache."}),d;let h=null;if(this.config.cacheBreakpoints===
|
|
1066
|
+
"auto"&&!l){let k=this.colocarConEspejo(e,n,r,o,s,p,a,c);if("marcado"in k)return k.marcado;h=k.observacion;}if(s<=0)return {...d,colocacion:h};let m=r.slice(0,s),g=this.tokensFor(this.assemblePromptText(
|
|
1067
|
+
m,o.tools),e),f=this.tokensFor(this.assemblePromptText(r,o.tools),e),v=te(ye({model:n,tools:(o.tools??[]).map(k=>k.id),prefijo:m.map(k=>`${k.role}:${k.content}`)})),b=l?`${v}|explicit`:v,y=this.verjaDeCache.
|
|
1068
|
+
decidir(b,{totalTokens:f,stablePrefixTokens:g,tier:u??p});return a.record("prefix-cache",y.marcar?"marked":"skipped",{reason:y.razon,stablePrefixTokens:g,breakEvenHitRate:y.umbral,observedHitRate:y.observada,
|
|
1069
|
+
...l?{mode:"explicit"}:{}}),y.marcar?{marcar:true,huella:v,claveDeVerja:b,mensajesDePrefijo:s,cacheWriteMultiplier:p.cacheWriteMultiplier,explicita:l,explicitaPorColocador:false,colocacion:h}:{...d,colocacion:h}}colocarConEspejo(e,n,r,o,i,s,a,c=null){
|
|
1070
|
+
let{tramoOpenAI:u,conPrima:l}=this.primasDelColocador(e,n,s);if(!l&&!u)return {observacion:null};let d=es(r),p=Math.max(d,Math.min(i,r.length)),h=r.length,m=c?.huellas??this.huellasDelColocador(e,n,r,o.
|
|
1071
|
+
tools),g=m[d],f=c?.clase===g?c:null,v=f?.espejo??this.espejoDeCache,b=this.now(),y=v.observar(g,m,b),k=v.estadistica(g,b),T=f?{mirrorStore:f.estado}:{},w={S:d,...p>d?{H:p}:{},T:h},S=z=>this.tokensFor(
|
|
1072
|
+
this.assemblePromptText(r.slice(0,z),o.tools),e),x={clase:g,huellas:m,tramos:w,coincidencia:y,enviada:b,...f?{conAlmacen:true}:{}};if(u){let z=Mu({estadistica:k,tramo:u,hayHistorial:p>d});a.record("pref\
|
|
1073
|
+
ix-cache-placement",z.explicita?"explicit":"provider-default",{reason:z.razon,breakEvenReuseRate:z.equilibrio,continuedWithin30m:k.T.en30m,samples:k.T.muestras30m,...T});let ee={...x,cola:!z.explicita,
|
|
1074
|
+
ttl:"5m",ultimo:z.explicita?null:"T",indiceDelUltimo:z.explicita?null:h};if(!z.explicita)return {observacion:ee};let L=z.historial?p:d;if(L<=0)return {marcado:{marcar:false,huella:"",claveDeVerja:"",mensajesDePrefijo:0,
|
|
1075
|
+
cacheWriteMultiplier:1,explicita:true,explicitaPorColocador:true,colocacion:{...ee,ultimo:null,indiceDelUltimo:null}}};let ae=L===d?"S":"H",ce=`${g}|explicit|${ae}`,Z=this.verjaDeCache.decidir(ce,{totalTokens:S(
|
|
1076
|
+
h),stablePrefixTokens:S(L),tier:u});return a.record("prefix-cache",Z.marcar?"marked":"skipped",{reason:Z.razon,breakEvenHitRate:Z.umbral,observedHitRate:Z.observada,mode:"explicit"}),{marcado:{marcar:Z.
|
|
1077
|
+
marcar,huella:Z.marcar?this.huellaDelPrefijo(n,o.tools,r,L):"",claveDeVerja:Z.marcar?ce:"",mensajesDePrefijo:Z.marcar?L:0,cacheWriteMultiplier:1,explicita:true,explicitaPorColocador:true,colocacion:{...ee,
|
|
1078
|
+
ultimo:Z.marcar?ae:null,indiceDelUltimo:Z.marcar?L:null}}}}let C={S:d>0?S(d):0,H:p>d?S(p):0,T:S(h)},_=Yo(n),R=Ou({estadistica:k,tramo:s,primaDeUnaHora:_>s.cacheWriteMultiplier?_:null,tokens:C,hayHistorial:p>
|
|
1079
|
+
d,lecturaPrevista:()=>y?S(y.indice):0}),E=R.historial&&p>d?p:d,D=R.cola?"T":E>0?E===p&&p>d?"H":"S":null,I=R.cola?h:E>0?E:null;a.record("prefix-cache-placement",D??"none",{reason:R.razon||"fixed placem\
|
|
1080
|
+
ent",boundary:E===0?"none":E===d?"system":"history",tail:R.cola,ttl:R.ttl,breakEvenReuseRate:R.equilibrio,historyReusedWithin5m:k.H.en5m,continuedWithin5m:k.T.en5m,samples:k.T.muestras5m,providerConfirmedReads:`${k.
|
|
1081
|
+
confirmadas}/${k.predichas}`,...T});let M={...x,cola:R.cola,ttl:R.ttl,ultimo:null,indiceDelUltimo:null};if(D==null||I==null)return {marcado:{marcar:false,huella:"",claveDeVerja:"",mensajesDePrefijo:0,cacheWriteMultiplier:1,
|
|
1082
|
+
explicita:false,explicitaPorColocador:false,colocacion:M}};let j=R.ttl==="1h"?{...s,cacheWriteMultiplier:_}:s,B=`${g}|${E===0?"-":E===d?"S":"H"}${R.cola?"+T":""}@${R.ttl}`,V=this.verjaDeCache.decidir(B,{totalTokens:C.
|
|
1083
|
+
T,stablePrefixTokens:R.cola?C.T:E===d?C.S:C.H,tier:j});return a.record("prefix-cache",V.marcar?"marked":"skipped",{reason:V.razon,stablePrefixTokens:R.cola?C.T:E===d?C.S:C.H,breakEvenHitRate:V.umbral,
|
|
1084
|
+
observedHitRate:V.observada}),V.marcar?{marcado:{marcar:true,huella:this.huellaDelPrefijo(n,o.tools,r,E),claveDeVerja:B,mensajesDePrefijo:E,cacheWriteMultiplier:s.cacheWriteMultiplier,explicita:false,explicitaPorColocador:false,
|
|
1085
|
+
colocacion:{...M,ultimo:D,indiceDelUltimo:I}}}:{marcado:{marcar:false,huella:"",claveDeVerja:"",mensajesDePrefijo:0,cacheWriteMultiplier:1,explicita:false,explicitaPorColocador:false,colocacion:M}}}apuntarEnElEspejo(e,n,r,o=this.
|
|
1086
|
+
espejoDeCache,i={}){let s=e.colocacion,a=n.complete!==false,c=Math.max(0,n.cachedInputTokens??0),u=Math.max(0,n.cacheWriteInputTokens??0),l=s.ultimo!=null&&s.indiceDelUltimo!=null,d=s.coincidencia?.indice;
|
|
1087
|
+
if(a&&l&&s.coincidencia&&d!==void 0&&s.indiceDelUltimo>=d&&s.indiceDelUltimo-d<Iu){let p=o.estadistica(s.clase,s.enviada);o.verificar(s.clase,s.coincidencia,c);let h=o.estadistica(s.clase,s.enviada);if(h.
|
|
1088
|
+
predichas>p.predichas){let m=h.confirmadas>p.confirmadas,g=i.diagnostico;r.record("prefix-cache-placement","verified",{predictedRead:s.coincidencia.posicionDelProveedor,providerCacheRead:c,confirmed:m,
|
|
1089
|
+
...!m&&g?{cacheMissReason:g.missReason,...g.missedInputTokens!==void 0?{cacheMissedInputTokensEstimate:g.missedInputTokens}:{}}:{},...h.apagada&&!p.apagada?{reason:`the provider's counter confirmed on\
|
|
1090
|
+
ly ${h.confirmadas} of ${h.predichas} predicted cache reads: this traffic goes back to the fixed placement`}:{}});}}o.registrar({clase:s.clase,huellas:s.huellas,tramos:s.tramos,enviada:s.enviada,ultimoMarcado:l?
|
|
1091
|
+
s.ultimo:null,posicionDelProveedor:a&&l?c+u:null,ttl:s.ttl,idDelProveedor:this.config.cacheMissDiagnostics===true&&l?i.id??null:null});}async apuntarEnElAlmacen(e,n,r,o){let i=this.config.cacheBreakpointStore,
|
|
1092
|
+
s=e.colocacion,a=ts(s.clase),c;try{c=await i.get(a);}catch(l){r.record("prefix-cache-placement","store-error",{reason:`could not read the placement store (${xl(l)}), so this request was not recorded`});
|
|
1093
|
+
return}let u=new Ft;if(c!=null&&u.importarClase(s.clase,c)==="newer"){r.record("prefix-cache-placement","store-error",{reason:"the placement store holds a state written by a newer SDK version; left un\
|
|
1094
|
+
touched"});return}u.observar(s.clase,s.huellas,s.enviada),this.apuntarEnElEspejo(e,n,r,u,o);try{await i.set(a,u.exportarClase(s.clase),Au);}catch(l){r.record("prefix-cache-placement","store-error",{reason:`\
|
|
1095
|
+
could not write the placement store (${xl(l)})`});}}async cargarEspejo(e,n,r,o,i){if(this.config.cacheBreakpoints!=="auto"||!o.setIsStable||i)return null;let s=dt(this.config.provider);if(e.savings?.standalone===
|
|
1096
|
+
true&<(n,s))return null;let a=hs(n,this.config.compressionEconomics);if(!a)return null;let{tramoOpenAI:c,conPrima:u}=this.primasDelColocador(e,n,a);if(!u&&!c)return null;let l=this.huellasDelColocador(
|
|
1097
|
+
e,n,r,o.tools),d=l[es(r)],p=new Ft,h;try{let m=await this.config.cacheBreakpointStore.get(ts(d));h=m==null?"empty":p.importarClase(d,m)==="loaded"?"loaded":"unreadable";}catch{h="unavailable";}return {clase:d,
|
|
1098
|
+
huellas:l,espejo:p,estado:h}}primasDelColocador(e,n,r){let o=dt(this.config.provider),i=e.savings?.standalone===void 0&<(n,o);return {tramoOpenAI:i?ti(n):null,conPrima:r.cacheWriteMultiplier>1&&!i}}huellasDelColocador(e,n,r,o){
|
|
1099
|
+
let i=ye({model:n,tools:(o??[]).map(s=>s.id),schema:e.response?.schema??null});return _u(i,r)}huellaDelPrefijo(e,n,r,o){return te(ye({model:e,tools:(n??[]).map(i=>i.id),prefijo:r.slice(0,o).map(i=>`${i.
|
|
1100
|
+
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,enruta:false,elegible:false,razon:"the model \
|
|
1101
|
+
cascade is off",fuerza:"none",bucket:"",economia:null,observada:null,muestras:0,precioBarato:null,tasaDeMuestreo:0};if(s==="off")return a;let c=$u({schema:e.response?.schema,tools:e.tools}),u=Nu(e.model,
|
|
1102
|
+
this.config.modelCascade?.pairs??ns),l=this.precioConocido(e.model,i),d=u?this.precioConocido(u,i):void 0,p=ju(d,l),h=te(ye({tenant:n.tenantId,scope:n.authorizationScope,contract:n.contractId,schema:n.
|
|
1103
|
+
schemaVersion,fuerte:e.model,barato:u,tools:n.toolsetHash})),m=this.verjaDeCascada.estado(h),g={modo:s,modeloPedido:e.model,modeloServido:e.model,candidato:u,enruta:false,elegible:false,razon:c.razon,fuerza:c.
|
|
1104
|
+
fuerza,bucket:h,economia:p,observada:m&&m.enrutadas>0?m.escaladas/m.enrutadas:null,muestras:m?.enrutadas??0,precioBarato:d??null,tasaDeMuestreo:0},f=y=>(o.record("model-cascade",s==="on"?"not routed":
|
|
1105
|
+
"not eligible",{reason:y}),{...g,razon:y});if(!c.elegible)return f(c.razon);if(!u)return f(`no cheaper model is paired with "${e.model}"; declare one in createSavingsLayer({ modelCascade: { pairs } })\
|
|
1106
|
+
if your provider has one`);if(!p){let y=[...this.precioConocido(e.model,i)?[]:[e.model],...d?[]:[u]];return f(`no known price for ${y.map(k=>`"${k}"`).join(" or ")||"this pair"}, so the arithmetic th\
|
|
1107
|
+
at decides whether routing pays cannot be run. The illustrative default price is deliberately NOT used here: it would approve a pair nobody has priced. Pass \`costModels\` for both models to enable the \
|
|
1108
|
+
cascade for them`)}if(!p.viable)return f(p.razon);let v=Math.min(1,Math.max(0,this.config.modelCascade?.shadowSampleRate??0));if(s==="shadow")return o.record("model-cascade","shadow",{candidateModel:u,
|
|
1109
|
+
costRatio:p.r,breakEvenEscalationRate:p.equilibrio,verifier:c.fuerza,workload:h,note:"measuring only: the request goes to the model you asked for. The escalation rate is not a quality score \u2014 a well-f\
|
|
1110
|
+
ormed answer with wrong content passes the verifier."}),{...g,elegible:true,razon:c.razon,tasaDeMuestreo:v};let b=this.verjaDeCascada.decidir(h,p);return b.enrutar?(this.avisar(`cascada:${e.model}->${u}`,
|
|
1111
|
+
`[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 against your output contract, nev\
|
|
1112
|
+
er its meaning, so a well-formed answer with wrong content is served and counted as a success. report.model always names the model that answered, and report.qualityStatus reads "bounded_degradation".`),
|
|
1113
|
+
o.record("model-cascade","routed",{candidateModel:u,costRatio:p.r,breakEvenEscalationRate:p.equilibrio,observedEscalationRate:b.observada,verifier:c.fuerza,workload:h,reason:b.razon}),{...g,modeloServido:u,
|
|
1114
|
+
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.observada,breakEvenEscalationRate:p.
|
|
1115
|
+
equilibrio}),{...g,elegible:true,razon:b.razon,observada:b.observada,muestras:b.muestras})}devOpen(){return false}exigirLicencia(){this.assertLicensed();}assertLicensed(){if(this.devOpen())return;let e=this.
|
|
1116
|
+
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():void 0;throw new Qe(yl(n,r),
|
|
1117
|
+
n)}throw e?new Qe(Fm(),"invalid"):new Qe(yl("none"),"none")}avisar(e,n){this.config.silenceWarnings||U(e,n);}avisarDeTruncado(e,n,r,o,i){let s=e.response?.maxOutputTokens,a=En(e)||"(no contractId)",c=i?
|
|
1118
|
+
" 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 your cap. If it still gets\
|
|
1119
|
+
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`), so there is no way to kno\
|
|
1120
|
+
w 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 PROVIDER cap (the Anthrop\
|
|
1121
|
+
ic 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 up to ~${o} tokens with t\
|
|
1122
|
+
his 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 NOT inherited \u2014 the schema\
|
|
1123
|
+
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 cap is not the problem: this m\
|
|
1124
|
+
odel 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 off after exhausting \`maxOutpu\
|
|
1125
|
+
tTokens\`${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. NOT retried: with the same cap\
|
|
1126
|
+
it would be cut off again, a paid call for the same failure.${u}`);}avisarDePalancasSinConfigurar(e){this.config.silenceWarnings||((e.compression===true||e.compression==="auto")&&!this.config.compressor&&
|
|
1127
|
+
this.avisar("palanca-sin-compresor","[bv-sala] `savings.compression` was requested but this layer has no compressor, so NOTHING is compressed: the long context travels and is paid in full. In the repo\
|
|
1128
|
+
rt, `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 latency and compute that only you sho\
|
|
1129
|
+
uld decide to pay for: plug it in with `createSavingsLayer({ compressor })`, any object with `compress({ text })`. If your plan does not include `long_context_compression`, that feature is needed too.\
|
|
1130
|
+
The rest of the layer keeps saving as usual."),e.semanticCache&&!this.deps.semanticCache&&this.avisar("palanca-sin-cache-semantica",'[bv-sala] `savings.semanticCache` was requested but this layer has\
|
|
1131
|
+
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, which is your own cost and provid\
|
|
1132
|
+
er: plug it in with `createSavingsLayer({ semanticCache: new InMemorySemanticCache({ embed }) })`. The exact cache and the rest of the layer keep working.'));}async generateOptimized(e,n={llamadas:0,falloDelProveedor:false,
|
|
1133
|
+
sinContador:0},r=null){this.assertLicensed();let o=new fn(this.now),i=new Ct,s=Po(e),a=Bn(s),c=e.savings??{};this.avisarDePalancasSinConfigurar(c),c.semanticCache&&c.semanticCache!=="include-agentic"&&
|
|
1134
|
+
this.deps.semanticCache&&kl(s,a)&&this.avisar("semantica-agentica-apagada",'[bv-sala] `savings.semanticCache` is on, but this request is agentic (it declares tools, carries tool calls or results, or h\
|
|
1135
|
+
olds 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, and the guard und\
|
|
1136
|
+
er 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 traffic.');let u=this.
|
|
1137
|
+
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.join("; ")||"no rest\
|
|
1138
|
+
rictions",{allowExactCache:a.allowExactCache,allowSemanticCache:a.allowSemanticCache});let p=this.tokensFor(this.assembleBaselinePrompt(e),e),h=e.response?.maxOutputTokens??256,m,g=()=>m??=fs(e);if(i.
|
|
1139
|
+
baselineInput=p,i.baselineOutput=h,i.baselineTools=e.tools?.length??0,c.deterministicResolvers!==false){let y=this.deps.resolvers.try(s);if(y)return i.avoidCall(p,this.tokensFor(y.text,e)),o.record("reso\
|
|
1140
|
+
lver",y.resolver,{avoided:true}),this.finish(e,s,{text:y.text,data:y.data,storedAtMs:this.now()},"deterministic",i,d,o,Tn(),Cn(),void 0,void 0,void 0,void 0,void 0,this.informeDeCascada(l,{servedModel:e.
|
|
1141
|
+
model}))}let f=Ro(s,{servedModel:l.modeloServido});if(a.allowExactCache&&c.exactCache!==false){let y=await this.deps.exactCache.get(f);if(y){let k=this.creditoPorReferencia(ol(y.meta),{request:e,cascada:l,
|
|
1142
|
+
toggles:c,huella:g,texto:y.text,claveLeida:f,calidad:()=>{let T=e.response?.schema;return !T||pe(y.data,T).valid}});return k.ok?i.avoidCallByReference(k.credit):(i.avoidCall(p,this.tokensFor(y.text,e)),
|
|
1143
|
+
i.referenceRejected=k.reason),o.record("exact-cache","hit",{ageMs:this.now()-y.storedAtMs,basis:k.ok?"reference":"estimated",...k.ok?{}:{referenceRejected:k.reason},...k.ok&&k.outputNotCredited?{outputNotCredited:k.
|
|
1144
|
+
outputNotCredited}:{}}),this.finish(e,s,y,"exact",i,d,o,Tn(),Cn(),this.now()-y.storedAtMs,void 0,void 0,void 0,void 0,this.informeDeCascada(l))}o.record("exact-cache","miss");}let v=Zs(s,{servedModel:l.
|
|
1050
1145
|
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,
|
|
1052
|
-
|
|
1053
|
-
asCoalescedFollower(
|
|
1054
|
-
run(
|
|
1055
|
-
this.referenciasDeLider.get(
|
|
1056
|
-
ejected"});return this.asCoalescedFollower(
|
|
1057
|
-
semanticCache&&i.semanticCache!=="include-agentic"&&this.deps.semanticCache&&
|
|
1058
|
-
lude it'),o.allowSemanticCache&&i.semanticCache&&this.deps.semanticCache&&!
|
|
1059
|
-
semanticCache&&
|
|
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,
|
|
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
|
|
1062
|
-
router.classify(r);c.record("router",
|
|
1063
|
-
passthrough(n.tools):this.deps.toolSelector.select(r.normalizedText,n.tools,
|
|
1064
|
-
actualTools=
|
|
1065
|
-
reason,{dropped:
|
|
1066
|
-
|
|
1067
|
-
|
|
1146
|
+
n,e,s,a,c,i,d,o,f,p,l,r,u)}catch(y){throw (n.falloDelProveedor||n.llamadas>0)&&$m(y),y}};if(a.allowSingleflight&&c.singleflight!==false){if(r){let T=this.deps.singleflight,w=typeof T.join=="function"?T.join(
|
|
1147
|
+
v):void 0;if(w){let S=await w;return this.noReproducibles.has(S)?(o.record("singleflight","not coalesced: the answer in flight cannot be replayed"),b()):(o.record("singleflight","coalesced",{key:v}),this.
|
|
1148
|
+
asCoalescedFollower(S,p,this.tokensFor(S.text??"",e),d,e))}return o.record("singleflight","skipped (streaming: a streamed request never leads)"),b()}let{value:y,coalesced:k}=await this.deps.singleflight.
|
|
1149
|
+
run(v,b);if(k&&this.noReproducibles.has(y))return o.record("singleflight","not coalesced: the answer in flight cannot be replayed"),b();if(k){o.record("singleflight","coalesced",{key:v});let T=this.creditoPorReferencia(
|
|
1150
|
+
this.referenciasDeLider.get(y)??"absent",{request:e,cascada:l,toggles:c,huella:g,texto:y.text??"",claveLeida:void 0,calidad:()=>y.report.constraints.structurallyValid!==false&&y.report.qualityStatus!=="r\
|
|
1151
|
+
ejected"});return this.asCoalescedFollower(y,p,this.tokensFor(y.text??"",e),d,e,T)}return y}return b()}async expensivePath(e,n,r,o,i,s,a,c,u,l,d,p,h){let m=this.entitled("semantic_cache"),g=null;if(i.
|
|
1152
|
+
semanticCache&&i.semanticCache!=="include-agentic"&&this.deps.semanticCache&&kl(r,o)&&c.record("semantic-cache",'skipped: agentic traffic (default); set savings.semanticCache: "include-agentic" to inc\
|
|
1153
|
+
lude it'),o.allowSemanticCache&&i.semanticCache&&this.deps.semanticCache&&!m&&c.record("semantic-cache","degraded: feature not included in this license"),o.allowSemanticCache&&i.semanticCache&&this.deps.
|
|
1154
|
+
semanticCache&&m){let P=this.deps.semanticCache,O=P.calibrated?await P.lookup(r,{agentic:o.isAgentic}):{hit:await P.find(r),probe:null},N=O.hit;if(g=O.probe,N)return s.avoidCall(l,this.tokensFor(N.record.
|
|
1155
|
+
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,Tn(),Cn(),N.ageMs,N.confidence,void 0,void 0,void 0,
|
|
1156
|
+
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 f=i.router===false,v=f?Tn():this.deps.
|
|
1157
|
+
router.classify(r);c.record("router",v.executionClass,{confidence:v.confidence,reason:v.reason});let b=this.planearBusquedaNativa(n,i,v.executionClass,f,d,a,c),y=b?b.seleccion:f?this.deps.toolSelector.
|
|
1158
|
+
passthrough(n.tools):this.deps.toolSelector.select(r.normalizedText,n.tools,v.executionClass,r.toolsetHash);if(!b&&$o(i.toolSearch).modo==="off"&&this.avisarDeCatalogoRecortado(n,y,d.modeloServido),s.
|
|
1159
|
+
actualTools=y.tools.length,y.droppedIds.length){let P=new Set(y.droppedIds),O=(n.tools??[]).filter(N=>P.has(N.id)).reduce((N,H)=>N+this.tokensFor(Yr(H),n),0);s.eliminate(O),c.record("tool-selector",y.
|
|
1160
|
+
reason,{dropped:y.droppedIds,eliminatedTokens:O});}s.baselineRetrieval=this.config.retriever?v.rounds:0;let k=await va({execution:v.executionClass,query:r.normalizedText,maxRounds:n.retrieval?.maxRounds??
|
|
1161
|
+
v.rounds,maxDocuments:n.retrieval?.maxDocuments??5},{...this.config.retriever?{retriever:this.config.retriever}:{},...this.config.reranker?{reranker:this.config.reranker}:{}});s.actualRetrieval=k.rounds,
|
|
1162
|
+
k.retrievedCount>0&&c.record("retrieval",`kept ${k.keptCount}/${k.retrievedCount}`,{rounds:k.rounds});let T=Cn(),w=[...n.messages],S=bs(n.messages),x=false,C=k.docs.length>0?{role:"system",content:`Retri\
|
|
1068
1163
|
eved context \u2014 answer using only this evidence and cite sources by [id]:
|
|
1069
1164
|
|
|
1070
|
-
`+
|
|
1165
|
+
`+k.docs.map((P,O)=>`[${P.source??P.id??`doc${O+1}`}]
|
|
1071
1166
|
${P.text}`).join(`
|
|
1072
1167
|
|
|
1073
|
-
`)}:null,
|
|
1074
|
-
JSON limits (not API-enforced): ${
|
|
1075
|
-
{model:n.model,...n.tokenizer?{tokenizer:n.tokenizer}:{}});let N=this.tokensFor(
|
|
1076
|
-
`:"")+
|
|
1077
|
-
disabled; sent compact JSON"});}if(C&&
|
|
1078
|
-
{},
|
|
1079
|
-
{}},H=0,
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
this.assemblePromptText(
|
|
1083
|
-
compressorCostTokens});
|
|
1084
|
-
xe=
|
|
1085
|
-
s.compressionReport={originalTokens:
|
|
1086
|
-
let
|
|
1087
|
-
record("elision","applied",{elided:P.indices.length,eliminatedTokens:N,grossBytes:P.bytesOriginales,live:
|
|
1088
|
-
ge\xD7size threshold"});}let
|
|
1089
|
-
luded in this license"),
|
|
1090
|
-
indice],xe=this.tokensFor(
|
|
1091
|
-
(
|
|
1092
|
-
compactados.length,before:
|
|
1093
|
-
cacheReadMultiplier:
|
|
1094
|
-
ery later turn"});}let I=n.response?.schema,
|
|
1095
|
-
null;
|
|
1096
|
-
schemaTokensCompact:
|
|
1097
|
-
breakEvenOutputDeltaTokens:
|
|
1098
|
-
deps.constraintBackends):{backend:"none",reason:"no output contract"};c.record("constraints",B.backend,{reason:B.reason});let
|
|
1099
|
-
|
|
1100
|
-
e,n,i,
|
|
1101
|
-
{},...
|
|
1102
|
-
backend},
|
|
1103
|
-
tail:L.colocacion.cola,ttl:L.colocacion.ttl}}:{}
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
A.
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
let
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1168
|
+
`)}:null,_=En(n),R=n.response?.maxOutputTokens!=null?Math.floor(n.response.maxOutputTokens*3.2):null,E=this.contratosQueIncumplen.has(_)?gs(n.response?.schema,"",R):"";if(E&&Pn(w,{role:"system",content:`\
|
|
1169
|
+
JSON limits (not API-enforced): ${E}`}),n.structuredData!==void 0){let P=JSON.stringify(n.structuredData),O=this.tokensFor(P,n);if(i.serialization!==false){T=this.deps.formatSelector.choose(n.structuredData,
|
|
1170
|
+
{model:n.model,...n.tokenizer?{tokenizer:n.tokenizer}:{}});let N=this.tokensFor(T.encoded+T.instruction,n);s.compress(O,N),Pn(w,{role:"system",content:(T.instruction?T.instruction+`
|
|
1171
|
+
`:"")+T.encoded}),c.record("serialization",T.chosen,{reason:T.reason,jsonTokens:O,chosenTokens:N});}else Pn(w,{role:"system",content:P}),c.record("serialization","json-compact",{reason:"format selector\
|
|
1172
|
+
disabled; sent compact JSON"});}if(C&&Pn(w,C),(i.compression===true||i.compression==="auto")&&o.allowCompression&&this.config.compressor&&this.entitled("long_context_compression")){let P=this.config.compressionEconomics??
|
|
1173
|
+
{},O=Jr(n.model,P),N={compressorCostTokens:P.compressorCostTokens??0,...P.minimumContextTokens!=null?{minimumContextTokens:P.minimumContextTokens}:{},...P.minimumNetTokens!=null?{minimumNetTokens:P.minimumNetTokens}:
|
|
1174
|
+
{}},H=0,Y=0;for(let le of w)le.role==="system"?H+=1:Y+=this.tokensFor(le.content,n);let Ue=this.tokensFor(this.assemblePromptText(w,y.tools),n),ue=Wo({...N,contextTokens:Y,projectedEliminable:Y}),se=0,
|
|
1175
|
+
W=0,Pe=false,xe=ue.reason;if(ue.compress){let le=[];for(let K of w){if(K.role==="system"){le.push(K);continue}let Kt=this.tokensFor(K.content,n),Gt=await this.config.compressor.compress({text:K.content}),
|
|
1176
|
+
Fs=!Gt.skipped&&Gt.fidelityPassed&&Da(K.content,Gt.compressed),zs=Fs?this.tokensFor(Gt.compressed,n):Kt;Fs&&zs<Kt?(le.push({...K,content:Gt.compressed}),se+=Kt,W+=zs):le.push(K);}let He=this.tokensFor(
|
|
1177
|
+
this.assemblePromptText(le,y.tools),n),ve=Wo({...N,contextTokens:Y,projectedEliminable:se-W}),Mn=Zu({originalTokens:Ue,compressedTokens:He,tier:O,...P.prefix?{prefix:P.prefix}:{},compressorCostTokens:N.
|
|
1178
|
+
compressorCostTokens});W>=se?xe="no fidelity-passed net reduction":ve.compress?Mn.comprimir?(Pe=true,xe=Mn.razon,x=le.slice(0,S).some((K,Kt)=>K.content!==w[Kt]?.content),w=le,s.compress(se,W)):xe=Mn.razon:
|
|
1179
|
+
xe=ve.reason;}Pe||(se=0,W=0),c.record("compression",Pe?"applied":"skipped",{reason:xe,before:se,after:W,contextTokens:Y,promptTokens:Ue,cacheTierMinimum:O.minimumCacheTokens,protectedSystemMessages:H,prefixRewritten:x}),
|
|
1180
|
+
s.compressionReport={originalTokens:se,compressedTokens:W,protectedSpans:H,fidelityPassed:true};}if(i.elision!==false&&o.allowElision&&this.entitled("tool_result_elision")){let P=Ku(w);if(P.indices.length>0){
|
|
1181
|
+
let O=this.tokensFor(ps,n),N=0;for(let H of P.indices){let Y=this.tokensFor(w[H].content,n);N+=Math.max(0,Y-O);}(P.indices.some(H=>H<S)&&(x=true),w=Gu(w,P.indices),s.eliminate(N),s.elididoLocal+=N),c.
|
|
1182
|
+
record("elision","applied",{elided:P.indices.length,eliminatedTokens:N,grossBytes:P.bytesOriginales,live:ms});}else c.record("elision","skipped",{reason:"no old/large tool_result over the a\
|
|
1183
|
+
ge\xD7size threshold"});}let D=Zm(this.config.toolOutputCompaction,i.toolOutputCompaction);if(D&&!this.entitled("long_context_compression")&&c.record("tool-output-compaction","degraded: feature not inc\
|
|
1184
|
+
luded in this license"),D&&o.allowCompression&&this.entitled("long_context_compression")){let P=Ma(w,D),O=0,N=0,H=0,Y=0,Ue={};if(P.compactados.length>0){let se=w.slice();for(let W of P.compactados){let Pe=w[W.
|
|
1185
|
+
indice],xe=this.tokensFor(Pe.content,n),le=this.tokensFor(W.texto,n);se[W.indice]={...Pe,content:W.texto},O+=xe,N+=le,W.enLaCola?H+=Math.max(0,xe-le):Y+=Math.max(0,xe-le);for(let He of W.aplicadas)Ue[He]=
|
|
1186
|
+
(Ue[He]??0)+1;}w=se,s.compress(O,N),s.compactedLocal+=Math.max(0,O-N);}let ue=Jr(n.model,this.config.compressionEconomics);c.record("tool-output-compaction",P.compactados.length>0?"applied":"skipped",{compacted:P.
|
|
1187
|
+
compactados.length,before:O,after:N,tailSavedTokens:H,replayedSavedTokens:Y,transforms:Ue,fileViewsKeptVerbatim:P.vistasDeFichero,exceptedTools:P.exceptuados,cacheWriteMultiplier:ue.cacheWriteMultiplier,
|
|
1188
|
+
cacheReadMultiplier:ue.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\
|
|
1189
|
+
ery later turn"});}let I=n.response?.schema,M=I&&i.outputCodebook===true?Vu(I,P=>this.tokensFor(P,n),a,{evidencia:this.memoriaDelCodebook.resolver(d.modeloServido,En(n),i.outputCodebookMeasuredOutputDeltaTokens)}):
|
|
1190
|
+
null;M&&c.record("output-codebook",M.applied?"applied":"skipped",{reason:M.reason,...M.applied?{renamedKeys:M.plan.renamedKeys,codedEnumValues:M.plan.codedEnumValues,schemaTokensOriginal:M.plan.schemaTokensOriginal,
|
|
1191
|
+
schemaTokensCompact:M.plan.schemaTokensCompact,modelledShapeSavingTokens:M.plan.modelledShapeSavingTokens,measuredOutputDeltaTokens:M.plan.measuredOutputDeltaTokens,outputDeltaProvenance:M.plan.outputDeltaProvenance,
|
|
1192
|
+
breakEvenOutputDeltaTokens:M.plan.breakEvenOutputDeltaTokens,netSavingUsd:M.plan.netSavingUsd,pricedForModel:d.modeloServido}:{}});let j=M?.applied?M.plan.compactSchema:I,B=j?Ra(d.modeloServido,j,this.
|
|
1193
|
+
deps.constraintBackends):{backend:"none",reason:"no output contract"};c.record("constraints",B.backend,{reason:B.reason});let V=b?{tools:b.prefijo,setIsStable:y.setIsStable}:y,z=i.toolDiscovery===true&&
|
|
1194
|
+
!b,ee=this.config.cacheBreakpointStore?await this.cargarEspejo(n,d.modeloServido,w,V,z):null,L=this.decidirMarcadoDeCache(n,d.modeloServido,w,V,z,x?bs(w,true):S,c,ee),ae=this.now();if(p?.senal.aborted)throw new ke(
|
|
1195
|
+
e.llamadas>0);let ce=b?this.sinDescubrimientoPorBusquedaNativa(i,y.tools,c):await this.descubrirHerramientas(e,n,i,y.tools,w,s,a,c),Z=ce.tools;s.actualTools=Z.length;let Ut={messages:w,...Z.length?{tools:Z}:
|
|
1196
|
+
{},...j?{schema:j}:{},...n.response?.maxOutputTokens!=null?{maxOutputTokens:n.response.maxOutputTokens}:{},...n.temperature!=null?{temperature:n.temperature}:{},...n.seed!=null?{seed:n.seed}:{},...i.deferrable?
|
|
1197
|
+
{deferrable:true}:{},...L.explicita?{explicitCacheWrites:true}:{},...b?{toolSearch:b.plan}:{},constraintBackend:B.backend},_n={model:d.modeloServido,...Ut,...L.marcar?{stablePrefixMessages:L.mensajesDePrefijo,
|
|
1198
|
+
promptCacheKey:L.huella,...L.colocacion&&!L.explicita&&(L.colocacion.cola||L.colocacion.ttl!=="5m")?{cachePlacement:{tail:L.colocacion.cola,ttl:L.colocacion.ttl}}:{},...this.config.cacheMissDiagnostics===
|
|
1199
|
+
true&&L.colocacion?{cacheDiagnostics:{previousMessageId:L.colocacion.coincidencia?.idDelProveedor??null}}:{}}:{}},A,As=false,Hl={...e};try{A=p?await this.llamarProveedorEnStream(_n,e,p):await this.llamarProveedor(
|
|
1200
|
+
_n,e);}catch(P){if(!this.respaldaFaltaDeCapacidad(i,P,p))throw P;Object.assign(e,Hl),As=true,c.record("deferred-tier","capacity-fallback",{error:P instanceof Error?P.message.slice(0,200):String(P),reason:'\
|
|
1201
|
+
the cheaper tier had no capacity; repeated once at the standard tier and price, as configured with priceLevers.onCapacityError: "standard"'});let{deferrable:O,...N}=_n;A=await this.llamarProveedor(N,e);}
|
|
1202
|
+
let Wl=cr(A),Jl=A.servedServiceTier;b&&c.record("tool-search","provider",{searches:A.toolSearch?.searches??null,loaded:A.toolSearch?.loaded??[],errors:A.toolSearch?.errors??0,resentResults:A.toolSearch?.
|
|
1203
|
+
resent?.results??0,resentTools:A.toolSearch?.resent?.tools??[],reason:A.toolSearch?"what the provider's tool search did in this call; its cost is in the provider's counter and credited to no ledger":"\
|
|
1204
|
+
the adapter did not report what the search did"}),s.actualLlm+=1;let fo=P=>{if(!M?.applied)return P;let O=ze(P);return O.ok?JSON.stringify(M.plan.expand(O.value)):P},fe=fo(A.text),Ae=A.usage,Os={...A.
|
|
1205
|
+
providerMessageId?{id:A.providerMessageId}:{},...A.cacheDiagnostics?{diagnostico:A.cacheDiagnostics}:{}},ct=false;if(d.enruta){let P=os({texto:fe,schema:I,finishReason:A.finishReason,pidioHerramientas:(A.
|
|
1206
|
+
toolCalls?.length??0)>0});this.verjaDeCascada.registrar(d.bucket,!P.acepta),c.record("model-cascade",P.acepta?"accepted":"escalating",{servedModel:d.modeloServido,reason:P.motivo,checks:P.comprobaciones}),
|
|
1207
|
+
P.acepta||(ct=true,s.cascadeAttempt(A.usage,d.precioBarato??a,L.marcar&&L.cacheWriteMultiplier>1?1:cn(d.modeloServido)),s.actualLlm+=1,A=await this.llamarProveedor({model:n.model,...Ut},e),fe=fo(A.text));}
|
|
1208
|
+
let Ee=ct?n.model:d.modeloServido,Ht=ct?this.costModelFor(n.model,h):a;s.actualInput+=A.usage.inputTokens,s.actualOutput+=A.usage.outputTokens;let Kl=A.usage,Gl=A.servedServiceTier,Zl=A.structuredNatively===
|
|
1209
|
+
true,An=cr(A),Yl=Za(this.config.provider),Ms;M?.applied&&c.record("output-codebook",ze(A.text).ok?"expanded":"not-expanded (response was not JSON)",ze(A.text).ok?{localOutputTokensCompact:this.tokensFor(
|
|
1210
|
+
A.text,n),localOutputTokensExpanded:this.tokensFor(fe,n),creditedLedger:"none",note:"local count of the served answer in both shapes; not credited to any ledger"}:{}),I&&B.backend==="provider-native"&&
|
|
1211
|
+
A.structuredNatively===false&&(B={backend:"none",reason:"provider did not enforce the contract natively; the schema travelled in the prompt and the layer is the only validator"},c.record("constraints","n\
|
|
1212
|
+
one",{downgradedFrom:"provider-native",reason:B.reason})),s.sentInputLocal=this.tokensFor(this.assemblePromptText(w,Z),n),s.removedInputLocal=Math.max(0,l-s.sentInputLocal-s.elididoLocal-s.compactedLocal);
|
|
1213
|
+
let Ql=s.sentInputLocal;s.sentInputLocal+=ce.tokensLocalesDelSondeo,s.estimatorExact=this.estimatorEsExacto(n),A.usage.cachedInputTokens&&s.providerCached(A.usage.cachedInputTokens);let Ls=cn(Ee),Xl=!ct&&
|
|
1214
|
+
L.marcar&&L.cacheWriteMultiplier>1;if(Ls>1&&!Xl&&(A.usage.cacheWriteInputTokens??0)>0&&s.providerCacheWritePremium(A.usage.cacheWriteInputTokens??0,Ls,Ht),L.marcar&&Ae.complete===false)c.record("prefix-c\
|
|
1215
|
+
ache","not measured: the provider reported no usage for this call");else if(L.marcar){let P=Math.max(0,Ae.cacheWriteInputTokens??0),O=Math.min(P,Math.max(0,Ae.cacheWrite1hInputTokens??(L.colocacion?.ttl===
|
|
1216
|
+
"1h"?P:0)));s.cacheWritePremium(P-O,L.cacheWriteMultiplier,d.precioBarato??a),O>0&&s.cacheWritePremium(O,Yo(d.modeloServido),d.precioBarato??a),this.verjaDeCache.registrar(L.claveDeVerja,Ae),c.record(
|
|
1217
|
+
"prefix-cache","measured",{cacheRead:Ae.cachedInputTokens??0,cacheWritePremiumTokens:Ae.cacheWriteInputTokens??0,...O>0?{cacheWrite1hTokens:O}:{}});}L.colocacion?.conAlmacen?await this.apuntarEnElAlmacen(
|
|
1218
|
+
L,Ae,c,Os):L.colocacion&&this.apuntarEnElEspejo(L,Ae,c,this.espejoDeCache,Os);let yt=null;if(d.modo==="shadow"&&d.elegible&&d.candidato&&d.precioBarato&&Km(u,d.tasaDeMuestreo))try{let P=await this.llamarProveedor(
|
|
1219
|
+
{model:d.candidato,...Ut},e);s.actualLlm+=1;let O=s.extraCostUsd;s.cascadeAttempt(P.usage,d.precioBarato,cn(d.candidato));let N=fo(P.text),H=os({texto:N,schema:I,finishReason:P.finishReason,pidioHerramientas:(P.
|
|
1220
|
+
toolCalls?.length??0)>0});this.verjaDeCascada.registrar(d.bucket,!H.acepta);let Y=H.acepta?Bu(N,fe):null;yt={coste:s.extraCostUsd-O,divergio:Y?Y.divergen:null},c.record("model-cascade",H.acepta?"sampl\
|
|
1221
|
+
e accepted":"sample escalated",{candidateModel:d.candidato,reason:H.motivo,sampleCost:yt.coste,...Y?{diverged:Y.divergen,divergence:Y.motivo}:{},note:"measurement only: this answer was NEVER served. T\
|
|
1222
|
+
he 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 Error?P.message:String(
|
|
1223
|
+
P)});}let On=fe,kt=true,Oe={},Wt=(A.toolCalls?.length??0)>0;if(Wt&&(kt=null,I&&c.record("validation","n/a: model requested tool calls (the output contract applies to the final answer)")),I&&!Wt){let P=ze(
|
|
1224
|
+
fe),O=P.ok?pe(P.value,I):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},N=false;P.ok&&P.rescatado!=null&&O.valid&&(fe=P.rescatado,N=true,c.record("validation","rescued-locally",{reason:"the model \
|
|
1225
|
+
wrapped valid JSON in prose or a markdown fence; it was extracted locally instead of paying a repair call"})),!O.valid&&Gm(O.errors)&&this.contratosQueIncumplen.add(En(n));let H=A.finishReason==="leng\
|
|
1226
|
+
th",Y=A.finishReason==="content_filter",Ue=!O.valid&&O.errors.some(ue=>/not a valid regular expression/.test(ue.message));if(!O.valid&&Ue)c.record("validation","repair-skipped",{reason:"schema defect \
|
|
1227
|
+
(uncompilable pattern); no output can satisfy it, a retry is a wasted call",errors:O.errors}),this.avisar("esquema-roto","[bvsala] The response contract has a `pattern` that is not a valid regex, so n\
|
|
1228
|
+
o response can satisfy it. NOT retried (it would be a paid call for the same failure). Fix the schema's `pattern`."),Oe.reparacion={outcome:"skipped",skipReason:"schema_defect"};else if(!O.valid&&Y)c.
|
|
1229
|
+
record("validation","repair-skipped",{reason:"the provider refused the request (finish reason content_filter); a repair on the same model would be refused, and may be billed, again",model:Ee}),Oe.reparacion=
|
|
1230
|
+
{outcome:"skipped",skipReason:"provider_refusal"};else if(!O.valid&&H){let ue=zu(I,Pe=>this.tokensFor(Pe,n)),se=n.response?.maxOutputTokens??null,W=ue!==null&&se!=null&&ue<=se;W&&this.contratosQueIncumplen.
|
|
1231
|
+
add(En(n)),c.record("validation","repair-skipped",{reason:"output truncated by maxOutputTokens; a retry with the same cap would truncate again",maxOutputTokens:n.response?.maxOutputTokens??null,outputTokens:A.
|
|
1232
|
+
usage.outputTokens,model:Ee,...ue!==null?{schemaAllowsTokens:ue}:{},learnedValueLimits:W}),this.avisarDeTruncado(n,Ee,A.usage.outputTokens,ue,W),Oe.reparacion={outcome:"skipped",skipReason:"output_tru\
|
|
1233
|
+
ncated"};}else if(!O.valid&&B.backend==="none"){let ue=O.errors.slice(0,5).map(K=>`- ${K.path}: ${K.message}`).join(`
|
|
1234
|
+
`),se=[{role:"user",content:`Your previous reply did not satisfy the required JSON contract.
|
|
1136
1235
|
|
|
1137
1236
|
Previous reply:
|
|
1138
|
-
${
|
|
1237
|
+
${fe}
|
|
1139
1238
|
|
|
1140
1239
|
Problems found:
|
|
1141
|
-
${
|
|
1240
|
+
${ue}
|
|
1142
1241
|
|
|
1143
|
-
Return ONLY the corrected JSON object. Keep the same content; fix only what is listed.`}],
|
|
1144
|
-
round(
|
|
1145
|
-
|
|
1146
|
-
invalid answer is served as-is and reported as invalid",errors:
|
|
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 ~$${
|
|
1148
|
-
actual}, repair ~$${
|
|
1149
|
-
uest carrying both tools and an output contract; see the adapter warning for the cheaper shapes.`),
|
|
1150
|
-
"validation","repair-attempt",{errors:
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
baselineInput:l,codebookAplicado:
|
|
1160
|
-
esquemaEnFormatoNativo===!0&&j===I,esquemaEstricto:
|
|
1161
|
-
cacheable:
|
|
1162
|
-
"object"?c.record("reference","written",{inputTokens:
|
|
1163
|
-
{},exactCache:
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
{
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
tools.length
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
tools,tokensLocalesDelSondeo:
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
tier
|
|
1200
|
-
|
|
1201
|
-
let
|
|
1202
|
-
|
|
1203
|
-
d.motivo
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
"estimated:
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
let
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
a.
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1242
|
+
Return ONLY the corrected JSON object. Keep the same content; fix only what is listed.`}],W=this.tokensFor(this.assemblePromptText(se),n),Pe=s.sentInputLocal>0?s.actualInput/s.sentInputLocal:1,xe=Math.
|
|
1243
|
+
round(Pe*W),le=Math.min(A.usage.outputTokens,n.response?.maxOutputTokens??Number.POSITIVE_INFINITY),He=xe/1e3*Ht.inputPer1k+le/1e3*Ht.outputPer1k,ve=this.config.skipRepairAboveBaseline?s.estimateCost(
|
|
1244
|
+
Ht):void 0;if(ve!=null&&ve.baselineEstimate>0&&ve.actual+He>ve.baselineEstimate&&ve!=null)c.record("validation","repair-skipped",{reason:"repairing would cost more than not using the layer at all; the\
|
|
1245
|
+
invalid answer is served as-is and reported as invalid",errors:O.errors,baselineUsd:ve.baselineEstimate,actualUsd:ve.actual,repairEstimateUsd:He}),this.avisar("reparacion-mas-cara-que-el-baseline",`[\
|
|
1246
|
+
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 ~$${ve.baselineEstimate}, already spent ~$${ve.
|
|
1247
|
+
actual}, repair ~$${He.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\
|
|
1248
|
+
uest carrying both tools and an output contract; see the adapter warning for the cheaper shapes.`),Oe.reparacion={outcome:"skipped",skipReason:"would_cost_more_than_no_layer"};else {s.retries=1,c.record(
|
|
1249
|
+
"validation","repair-attempt",{errors:O.errors}),A=await this.llamarProveedor({model:Ee,messages:se,schema:I,...n.response?.maxOutputTokens!=null?{maxOutputTokens:n.response.maxOutputTokens}:{}},e),Ms=
|
|
1250
|
+
A.usage,s.actualLlm+=1,s.actualInput+=A.usage.inputTokens,s.actualOutput+=A.usage.outputTokens,s.repairOutput+=A.usage.outputTokens,s.repairInput+=A.usage.inputTokens,s.sentInputLocal+=W,fe=A.text;let K=ze(
|
|
1251
|
+
fe);O=K.ok?pe(K.value,I):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},K.ok&&(On=K.value,K.rescatado!=null&&O.valid&&(fe=K.rescatado)),Oe.reparacion={outcome:O.valid?"repaired":"still_invali\
|
|
1252
|
+
d"};}}else P.ok&&(On=P.value);kt=O.valid,!O.valid&&Oe.reparacion===void 0&&(Oe.reparacion={outcome:"skipped",skipReason:"decode_time_constraint"}),Oe.validacion={resultado:O.valid?"passed":"failed",errores:O.
|
|
1253
|
+
errors.length,desenvuelto:N},c.record("validation",kt?"valid":"invalid");}let ed=this.now()-ae,td=Um(On),xt={text:fe,data:On,rendered:td,storedAtMs:this.now()},Ve=this.informeDeDiferido(i,A,Ee,As),ut=this.
|
|
1254
|
+
informeDeEscrituras(i,Wl,Ae,Jl,d.modeloServido,L.marcar,L.explicitaPorColocador);ut&&c.record("cache-writes",ut.mode,{breakpoints:ut.breakpoints,...ut.avoidedWritePremium?{avoidedWritePremium:ut.avoidedWritePremium.
|
|
1255
|
+
amount,basis:"estimated"}:{},creditedLedger:"none",reason:ut.reason}),Ve&&c.record("deferred-tier",Ve.credited?"credited":"not-credited",{...Ve.requestedTier?{requestedTier:Ve.requestedTier}:{},...Ve.
|
|
1256
|
+
servedTier?{servedTier:Ve.servedTier}:{},creditedLedger:"none",reason:Ve.reason});let nd=ce.aplicado,js=A.finishReason==="length",mo=A.replayable===false,Ns=A.finishReason==="content_filter",wt=kt!==false&&
|
|
1257
|
+
!Wt&&!nd&&!js&&!mo&&!Ns,$s=this.generateId(),me;try{me=rl({contadorSimulado:Ko(this.config.provider),origen:Yl,usoPrimario:Kl,usoReparacion:Ms,tierServido:Gl,eliminatedInput:s.eliminatedInput,compressedInput:s.
|
|
1258
|
+
compressedInput,elididoLocal:s.elididoLocal,sentLocalSinSondeo:Ql,baselineInput:l,codebookAplicado:M?.applied===!0,tokensDelSondeo:ce.tokensLocalesDelSondeo,sondeoAplicado:ce.aplicado,busquedaNativa:b!==
|
|
1259
|
+
null,hayEsquema:I!=null,esquemaNativo:Zl,esquemaEnFormatoNativo:An?.esquemaEnFormatoNativo===!0&&j===I,esquemaEstricto:An?.esquemaEstricto===!0,esquemaPorPrompt:An?.esquemaPorPrompt===!0,piezasDelAdaptador:An?.
|
|
1260
|
+
piezasDelAdaptador??0,modeloPedido:n.model,modeloServido:Ee,cacheable:wt,mensajesDeLaCapa:w.length-n.messages.length,requestId:$s,at:this.now(),textoServido:fe,huella:()=>fs(n)});}catch{me="fingerprint\
|
|
1261
|
+
-failed";}let Bs=wt&&o.allowExactCache&&i.exactCache!==false;typeof me=="object"?c.record("reference","written",{inputTokens:me.inputTokens,outputTokens:me.outputTokens,layerInsertions:me.layerInsertions,
|
|
1262
|
+
...me.reasoningTokens!==void 0?{reasoningTokens:me.reasoningTokens}:{},exactCache:Bs}):c.record("reference","not-written",{reason:me});try{wt||c.record("cache-write",Wt?"skipped: tool-call turn (an ac\
|
|
1263
|
+
tion request must not be replayed from cache)":kt===!1?"skipped: response fails its output contract":js?'skipped: answer cut off by the output cap (finish_reason "length"); replaying half an answer wo\
|
|
1264
|
+
uld bill it as a 100% avoided call':mo?"skipped: the provider answer carries content this layer cannot replay":Ns?'skipped: the provider refused (stop_reason "refusal" / finish_reason "content_filter"\
|
|
1265
|
+
); a refusal is not an answer, and replaying it would credit an avoided call the provider may not have billed':"skipped: answered with a reduced tool view (tool discovery), so it must not be replayed");
|
|
1266
|
+
let P=ct?Ro(r,{servedModel:Ee}):u;if(Bs){let N=this.config.exactCacheTtlMs??864e5,H=o.maxCacheAgeMs==null?N:Math.min(N,o.maxCacheAgeMs);await this.deps.exactCache.set(P,typeof me=="object"?{...xt,meta:{
|
|
1267
|
+
...xt.meta??{},reference:{...me,cacheKey:P}}}:xt,H);}let O=Ee!==n.model;wt&&!O&&o.allowSemanticCache&&i.semanticCache&&this.deps.semanticCache?await this.deps.semanticCache.store(r,xt):wt&&O&&i.semanticCache&&
|
|
1268
|
+
c.record("cache-write","semantic write skipped: a cheaper model answered, and this cache keys on the model the caller asked for"),g&&this.deps.semanticCache&&(wt&&!O&&o.allowSemanticCache&&i.semanticCache?
|
|
1269
|
+
(c.record("semantic-calibration","label requested",{reason:g.reason,score:g.score}),this.deps.semanticCache.observe(g,xt)):c.record("semantic-calibration","no label: the cache would not store this ans\
|
|
1270
|
+
wer"));}catch(P){c.record("cache-write","failed (non-fatal; answer already served)",{error:P instanceof Error?P.message:String(P)});}s.callsWithoutUsage=e.sinContador;let Jt=this.finish(n,r,xt,"miss",s,
|
|
1271
|
+
Ht,c,v,T,void 0,void 0,kt,B.backend,ed,this.informeDeCascada(d,{servedModel:Ee,...d.enruta?{escalated:ct}:{},...d.elegible&&d.precioBarato?{estimatedSwapSaving:Jm(s,ct,d.precioBarato,this.costModelFor(
|
|
1272
|
+
n.model,h))}:{},...yt?{sampled:true,sampleCost:gt(yt.coste),...yt.divergio!==null?{divergedOnSample:yt.divergio}:{}}:{},...s.cascadeInput>0||s.cascadeOutput>0?{cascadeInputTokens:s.cascadeInput,cascadeOutputTokens:s.
|
|
1273
|
+
cascadeOutput}:{}}),Ve,$s,ut,{...Oe,final:{...A.finishReason!==void 0?{finishReason:A.finishReason}:{},...n.response?.maxOutputTokens!=null?{topeDelLlamante:n.response.maxOutputTokens}:{}}});return typeof me==
|
|
1274
|
+
"object"&&this.referenciasDeLider.set(Jt,me),mo&&this.noReproducibles.add(Jt),Wt&&(Jt.toolCalls=A.toolCalls),A.finishReason!==void 0&&(Jt.finishReason=A.finishReason),Jt}planearBusquedaNativa(e,n,r,o,i,s,a){
|
|
1275
|
+
let c=$o(n.toolSearch),u=e.tools??[];if(c.modo==="off"||u.length===0)return null;let l=ba(u,r==="TOOL_ACTION",o),d=ga({opciones:c,capacidad:ni(this.config.provider),modelo:i.modeloServido,herramientas:l.
|
|
1276
|
+
map(g=>({id:g.id,tokens:this.tokensFor(Yr(g),e)})),hayContrato:e.response?.schema!=null,cascadaActiva:i.modo!=="off",precio:s,lecturaDeCache:this.lecturaDeCacheDe(i.modeloServido,s)});if(a.record("too\
|
|
1277
|
+
l-search",d.aplicar?"native":"selector",{mode:c.modo,variant:d.variante,reason:d.razon,deferred:d.diferidas,deferredTokens:d.tokensDiferidos,alwaysLoaded:d.siempreCargadas,...d.ahorroDelPrefijo!=null?
|
|
1278
|
+
{prefixSavingPerRequest:d.ahorroDelPrefijo}:{},...d.costeDeUnaBusqueda!=null?{worstCaseSearchCost:d.costeDeUnaBusqueda}:{}}),!d.aplicar)return null;let p=new Set(l.map(g=>g.id)),h=new Set(d.siempreCargadas),
|
|
1279
|
+
m=c.siempreCargadas.filter(g=>u.some(f=>f.id===g));return {seleccion:{tools:l,droppedIds:u.filter(g=>!p.has(g.id)).map(g=>g.id),reason:d.razon,setIsStable:m.every(g=>p.has(g))},prefijo:l.filter(g=>h.has(
|
|
1280
|
+
g.id)),plan:{variant:d.variante,alwaysLoaded:d.siempreCargadas}}}lecturaDeCacheDe(e,n){let r=hs(e,this.config.compressionEconomics)?.cacheReadMultiplier??1,o=n.cachedInputPer1k!=null&&n.inputPer1k>0?n.
|
|
1281
|
+
cachedInputPer1k/n.inputPer1k:void 0;return o!=null?Math.min(o,r):r}sinDescubrimientoPorBusquedaNativa(e,n,r){return e.toolDiscovery===true&&r.record("tool-discovery","skipped (native tool search applie\
|
|
1282
|
+
s)",{reason:"the provider's tool search already keeps unused schemas out of the prompt, with no second call and without moving the cached prefix"}),{tools:n,tokensLocalesDelSondeo:0,aplicado:false}}avisarDeCatalogoRecortado(e,n,r){
|
|
1283
|
+
let o=e.tools??[];n.droppedIds.length===0||!sn(o)||ni(this.config.provider)===void 0||!No(r)||this.avisar("catalogo-recortado-con-busqueda-nativa",`[bv-sala] Your tool catalogue declares no \`intents\` \
|
|
1284
|
+
or \`risk\`, so the tool selector has nothing to select on and sent only the first ${n.tools.length} of ${o.length} tools: the model cannot call the others. This provider and model support native tool\
|
|
1285
|
+
search: \`savings: { toolSearch: "auto" }\` sends all of them deferred and lets the model 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){
|
|
1286
|
+
let u={tools:o,tokensLocalesDelSondeo:0,aplicado:false};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=f=>this.
|
|
1287
|
+
tokensFor(Yr(f),n),d=o.map(Xu),p=Qu({promptTokens:this.tokensFor(this.assemblePromptText(i),n),esquemasCompletos:o.reduce((f,v)=>f+l(v),0),descriptoresLigeros:d.reduce((f,v)=>f+l(v),0),esquemasDeLaSegunda:tl(
|
|
1288
|
+
o.map(f=>({risk:f.risk,tokens:l(f)})),3),salidaFinal:n.response?.maxOutputTokens??256,salidaDelSondeo:96,precio:a});if(!p.aplicar)return c.record("tool-discovery","skipped (not worth a second call)",{
|
|
1289
|
+
reason:p.razon,oneCall:p.costeDeUnaLlamada,twoCalls:p.costeDeDosLlamadas}),u;let h,m=this.tokensFor(this.assemblePromptText(i,d),n);try{h=await this.llamarProveedor({model:n.model,messages:i,tools:d,maxOutputTokens:96,
|
|
1290
|
+
...n.temperature!=null?{temperature:n.temperature}:{},...n.seed!=null?{seed:n.seed}:{}},e);}catch(f){return c.record("tool-discovery","failed (falling back to a single call with every schema)",{error:f instanceof
|
|
1291
|
+
Error?f.message:String(f)}),u}s.actualLlm+=1,s.actualInput+=h.usage.inputTokens,s.actualOutput+=h.usage.outputTokens,s.discoveryInput+=h.usage.inputTokens,s.discoveryOutput+=h.usage.outputTokens;let g=el(
|
|
1292
|
+
(h.toolCalls??[]).map(f=>f.name),o,3);return g.reconocidos.length===0?(c.record("tool-discovery","degraded: probe named no known tool",{finishReason:h.finishReason??null,...g.ignorados.length?{unknownNames:g.
|
|
1293
|
+
ignorados}:{}}),{tools:o,tokensLocalesDelSondeo:m,aplicado:false}):(c.record("tool-discovery","applied (two provider calls)",{chosen:g.reconocidos,sent:g.tools.map(f=>f.id),candidates:o.length,...g.ignorados.
|
|
1294
|
+
length?{unknownNames:g.ignorados}:{}}),{tools:g.tools,tokensLocalesDelSondeo:m,aplicado:true})}informeDeCascada(e,n={}){if(e.modo!=="off")return {mode:e.modo,servedModel:n.servedModel??e.modeloServido,eligible:e.
|
|
1295
|
+
elegible,reason:e.razon,verifier:e.fuerza,creditedLedger:"none",...e.candidato?{candidateModel:e.candidato}:{},...e.economia?{costRatio:Sn(e.economia.r),breakEvenEscalationRate:Sn(e.economia.equilibrio),
|
|
1296
|
+
targetEscalationRate:Sn(e.economia.escaladoMaximo)}:{},...e.bucket?{workload:e.bucket}:{},...e.observada!=null?{escalationRate:Sn(e.observada),escalationSamples:e.muestras}:{},...n,requestedModel:e.modeloPedido}}informeDeDiferido(e,n,r,o=false){
|
|
1297
|
+
if(e.deferrable!==true)return;let i=cr(n),s=i?.origen??null,a=n.servedServiceTier;if(o)return {...dt(this.config.provider)!==void 0?{requestedTier:Pt}:{},...a?{servedTier:a}:{},credited:false,capacityFallback:true,
|
|
1298
|
+
creditedLedger:"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:'\
|
|
1299
|
+
the cheaper 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\
|
|
1300
|
+
not counted as a call and nothing is credited'};let c=n.requestedServiceTier,u={...c?{requestedTier:c}:{},...a?{servedTier:a}:{},credited:false,creditedLedger:"none",latency:qa(c,s),reason:""};if(!c)return {
|
|
1301
|
+
...u,reason:za};let l=this.precioDelCliente(r),d=ir({modelo:r,uso:n.usage,tierServido:a,origen:s,...i?.tierLeidoDe?{tierLeidoDe:i.tierLeidoDe}:{},...l?{precioDelCliente:l}:{},ahoraMs:this.now()});if(!d.
|
|
1302
|
+
ok){let p=d.motivo==="no-tier-price"&&s==="openai"&&Fa(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\
|
|
1303
|
+
()":"";return {...u,reason:Wm(d.motivo,c,a)+p}}return {...u,credited:true,discountRate:Sn(d.factorEfectivo),estimatedTierSaving:d.importe,tierSaving:{amount:d.importe,basis:d.basis,standardCost:gt(d.costeEstandar),
|
|
1304
|
+
appliedCost:gt(d.costeAplicado),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}\
|
|
1305
|
+
" published rate cards, component 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){
|
|
1306
|
+
if(e.standalone!==true&&!a)return;let c=n?.cacheExplicita;if(!c){let f=dt(this.config.provider),v="the provider chose where to write its prompt cache, as it does by default";return {mode:"provider-defaul\
|
|
1307
|
+
t",breakpoints:0,reason:lt(i,"openai")?f===void 0?`this provider is not one of this package's adapters, so nothing attests explicit prompt-cache control on it: ${v}`:f!=="openai"?`explicit prompt-cach\
|
|
1308
|
+
e control only exists on OpenAI's own API, and this endpoint is not it: ${v}`:`model "${i}" has no list price of its own here, so the layer cannot tell whether writing its prefix pays: ${v}`:`model "${i}\
|
|
1309
|
+
" is not an OpenAI model that bills prompt-cache writes above the input rate, so there was no write premium to avoid: ${v}`}}let u=c.puntos,l=(a?`Chosen by cacheBreakpoints: "auto" because continuatio\
|
|
1310
|
+
ns of this traffic within 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 th\
|
|
1311
|
+
e cache reads the provider 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 t\
|
|
1312
|
+
he input rate with no cache-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 w\
|
|
1313
|
+
orth writing, or the measured 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,p=o?ln("openai",o,i,this.now()):void 0,
|
|
1314
|
+
h=nr(i),m=p&&p.cacheWritePer1k!==void 0?{inputPer1k:p.inputPer1k,cacheWritePer1k:p.cacheWritePer1k,consultado:p.consultado}:h?{inputPer1k:h.inputPer1k,cacheWritePer1k:h.cacheWritePer1k,consultado:void 0}:
|
|
1315
|
+
void 0;if(!m||r.complete===false)return {mode:"explicit",breakpoints:u,reason:d};let g=Ua({uso:r,fila:{inputPer1k:m.inputPer1k,cacheWritePer1k:m.cacheWritePer1k},...m.consultado?{consultado:m.consultado}:
|
|
1316
|
+
{}});return {mode:"explicit",breakpoints:u,avoidedWritePremium:{amount:g.importe,basis:"estimated",standardCost:gt(g.costeEstandar),appliedCost:gt(g.costeAplicado),pricesCheckedOn:g.consultado,basisReason:g.
|
|
1317
|
+
tokensOrdinarios>0&&r.inputTokens>=1024?"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;\
|
|
1318
|
+
it does not subtract the cache reads the default could have given a later repeat":"estimated: below the provider's minimum cacheable length (or with nothing written past the breakpoint) the default w\
|
|
1319
|
+
ould not have charged a write premium either"},reason:d}}escriturasSinLlamada(e){if(e.savings?.standalone===true)return {mode:"provider-default",breakpoints:0,reason:"no provider call was made, so nothin\
|
|
1320
|
+
g was written to or read from the provider's prompt cache for this request"}}respaldaFaltaDeCapacidad(e,n,r){return e.deferrable!==true||r!==null||this.config.priceLevers?.onCapacityError!=="standard"||
|
|
1321
|
+
dt(this.config.provider)===void 0?false:n instanceof Error&&/^provider (429|503)\b/.test(n.message)}diferidoSinLlamada(e){if(e.savings?.deferrable===true)return {credited:false,creditedLedger:"none",latency:"n\
|
|
1322
|
+
ot applicable: no provider call was made for this request.",reason:"no provider call was made, so no processing tier was served and none is credited; the call was avoided outright, which is worth more\
|
|
1323
|
+
than any tier discount on it"}}finish(e,n,r,o,i,s,a,c,u,l,d,p,h="none",m=0,g,f,v,b,y){let k=e.response?.schema,T,w=p===null?null:p??(k?(()=>{let C=pe(r.data,k);return T={resultado:C.valid?"passed":"f\
|
|
1324
|
+
ailed",errores:C.errors.length,desenvuelto:false},C.valid})():true),S=T&&!y?.validacion?{...y,validacion:T}:y,x=this.buildReport(e,n,o,i,s,a,c,u,l,d,w,h,m,g,f??this.diferidoSinLlamada(e),v,b??this.escriturasSinLlamada(
|
|
1325
|
+
e),S);return {requestId:x.requestId,data:r.data,text:r.text,...r.rendered!==void 0?{rendered:r.rendered}:{},report:x}}buildReport(e,n,r,o,i,s,a,c,u,l,d,p,h,m,g,f,v,b){let y=o.estimateCost(i),k=s.elapsed(),
|
|
1326
|
+
T=m!=null&&m.servedModel!==m.requestedModel;return {requestId:f??this.generateId(),model:m?.servedModel??e.model,calls:{baselineLlm:o.baselineLlm,actualLlm:o.actualLlm,avoidedLlm:o.avoidedLlm,baselineRetrieval:o.
|
|
1327
|
+
baselineRetrieval,actualRetrieval:o.actualRetrieval,baselineTools:o.baselineTools,actualTools:o.actualTools,retries:o.retries},tokens:{baselineInput:o.baselineInput,actualInput:o.actualInput,eliminatedInput:o.
|
|
1328
|
+
eliminatedInput,compressedInput:o.compressedInput,baselineOutput:o.publishedBaselineOutput,actualOutput:o.actualOutput,eliminatedOutput:o.eliminatedOutput,...o.providerCachedInput?{providerCachedInput:o.
|
|
1329
|
+
providerCachedInput}:{}},cache:{result:r,...l!==void 0?{confidence:l}:{},...u!==void 0?{ageMs:u}:{},...o.reference?{reference:{...o.reference}}:{},...o.referenceRejected?{referenceRejected:o.referenceRejected}:
|
|
1330
|
+
{}},routing:{executionClass:a.executionClass,confidence:a.confidence,rounds:o.actualRetrieval,reason:a.reason},serialization:{chosen:c.chosen,candidateTokens:c.candidateTokens,instructionOverheadTokens:c.
|
|
1331
|
+
instructionOverheadTokens},...o.compressionReport?{compression:o.compressionReport}:{},constraints:{backend:p,schemaVersion:n.schemaVersion,...d===null?{}:{structurallyValid:d}},qualityStatus:Hm(r,d,T),
|
|
1332
|
+
qualityLedger:sl({cacheResult:r,structurallyValid:d,backend:p,hayEsquema:e.response?.schema!=null,ageMs:u,cascada:m,hechos:b}),...m?{modelCascade:m}:{},...g?{deferred:g}:{},...v?{cacheWrites:v}:{},quality:{
|
|
1333
|
+
...r!=="miss"?{freshnessPassed:!Bn(n).requiresFreshData}:{},...r==="semantic"&&b?.semantico?{semanticScore:b.semantico.similarity}:{}},cost:y,latencyMs:{total:k,preprocessing:Math.max(0,k-h),provider:h},
|
|
1334
|
+
traces:s.all()}}async failOpenDirect(e,n){let r=new fn(this.now);r.record("fail-open","internal optimizer error \u2014 bypassed to a direct provider call",{error:n instanceof Error?n.message:String(n)});
|
|
1335
|
+
let o=new Ct,i=this.costModelFor(e.model),s;try{s=Po(e);}catch{s={schemaVersion:e.response?.version??e.response?.contractId??"none"};}let a=e.response?.schema,c=[...e.messages];e.structuredData!==void 0&&
|
|
1336
|
+
Pn(c,{role:"system",content:JSON.stringify(e.structuredData)});let u=this.now(),l=await this.config.provider.generate({model:e.model,messages:c,...e.tools?.length?{tools:e.tools}:{},...a?{schema:a}:{},
|
|
1337
|
+
...e.response?.maxOutputTokens!=null?{maxOutputTokens:e.response.maxOutputTokens}:{},...e.temperature!=null?{temperature:e.temperature}:{},...e.seed!=null?{seed:e.seed}:{}}),d=this.now()-u;o.baselineLlm=
|
|
1338
|
+
1,o.actualLlm=1,o.actualInput=l.usage.inputTokens,o.actualOutput=l.usage.outputTokens,o.baselineInput=l.usage.inputTokens,o.baselineOutput=l.usage.outputTokens,l.usage.cachedInputTokens&&o.providerCached(
|
|
1339
|
+
l.usage.cachedInputTokens);let p=cn(e.model);p>1&&(l.usage.cacheWriteInputTokens??0)>0&&o.providerCacheWritePremium(l.usage.cacheWriteInputTokens??0,p,i),l.usage.complete===false&&(o.callsWithoutUsage=1);
|
|
1340
|
+
let h=l.text,m=true,g={origen:"fail_open",final:{...l.finishReason!==void 0?{finishReason:l.finishReason}:{},...e.response?.maxOutputTokens!=null?{topeDelLlamante:e.response.maxOutputTokens}:{}}},f=(l.toolCalls?.
|
|
1341
|
+
length??0)>0;if(f&&(m=null),a&&!f){let b=ze(l.text),y=b.ok?pe(b.value,a).errors.length:1;m=y===0,g.validacion={resultado:m?"passed":"failed",errores:y,desenvuelto:false},b.ok&&(h=b.value);}let v=this.buildReport(
|
|
1342
|
+
e,s,"miss",o,i,r,Tn(),Cn(),void 0,void 0,m,"none",d,void 0,e.savings?.deferrable===true?{credited:false,creditedLedger:"none",latency:"unchanged: the fail-open path asks for no processing tier, so this req\
|
|
1343
|
+
uest was scheduled exactly as an ordinary one.",reason:"the optimizer failed and this request went out on the direct fail-open path, which asks for no cheaper tier: that tier can be refused for lack o\
|
|
1344
|
+
f capacity, and trading availability for a discount on a last-resort call is the wrong trade"}:void 0,void 0,e.savings?.standalone===true?{mode:"provider-default",breakpoints:0,reason:"the optimizer fai\
|
|
1345
|
+
led and this request went out unchanged on the direct fail-open path, so the provider chose where to write its prompt cache, as it does by default"}:void 0,g);return {requestId:v.requestId,data:h,text:l.
|
|
1346
|
+
text,...f?{toolCalls:l.toolCalls}:{},...l.finishReason!==void 0?{finishReason:l.finishReason}:{},report:v}}asCoalescedFollower(e,n,r,o,i,s={ok:false,reason:"absent"}){let a=new Ct;s.ok?a.avoidCallByReference(
|
|
1347
|
+
s.credit):(a.avoidCall(n,r),a.referenceRejected=s.reason);let c=a.estimateCost(o),u=this.generateId(),l=this.diferidoSinLlamada(i),d=l?{deferred:l}:{},p=this.escriturasSinLlamada(i),{deferred:h,streaming:m,
|
|
1348
|
+
cacheWrites:g,...f}=e.report;return {...e,requestId:u,report:{...f,requestId:u,calls:{...e.report.calls,actualLlm:0,avoidedLlm:1},tokens:{baselineInput:a.baselineInput,actualInput:a.actualInput,eliminatedInput:a.
|
|
1349
|
+
eliminatedInput,compressedInput:a.compressedInput,baselineOutput:a.publishedBaselineOutput,actualOutput:a.actualOutput,eliminatedOutput:a.eliminatedOutput,...a.providerCachedInput?{providerCachedInput:a.
|
|
1350
|
+
providerCachedInput}:{}},cache:{result:"singleflight",...a.reference?{reference:{...a.reference}}:a.referenceRejected?{referenceRejected:a.referenceRejected}:{}},...d,...p?{cacheWrites:p}:{},qualityLedger:al(
|
|
1351
|
+
e.report.qualityLedger),cost:c}}}creditoPorReferencia(e,n){if(typeof e=="string")return {ok:false,reason:e};let r;try{r=n.calidad();}catch{r=false;}try{return il(e,{ahoraMs:this.now(),modeloPedido:n.request.model,
|
|
1352
|
+
modeloServido:n.cascada.modeloServido,huella:n.huella(),textoServidoSha256:te(n.texto),claveLeida:n.claveLeida,calidadOk:r,precio:this.precioDocumentado(n.request.model),determinista:nl(n.request),salidaDelModelo:Tu(
|
|
1353
|
+
n.request.model),topeDeSalida:n.request.response?.maxOutputTokens,diferible:n.toggles.deferrable===!0})}catch{return {ok:false,reason:"different-request"}}}assembleBaselinePrompt(e){return this.assemblePromptText(
|
|
1354
|
+
e.messages,e.tools,e.structuredData)}assemblePromptText(e,n,r){let o=e.map(i=>i.content);r!==void 0&&o.push(JSON.stringify(r));for(let i of n??[])o.push(Yr(i));return o.join(`
|
|
1255
1355
|
`)}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;
|
|
1256
1356
|
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(
|
|
1257
|
-
e)}precioConocido(e,n=this.now()){return this.precioDelCliente(e)??
|
|
1258
|
-
slice(o+1)];if(i)return i}}precioDocumentado(e){return this.precioDelCliente(e)??
|
|
1357
|
+
e)}precioConocido(e,n=this.now()){return this.precioDelCliente(e)??Ln(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.
|
|
1358
|
+
slice(o+1)];if(i)return i}}precioDocumentado(e){return this.precioDelCliente(e)??We(e,this.now())}costModelFor(e,n=this.now()){let r=this.precioConocido(e,n);return r||(this.config.defaultCostModel?this.
|
|
1259
1359
|
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. \
|
|
1260
|
-
Pass { costModels: { "${e}": { inputPer1k, outputPer1k } } }.`),
|
|
1261
|
-
n.value,t.schema).valid?"met":"missed"}function
|
|
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=
|
|
1263
|
-
e.push(i);}return e}function
|
|
1264
|
-
n)o+=1;else if(c===r&&(o-=1,o===0))return t.slice(e,a+1)}}function
|
|
1265
|
-
dation";switch(t){case "deterministic":case "exact":return "exact";case "semantic":return "task_equivalent";default:return "not_verified"}}function
|
|
1360
|
+
Pass { costModels: { "${e}": { inputPer1k, outputPer1k } } }.`),wu))}};function zm(t,e){if((e.toolCalls?.length??0)>0||!t.schema)return "none";let n=ze(typeof e.text=="string"?e.text:"");return n.ok&&pe(
|
|
1361
|
+
n.value,t.schema).valid?"met":"missed"}function ze(t){try{return {ok:!0,value:JSON.parse(t)}}catch{}for(let e of qm(t))try{return {ok:!0,value:JSON.parse(e),rescatado:e}}catch{continue}return {ok:false}}function qm(t){
|
|
1362
|
+
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=Vm(t,o);i&&
|
|
1363
|
+
e.push(i);}return e}function Vm(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===
|
|
1364
|
+
n)o+=1;else if(c===r&&(o-=1,o===0))return t.slice(e,a+1)}}function Um(t){return typeof t=="string"?t:JSON.stringify(t,null,2)}function Hm(t,e,n=false){if(e===false)return "rejected";if(n)return "bounded_degra\
|
|
1365
|
+
dation";switch(t){case "deterministic":case "exact":return "exact";case "semantic":return "task_equivalent";default:return "not_verified"}}function Wm(t,e,n){switch(t){case "no-served-tier":return `asked the \
|
|
1266
1366
|
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\
|
|
1267
1367
|
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\
|
|
1268
1368
|
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\
|
|
1269
1369
|
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\
|
|
1270
1370
|
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\
|
|
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
|
|
1272
|
-
round(t*1e6)/1e6}function
|
|
1273
|
-
return
|
|
1274
|
-
return false;let n=t.original;return
|
|
1275
|
-
reason:"n/a (short-circuited)",rounds:0}}function
|
|
1276
|
-
if(t==null||typeof t!="object")return "";let r=t,o=[],i=e||"the value",s=
|
|
1277
|
-
if(a!=null){let
|
|
1278
|
-
null&&o.push(`${i}>=${
|
|
1279
|
-
|
|
1280
|
-
0,200):""}function
|
|
1281
|
-
{type:"function",function:{name:t.id,...t.description?{description:t.description}:{},parameters:t.parameters??{type:"object",properties:{}}}})}function
|
|
1282
|
-
"user"){t.splice(n,0,e);return}t.push(e);}function
|
|
1283
|
-
role==="system";)n+=1;return n}for(let n=t.length-1;n>=0;n--)if(t[n].role==="user")return n;return
|
|
1284
|
-
|
|
1371
|
+
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 Sn(t){return Math.
|
|
1372
|
+
round(t*1e6)/1e6}function gt(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}function Jm(t,e,n,r){if(e)return gt(-t.extraCostUsd);let o=i=>t.actualInput/1e3*i.inputPer1k+t.actualOutput/1e3*i.outputPer1k;
|
|
1373
|
+
return gt(o(r)-o(n))}function Km(t,e){if(!(e>0))return false;if(e>=1)return true;let n=te(`${t}:cascade-sample`);return Number.parseInt(n.slice(0,13),16)/2**52<e}function kl(t,e){if(!e.isAgentic||e.allowSemanticCache)
|
|
1374
|
+
return false;let n=t.original;return Bn({...t,original:{...n,savings:{...n.savings??{},semanticCache:"include-agentic"}}}).allowSemanticCache}function Tn(){return {executionClass:"NO_RETRIEVAL",confidence:1,
|
|
1375
|
+
reason:"n/a (short-circuited)",rounds:0}}function Cn(){return {chosen:"json-compact",encoded:"",instruction:"",candidateTokens:{},instructionOverheadTokens:0,reason:"no structured payload"}}function gs(t,e="",n=null){
|
|
1376
|
+
if(t==null||typeof t!="object")return "";let r=t,o=[],i=e||"the value",s=m=>typeof r[m]=="number"?r[m]:null,a=s("maxLength"),c=s("minLength"),u=s("maxItems"),l=s("minItems"),d=s("maximum"),p=s("minimum");
|
|
1377
|
+
if(a!=null){let m=n!=null?Math.min(a,n):a;o.push(`${i}<=${m}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}`),p!=
|
|
1378
|
+
null&&o.push(`${i}>=${p}`),typeof r.pattern=="string"&&o.push(`${i} matches /${r.pattern}/`);let h=r.properties;if(h&&typeof h=="object")for(let[m,g]of Object.entries(h)){let f=gs(g,e?`${e}.${m}`:m,n);
|
|
1379
|
+
f&&o.push(f);}if(r.items!==void 0){let m=gs(r.items,`${i} entries`,n);m&&o.push(m);}return o.join("; ")}function En(t){let e=t.response;return e?e.contractId??e.version??JSON.stringify(e.schema??{}).slice(
|
|
1380
|
+
0,200):""}function Gm(t){return t.some(e=>/exceeds maxItems|exceeds maxLength|match pattern|exceeds maximum|below minimum|below minLength|below minItems/.test(e.message))}function Yr(t){return JSON.stringify(
|
|
1381
|
+
{type:"function",function:{name:t.id,...t.description?{description:t.description}:{},parameters:t.parameters??{type:"object",properties:{}}}})}function Pn(t,e){for(let n=t.length-1;n>=0;n--)if(t[n].role===
|
|
1382
|
+
"user"){t.splice(n,0,e);return}t.push(e);}function Zm(t,e){if(e===false)return null;let n=typeof t=="object"&&t!==null?t:{};return e===true||t?n:null}function bs(t,e=false){if(e){let n=0;for(;n<t.length&&t[n].
|
|
1383
|
+
role==="system";)n+=1;return n}for(let n=t.length-1;n>=0;n--)if(t[n].role==="user")return n;return bs(t,true)}function xl(t){return t instanceof Error?t.name:typeof t}function hs(t,e){let n=Jr(t,e);return n.
|
|
1384
|
+
cacheReadMultiplier<1?n:null}var Cl={anthropic:{peticiones:1e5,bytes:256e6},openai:{peticiones:5e4,bytes:2e8}},Ym=/^[A-Za-z0-9_-]{1,64}$/,El="/v1/chat/completions",Qm=new Set(["completed","failed","expired","cancelled"]);function Pl(t){
|
|
1385
|
+
return {submit:(e,n)=>Xm(t,e,n??{}),status:(e,n)=>sh(t,e,n?.signal),results:(e,n)=>lh(t,e,n?.signal),cancel:(e,n)=>uh(t,e,n?.signal)}}function no(t){let e=oc(t.provider);if(!e)throw new Error("[bvsala]\
|
|
1285
1386
|
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
1387
|
"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
|
|
1288
|
-
anthropic",s=new TextEncoder,a=e.map(({customId:
|
|
1289
|
-
params:
|
|
1290
|
-
l=new Map,d=new Map;c.forEach((
|
|
1291
|
-
u.push(
|
|
1292
|
-
t.now()).toISOString(),requests:
|
|
1293
|
-
length,
|
|
1294
|
-
provider batch was created: ${
|
|
1295
|
-
.`,
|
|
1296
|
-
n,r]of t.entries()){let o=r?.customId;if(typeof o!="string"||!
|
|
1388
|
+
ini's own Files API). Nothing was sent.");return e}async function Xm(t,e,n){t.exigirLicencia();let r=no(t);eh(e);let o=th(n.maxRequestsPerBatch,r.protocolo),i=n.cacheSharedPrefix===true&&r.protocolo==="\
|
|
1389
|
+
anthropic",s=new TextEncoder,a=e.map(({customId:m,request:g})=>{let f;try{f=r.cuerpo(nh(g,i));}catch(y){throw new TypeError(`[bvsala] batch request "${m}": ${Xr(y)}`)}let v=r.protocolo==="anthropic"?{custom_id:m,
|
|
1390
|
+
params:f}:{custom_id:m,method:"POST",url:El,body:f},b=JSON.stringify(v);return {customId:m,linea:v,bytes:s.encode(b).length,modelo:typeof f.model=="string"?f.model:g.model}}),c=rh(a,r.protocolo,o),u=[],
|
|
1391
|
+
l=new Map,d=new Map;c.forEach((m,g)=>m.forEach(f=>d.set(f.customId,g)));let p=e.map(({customId:m,request:g})=>{let f=g.response?.schema,v;if(f){let b=JSON.stringify(f);v=l.get(b),v===void 0&&(v=u.length,
|
|
1392
|
+
u.push(f),l.set(b,v));}return {customId:m,model:g.model,batch:d.get(m),...v!==void 0?{schema:v}:{}}}),h={kind:"bvsala.batch",version:1,provider:r.protocolo,endpoint:r.endpoint,batchIds:[],submittedAt:new Date(
|
|
1393
|
+
t.now()).toISOString(),requests:p,schemas:u};for(let m=0;m<c.length;m++)try{let g=r.protocolo==="anthropic"?await oh(r,c[m],n.signal):await ih(r,c[m],n.signal);h.batchIds.push(g);}catch(g){let f=h.batchIds.
|
|
1394
|
+
length,v={...h,batchIds:[...h.batchIds],requests:h.requests.filter(y=>y.batch<f)},b=h.requests.filter(y=>y.batch>=f).map(y=>y.customId);throw new Br(f===0?`[bvsala] batch submission failed before any \
|
|
1395
|
+
provider batch was created: ${Xr(g)}.`:`[bvsala] batch submission failed after ${f} of ${c.length} provider batches were created: ${Xr(g)}. The created batches run and are billed; error.job holds them\
|
|
1396
|
+
.`,v,b,{cause:g})}return h}function eh(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[
|
|
1397
|
+
n,r]of t.entries()){let o=r?.customId;if(typeof o!="string"||!Ym.test(o))throw new TypeError(`[bvsala] batch request #${n}: customId must be 1 to 64 letters, digits, "_" or "-" (got ${JSON.stringify(o)}\
|
|
1297
1398
|
).`);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
1399
|
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
1400
|
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
|
|
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
|
|
1401
|
+
batch request "${o}": structuredData is serialized by the layer's pipeline, which batches skip. Put the payload in the messages instead.`)}}function th(t,e){let n=Cl[e].peticiones;if(t===void 0)return n;
|
|
1402
|
+
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 nh(t,e){let n=0;for(;n<t.messages.length&&
|
|
1302
1403
|
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
|
|
1404
|
+
null?{maxOutputTokens:t.response.maxOutputTokens}:{},...t.temperature!=null?{temperature:t.temperature}:{},...t.seed!=null?{seed:t.seed}:{},...e&&n>0?{stablePrefixMessages:n}:{}}}function rh(t,e,n){let r=Cl[e],
|
|
1304
1405
|
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
1406
|
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
|
|
1307
|
-
r,"Message Batch")}async function
|
|
1407
|
+
(s.push(c),c=[],u=i),c.push(l),u+=d;}c.length>0&&s.push(c);}return s}async function oh(t,e,n){let r=await Rn(t,"/messages/batches",{method:"POST",json:{requests:e.map(o=>o.linea)},...n?{signal:n}:{}});return ks(
|
|
1408
|
+
r,"Message Batch")}async function ih(t,e,n){let r=e.map(a=>JSON.stringify(a.linea)).join(`
|
|
1308
1409
|
`)+`
|
|
1309
|
-
`,o=new FormData;o.append("purpose","batch"),o.append("file",new Blob([r],{type:"application/jsonl"}),"bvsala-batch.jsonl");let i=await
|
|
1310
|
-
t,"/batches",{method:"POST",json:{input_file_id:
|
|
1311
|
-
r);let o=await
|
|
1312
|
-
o).length;r.push(t.protocolo==="anthropic"?
|
|
1313
|
-
estado:r,terminado:r==="ended",cancelando:r==="canceling",cuentas:{processing:
|
|
1314
|
-
let r=
|
|
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},
|
|
1316
|
-
map(
|
|
1317
|
-
{},...typeof r.error_file_id=="string"&&r.error_file_id!==""?{errores:r.error_file_id}:{},...o==="failed"?{fallo:
|
|
1410
|
+
`,o=new FormData;o.append("purpose","batch"),o.append("file",new Blob([r],{type:"application/jsonl"}),"bvsala-batch.jsonl");let i=await Rn(t,"/files",{method:"POST",form:o,...n?{signal:n}:{}}),s=await Rn(
|
|
1411
|
+
t,"/batches",{method:"POST",json:{input_file_id:ks(i,"file"),endpoint:El,completion_window:"24h"},...n?{signal:n}:{}});return ks(s,"batch")}async function sh(t,e,n){t.exigirLicencia();let r=no(t);xs(e,
|
|
1412
|
+
r);let o=await eo(r,e,n);return Rl(e,o)}async function eo(t,e,n){let r=[];for(let[o,i]of e.batchIds.entries()){let s=await Rn(t,ws(t,i),{method:"GET",...n?{signal:n}:{}}),a=e.requests.filter(c=>c.batch===
|
|
1413
|
+
o).length;r.push(t.protocolo==="anthropic"?ah(i,s):ch(i,s,a));}return r}function ah(t,e){let n=ie(e),r=typeof n.processing_status=="string"?n.processing_status:"unknown",o=ie(n.request_counts);return {id:t,
|
|
1414
|
+
estado:r,terminado:r==="ended",cancelando:r==="canceling",cuentas:{processing:st(o.processing),succeeded:st(o.succeeded),errored:st(o.errored),canceled:st(o.canceled),expired:st(o.expired)}}}function ch(t,e,n){
|
|
1415
|
+
let r=ie(e),o=typeof r.status=="string"?r.status:"unknown",i=ie(r.request_counts),s=st(i.total)||n,a=st(i.completed),c=st(i.failed),u=Math.max(0,s-a-c),l=Qm.has(o),d=o==="failed"?{processing:0,succeeded:0,
|
|
1416
|
+
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},p=Array.isArray(ie(r.errors).data)?ie(r.errors).data.
|
|
1417
|
+
map(h=>ie(h).message).filter(h=>typeof h=="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}:
|
|
1418
|
+
{},...typeof r.error_file_id=="string"&&r.error_file_id!==""?{errores:r.error_file_id}:{},...o==="failed"?{fallo:p.length>0?p.join("; "):"the provider rejected the batch"}:{}}}function Rl(t,e){let n={
|
|
1318
1419
|
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
1420
|
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
|
|
1321
|
-
{}});return
|
|
1322
|
-
r,`${
|
|
1323
|
-
ntent`,{method:"GET",...n?{signal:n}:{}});for await(let
|
|
1324
|
-
continue}let d=u.schema!==void 0?e.schemas[u.schema]:void 0;a.push(
|
|
1325
|
-
if(typeof r!="string"||t.has(r))return;let o=
|
|
1421
|
+
estado}))}}async function uh(t,e,n){t.exigirLicencia();let r=no(t);xs(e,r);let o=await eo(r,e,n);for(let i of o)i.terminado||i.cancelando||await Rn(r,`${ws(r,i.id)}/cancel`,{method:"POST",...n?{signal:n}:
|
|
1422
|
+
{}});return Rl(e,await eo(r,e,n))}async function lh(t,e,n){t.exigirLicencia();let r=no(t);xs(e,r);let o=await eo(r,e,n),i=new Map;for(let u of o)if(u.terminado)if(r.protocolo==="anthropic"){let l=await ys(
|
|
1423
|
+
r,`${ws(r,u.id)}/results`,{method:"GET",...n?{signal:n}:{}});for await(let d of Tl(l))dh(i,d);}else for(let l of [u.salida,u.errores]){if(!l)continue;let d=await ys(r,`/files/${encodeURIComponent(l)}/co\
|
|
1424
|
+
ntent`,{method:"GET",...n?{signal:n}:{}});for await(let p of Tl(d))ph(i,p);}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;
|
|
1425
|
+
continue}let d=u.schema!==void 0?e.schemas[u.schema]:void 0;a.push(fh(t,r,u,d,i.get(u.customId),l,s));}return {ended:o.every(u=>u.terminado),items:a,summary:gh(e,a,c)}}function dh(t,e){let n=ie(e),r=n.custom_id;
|
|
1426
|
+
if(typeof r!="string"||t.has(r))return;let o=ie(n.result);switch(o.type){case "succeeded":t.set(r,{tipo:"ok",cuerpo:o.message});return;case "errored":{let i=ie(ie(o.error).error);t.set(r,{tipo:"errored",
|
|
1326
1427
|
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
|
|
1428
|
+
t.set(r,{tipo:"expired"});return;default:return}}function ph(t,e){let n=ie(e),r=n.custom_id;if(typeof r!="string"||t.has(r))return;let o=n.error;if(o!=null){let u=ie(o),l=typeof u.code=="string"?u.code:
|
|
1328
1429
|
"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=
|
|
1330
|
-
let c=
|
|
1331
|
-
rror"}});}function
|
|
1430
|
+
message=="string"?u.message:"the provider reported an error"}});return}let i=ie(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}
|
|
1431
|
+
let c=ie(ie(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\
|
|
1432
|
+
rror"}});}function fh(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
1433
|
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
1434
|
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
1435
|
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
1436
|
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
1437
|
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
1438
|
-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 (${
|
|
1339
|
-
): nothing is credited`}}let d=
|
|
1340
|
-
origen:
|
|
1341
|
-
{finishReason:l.finishReason}:{},usage:l.usage,...
|
|
1342
|
-
g.costeAplicado),pricesCheckedOn:g.consultado,basisReason:g.motivoBasis};return {...
|
|
1343
|
-
blished rate cards, component by component (${(g.factorEfectivo*100).toFixed(1)}% of standard)`}}function
|
|
1344
|
-
return n.ok?
|
|
1439
|
+
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 (${Xr(b)}\
|
|
1440
|
+
): nothing is credited`}}let d=mh(l,r),p=c?l.servedServiceTier:"batch",h=e.origen==="anthropic"||e.origen==="openai"?e.origen:null,m=bh(t.costModels,n.model),g=ir({modelo:n.model,uso:l.usage,tierServido:p,
|
|
1441
|
+
origen:h,tierLeidoDe:c?"cuerpo":"lote",...m?{precioDelCliente:m}:{},ahoraMs:s}),f={...a,outcome:"succeeded",text:l.text,...d,...l.toolCalls&&l.toolCalls.length>0?{toolCalls:l.toolCalls}:{},...l.finishReason?
|
|
1442
|
+
{finishReason:l.finishReason}:{},usage:l.usage,...p?{servedTier:p}:{}};if(!g.ok)return {...f,reason:hh(g.motivo,p)};let v={amount:g.importe,basis:g.basis,standardCost:to(g.costeEstandar),appliedCost:to(
|
|
1443
|
+
g.costeAplicado),pricesCheckedOn:g.consultado,basisReason:g.motivoBasis};return {...f,tierSaving:v,reason:`billed at the "${p}" tier; this request's usage was priced at the standard and at the batch pu\
|
|
1444
|
+
blished rate cards, component by component (${(g.factorEfectivo*100).toFixed(1)}% of standard)`}}function mh(t,e){if(!e||(t.toolCalls?.length??0)>0)return {};let n=ze(typeof t.text=="string"?t.text:"");
|
|
1445
|
+
return n.ok?pe(n.value,e).valid?{data:n.value,contract:"met"}:{contract:"missed"}:{contract:"missed"}}function hh(t,e){switch(t){case "no-served-tier":return "the provider reported no service tier for t\
|
|
1345
1446
|
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
1447
|
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
1448
|
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
1449
|
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
|
|
1350
|
-
|
|
1351
|
-
Math.round(
|
|
1352
|
-
ucceeded`+(n>0?` (${n} still running)`:"")+`; ${c} were valued at the provider's standard and batch published rate cards`+(
|
|
1450
|
+
is credited";case "no-difference":return "this result's usage costs the same at both published rate cards: nothing is credited"}}var Sl=1e10;function gh(t,e,n){let r=0,o=0,i=0,s=0,a=0,c=0,u=0,l=0n,d=0,
|
|
1451
|
+
p=0,h;for(let f of e){f.outcome==="succeeded"?r+=1:f.outcome==="errored"?o+=1:f.outcome==="canceled"?i+=1:f.outcome==="expired"?s+=1:a+=1;let v=f.tierSaving;v&&(c+=1,v.basis==="measured"&&(u+=1),l+=BigInt(
|
|
1452
|
+
Math.round(v.amount*Sl)),d+=v.standardCost,p+=v.appliedCost,(!h||v.pricesCheckedOn<h)&&(h=v.pricesCheckedOn));}let m=c===0?"none":u===c?"measured":"estimated",g=`${r} of ${t.requests.length} requests s\
|
|
1453
|
+
ucceeded`+(n>0?` (${n} still running)`:"")+`; ${c} were valued at the provider's standard and batch published rate cards`+(m==="none"?"":` (${m})`)+". Reported only: batch requests are not metered and\
|
|
1353
1454
|
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)/
|
|
1455
|
+
tierSaving:Number(l)/Sl,standardCost:to(d),appliedCost:to(p),basis:m,...h?{pricesCheckedOn:h}:{},creditedLedger:"none",reason:g}}function xs(t,e){let n=t;if(!n||n.kind!=="bvsala.batch"||n.version!==1||
|
|
1355
1456
|
!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
1457
|
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
|
|
1358
|
-
e)}`:`/batches/${encodeURIComponent(e)}`}async function
|
|
1359
|
-
async function
|
|
1458
|
+
layer's provider is ${e.protocolo} at ${e.endpoint}. Read it with a layer configured like the one that submitted it.`)}function ws(t,e){return t.protocolo==="anthropic"?`/messages/batches/${encodeURIComponent(
|
|
1459
|
+
e)}`:`/batches/${encodeURIComponent(e)}`}async function ys(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}
|
|
1460
|
+
async function Rn(t,e,n){return await(await ys(t,e,n)).json()}function ks(t,e){let n=ie(t).id;if(typeof n!="string"||n==="")throw new Error(`the provider returned no ${e} id`);return n}async function*Tl(t){
|
|
1360
1461
|
let e=t.body;if(!e||typeof e.getReader!="function"){for(let s of (await t.text()).split(`
|
|
1361
|
-
`)){let a=
|
|
1362
|
-
`);for(;c>=0;){let u=
|
|
1363
|
-
`);}}o+=r.decode();let i=
|
|
1364
|
-
"/");return r>=0?t[e.slice(r+1)]:void 0}function
|
|
1365
|
-
Error?t.message:String(t)}function
|
|
1366
|
-
e,this.pollIntervalMs=e.pollIntervalMs??
|
|
1462
|
+
`)){let a=vs(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(`
|
|
1463
|
+
`);for(;c>=0;){let u=vs(o.slice(0,c));u!==void 0&&(yield u),o=o.slice(c+1),c=o.indexOf(`
|
|
1464
|
+
`);}}o+=r.decode();let i=vs(o);i!==void 0&&(yield i);}function vs(t){let e=t.trim();if(e!=="")try{return JSON.parse(e)}catch{return}}function bh(t,e){if(!t)return;let n=t[e];if(n)return n;let r=e.indexOf(
|
|
1465
|
+
"/");return r>=0?t[e.slice(r+1)]:void 0}function ie(t){return typeof t=="object"&&t!==null?t:{}}function st(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.floor(t):0}function Xr(t){return t instanceof
|
|
1466
|
+
Error?t.message:String(t)}function to(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}var vh=36e5,yh=7*86400,kh=3e4,ro=class{opts;pollIntervalMs;refreshLeadSeconds;timer=null;enVuelo=false;parado=false;controller=null;avisadoDeCredencial=false;currentExpiresAt;currentOrg;constructor(e){this.opts=
|
|
1467
|
+
e,this.pollIntervalMs=e.pollIntervalMs??vh,this.refreshLeadSeconds=e.refreshLeadSeconds??yh;let n=Mt(Ot(e.initialToken),e.publicKey);this.currentExpiresAt=n.signatureValid&&n.payload?n.payload.expires_at:
|
|
1367
1468
|
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
1469
|
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
1470
|
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
|
-
|
|
1471
|
+
kh);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
1472
|
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
1473
|
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=
|
|
1474
|
+
will stop operating when the grace period ends.`)),!1;let i=await o.json();if(typeof i.token!="string")return !1;let s=Ot(i.token),a=Mt(s,this.opts.publicKey);return !a.signatureValid||!a.payload||a.payload.
|
|
1374
1475
|
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
|
|
1376
|
-
1e3;function
|
|
1377
|
-
er"?e.ahora:Date.now();if(t.at>n+
|
|
1378
|
-
o.outputPer1k)||o.cachedInputPer1k!==void 0&&!
|
|
1476
|
+
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 Dl=2e3,Il=200,xh=200,wh=10,Sh=1e7,Th=5,Ch=48*3600*1e3,Ss=/^[A-Za-z0-9._:/-]{1,128}$/,qt=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0,Dn=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=
|
|
1477
|
+
1e3;function Eh(t,e={}){if(!Ss.test(t.requestId)||!Ss.test(t.requestedModel)||!Ss.test(t.servedModel)||typeof t.at!="number"||!Number.isFinite(t.at)||t.at<1e12)return null;let n=typeof e?.ahora=="numb\
|
|
1478
|
+
er"?e.ahora:Date.now();if(t.at>n+Ch)return null;let r=t.optimized;if(!Dn(r.cost)||!qt(r.inputTokens)||!qt(r.cachedInputTokens)||!qt(r.outputTokens))return null;let o=t.prices;if(!Dn(o.inputPer1k)||!Dn(
|
|
1479
|
+
o.outputPer1k)||o.cachedInputPer1k!==void 0&&!Dn(o.cachedInputPer1k))return null;let i={basis:"verification",requestId:t.requestId,at:Math.floor(t.at),stratum:t.stratum,outcome:t.outcome,requestedModel:t.
|
|
1379
1480
|
requestedModel,servedModel:t.servedModel,cacheResult:t.cacheResult,optimizedCost:r.cost,optimizedInputTokens:r.inputTokens,optimizedCachedInputTokens:Math.min(r.cachedInputTokens,r.inputTokens),optimizedOutputTokens:r.
|
|
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||!
|
|
1381
|
-
inputTokens)||!
|
|
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
|
|
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=
|
|
1384
|
-
push(n),this.pendientes.length>
|
|
1481
|
+
outputTokens,inputPer1k:o.inputPer1k,...o.cachedInputPer1k!==void 0?{cachedInputPer1k:o.cachedInputPer1k}:{},outputPer1k:o.outputPer1k};if(t.outcome==="paired"){let s=t.naive;if(!s||!Dn(s.cost)||!qt(s.
|
|
1482
|
+
inputTokens)||!qt(s.cachedInputTokens)||!qt(s.outputTokens)||s.cachedInputTokens>s.inputTokens)return null;if(i.naiveCost=s.cost,i.naiveInputTokens=s.inputTokens,i.naiveCachedInputTokens=s.cachedInputTokens,
|
|
1483
|
+
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 oo=class{o;flushIntervalMs;pendientes=[];conteos=new Map;reintentos=[];inflight=null;timer;fallosSeguidos=0;ultimoFallo=Number.
|
|
1484
|
+
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=Eh(e,{ahora:this.ahora()});}catch{n=null;}n&&(this.pendientes.
|
|
1485
|
+
push(n),this.pendientes.length>Dl&&this.pendientes.splice(0,this.pendientes.length-Dl),this.pendientes.length>=Il&&this.flushSiToca());}flushSiToca(){return this.reintentos.length>0&&this.ahora()-this.
|
|
1385
1486
|
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();},
|
|
1386
1487
|
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();
|
|
1387
1488
|
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;
|
|
1388
|
-
if(this.pendientes.length===0&&this.conteos.size===0)return null;let n=this.pendientes.splice(0,
|
|
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??
|
|
1390
|
-
fetch;if(e)for(let n=0;n<
|
|
1391
|
-
Bearer ${this.o.serviceAccountKey}`,"content-type":"application/json",[
|
|
1392
|
-
this.ahora(),this.reencolar(n),this.avisarDeFallo(`the server responded ${r.status}`),!1):r.status===401||r.status===403?(this.o.silenceWarnings||
|
|
1489
|
+
if(this.pendientes.length===0&&this.conteos.size===0)return null;let n=this.pendientes.splice(0,Il),r=[];for(let[o,i]of this.conteos){if(r.length>=xh)break;let[s="",a=""]=o.split("|"),c=Math.min(i,Sh);
|
|
1490
|
+
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??Yt)(),samples:n,counts:r}}async hacerFlush(){let e=this.o.fetchImpl??globalThis.
|
|
1491
|
+
fetch;if(e)for(let n=0;n<Th&&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:`\
|
|
1492
|
+
Bearer ${this.o.serviceAccountKey}`,"content-type":"application/json",[jn]:`sdk/${Me}`},body:JSON.stringify(n)});return r.ok?(this.fallosSeguidos=0,!0):r.status>=500?(this.fallosSeguidos++,this.ultimoFallo=
|
|
1493
|
+
this.ahora(),this.reencolar(n),this.avisarDeFallo(`the server responded ${r.status}`),!1):r.status===401||r.status===403?(this.o.silenceWarnings||U(`verification-auth-${r.status}`,`[bvsala] verificati\
|
|
1393
1494
|
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):
|
|
1394
1495
|
(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 \
|
|
1395
1496
|
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.
|
|
1396
|
-
reintentos.unshift(e);this.reintentos.length>
|
|
1497
|
+
reintentos.unshift(e);this.reintentos.length>wh;)this.reintentos.pop();}avisarDeFallo(e){if(this.o.silenceWarnings)return;let n=this.fallosSeguidos;n<3||(n-3)%12!==0||console.warn(`[bvsala] verificatio\
|
|
1397
1498
|
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,
|
|
1398
|
-
conteos:this.conteos.size,reintentos:this.reintentos.length}}};var
|
|
1499
|
+
conteos:this.conteos.size,reintentos:this.reintentos.length}}};var Ph=72*3600,Rh,_l=new Set(Object.values(Nn).flatMap(t=>t.flatMap(e=>[e,`openai/${e}`]))),Al="[bvsala] `gpt-tokenizer` is not installed, so token counts for OpenAI models are ESTIMATED with a built-\
|
|
1399
1500
|
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 \
|
|
1400
|
-
(`npm i gpt-tokenizer`) and the SDK loads it automatically.";function
|
|
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??
|
|
1402
|
-
tokenizer==null&&t.exactTokenizer!==false?
|
|
1403
|
-
|
|
1404
|
-
status(),reason:()=>
|
|
1501
|
+
(`npm i gpt-tokenizer`) and the SDK loads it automatically.";function fx(t){t.licenseGate&&(console.warn("[bvsala] Ignoring the injected `licenseGate`: in the published package a license is only accep\
|
|
1502
|
+
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??xo},r=t.
|
|
1503
|
+
tokenizer==null&&t.exactTokenizer!==false?Rh??=So(xo).catch(()=>false):Promise.resolve(true),o,i;if(t.licenseKey&&!t.licenseGate){let h=mu;if(t.licenseServerUrl){let m=new Lt,g=b=>jr(b,
|
|
1504
|
+
h,{revocation:m,...t.now?{now:t.now}:{},maxStalenessSeconds:t.licenseRevocation?.maxStalenessSeconds??Ph}),f=g(t.licenseKey);n.licenseGate={isEntitled:b=>f.isEntitled(b),isActive:()=>f.isActive(),status:()=>f.
|
|
1505
|
+
status(),reason:()=>f.reason()};let v=`${t.licenseServerUrl.replace(/\/+$/,"")}/licenses/revocations`;o=new Nr({url:v,publicKeyPem:h,snapshot:m,getRefreshAfter:()=>f.refreshAfter?.(),...t.now?{nowSeconds:()=>Math.
|
|
1405
1506
|
floor(t.now()/1e3)}:{},...t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.licensePollIntervalSeconds!=null?{pollIntervalSeconds:t.licensePollIntervalSeconds}:{},...t.silenceWarnings!=null?{silenceWarnings:t.
|
|
1406
|
-
silenceWarnings}:{},...t.licenseRevocation??{}}),o.start(),t.serviceAccountKey&&t.licenseRefresh?.enabled!==false&&(i=new
|
|
1407
|
-
serviceAccountKey,publicKey:
|
|
1408
|
-
{pollIntervalMs:t.licenseRefresh.intervalMs}:{},...t.licenseRefresh?.leadSeconds!=null?{refreshLeadSeconds:t.licenseRefresh.leadSeconds}:{}}),i.start());}else n.licenseGate=
|
|
1409
|
-
t.verification),a=(
|
|
1410
|
-
enabled!==false)if(t.meteringUrl){let
|
|
1411
|
-
/api/metering/verification`);if(!
|
|
1507
|
+
silenceWarnings}:{},...t.licenseRevocation??{}}),o.start(),t.serviceAccountKey&&t.licenseRefresh?.enabled!==false&&(i=new ro({url:`${t.licenseServerUrl.replace(/\/+$/,"")}/api/license/current`,serviceAccountKey:t.
|
|
1508
|
+
serviceAccountKey,publicKey:h,initialToken:t.licenseKey,revocados:m,onNewToken:b=>{f=g(b);},...t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.now?{now:t.now}:{},...t.licenseRefresh?.intervalMs!=null?
|
|
1509
|
+
{pollIntervalMs:t.licenseRefresh.intervalMs}:{},...t.licenseRefresh?.leadSeconds!=null?{refreshLeadSeconds:t.licenseRefresh.leadSeconds}:{}}),i.start());}else n.licenseGate=ku(t.licenseKey,h,t.now);}let s=Gr(
|
|
1510
|
+
t.verification),a=(h,m)=>{t.silenceWarnings!==true&&U(h,m);};!s.activo&&s.motivo==="invalido"&&a("verificacion-invalida",ul(t.verification));let c,u;if(s.activo){let h;if(t.serviceAccountKey&&t.metering?.
|
|
1511
|
+
enabled!==false)if(t.meteringUrl){let m=/^(.*)\/api\/metering\/usage\/?$/.exec(t.meteringUrl);m&&(h=`${m[1]}/api/metering/verification`);}else t.licenseServerUrl&&(h=`${t.licenseServerUrl.replace(/\/+$/,"")}\
|
|
1512
|
+
/api/metering/verification`);if(!h&&!s.onCheck)a("verificacion-sin-destino",ll);else {h&&t.serviceAccountKey&&(c=new oo({url:h,serviceAccountKey:t.serviceAccountKey,...t.meteringFetch?{fetchImpl:t.meteringFetch}:
|
|
1412
1513
|
t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.now?{now:t.now}:{},...t.metering?.flushIntervalMs!=null?{flushIntervalMs:t.metering.flushIntervalMs}:{},...t.silenceWarnings!=null?{silenceWarnings:t.
|
|
1413
|
-
silenceWarnings}:{}}),c.start());let
|
|
1414
|
-
u?{verificacion:u}:{}),d;if(t.serviceAccountKey&&t.metering?.enabled!==false){let
|
|
1514
|
+
silenceWarnings}:{}}),c.start());let m=c;u={encolar:g=>m?.encolar(g),...m?{contar:(g,f)=>m.contar(g,f)}:{},enReposo:()=>m?.flushSiToca()},a(`verificacion-activa:${s.tasa}`,cl(s.tasa));}}let l=new Qr(n,
|
|
1515
|
+
u?{verificacion:u}:{}),d;if(t.serviceAccountKey&&t.metering?.enabled!==false){let h=t.meteringUrl??(t.licenseServerUrl?`${t.licenseServerUrl.replace(/\/+$/,"")}/api/metering/usage`:void 0);if(!h&&t.silenceWarnings!==
|
|
1415
1516
|
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\
|
|
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.'),
|
|
1517
|
+
nd a renewed license will not be picked up. Add `licenseServerUrl: "https://savings.bivelio.com"` \u2014 or drop `serviceAccountKey` for a zero-network deployment.'),h){d=new kn({url:h,serviceAccountKey:t.
|
|
1417
1518
|
serviceAccountKey,surface:"sdk",...t.metering?.orgId?{orgId:t.metering.orgId}:{},...t.metering?.flushIntervalMs!=null?{flushIntervalMs:t.metering.flushIntervalMs}:{},...t.metering?.maxBatch!=null?{maxBatch:t.
|
|
1418
1519
|
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}:
|
|
1419
|
-
{},...t.metering?.ci!=null?{ci:t.metering.ci}:{},...t.silenceWarnings!=null?{silenceWarnings:t.silenceWarnings}:{}});let
|
|
1420
|
-
let g=d;
|
|
1421
|
-
now:n.now??Date.now}),generate:async
|
|
1422
|
-
generateStream:(
|
|
1423
|
-
nte",
|
|
1424
|
-
toFixed(10).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"");return e==="-0"?"0":e}function
|
|
1425
|
-
column "${e}" holds a non-finite number`);return
|
|
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
|
|
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=>
|
|
1428
|
-
i=>
|
|
1429
|
-
`).join("")}var
|
|
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
|
|
1431
|
-
indexOf("/");return e>0?t.slice(0,e):void 0}function
|
|
1432
|
-
t)?.nombre}function
|
|
1520
|
+
{},...t.metering?.ci!=null?{ci:t.metering.ci}:{},...t.silenceWarnings!=null?{silenceWarnings:t.silenceWarnings}:{}});let m=t.metering?.ci??qi();if(t.metering?.seatId)d.setSeat(t.metering.seatId,m);else {
|
|
1521
|
+
let g=d;Vi(t.serviceAccountKey).then(f=>g.setSeat(f,m)).catch(()=>{});}d.start();}}return {batches:Pl({provider:n.provider,...n.costModels?{costModels:n.costModels}:{},exigirLicencia:()=>l.exigirLicencia(),
|
|
1522
|
+
now:n.now??Date.now}),generate:async h=>{let m=await r,g=await l.generate(h);if(!m&&t.silenceWarnings!==true&&_l.has(h.model)&&U("tokenizador-exacto-ausente",Al),d)try{d.record(g.report);}catch{}return g},
|
|
1523
|
+
generateStream:(h,m)=>{let g=l.generateStream(h,m??{},r);return g.result.then(async f=>{if(d)try{d.record(f.report);}catch{}!await r&&t.silenceWarnings!==true&&_l.has(h.model)&&U("tokenizador-exacto-ause\
|
|
1524
|
+
nte",Al);},()=>{}),g},close:()=>{l.cerrarVerificacion(),c?.stop(),o?.stop(),i?.stop(),d?.stop();}}}function Ts(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.
|
|
1525
|
+
toFixed(10).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"");return e==="-0"?"0":e}function Ol(t,e){if(t==null)return "";if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`[bvsala] toCsv: \
|
|
1526
|
+
column "${e}" holds a non-finite number`);return Ts(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\
|
|
1527
|
+
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 Dh(t,e){
|
|
1528
|
+
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=>Ol(o,o)).join(",")];for(let o of t)r.push(n.map(
|
|
1529
|
+
i=>Ol(o[i],i)).join(","));return r.map(o=>`${o}\r
|
|
1530
|
+
`).join("")}var Ml={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:"\
|
|
1531
|
+
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 Ll(t){let e=t.
|
|
1532
|
+
indexOf("/");return e>0?t.slice(0,e):void 0}function Cs(t){let e=Ll(t)?.toLowerCase();return e!==void 0&&Object.hasOwn(Ml,e)?Ml[e]:void 0}function jl(t){return Cs(t)?.otel??Ll(t)}function Nl(t){return Cs(
|
|
1533
|
+
t)?.nombre}function bt(t){return Cs(t)?t.slice(t.indexOf("/")+1):t}var de={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
1534
|
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"}
|
|
1435
|
-
request_sent`;function
|
|
1436
|
-
actual)}function
|
|
1437
|
-
bivelio_basis:n.basis,bivelio_currency:e}
|
|
1535
|
+
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"},$l="error.type",q="com.bivelio.",Bl=`${q}stream.\
|
|
1536
|
+
request_sent`;function qe(t){return t==="measured"||t==="reference"||t==="estimated"}function Vt(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}function Fl(t){return Vt(t.cost.baselineEstimate-t.cost.
|
|
1537
|
+
actual)}function F(t,e,n){(typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n))&&(t[e]=n);}function Es(t,e){let{cost:n,tokens:r,calls:o,cache:i}=t,s={bivelio_request_id:t.requestId,
|
|
1538
|
+
bivelio_basis:n.basis,bivelio_currency:e};qe(n.basis)&&(s.bivelio_baseline_cost=n.baselineEstimate,s.bivelio_actual_cost=n.actual,s[`bivelio_saved_${n.basis}`]=Fl(t),s.bivelio_net_savings_ratio=n.netSavings),
|
|
1438
1539
|
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=
|
|
1439
1540
|
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
|
|
1441
|
-
void 0&&
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
baseline`,i.baselineLlm),
|
|
1445
|
-
ctual_input`,o.actualInput),
|
|
1446
|
-
`${q}tokens.baseline_output`,o.baselineOutput),
|
|
1447
|
-
erence_request_id`,s.reference?.requestId),
|
|
1448
|
-
|
|
1449
|
-
on.metadata.${l}`]=typeof d=="number"?
|
|
1450
|
-
metadata){let l={};for(let[d,
|
|
1451
|
-
"function"}function
|
|
1452
|
-
ngsLayer: `tracer` must be an OpenTelemetry Tracer, a TracerProvider or the `trace` object of the OpenTelemetry API")}function
|
|
1453
|
-
test(e)?e:"_OTHER"}function
|
|
1454
|
-
isFinite(c)&&(r[a]=c);};i(
|
|
1455
|
-
(r[
|
|
1456
|
-
let i=r.streaming;i?.delivery==="live"&&typeof i.firstEventMs=="number"&&Number.isFinite(i.firstEventMs)&&(o[
|
|
1457
|
-
function
|
|
1458
|
-
let n=
|
|
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,
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
s),(a,c)=>c.then(u=>(
|
|
1463
|
-
try{return typeof t.model=="string"?
|
|
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
|
|
1465
|
-
ust be "hour" or "day"`)}function
|
|
1466
|
-
USD"`)}function
|
|
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
|
|
1468
|
-
t/n)*n}function
|
|
1469
|
-
`[bvsala] ${r}: report ${n} has no finite number in ${e}`)}function
|
|
1470
|
-
la] ${n}: every record must be { at, report }`);let a=s.report,c=a.cost?.basis;if(c==="shadow")continue;if(!
|
|
1471
|
-
own cost basis`);let u=c,l=
|
|
1541
|
+
return s}function Ps(t){let e={};return F(e,de.modeloRespuesta,bt(t.model)),qe(t.cost.basis)&&(F(e,de.entrada,t.tokens.actualInput),F(e,de.salida,t.tokens.actualOutput),t.tokens.providerCachedInput!==
|
|
1542
|
+
void 0&&F(e,de.lecturaDeCache,t.tokens.providerCachedInput)),e}function io(t,e){let n=e?.currency??"USD",{cost:r,tokens:o,calls:i,cache:s}=t,a={};F(a,`${q}request_id`,t.requestId),F(a,`${q}sdk.version`,
|
|
1543
|
+
Me),F(a,`${q}model.id`,t.model),F(a,`${q}model.requested_id`,t.modelCascade?.requestedModel),F(a,`${q}cost.basis`,r.basis),F(a,`${q}cost.currency`,n),qe(r.basis)&&(F(a,`${q}cost.baseline`,r.baselineEstimate),
|
|
1544
|
+
F(a,`${q}cost.actual`,r.actual),F(a,`${q}cost.saved.${r.basis}`,Fl(t)),F(a,`${q}cost.net_savings_ratio`,r.netSavings),F(a,`${q}cost.eliminated_input_floor`,r.eliminatedInputFloorCost)),F(a,`${q}calls.\
|
|
1545
|
+
baseline`,i.baselineLlm),F(a,`${q}calls.actual`,i.actualLlm),F(a,`${q}calls.avoided`,i.avoidedLlm),F(a,`${q}calls.retries`,i.retries),F(a,`${q}tokens.baseline_input`,o.baselineInput),F(a,`${q}tokens.a\
|
|
1546
|
+
ctual_input`,o.actualInput),F(a,`${q}tokens.eliminated_input`,o.eliminatedInput),F(a,`${q}tokens.compressed_input`,o.compressedInput),F(a,`${q}tokens.provider_cached_input`,o.providerCachedInput),F(a,
|
|
1547
|
+
`${q}tokens.baseline_output`,o.baselineOutput),F(a,`${q}tokens.actual_output`,o.actualOutput),F(a,`${q}tokens.eliminated_output`,o.eliminatedOutput),F(a,`${q}cache.result`,s.result),F(a,`${q}cache.ref\
|
|
1548
|
+
erence_request_id`,s.reference?.requestId),F(a,`${q}cache.reference_rejected`,s.referenceRejected),F(a,`${q}quality.status`,t.qualityStatus),F(a,`${q}latency.preprocessing_ms`,t.latencyMs?.preprocessing),
|
|
1549
|
+
F(a,`${q}latency.provider_ms`,t.latencyMs?.provider);let u=e?.langfuse?.metadata||e?.datadog?.metadata?Es(t,n):void 0;if(u&&e?.langfuse?.metadata)for(let[l,d]of Object.entries(u))a[`langfuse.observati\
|
|
1550
|
+
on.metadata.${l}`]=typeof d=="number"?Ts(d):d;if(e?.langfuse?.cost&&n==="USD"&&qe(r.basis)&&Number.isFinite(r.actual)&&(a["langfuse.observation.cost_details"]=JSON.stringify({total:r.actual})),u&&e?.datadog?.
|
|
1551
|
+
metadata){let l={};for(let[d,p]of Object.entries(u))l[d.replace(/^bivelio_/,"")]=p;a["_dd.ml_obs.metadata"]=JSON.stringify({bivelio:l});}return a}var Ih=2,_h=2,Ah="@bivelio/savings-layer";function Oh(t,e,n){try{if(t.isRecording?.()===!1)return;let r=io(e,n);n?.genAi&&Object.assign(r,Ps(e)),t.setAttributes(r);}catch{}}function Rs(t){return typeof t==
|
|
1552
|
+
"function"}function Mh(t){let e=t;if(e&&Rs(e.startActiveSpan))return e;if(e&&Rs(e.getTracer)){let n=e.getTracer(Ah,Me);if(n&&Rs(n.startActiveSpan))return n}throw new TypeError("[bvsala] instrumentSavi\
|
|
1553
|
+
ngsLayer: `tracer` must be an OpenTelemetry Tracer, a TracerProvider or the `trace` object of the OpenTelemetry API")}function Lh(t){let e=t?.name;return typeof e=="string"&&/^[A-Za-z_$][\w$.-]{0,127}$/.
|
|
1554
|
+
test(e)?e:"_OTHER"}function jh(t,e,n){let r={[de.operacion]:"chat"},o=n??jl(t.model);typeof o=="string"&&o!==""&&(r[de.proveedor]=o),r[de.modeloPedido]=bt(t.model);let i=(a,c)=>{typeof c=="number"&&Number.
|
|
1555
|
+
isFinite(c)&&(r[a]=c);};i(de.temperatura,t.temperature),i(de.semilla,t.seed),i(de.maxTokens,t.response?.maxOutputTokens),e&&(r[de.stream]=true);let s=t.context?.sessionId;return typeof s=="string"&&s!==""&&
|
|
1556
|
+
(r[de.conversacion]=s),r}function zl(t,e,n){try{if(t.isRecording?.()!==!1){let r=e.report,o={...Ps(r),...io(r,n)};typeof e.finishReason=="string"&&e.finishReason!==""&&(o[de.motivosDeFin]=[e.finishReason]);
|
|
1557
|
+
let i=r.streaming;i?.delivery==="live"&&typeof i.firstEventMs=="number"&&Number.isFinite(i.firstEventMs)&&(o[de.primerTrozo]=i.firstEventMs/1e3),t.setAttributes(o);}}catch{}finally{try{t.end();}catch{}}}
|
|
1558
|
+
function Ds(t,e){try{if(t.isRecording?.()!==!1){let n={[$l]:Lh(e)};e instanceof ke&&(n[Bl]=e.requestSent),t.setAttributes(n),t.setStatus?.({code:_h});}}catch{}finally{try{t.end();}catch{}}}function Nh(t,e){
|
|
1559
|
+
let n=Mh(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}")`);
|
|
1560
|
+
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,p=false,h;try{h=jh(s,a,o);}catch{
|
|
1561
|
+
h=void 0;}let m=`chat ${$h(s)}`;try{n.startActiveSpan(m,{kind:Ih,...h?{attributes:h}:{}},g=>{if(l)return l.valor;if(d)throw d.error;if(p){try{g.end();}catch{}return}let f;try{f=c();}catch(v){throw d={error:v},
|
|
1562
|
+
Ds(g,v),v}try{l={valor:u(g,f)};}catch{l={valor:f};try{g.end();}catch{}}return l.valor});}catch{}if(d)throw d.error;return l?l.valor:(p=true,c())}return {batches:t.batches,generate(s){return i(s,false,()=>t.generate(
|
|
1563
|
+
s),(a,c)=>c.then(u=>(zl(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=>zl(c,l,r),l=>Ds(c,l)),u))},close(){t.close();}}}function $h(t){
|
|
1564
|
+
try{return typeof t.model=="string"?bt(t.model):""}catch{return ""}}function Bh(t,e){let n=e?.currency??"USD",r={model:bt(t.model),metadata:Es(t,n)};if(qe(t.cost.basis)){let{actualInput:o,actualOutput:i,providerCachedInput:s}=t.tokens,a={input:Math.max(0,o-(s??0)),output:i};
|
|
1565
|
+
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 ql=["measured","reference","estimated","unmeasured"],Is=36e5,Vl=24*Is;function so(t,e){if(t===void 0)return "day";if(t==="hour"||t==="day")return t;throw new TypeError(`[bvsala] ${e}: granularity m\
|
|
1566
|
+
ust be "hour" or "day"`)}function ao(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 "\
|
|
1567
|
+
USD"`)}function Fh(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(`\
|
|
1568
|
+
[bvsala] ${e}: invalid "at" for request ${String(t.report?.requestId)}: expected an ISO 8601 string, epoch milliseconds or a valid Date`);return r}function zh(t,e){let n=e==="hour"?Is:Vl;return Math.floor(
|
|
1569
|
+
t/n)*n}function qh(t,e){return t+(e==="hour"?Is:Vl)}function at(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(
|
|
1570
|
+
`[bvsala] ${r}: report ${n} has no finite number in ${e}`)}function co(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\
|
|
1571
|
+
la] ${n}: every record must be { at, report }`);let a=s.report,c=a.cost?.basis;if(c==="shadow")continue;if(!ql.includes(c))throw new TypeError(`[bvsala] ${n}: report ${String(a.requestId)} has an unkn\
|
|
1572
|
+
own cost basis`);let u=c,l=zh(Fh(s,n),e),{clave:d,extra:p}=r(s,l),h=JSON.stringify([l,a.model,u,d]),m=o.get(h);m||(m={inicio:l,fin:qh(l,e),modelo:a.model,basis:u,clave:d,extra:p,peticiones:0,llamadas:0,
|
|
1472
1573
|
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}},
|
|
1473
|
-
o.set(
|
|
1474
|
-
ge(
|
|
1475
|
-
compressedInput+=ge(
|
|
1476
|
-
Output",g,n),
|
|
1477
|
-
"tokens.providerCachedInput",g,n))
|
|
1478
|
-
void 0&&(
|
|
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
|
|
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?
|
|
1481
|
-
keys(t).sort().map(e=>[e,t[e]]))}function
|
|
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
|
|
1574
|
+
o.set(h,m));let g=String(a.requestId);m.peticiones+=1,m.llamadas+=ge(a.calls?.actualLlm,"calls.actualLlm",g,n),m.evitadas+=ge(a.calls?.avoidedLlm,"calls.avoidedLlm",g,n);let f=a.tokens;if(m.tokens.baselineInput+=
|
|
1575
|
+
ge(f?.baselineInput,"tokens.baselineInput",g,n),m.tokens.actualInput+=ge(f?.actualInput,"tokens.actualInput",g,n),m.tokens.eliminatedInput+=ge(f?.eliminatedInput,"tokens.eliminatedInput",g,n),m.tokens.
|
|
1576
|
+
compressedInput+=ge(f?.compressedInput,"tokens.compressedInput",g,n),m.tokens.baselineOutput+=ge(f?.baselineOutput,"tokens.baselineOutput",g,n),m.tokens.actualOutput+=ge(f?.actualOutput,"tokens.actual\
|
|
1577
|
+
Output",g,n),m.tokens.eliminatedOutput+=ge(f?.eliminatedOutput,"tokens.eliminatedOutput",g,n),f.providerCachedInput!==void 0&&(m.tokens.providerCachedInput=(m.tokens.providerCachedInput??0)+ge(f.providerCachedInput,
|
|
1578
|
+
"tokens.providerCachedInput",g,n)),qe(u)){let v=ge(a.cost.baselineEstimate,"cost.baselineEstimate",g,n),b=ge(a.cost.actual,"cost.actual",g,n);m.baseline+=v,m.actual+=b,m.ahorro+=v-b,a.cost.eliminatedInputFloorCost!==
|
|
1579
|
+
void 0&&(m.suelo=(m.suelo??0)+ge(a.cost.eliminatedInputFloorCost,"cost.eliminatedInputFloorCost",g,n));}}let i=s=>ql.indexOf(s);return [...o.values()].sort((s,a)=>s.inicio-a.inicio||(s.modelo<a.modelo?-1:
|
|
1580
|
+
s.modelo>a.modelo?1:0)||i(s.basis)-i(a.basis)||(s.clave<a.clave?-1:s.clave>a.clave?1:0))}function uo(t){let e=qe(t.basis),n=Vt(t.ahorro);return {baseline:e?Vt(t.baseline):null,actual:e?Vt(t.actual):null,
|
|
1581
|
+
measured:t.basis==="measured"?n:null,reference:t.basis==="reference"?n:null,estimated:t.basis==="estimated"?n:null,suelo:e&&t.suelo!==void 0?Vt(t.suelo):null}}function lo(t){return JSON.stringify(Object.
|
|
1582
|
+
keys(t).sort().map(e=>[e,t[e]]))}function po(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[
|
|
1583
|
+
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 Vh=new Set(["periodStart","periodEnd","date","model","basis","currency","requests","providerCalls","avoidedCalls","baselineCost","actualCost","measuredSavings","referenceSavings","estimatedSavings",
|
|
1483
1584
|
"eliminatedInputFloorCost","baselineInputTokens","actualInputTokens","eliminatedInputTokens","compressedInputTokens","providerCachedInputTokens","baselineOutputTokens","actualOutputTokens","eliminated\
|
|
1484
|
-
OutputTokens","dimensions"]),
|
|
1485
|
-
keys(a))if(
|
|
1585
|
+
OutputTokens","dimensions"]),In="toSavingsSeries";function Uh(t,e){let n=so(e?.granularity,In),r=ao(e?.currency,In),o=e?.dimensions;return co(t,n,In,s=>{let a=o?po(o(s),"dimensions",In):{};for(let c of Object.
|
|
1586
|
+
keys(a))if(Vh.has(c))throw new TypeError(`[bvsala] ${In}: dimension "${c}" repeats a column of the series`);return {clave:lo(a),extra:a}}).map(s=>{let a=uo(s),c=at(s.inicio);return {periodStart:c,periodEnd:at(
|
|
1486
1587
|
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,
|
|
1487
1588
|
referenceSavings:a.reference,estimatedSavings:a.estimated,eliminatedInputFloorCost:a.suelo,baselineInputTokens:s.tokens.baselineInput,actualInputTokens:s.tokens.actualInput,eliminatedInputTokens:s.tokens.
|
|
1488
1589
|
eliminatedInput,compressedInputTokens:s.tokens.compressedInput,providerCachedInputTokens:s.tokens.providerCachedInput??null,baselineOutputTokens:s.tokens.baselineOutput,actualOutputTokens:s.tokens.actualOutput,
|
|
1489
|
-
eliminatedOutputTokens:s.tokens.eliminatedOutput,dimensions:Object.freeze({...s.extra})}})}var be="toFocusRows",
|
|
1490
|
-
`[bvsala] ${be}: cannot determine the FOCUS ${r} for model "${n}". FOCUS allows no placeholder there: pass it in the options.`)}function
|
|
1590
|
+
eliminatedOutputTokens:s.tokens.eliminatedOutput,dimensions:Object.freeze({...s.extra})}})}var be="toFocusRows",Hh="BV-SALA savings ledger",Ul="bivelio/";function vt(t){return typeof t=="string"&&t.trim()!==""}function _s(t,e,n,r){let o=typeof t=="function"?t(n):t??e;if(vt(o))return o;throw new TypeError(
|
|
1591
|
+
`[bvsala] ${be}: cannot determine the FOCUS ${r} for model "${n}". FOCUS allows no placeholder there: pass it in the options.`)}function Wh(t,e,n){if(!n){let s=new Date(t);return {start:Date.UTC(s.getUTCFullYear(),
|
|
1491
1592
|
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;
|
|
1492
1593
|
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
|
|
1494
|
-
red`);let n=
|
|
1495
|
-
Id must be a non-empty string or a function`);let c=e.serviceName??
|
|
1496
|
-
tion"?o(l):o;if(!
|
|
1497
|
-
(!
|
|
1498
|
-
startsWith(
|
|
1499
|
-
[g.id,g.nombre,g.subId,g.subNombre,
|
|
1500
|
-
|
|
1501
|
-
EffectiveCost:0,ListCost:0,ContractedCost:0,BillingCurrency:r,BillingAccountId:
|
|
1502
|
-
ChargePeriodEnd:
|
|
1503
|
-
Usage-Based",InvoiceIssuerName:
|
|
1504
|
-
SubAccountId:
|
|
1505
|
-
evitadas,x_BiVelioBaselineCost:
|
|
1594
|
+
llingPeriod must contain the charge period it is given`);return {start:o,end:i}}function Jh(t,e){if(!e||typeof e!="object")throw new TypeError(`[bvsala] ${be}: options with a billingAccountId are requi\
|
|
1595
|
+
red`);let n=so(e.granularity,be),r=ao(e.currency,be),{billingAccountId:o,billingAccountName:i,subAccount:s,tags:a}=e;if(typeof o!="function"&&!vt(o))throw new TypeError(`[bvsala] ${be}: billingAccount\
|
|
1596
|
+
Id must be a non-empty string or a function`);let c=e.serviceName??Hh;if(!vt(c))throw new TypeError(`[bvsala] ${be}: serviceName must be a non-empty string`);return co(t,n,be,l=>{let d=typeof o=="func\
|
|
1597
|
+
tion"?o(l):o;if(!vt(d))throw new TypeError(`[bvsala] ${be}: billingAccountId returned no id for request ${String(l.report.requestId)}`);let p=typeof i=="function"?i(l):i,h=s?s(l):void 0;if(h!==void 0&&
|
|
1598
|
+
(!vt(h?.id)||!vt(h?.name)))throw new TypeError(`[bvsala] ${be}: subAccount must return { id, name } as non-empty strings, or undefined`);let m=po(a?a(l):void 0,"tags",be);for(let f of Object.keys(m))if(f.
|
|
1599
|
+
startsWith(Ul))throw new TypeError(`[bvsala] ${be}: tag "${f}" uses the reserved "${Ul}" prefix`);let g={id:d,nombre:vt(p)?p:null,subId:h?h.id:null,subNombre:h?h.name:null,tags:m};return {clave:JSON.stringify(
|
|
1600
|
+
[g.id,g.nombre,g.subId,g.subNombre,lo(m)]),extra:g}}).map(l=>{let d=l.modelo,p=_s(e.serviceProviderName,Nl(d),d,"ServiceProviderName"),h=_s(e.invoiceIssuerName,p,d,"InvoiceIssuerName"),m=_s(e.hostProviderName,
|
|
1601
|
+
p,d,"HostProviderName"),g=Wh(l.inicio,l.fin,e.billingPeriod),f=uo(l),v=l.extra,b={"bivelio/basis":l.basis,"bivelio/model":d};for(let y of Object.keys(v.tags).sort())b[y]=v.tags[y];return {BilledCost:0,
|
|
1602
|
+
EffectiveCost:0,ListCost:0,ContractedCost:0,BillingCurrency:r,BillingAccountId:v.id,BillingAccountName:v.nombre,BillingPeriodStart:at(g.start),BillingPeriodEnd:at(g.end),ChargePeriodStart:at(l.inicio),
|
|
1603
|
+
ChargePeriodEnd:at(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:"\
|
|
1604
|
+
Usage-Based",InvoiceIssuerName:h,ServiceProviderName:p,HostProviderName:m,ServiceName:c,ServiceCategory:"AI and Machine Learning",ServiceSubcategory:"Generative AI",PricingQuantity:null,PricingUnit:null,
|
|
1605
|
+
SubAccountId:v.subId,SubAccountName:v.subNombre,Tags:JSON.stringify(b),x_BiVelioBasis:l.basis,x_BiVelioModelId:d,x_BiVelioRequestCount:l.peticiones,x_BiVelioProviderCallCount:l.llamadas,x_BiVelioAvoidedCallCount:l.
|
|
1606
|
+
evitadas,x_BiVelioBaselineCost:f.baseline,x_BiVelioActualCost:f.actual,x_BiVelioMeasuredSavings:f.measured,x_BiVelioReferenceSavings:f.reference,x_BiVelioEstimatedSavings:f.estimated,x_BiVelioEliminatedInputFloorCost:f.
|
|
1506
1607
|
suelo,x_BiVelioBaselineInputTokens:l.tokens.baselineInput,x_BiVelioActualInputTokens:l.tokens.actualInput,x_BiVelioEliminatedInputTokens:l.tokens.eliminatedInput,x_BiVelioCompressedInputTokens:l.tokens.
|
|
1507
1608
|
compressedInput,x_BiVelioProviderCachedInputTokens:l.tokens.providerCachedInput??null,x_BiVelioBaselineOutputTokens:l.tokens.baselineOutput,x_BiVelioActualOutputTokens:l.tokens.actualOutput,x_BiVelioEliminatedOutputTokens:l.
|
|
1508
1609
|
tokens.eliminatedOutput}})}/*! Bundled license information:
|
|
@@ -1513,4 +1614,4 @@ tokens.eliminatedOutput}})}/*! Bundled license information:
|
|
|
1513
1614
|
@noble/curves/abstract/edwards.js:
|
|
1514
1615
|
@noble/curves/ed25519.js:
|
|
1515
1616
|
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
1516
|
-
*/export{
|
|
1617
|
+
*/export{hc as AnthropicProvider,Me as BV_SALA_VERSION,Br as BatchSubmitError,Zt as CATALOGO,Jo as COMPACTION_TRANSFORMS,ip as COMPACT_ROWS_INSTRUCTION,we as CalibrationStateError,wu as DEFAULT_COST_MODEL,Ph as DEFAULT_MAX_STALENESS_SECONDS,mp as DEFAULT_MIN_SAVED_CHARS,mu as EMBEDDED_PUBLIC_KEY,wo as ExactTokenizer,Jn as ExecutionRouter,Xn as FormatSelector,yo as HeuristicEstimator,ua as InMemoryCacheBreakpointStore,Fn as InMemoryExactCache,ca as InMemorySemanticCache,Bo as InMemoryToolSetFreezer,Qe as LicenseError,pg as MODELOS_POR_CODIFICACION,Nn as MODELS_BY_ENCODING,Go as MockProvider,ac as OpenAICompatibleProvider,go as PRECIOS_AL_DIA,Xh as QUALITY_STATUSES,Hs as REFERENCE_MAX_AGE_MS,Js as REFERENCE_MESSAGE_ALLOWANCE,Ws as REFERENCE_OUTPUT_SHARE,jo as ResolverRegistry,Nr as RevocationPoller,Lt as RevocationSnapshot,Ct as SavingsLedger,er as SchemaRegistry,zn as Singleflight,ke as StreamAbortedError,ko as TokenizerRegistry,Gn as ToolSelector,fn as TraceCollector,sa as UMBRAL_LOCAL,kn as UsageEmitter,Kd as adaptiveK,jd as arithmeticResolver,Ro as buildExactKey,Zs as buildInflightKey,jg as calibrateSemanticFloor,Po as canonicalize,Ta as compactRowsSerializer,Oa as compactToolOutput,Da as compresionFiel,Nf as computeNextDelay,Rd as cosine,sp as createCompactRowsSerializer,la as createDefaultResolvers,tg as createHandoff,X0 as createMockProvider,fx as createSavingsLayer,Ea as csvSerializer,ka as decodeCompactRows,Jd as dedupe,xo as defaultTokenizerRegistry,Vi as deriveSeatId,zi as deriveStatus,qi as detectCi,ia as embebedorLocal,d0 as emptyState,np as encodeCompactRows,Bd as evalArithmetic,Bn as evaluatePolicy,va as executeRetrievalPlan,ku as gateFromKey,Tt as heuristicEstimator,Nh as instrumentSavingsLayer,Af as isKeyset,Ze as isStrictCompatible,ya as jsonCompactSerializer,Ad as keyTokensMatch,Bi as licenseKeyShape,jr as liveGateFromKey,p0 as mergeDelta,Eo as modelFamilyOf,Lo as multisetEqual,on as negationCount,U0 as noopCompressor,Ot as normalizeLicenseKey,$n as normalizeText,nn as numericTokens,Ln as precioDeLista,f0 as projectContext,j0 as providerNativeBackend,oi as quitarPrefijoDeProveedor,Yt as randomId,Oh as recordSavingsOnSpan,So as registerExactTokenizer,fg as registrarTokenizadorExacto,Zd as renderState,Ra as resolveConstraintBackend,Su as resolveDependencies,Av as resolveLicense,Mo as sameAnswer,io as savingsSpanAttributes,te as sha256,Wo as shouldCompress,ye as stableStringify,Dh as toCsv,Jh as toFocusRows,Bh as toLangfuseGeneration,Uh as toSavingsSeries,Qn as uniformColumns,pe as validateAgainstSchema,Pd as vectorLocal,Fi as verifyCompactSignature,Mt as verifyLicenseToken,yu as verifyRevocationList,V0 as withProtectedSpans,rn as words};
|