@bivelio/savings-layer 0.4.29 → 0.4.31
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 +80 -6
- package/dist/adapters/anthropic-sdk.js +69 -66
- package/dist/gateway/bin.js +759 -698
- package/dist/index.d.ts +131 -17
- package/dist/index.js +1306 -1225
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Eo="2026-09-27",nn={"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,
|
|
@@ -15,79 +15,80 @@ outputPer1k:.02,cachedInputPer1k:2e-4},"claude-opus-4":{inputPer1k:.015,outputPe
|
|
|
15
15
|
nnet-4-6":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-sonnet-5":{inputPer1k:.002,outputPer1k:.01,cachedInputPer1k:2e-4},"claude-fable-5":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:.001},
|
|
16
16
|
"claude-fable-5-1":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:25e-5},"claude-mythos-5-1":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:25e-5},"claude-mythos-5":{inputPer1k:.01,outputPer1k:.05,
|
|
17
17
|
cachedInputPer1k:.001},"claude-sonnet-4":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-haiku-4-5":{inputPer1k:.001,outputPer1k:.005,cachedInputPer1k:1e-4},"claude-3-5-sonnet":{inputPer1k:.003,
|
|
18
|
-
outputPer1k:.015,cachedInputPer1k:3e-4},"claude-3-5-haiku":{inputPer1k:8e-4,outputPer1k:.004,cachedInputPer1k:8e-5},"claude-3-opus":{inputPer1k:.015,outputPer1k:.075,cachedInputPer1k:.0015},"
|
|
19
|
-
|
|
20
|
-
cachedInputPer1k:75e-6},"gemini-3.
|
|
21
|
-
|
|
22
|
-
cachedInputPer1k:
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
""
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
return
|
|
32
|
-
1))))return Us(n,Vs(e))}var Me="0.4.29",Nn="x-bvsala-version";var fd=0;function Qt(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else {let r=++fd,o=Date.now?Date.now():0;for(let i=0;i<
|
|
18
|
+
outputPer1k:.015,cachedInputPer1k:3e-4},"claude-3-5-haiku":{inputPer1k:8e-4,outputPer1k:.004,cachedInputPer1k:8e-5},"claude-3-opus":{inputPer1k:.015,outputPer1k:.075,cachedInputPer1k:.0015},"gemini-3.\
|
|
19
|
+
8-flash":{inputPer1k:75e-5,outputPer1k:.00375,cachedInputPer1k:75e-6},"gemini-3.7-flash":{inputPer1k:75e-5,outputPer1k:.00375,cachedInputPer1k:75e-6},"gemini-3.6-flash":{inputPer1k:75e-5,outputPer1k:.00375,
|
|
20
|
+
cachedInputPer1k:75e-6},"gemini-3.1-flash-lite":{inputPer1k:25e-5,outputPer1k:.0015,cachedInputPer1k:25e-6},"gemini-3-flash-preview":{inputPer1k:5e-4,outputPer1k:.003,cachedInputPer1k:5e-5},"gemini-3.\
|
|
21
|
+
5-flash":{inputPer1k:.0015,outputPer1k:.009,cachedInputPer1k:15e-5},"gemini-3.5-flash-lite":{inputPer1k:3e-4,outputPer1k:.0025,cachedInputPer1k:3e-5},"gemini-3.1-pro-preview":{inputPer1k:.002,outputPer1k:.012,
|
|
22
|
+
cachedInputPer1k:2e-4},"gemini-2.5-pro":{inputPer1k:.00125,outputPer1k:.01,cachedInputPer1k:125e-6},"gemini-2.5-flash":{inputPer1k:3e-4,outputPer1k:.0025,cachedInputPer1k:3e-5}},Sd={"gemini-3.8-flash":{
|
|
23
|
+
vigenteHasta:"2027-01-01"},"gemini-3.7-flash":{vigenteHasta:"2027-01-01"},"gemini-3.6-flash":{vigenteHasta:"2027-01-01"}},Td={"gemini-3.8-flash":[{vigenteDesde:"2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,
|
|
24
|
+
cachedInputPer1k:15e-5}}],"gemini-3.7-flash":[{vigenteDesde:"2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}],"gemini-3.6-flash":[{vigenteDesde:"2027-01-01",precio:{inputPer1k:.0015,
|
|
25
|
+
outputPer1k:.0075,cachedInputPer1k:15e-5}}]},Cd=Object.fromEntries(Object.keys(nn).map(t=>[t,[{...Sd[t],precio:nn[t]},...Td[t]??[]]]));var Ed=864e13;function ta(t){let e=t instanceof Date?t.getTime():t,n=typeof e=="number"&&Number.isFinite(e)&&Math.abs(e)<=Ed?e:Date.now();return new Date(n).toISOString().slice(0,10)}function na(t,e){
|
|
26
|
+
for(let n of Cd[t]??[])if(!(n.vigenteDesde!==void 0&&e<n.vigenteDesde)&&!(n.vigenteHasta!==void 0&&e>=n.vigenteHasta))return n.precio}function Po(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!==
|
|
27
|
+
""&&c!=="-"&&c!=="."&&c!=="_")continue;let u=i.slice(a.length+1);if(!(/^\d/.test(u)&&!/^\d{4}/.test(u)))return t[a]}}function Ro(t){return Object.keys(t).sort((e,n)=>n.length-e.length)}var Pd=["o3-dee\
|
|
28
|
+
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"],Co={...nn,...Object.
|
|
29
|
+
fromEntries(Pd.map(t=>[t,null]))},Rd=Ro(Co);function Vn(t,e){let n=_t(t);return n===void 0?void 0:na(n,ta(e))}var Dd=Object.fromEntries(Object.keys(Co).map(t=>[t,Co[t]===null?null:t]));function _t(t){
|
|
30
|
+
return Po(Dd,Rd,t)??void 0}var _d=/^\d{4}-?\d{2}-?\d{2}$/;function Ze(t,e){let n=_t(t);if(n===void 0)return;let r=t.lastIndexOf("/"),o=r>=0?t.slice(r+1):t;if(!(n!==t&&n!==o&&!_d.test(o.slice(n.length+
|
|
31
|
+
1))))return na(n,ta(e))}var Be="0.4.31",Un="x-bvsala-version";var Id=0;function rn(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else {let r=++Id,o=Date.now?Date.now():0;for(let i=0;i<
|
|
33
32
|
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
|
|
33
|
+
-${n[8]}${n[9]}-${n[10]}${n[11]}${n[12]}${n[13]}${n[14]}${n[15]}`}var r0=["exact","task_equivalent","not_verified","bounded_degradation","rejected"];function i0(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 Do=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
34
|
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))}},
|
|
35
|
+
Math.ceil(e.length/4))}},It=new Do;var _o=class{estimators=new Map;modelToTokenizer=new Map;fallbackId;constructor(e=It){this.fallbackId=e.id,this.estimators.set(e.id,e);}register(e){return this.estimators.set(e.id,e),this}mapModel(e,n){
|
|
37
36
|
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
|
|
37
|
+
get(r);if(o)return o}}return this.estimators.get(this.fallbackId)}count(e,n){return this.resolve(n).count(e)}},Io=new _o;var Ao=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}},Hn={o200k_base:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini",
|
|
38
|
+
"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 Oo(t,e={}){let n=e.codificaciones??
|
|
39
|
+
["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 Ao(o,i)),r=true;for(let s of Hn[o]??
|
|
40
|
+
[])t.mapModel(s,o),t.mapModel(`openai/${s}`,o);}}return r}var g0=Hn,b0=Oo;var oa=2592e6,ia=.95,sa=8,At=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
41
|
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
42
|
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
43
|
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
|
-
let o=Math.max(0,e);this.providerCacheWritePremiumUsd+=o/1e3*r.inputPer1k*Math.max(0,n-1);}
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
0
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
p
|
|
44
|
+
let o=Math.max(0,e);this.providerCacheWritePremiumUsd+=o/1e3*r.inputPer1k*Math.max(0,n-1);}unbilledInput=0;unbilledOutput=0;unbilledCachedInput=0;servedUnbilledRefusal=false;unbilledCall(e){this.unbilledInput+=
|
|
45
|
+
Math.max(0,e.inputTokens),this.unbilledOutput+=Math.max(0,e.outputTokens),this.unbilledCachedInput+=Math.max(0,e.cachedInputTokens??0);}reference=null;referenceRejected=null;avoidCallByReference(e){this.
|
|
46
|
+
avoidCall(e.creditedInputTokens,e.creditedOutputTokens),this.reference=e;}avoidCall(e,n){this.avoidedLlm+=1,this.actualLlm=0,this.baselineInput=e,this.baselineOutput=n;}get publishedBaselineOutput(){return this.
|
|
47
|
+
avoidedLlm===0?Math.max(0,this.actualOutput-this.repairOutput-this.discoveryOutput):this.baselineOutput}estimateCost(e){let n=this.avoidedLlm===0,r="estimated";if(n)if(this.callsWithoutUsage>0)this.baselineInput=
|
|
48
|
+
0,r="unmeasured";else if(this.actualInput>0&&this.sentInputLocal>0){let g=this.actualInput/this.sentInputLocal,f=Math.max(0,this.actualInput-this.repairInput-this.discoveryInput);this.baselineInput=f+
|
|
49
|
+
Math.round(g*this.removedInputLocal),r=this.removedInputLocal===0?"measured":"estimated";}else this.actualInput>0?(this.baselineInput=this.actualInput,r="measured"):(this.baselineInput=0,r="unmeasured");
|
|
50
|
+
let o=n?Math.max(0,this.actualOutput-this.repairOutput-this.discoveryOutput):this.baselineOutput,i=e.cachedInputPer1k??e.inputPer1k,s=Math.max(0,this.actualInput-this.unbilledInput),a=Math.max(0,this.
|
|
51
|
+
actualOutput-this.unbilledOutput),c=Math.min(Math.max(0,this.providerCachedInput-this.unbilledCachedInput),s),u=g=>Math.max(0,g-c)/1e3*e.inputPer1k+c/1e3*i,l=n?null:this.reference,d=n?this.providerCacheWritePremiumUsd:
|
|
52
|
+
0,p=this.servedUnbilledRefusal?0:l?l.tierFactor*(this.baselineInput/1e3*l.cachedInputPer1k+this.baselineOutput/1e3*l.outputPer1k):u(this.baselineInput)+o/1e3*e.outputPer1k+d;l&&(r=p>0?"reference":"est\
|
|
53
|
+
imated"),this.servedUnbilledRefusal&&(l?r="estimated":n&&r==="estimated"&&(r="measured"));let h=u(s)+a/1e3*e.outputPer1k+this.extraCostUsd+this.cacheWritePremiumUsd+d,m=p===0?0:1-h/p;return {baselineEstimate:ra(
|
|
54
|
+
p),actual:ra(h),netSavings:Ad(m),basis:r}}};function ra(t){return Math.round(t*1e10)/1e10}function Ad(t){return Math.round(t*1e6)/1e6}var Od=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,
|
|
54
55
|
4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,
|
|
55
56
|
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]),
|
|
57
|
+
1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Md=new TextEncoder;function Oe(t,e){return t>>>e|t<<32-e}function aa(t){let e=Md.encode(t),n=e.length*
|
|
57
58
|
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
59
|
[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 y=a[b-15],k=a[b-2],T=
|
|
60
|
-
m,6)^
|
|
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
|
|
62
|
-
|
|
63
|
-
normalize("NFC"),e=e.replace(
|
|
64
|
-
|
|
65
|
-
return
|
|
66
|
-
return t}function
|
|
60
|
+
64;b++){let y=a[b-15],k=a[b-2],T=Oe(y,7)^Oe(y,18)^y>>>3,x=Oe(k,17)^Oe(k,19)^k>>>10;a[b]=a[b-16]+T+a[b-7]+x|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=Oe(
|
|
61
|
+
m,6)^Oe(m,11)^Oe(m,25),k=m&g^~m&f,T=v+y+k+Od[b]+a[b]|0,x=Oe(l,2)^Oe(l,13)^Oe(l,22),P=l&d^l&p^d&p,M=x+P|0;v=f,f=g,g=m,m=h+T|0,h=p,p=d,d=l,l=T+M|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,
|
|
62
|
+
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 Ld=/\s+/g,$d=[[/′′/g,'"'],[/[‘’‚‛′´`]/g,"'"],[/[“”„‟″«»]/g,'"'],[/[‐-―−]/g,"-"],[/⁄/g,"/"],[/…/g,""]],jd=/[¿?¡!;.,:'"·•]/g,Nd=/([a-z])\p{M}+/gu,Bd=/(^|\s)\p{M}+/gu,
|
|
63
|
+
Mo=/\p{L}/u;function be(t){return t>="0"&&t<="9"}function Wn(t){let e=t.normalize("NFKC").toLowerCase();for(let[n,r]of $d)e=e.replace(n,r);return e=e.normalize("NFD").replace(Nd,"$1").replace(Bd,"$1").
|
|
64
|
+
normalize("NFC"),e=e.replace(jd,(n,r,o)=>{let i=o[r-1]??"",s=o[r+1]??"";switch(n){case "\xBF":case "?":case "\xA1":case ";":return be(i)&&be(s)?n:"";case "!":return be(i)?n:"";case ".":case ",":return be(i)&&
|
|
65
|
+
be(s)||be(s)&&!be(i)&&!Mo.test(i)?n:"";case ":":return be(i)&&be(s)?n:"";case "'":case '"':return Mo.test(i)&&Mo.test(s)||be(i)||be(s)?n:"";default:return be(i)||be(s)?n:""}}),e.replace(Ld," ").trim()}function ne(t){
|
|
66
|
+
return aa(t)}function ve(t){return JSON.stringify(Lo(t))}function Lo(t){if(Array.isArray(t))return t.map(Lo);if(t&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=Lo(t[n]);return e}
|
|
67
|
+
return t}function $o(t){return t.replace(/[-_]?\d{4,}.*$/,"").replace(/[-_](mini|nano|small|large|latest)$/i,"")}function Fd(t){let e=new Map,n=o=>{if(typeof o!="string"||o==="")return {sin:o??null};let i=e.
|
|
67
68
|
get(o);return i===void 0&&e.set(o,i=e.size),i},r=t.map(o=>{if(o.role==="assistant")return !o.toolCalls||o.toolCalls.length===0?null:{calls:o.toolCalls.map(a=>({...a.id!=null?{id:n(a.id)}:{},name:a.name,
|
|
68
69
|
arguments:a.arguments}))};if(o.role!=="tool")return null;let i=o.toolCallId??o.metadata?.tool_call_id,s={...i!==void 0?{id:n(i)}:{},...o.isError===true?{isError:true}:{},...o.name?{name:o.name}:{}};return Object.
|
|
69
|
-
keys(s).length>0?s:null});if(!r.every(o=>o===null))return
|
|
70
|
-
`),o=t.messages.filter(s=>s.role!=="system").map(s=>`${s.role}:${
|
|
71
|
-
`),i=(t.tools??[]).map(s=>({id:s.id,risk:s.risk,parameters:s.parameters??null})).sort((s,a)=>s.id.localeCompare(a.id));return {model:t.model,modelFamily
|
|
72
|
-
systemPromptHash:
|
|
70
|
+
keys(s).length>0?s:null});if(!r.every(o=>o===null))return ne(ve(r))}function jo(t){let e=t.context??{},n=Fd(t.messages),r=t.messages.filter(s=>s.role==="system").map(s=>s.content).join(`
|
|
71
|
+
`),o=t.messages.filter(s=>s.role!=="system").map(s=>`${s.role}:${Wn(s.content)}`).join(`
|
|
72
|
+
`),i=(t.tools??[]).map(s=>({id:s.id,risk:s.risk,parameters:s.parameters??null})).sort((s,a)=>s.id.localeCompare(a.id));return {model:t.model,modelFamily:$o(t.model),messages:t.messages,normalizedText:o,
|
|
73
|
+
systemPromptHash:ne(r),toolsetHash:ne(ve(i)),...n!==void 0?{toolTurnsHash:n}:{},structuredDataHash:t.structuredData!==void 0?ne(ve(t.structuredData)):"none",schemaVersion:t.response?.version??t.response?.
|
|
73
74
|
contractId??"none",contractId:t.response?.contractId??null,temperature:t.temperature??null,seed:t.seed??null,tenantId:e.tenantId??"anonymous",authorizationScope:e.authorizationScope??"default",principal:e.
|
|
74
|
-
sessionId??null,locale:e.locale??"und",knowledgeEpoch:e.knowledgeEpoch??"none",freshnessBucket:e.freshnessBucket??"any",safetyPolicyVersion:e.safetyPolicyVersion??"none",tokenizer:t.tokenizer,original:t}}var
|
|
75
|
-
principal,text:t.normalizedText,modelFamily:n===t.model?t.modelFamily
|
|
76
|
-
locale:t.locale,temperature:t.temperature,seed:t.seed,knowledgeEpoch:t.knowledgeEpoch,freshness:t.freshnessBucket,safety:t.safetyPolicyVersion});return `bvsala:exact:${
|
|
77
|
-
let n=
|
|
78
|
-
toolsetHash,...
|
|
79
|
-
ight:${
|
|
75
|
+
sessionId??null,locale:e.locale??"und",knowledgeEpoch:e.knowledgeEpoch??"none",freshnessBucket:e.freshnessBucket??"any",safetyPolicyVersion:e.safetyPolicyVersion??"none",tokenizer:t.tokenizer,original:t}}var ca="n2";function ua(t){return t.toolTurnsHash!==void 0?{toolTurns:t.toolTurnsHash}:{}}function No(t,e={}){let n=e.servedModel??t.model,r=ve({tenant:t.tenantId,scope:t.authorizationScope,principal:t.
|
|
76
|
+
principal,text:t.normalizedText,modelFamily:n===t.model?t.modelFamily:$o(n),model:n,system:t.systemPromptHash,contract:t.contractId,schema:t.schemaVersion,tools:t.toolsetHash,...ua(t),data:t.structuredDataHash,
|
|
77
|
+
locale:t.locale,temperature:t.temperature,seed:t.seed,knowledgeEpoch:t.knowledgeEpoch,freshness:t.freshnessBucket,safety:t.safetyPolicyVersion});return `bvsala:exact:${ca}:${ne(r)}`}function la(t,e={}){
|
|
78
|
+
let n=ve({tenant:t.tenantId,scope:t.authorizationScope,principal:t.principal,text:t.normalizedText,model:e.servedModel??t.model,system:t.systemPromptHash,contract:t.contractId,schema:t.schemaVersion,tools:t.
|
|
79
|
+
toolsetHash,...ua(t),data:t.structuredDataHash,temperature:t.temperature,seed:t.seed,deferrable:e.deferrable===true,toolDiscovery:e.toolDiscovery===true,maxOut:e.maxOutputTokens??null});return `bvsala:infl\
|
|
80
|
+
ight:${ca}:${ne(n)}`}var qd=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\
|
|
80
81
|
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|\
|
|
81
82
|
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\
|
|
82
83
|
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\
|
|
83
84
|
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\
|
|
84
|
-
nhat|m\u1EDBi nh\u1EA5t|gia|gi\xE1|thoi tiet|th\u1EDDi ti\u1EBFt"].join("|")+")\\b","i"),
|
|
85
|
+
nhat|m\u1EDBi nh\u1EA5t|gia|gi\xE1|thoi tiet|th\u1EDDi ti\u1EBFt"].join("|")+")\\b","i"),zd=new RegExp("\\b("+["my|mine|our|ours|account|balance|subscription|invoice|order|profile","mi|mis|mio|m\xEDo|nu\
|
|
85
86
|
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\
|
|
86
87
|
|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\
|
|
87
88
|
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\
|
|
88
89
|
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\
|
|
89
|
-
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
|
|
90
|
-
r=(t.original.tools??[]).some(b=>b.risk==="write"||b.risk==="destructive"),o=t.freshnessBucket==="live"||t.freshnessBucket==="hour"||
|
|
90
|
+
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 Jn(t){let e=[],n=t.normalizedText,
|
|
91
|
+
r=(t.original.tools??[]).some(b=>b.risk==="write"||b.risk==="destructive"),o=t.freshnessBucket==="live"||t.freshnessBucket==="hour"||qd.test(n),i=zd.test(n),s=(t.temperature??0)>.3&&t.seed==null,a=t.messages.
|
|
91
92
|
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===
|
|
92
93
|
"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\
|
|
93
94
|
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 \
|
|
@@ -95,414 +96,450 @@ effects must execute)"),h&&e.push("freshnessBucket=live \u2192 exact cache off (
|
|
|
95
96
|
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\
|
|
96
97
|
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\
|
|
97
98
|
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,
|
|
98
|
-
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
|
|
99
|
-
now()>n.expiresAtMs?(this.store.delete(e),null):(this.store.delete(e),this.store.set(e,n),
|
|
100
|
-
next().value;o!==void 0&&this.store.delete(o);}this.store.set(e,{value:
|
|
101
|
-
try{return structuredClone(t)}catch{return t}}var
|
|
99
|
+
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 Kn=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.
|
|
100
|
+
now()>n.expiresAtMs?(this.store.delete(e),null):(this.store.delete(e),this.store.set(e,n),da(n.value)):null}async set(e,n,r){if(this.store.size>=this.maxEntries&&!this.store.has(e)){let o=this.store.keys().
|
|
101
|
+
next().value;o!==void 0&&this.store.delete(o);}this.store.set(e,{value:da(n),expiresAtMs:r!=null?this.now()+r:null});}async delete(e){this.store.delete(e);}get size(){return this.store.size}};function da(t){
|
|
102
|
+
try{return structuredClone(t)}catch{return t}}var Gn=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.
|
|
102
103
|
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.
|
|
103
|
-
waiters.get(e)??1)+1),n}get activeKeys(){return this.inflight.size}};function
|
|
104
|
-
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
|
|
105
|
-
return t<=0||e>=t*n?false:
|
|
104
|
+
waiters.get(e)??1)+1),n}get activeKeys(){return this.inflight.size}};function an(t){return !Number.isFinite(t)||t<0?-1:t>=1?1e3:Math.floor(t*1e3+1e-9)}var cn=t=>t/1e3;function Vd(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),
|
|
105
|
+
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 qo(t,e,n,r){
|
|
106
|
+
return t<=0||e>=t*n?false:Vd(t,e,n)<=r}function Qn(t,e){return Math.ceil(Math.log(e)/Math.log1p(-t))}function Zn(t,e){return 6*t/(Math.PI*Math.PI*(e+1)*(e+1))}var Ye=class{total=new Uint32Array(1001);erroneas=new Uint32Array(
|
|
106
107
|
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(
|
|
107
|
-
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
|
|
108
|
-
s);if(i==null)return null;for(;i<1e3&&t.total[i]===0;)i++;return i}function
|
|
109
|
-
n:o,e:i}=t.acumulados(),s=[...new Set(e)].sort((c,u)=>u-c),a=null;for(let c of s){if(!
|
|
110
|
-
e;this.alfa=n;this.primeraMirada=2*
|
|
108
|
+
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 Ud(t,e,n){let{n:r,e:o}=t.acumulados(),i=null;for(let s=1e3;s>=0;s--)qo(r[s],o[s],e,n)&&(i=
|
|
109
|
+
s);if(i==null)return null;for(;i<1e3&&t.total[i]===0;)i++;return i}function zo(t,e,n){let r=[];for(let o of [1,1/4,1/16,1/64,1/256]){let i=Ud(t,e,n*o);i!=null&&r.push(i);}return r}function Vo(t,e,n,r){let{
|
|
110
|
+
n:o,e:i}=t.acumulados(),s=[...new Set(e)].sort((c,u)=>u-c),a=null;for(let c of s){if(!qo(o[c],i[c],n,r))break;a={indice:c,retenidas:o[c],erroneas:i[c]};}return a}var sn=class t{constructor(e,n){this.delta=
|
|
111
|
+
e;this.alfa=n;this.primeraMirada=2*Qn(e,Zn(n,0));}delta;alfa;seleccion=new Ye;retenida=new Ye;etiquetas=0;miradas=0;candidatoPrevio=null;certificado=null;primeraMirada;etiquetasDeLaMirada(e){return Bo(
|
|
111
112
|
this.primeraMirada,e)}exportar(){return {labeled:this.etiquetas,looks:this.miradas,previousCandidate:this.candidatoPrevio,certified:this.certificado?{floorIndex:this.certificado.indice,heldOut:this.certificado.
|
|
112
|
-
retenidas,wrong:this.certificado.erroneas}:null,selection:
|
|
113
|
-
(r===null||typeof r!="object"||Array.isArray(r))&&s("not an object");let a=r,c=a.labeled;
|
|
114
|
-
`${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=
|
|
113
|
+
retenidas,wrong:this.certificado.erroneas}:null,selection:pa(this.seleccion),heldOut:pa(this.retenida)}}static restaurar(e,n,r,o){let i=new t(e,n),s=f=>{throw new Pe(`importCalibration: ${o}: ${f}`)};
|
|
114
|
+
(r===null||typeof r!="object"||Array.isArray(r))&&s("not an object");let a=r,c=a.labeled;on(c)||s("`labeled` must be a non-negative integer");let u=c,l=fa(a.selection,`${o}.selection`),d=fa(a.heldOut,
|
|
115
|
+
`${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=Hd(
|
|
115
116
|
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;
|
|
116
|
-
h!==null&&!
|
|
117
|
-
ct");let f=m;
|
|
118
|
-
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=
|
|
119
|
-
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"),
|
|
120
|
-
te does not pass the test it claims to have passed");let{n:k,e:T}=d.acumulados(),
|
|
117
|
+
h!==null&&!Fo(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\
|
|
118
|
+
ct");let f=m;Fo(f.floorIndex)||s("`certified.floorIndex` must be a grid index"),(!on(f.heldOut)||!on(f.wrong))&&s("`certified.heldOut` and `certified.wrong` must be non-negative integers"),g={indice:f.
|
|
119
|
+
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=Bo(i.primeraMirada,
|
|
120
|
+
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"),qo(g.retenidas,g.erroneas,e,Zn(n,v))||s("the certifica\
|
|
121
|
+
te does not pass the test it claims to have passed");let{n:k,e:T}=d.acumulados(),x=k[g.indice]-g.retenidas,P=T[g.indice]-g.erroneas;(x<0||P<0||P>x||x>d.n-y)&&s("the held-out labels at the floor do not\
|
|
121
122
|
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,
|
|
122
|
-
i.candidatoPrevio=h,i.certificado=g,i}anotar(e,n){let r=
|
|
123
|
-
this.mirar());}mirar(){let e=
|
|
123
|
+
i.candidatoPrevio=h,i.certificado=g,i}anotar(e,n){let r=an(e);r<0||((this.etiquetas%2===0?this.seleccion:this.retenida).anotar(r,n),this.etiquetas++,this.etiquetas>=this.etiquetasDeLaMirada(this.miradas)&&
|
|
124
|
+
this.mirar());}mirar(){let e=Zn(this.alfa,this.miradas);this.miradas++;let n=zo(this.seleccion,this.delta,e),r=this.candidatoPrevio==null?n:[...n,this.candidatoPrevio],o=Vo(this.retenida,r,this.delta,e);
|
|
124
125
|
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.
|
|
125
|
-
retenida.n,retenidasEnSuelo:this.certificado?.retenidas??0,erroneasEnSuelo:this.certificado?.erroneas??0,miradas:this.miradas,minimasParaLaSiguiente:
|
|
126
|
-
etiquetasDeLaMirada(this.miradas)}}},
|
|
127
|
-
function
|
|
128
|
-
confidence,similarityThreshold:t.similarityThreshold,grid:1e3},segments:n}}function
|
|
129
|
-
state must be an object");let r=t;r.format!==
|
|
130
|
-
wer SDK (version ${o}); this one reads version ${
|
|
126
|
+
retenida.n,retenidasEnSuelo:this.certificado?.retenidas??0,erroneasEnSuelo:this.certificado?.erroneas??0,miradas:this.miradas,minimasParaLaSiguiente:Qn(this.delta,Zn(this.alfa,this.miradas)),etiquetasParaLaSiguiente:this.
|
|
127
|
+
etiquetasDeLaMirada(this.miradas)}}},Pe=class extends Error{constructor(e){super(`[bvsala] ${e}`),this.name="CalibrationStateError";}},ma="bvsala.semantic-calibration",Yn=1,ha=["single_shot","agentic"];
|
|
128
|
+
function ga(t,e){let n={};for(let r of ha){let o=e.get(r);o&&(n[r]=o.exportar());}return {format:ma,version:Yn,embedder:t.embedder,verifier:t.verifier,judge:t.judge,config:{maxErrorRate:t.maxErrorRate,confidence:t.
|
|
129
|
+
confidence,similarityThreshold:t.similarityThreshold,grid:1e3},segments:n}}function ba(t,e){let n=l=>{throw new Pe(`importCalibration: ${l}`)};(t===null||typeof t!="object"||Array.isArray(t))&&n("the \
|
|
130
|
+
state must be an object");let r=t;r.format!==ma&&n(`not a semantic calibration state (format ${JSON.stringify(r.format)})`);let o=r.version;typeof o=="number"&&o>Yn&&n(`this state was exported by a ne\
|
|
131
|
+
wer SDK (version ${o}); this one reads version ${Yn}`),o!==Yn&&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\
|
|
131
132
|
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,
|
|
132
133
|
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\
|
|
133
134
|
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[
|
|
134
|
-
l,d]of Object.entries(c))
|
|
135
|
-
e)}function
|
|
136
|
-
t)&&t>=0&&t<=1e3}function
|
|
137
|
-
isArray(t)||n("must be an array of [gridIndex, labels, wrong]");let r=new
|
|
138
|
-
s)||s<=o)&&n("grid indices must be increasing integers in [0, 1000]"),(!
|
|
139
|
-
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
|
|
135
|
+
l,d]of Object.entries(c))ha.includes(l)||n(`unknown segment ${JSON.stringify(l)}`),u.set(l,sn.restaurar(e.maxErrorRate,1-e.confidence,d,`segments.${l}`));return u}function Bo(t,e){return Math.ceil(t*1.5**
|
|
136
|
+
e)}function Hd(t,e){let n=0;for(;Bo(t,n)<=e;)n++;return n}function on(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=4294967295}function Fo(t){return typeof t=="number"&&Number.isInteger(
|
|
137
|
+
t)&&t>=0&&t<=1e3}function pa(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 fa(t,e){let n=i=>{throw new Pe(`importCalibration: ${e}: ${i}`)};Array.
|
|
138
|
+
isArray(t)||n("must be an array of [gridIndex, labels, wrong]");let r=new Ye,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;(!Fo(
|
|
139
|
+
s)||s<=o)&&n("grid indices must be increasing integers in [0, 1000]"),(!on(a)||a===0)&&n("label counts must be positive integers"),(!on(c)||c>a)&&n("wrong counts must be integers between 0 and the lab\
|
|
140
|
+
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 Xn(t){let{maxErrorRate:e}=t,n=t.confidence??.95,r=t.auditRate??.05;if(!(e>0&&e<=.5))throw new RangeError(
|
|
140
141
|
`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\
|
|
141
|
-
.auditRate must be in [0, 1); got ${r}`);return {maxErrorRate:e,confidence:n,auditRate:r}}function
|
|
142
|
-
7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}function
|
|
143
|
-
isArray(t))return `[${t.map(
|
|
144
|
-
stringify(t)??"null"}function
|
|
145
|
-
let u=
|
|
146
|
-
o)}}function
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
142
|
+
.auditRate must be in [0, 1); got ${r}`);return {maxErrorRate:e,confidence:n,auditRate:r}}function va(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>>>
|
|
143
|
+
7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}function Uo(t,e){let n=o=>o!==null&&typeof o=="object";if(n(t.data)&&n(e.data))return er(t.data)===er(e.data);let r=o=>o.trim().replace(/\s+/g," ");return r(t.text)===r(e.text)}function er(t){if(Array.
|
|
144
|
+
isArray(t))return `[${t.map(er).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)}:${er(e[n])}`).join(",")}}`}return JSON.
|
|
145
|
+
stringify(t)??"null"}function F0(t,e){let{maxErrorRate:n,confidence:r}=Xn(e),o=1-r,i=new Ye,s=new Ye,a=va(1592642065),c=0;for(let l of t){let d=an(l.score),p=a()<.5;d<0||((p?i:s).anotar(d,l.correct),c++);}
|
|
146
|
+
let u=Vo(s,zo(i,n,o),n,o);return {maxErrorRate:n,confidence:r,floor:u?cn(u.indice):null,labeled:c,heldOut:s.n,heldOutAtFloor:u?.retenidas??0,wrongHeldOutAtFloor:u?.erroneas??0,minHeldOutToCertify:Qn(n,
|
|
147
|
+
o)}}var Ho=new Map;function $(t,e){for(let n of t.split(/\s+/).filter(Boolean))Ho.set(n,e);}var Wd=["zero","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen",
|
|
148
|
+
"fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"];Wd.forEach((t,e)=>$(t,{k:"unidad",v:e}));["twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"].forEach((t,e)=>$(t,{k:"\
|
|
149
|
+
decena",v:20+10*e}));$("hundred hundreds",{k:"cien"});$("thousand thousands",{k:"escala",v:1e3});$("million millions",{k:"escala",v:1e6});$("billion billions",{k:"escala",v:1e9});var Jd=["","first","s\
|
|
150
|
+
econd","third","fourth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelfth","thirteenth","fourteenth","fifteenth","sixteenth","seventeenth","eighteenth","nineteenth"];Jd.forEach((t,e)=>{
|
|
151
|
+
t&&($(t,{k:"ordinal",v:e}),e>=3&&$(`${t}s`,{k:"ordinal",v:e}));});["twentieth","thirtieth","fortieth","fiftieth","sixtieth","seventieth","eightieth","ninetieth"].forEach((t,e)=>{$(t,{k:"ordinal",v:20+10*
|
|
152
|
+
e}),$(`${t}s`,{k:"ordinal",v:20+10*e});});$("hundredth hundredths",{k:"ordinal",v:100});$("thousandth thousandths",{k:"ordinal",v:1e3});$("millionth millionths",{k:"ordinal",v:1e6});$("half halves",{k:"\
|
|
153
|
+
token",t:"f:1/2"});$("quarter quarters",{k:"token",t:"f:1/4"});$("once single",{k:"token",t:"m:1"});$("twice double doubled doubles doubling",{k:"token",t:"m:2"});$("thrice triple tripled triples trip\
|
|
154
|
+
ling",{k:"token",t:"m:3"});$("quadruple quadrupled quadruples quadrupling",{k:"token",t:"m:4"});$("dozen dozens",{k:"token",t:"c:12"});$("pair pairs",{k:"token",t:"c:2"});$("times time",{k:"veces"});$(
|
|
155
|
+
"and",{k:"conector"});var Kd=["cero","uno","dos","tres","cuatro","cinco","seis","siete","ocho","nueve","diez","","doce","trece","catorce","quince","dieciseis","diecisiete","dieciocho","diecinueve"];Kd.
|
|
156
|
+
forEach((t,e)=>t&&$(t,{k:"unidad",v:e}));$("veinte",{k:"decena",v:20});["veintiuno","veintidos","veintitres","veinticuatro","veinticinco","veintiseis","veintisiete","veintiocho","veintinueve"].forEach(
|
|
157
|
+
(t,e)=>$(t,{k:"unidad",v:21+e}));["treinta","cuarenta","cincuenta","sesenta","setenta","ochenta","noventa"].forEach((t,e)=>$(t,{k:"decena",v:30+10*e}));$("cien ciento",{k:"centena",v:100});[["doscient\
|
|
158
|
+
os doscientas",200],["trescientos trescientas",300],["cuatrocientos cuatrocientas",400],["quinientos quinientas",500],["seiscientos seiscientas",600],["setecientos setecientas",700],["ochocientos ocho\
|
|
159
|
+
cientas",800],["novecientos novecientas",900]].forEach(([t,e])=>$(t,{k:"centena",v:e}));$("mil miles",{k:"escala",v:1e3});$("millon millones",{k:"escala",v:1e6});$("billon billones",{k:"escala",v:1e12});
|
|
160
|
+
[["primero primera primer primeros primeras",1],["segundo segunda segundos segundas",2],["tercero tercera tercer terceros terceras tercio tercios",3],["cuarto cuarta cuartos cuartas",4],["quinto quint\
|
|
161
|
+
a quintos quintas",5],["sexto sexta sextos sextas",6],["septimo septima septimos septimas",7],["octavo octava octavos octavas",8],["noveno novena novenos novenas",9],["decimo decima decimos decimas",10]].
|
|
162
|
+
forEach(([t,e])=>$(t,{k:"ordinal",v:e}));$("mitad mitades medio media medios medias",{k:"token",t:"f:1/2"});$("doble dobles",{k:"token",t:"m:2"});$("cuadruple",{k:"token",t:"m:4"});$("docena docenas",
|
|
163
|
+
{k:"token",t:"c:12"});$("par pares",{k:"token",t:"c:2"});$("veces vez",{k:"veces"});$("y",{k:"conector"});[["zero",0],["dues",2],["quatre",4],["cinc",5],["sis",6],["set",7],["vuit",8],["nou",9],["deu",
|
|
164
|
+
10],["onze",11],["dotze",12],["tretze",13],["catorze",14],["quinze",15],["setze",16],["disset",17],["divuit",18],["dinou",19]].forEach(([t,e])=>$(t,{k:"unidad",v:e}));["vint","trenta","quaranta","cinq\
|
|
165
|
+
uanta","seixanta","setanta","vuitanta","noranta"].forEach((t,e)=>$(t,{k:"decena",v:20+10*e}));$("cent",{k:"centena",v:100});$("cents centes",{k:"cien"});$("milio milions",{k:"escala",v:1e6});[["segon \
|
|
166
|
+
segona segons segones",2],["terc tercos",3],["quart quarta quarts quartes",4],["cinque cinquena",5],["sise sisena",6],["sete setena",7],["vuite vuitena",8],["nove novena",9],["dese desena",10]].forEach(
|
|
167
|
+
([t,e])=>$(t,{k:"ordinal",v:e}));$("meitat meitats mig mitja",{k:"token",t:"f:1/2"});$("dotzena dotzenes",{k:"token",t:"c:12"});$("parell parells",{k:"token",t:"c:2"});$("vegades vegada",{k:"veces"});
|
|
168
|
+
$("i",{k:"conector"});var Gd=/\p{M}+/gu;function Zd(t){return t.toLowerCase().normalize("NFD").replace(Gd,"").split(/[^\p{L}]+/u).filter(Boolean)}function Wo(t){let e=[],n=Zd(t),r=false,o=0,i=0,s=null,a=1/0,
|
|
169
|
+
c=(l="n")=>{r&&e.push(`${l}:${o+i}`),r=false,o=0,i=0,s=null,a=1/0;},u=(l,d)=>{c(),r=true,i=l,s=d;};for(let l=0;l<n.length;l++){let d=Ho.get(n[l]);if(!d){c();continue}switch(d.k){case "unidad":{r&&(s==="decena"&&
|
|
170
|
+
d.v<10&&i%10===0||(s==="cien"||s==="centena")&&i%100===0||s==="escala")?(i+=d.v,s="unidad"):u(d.v,"unidad");break}case "decena":{r&&((s==="cien"||s==="centena")&&i%100===0||s==="escala")?(i+=d.v,s="dec\
|
|
171
|
+
ena"):u(d.v,"decena");break}case "centena":{r&&s==="escala"?(i+=d.v,s="centena"):u(d.v,"centena");break}case "cien":{r&&(s==="unidad"||s==="decena")&&i>0&&i<100?(i*=100,s="cien"):u(100,"cien");break}case "\
|
|
172
|
+
escala":{r&&s!=="escala"&&d.v<a?(o+=(i||1)*d.v,i=0,s="escala",a=d.v):(u(0,"escala"),o=d.v,a=d.v);break}case "ordinal":{if(r&&s==="decena"&&d.v<10&&i%10===0){let p=o+i+d.v;r=false,c(),e.push(`o:${p}`);}else
|
|
173
|
+
c(),e.push(`o:${d.v}`);break}case "veces":{r&&c("m");break}case "conector":{let p=Ho.get(n[l+1]??"");r&&(s==="decena"||s==="cien"||s==="centena"||s==="escala")&&p!=null&&(p.k==="unidad"||p.k==="decena")||
|
|
174
|
+
c();break}case "token":{c(),e.push(d.t);break}}}return c(),e}function Yd(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 Qd(t){return t.toLowerCase().normalize("NFKC").split(/[^\p{L}\p{N}]+/u).filter(
|
|
175
|
+
Boolean)}function Xd(t){let e=new Array(256).fill(0),n=Qd(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+
|
|
176
|
+
1]}`;r.set(a,(r.get(a)??0)+1);}}for(let[i,s]of r){let a=Yd(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++)
|
|
177
|
+
e[i]/=o;return e}function ya(t){return Xd(t)}var ka=.72;function ep(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 tp=new Set(
|
|
150
178
|
["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\
|
|
151
|
-
\xFAn","ninguna","ninguno","nada","nadie","sense","mai","tampoc","cap","gens","ningu","ning\xFA","res"]),
|
|
179
|
+
\xFAn","ninguna","ninguno","nada","nadie","sense","mai","tampoc","cap","gens","ningu","ning\xFA","res"]),np=new Set(["the","a","an","of","to","in","on","for","and","or","is","are","was","were","what",
|
|
152
180
|
"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",
|
|
153
181
|
"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\
|
|
154
182
|
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",
|
|
155
183
|
"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",
|
|
156
|
-
"aquests","aquestes","aquell","aquella","que","quin","quina","qui","com","quan","on","dona","vull","necessito","pots","podries","sisplau","gracies","meu","meva","seu","seva","hi"]);function
|
|
157
|
-
match(/\d[\d.,:/-]*/g)??[]).map(e=>e.replace(/[.,:/-]+$/,""))}function
|
|
158
|
-
return false;n.set(r,o-1);}return true}function
|
|
159
|
-
function
|
|
160
|
-
`).map(e=>{let n=
|
|
161
|
-
r[o].rol||!
|
|
162
|
-
|
|
163
|
-
|
|
184
|
+
"aquests","aquestes","aquell","aquella","que","quin","quina","qui","com","quan","on","dona","vull","necessito","pots","podries","sisplau","gracies","meu","meva","seu","seva","hi"]);function un(t){return (t.
|
|
185
|
+
match(/\d[\d.,:/-]*/g)??[]).map(e=>e.replace(/[.,:/-]+$/,""))}function Jo(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)
|
|
186
|
+
return false;n.set(r,o-1);}return true}function ln(t){return t.split(/\s+/).filter(Boolean)}function dn(t){return t.filter(e=>tp.has(e.replace(/'/g,""))||e.endsWith("n't")).length}var rp=/^(system|user|assistant|tool):/;
|
|
187
|
+
function xa(t){return t.split(`
|
|
188
|
+
`).map(e=>{let n=rp.exec(e);return n?{rol:n[1],texto:e.slice(n[0].length)}:{rol:"",texto:e}})}function op(t,e){let n=xa(t),r=xa(e);if(n.length!==r.length)return false;for(let o=0;o<n.length;o++)if(n[o].rol!==
|
|
189
|
+
r[o].rol||!ip(n[o].texto,r[o].texto))return false;return true}function ip(t,e){let n=[...un(t),...Wo(t)],r=[...un(e),...Wo(e)];if(!Jo(n,r))return false;let o=ln(t),i=ln(e);if(dn(o)!==dn(i))return false;let s=d=>d.length>
|
|
190
|
+
1&&!np.has(d)&&!/^\d/.test(d),a=new Set(o.filter(s)),c=new Set(i.filter(s));if(a.size===0&&c.size===0)return true;let u=0;for(let d of a)c.has(d)&&u++;let l=a.size+c.size-u;return l===0?true:u/l>=.75}var sp="\
|
|
191
|
+
lexical-256-v1",ap="same-answer-v1",wa=class{records=[];embed;verify;similarityThreshold;acceptThreshold;ttlMs;maxRecords;now;embebedorPropio;calibracion;estados=new Map;nombres;pendientes=new Set;aceptacionExplicita;constructor(e={}){
|
|
192
|
+
let n=e.embed==null;if(this.embebedorPropio=n,this.embed=e.embed??ya,this.verify=e.verify,this.similarityThreshold=e.similarityThreshold??(n?ka:.9),this.acceptThreshold=e.acceptThreshold??.85,this.aceptacionExplicita=
|
|
164
193
|
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}:{}},
|
|
165
|
-
this.ttlMs=e.ttlMs,this.maxRecords=e.maxRecords??5e3,this.now=e.now??(()=>Date.now()),e.calibration){let r=
|
|
194
|
+
this.ttlMs=e.ttlMs,this.maxRecords=e.maxRecords??5e3,this.now=e.now??(()=>Date.now()),e.calibration){let r=Xn(e.calibration);this.calibracion={...r,judge:e.calibration.judge??Uo,perRecordFloors:e.calibration.
|
|
166
195
|
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){
|
|
167
196
|
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!==
|
|
168
197
|
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||
|
|
169
198
|
i.schemaVersion!==e.schemaVersion||i.safetyPolicyVersion!==e.safetyPolicyVersion||i.toolsetHash!==e.toolsetHash||i.toolTurnsHash!==e.toolTurnsHash||i.temperature!==e.temperature||i.seed!==e.seed||this.
|
|
170
|
-
ttlMs!=null&&this.now()-i.storedAtMs>this.ttlMs)continue;let s=
|
|
199
|
+
ttlMs!=null&&this.now()-i.storedAtMs>this.ttlMs)continue;let s=ep(r,i.embedding);if(s<this.similarityThreshold||!op(e.normalizedText,i.query))continue;let a=this.verify?await this.verify(e.normalizedText,
|
|
171
200
|
i.query):s,c=Math.min(s,a);n&&c<this.acceptThreshold||(!o||c>o.confidence)&&(o={record:i,similarity:s,verifierScore:a,confidence:c,ageMs:this.now()-i.storedAtMs,similarityFloor:this.similarityThreshold,
|
|
172
201
|
acceptFloor:this.acceptThreshold,embedder:this.embebedorPropio?"built_in":"custom",verifierRan:this.verify!=null});}return o}async lookup(e,n={}){let r=this.calibracion;if(!r)return {hit:await this.mejorCandidata(
|
|
173
202
|
e,true),probe:null};let o=n.agentic?"agentic":"single_shot",i=await this.mejorCandidata(e,false);if(!i)return {hit:null,probe:null};let s=this.estadoDe(o),a=s.suelo,c=i.confidence,u=p=>({hit:null,probe:{reason:p,
|
|
174
|
-
score:c,segment:o,record:i.record}});if(a==null)return u("calibrating");if(
|
|
175
|
-
null&&c<=i.record.failedAtScore)return u("record_floor");if(r.auditRate>0&&r.random()<r.auditRate)return u("audit");let l=
|
|
203
|
+
score:c,segment:o,record:i.record}});if(a==null)return u("calibrating");if(an(c)<a||this.aceptacionExplicita&&c<this.acceptThreshold)return u("below_floor");if(r.perRecordFloors&&i.record.failedAtScore!=
|
|
204
|
+
null&&c<=i.record.failedAtScore)return u("record_floor");if(r.auditRate>0&&r.random()<r.auditRate)return u("audit");let l=cn(a),d=s.resumen();return {hit:{...i,acceptFloor:this.aceptacionExplicita?Math.
|
|
176
205
|
max(l,this.acceptThreshold):l,calibration:{maxErrorRate:r.maxErrorRate,confidence:r.confidence,floor:l,heldOutAtFloor:d.retenidasEnSuelo,wrongHeldOutAtFloor:d.erroneasEnSuelo,labeled:d.etiquetas,segment:o}},
|
|
177
206
|
probe:null}}observe(e,n){let r=this.etiquetar(e,n);return this.pendientes.add(r),r.finally(()=>this.pendientes.delete(r)),r}async etiquetar(e,n){let r=this.calibracion;if(!r)return null;let o;try{o=await r.
|
|
178
207
|
judge(e.record.answer,n)===!0;}catch{return null}return this.estadoDe(e.segment).anotar(e.score,o),!o&&r.perRecordFloors&&(e.record.failedAtScore=Math.max(e.record.failedAtScore??-1/0,e.score)),o}async settled(){
|
|
179
208
|
for(;this.pendientes.size>0;)await Promise.allSettled([...this.pendientes]);}calibrationStatus(e="single_shot"){let n=this.calibracion;if(!n)return null;let r=this.estadoDe(e).resumen();return {maxErrorRate:n.
|
|
180
|
-
maxErrorRate,confidence:n.confidence,floor:r.suelo==null?null:
|
|
181
|
-
minimasParaLaSiguiente,nextTestAt:r.etiquetasParaLaSiguiente}}exportCalibration(){return
|
|
182
|
-
on"),r=e;if(typeof e=="string")try{r=JSON.parse(e);}catch{throw new
|
|
183
|
-
etiquetas>0)throw new
|
|
184
|
-
i,s);}identidad(e){let n=this.calibracion;if(!n)throw new
|
|
185
|
-
on is only ever restored under the same one`)},o=this.embebedorPropio?`built_in:${
|
|
186
|
-
verifier??r("verifierId","verifier")}`,s=n.judge===
|
|
187
|
-
confidence:n.confidence,similarityThreshold:this.similarityThreshold}}estadoDe(e){let n=this.estados.get(e);if(!n){let r=this.calibracion;n=new
|
|
209
|
+
maxErrorRate,confidence:n.confidence,floor:r.suelo==null?null:cn(r.suelo),labeled:r.etiquetas,heldOut:r.retenidas,heldOutAtFloor:r.retenidasEnSuelo,wrongHeldOutAtFloor:r.erroneasEnSuelo,minHeldOutToCertify:r.
|
|
210
|
+
minimasParaLaSiguiente,nextTestAt:r.etiquetasParaLaSiguiente}}exportCalibration(){return ga(this.identidad("exportCalibration"),this.estados)}importCalibration(e){let n=this.identidad("importCalibrati\
|
|
211
|
+
on"),r=e;if(typeof e=="string")try{r=JSON.parse(e);}catch{throw new Pe("importCalibration: the state is a string but not JSON")}let o=ba(r,n);for(let[i]of o){let s=this.estados.get(i);if(s&&s.resumen().
|
|
212
|
+
etiquetas>0)throw new Pe(`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(
|
|
213
|
+
i,s);}identidad(e){let n=this.calibracion;if(!n)throw new Pe(`${e}: this cache runs without \`calibration\``);let r=(a,c)=>{throw new Pe(`${e}: pass \`${a}\` naming your ${c}, so that a saved calibrati\
|
|
214
|
+
on is only ever restored under the same one`)},o=this.embebedorPropio?`built_in:${sp}`:`custom:${this.nombres.embedder??r("embedderId","embed function")}`,i=this.verify==null?null:`custom:${this.nombres.
|
|
215
|
+
verifier??r("verifierId","verifier")}`,s=n.judge===Uo?`built_in:${ap}`:`custom:${this.nombres.judge??r("calibration.judgeId","judge")}`;return {embedder:o,verifier:i,judge:s,maxErrorRate:n.maxErrorRate,
|
|
216
|
+
confidence:n.confidence,similarityThreshold:this.similarityThreshold}}estadoDe(e){let n=this.estados.get(e);if(!n){let r=this.calibracion;n=new sn(r.maxErrorRate,1-r.confidence),this.estados.set(e,n);}
|
|
188
217
|
return n}async store(e,n){let r=await this.embed(e.normalizedText);this.records.length>=this.maxRecords&&this.records.shift(),this.records.push({embedding:r,query:e.normalizedText,answer:n,tenantId:e.
|
|
189
218
|
tenantId,authorizationScope:e.authorizationScope,principal:e.principal,knowledgeEpoch:e.knowledgeEpoch,contractId:e.contractId,model:e.model,systemPromptHash:e.systemPromptHash,structuredDataHash:e.structuredDataHash,
|
|
190
219
|
locale:e.locale,schemaVersion:e.schemaVersion,safetyPolicyVersion:e.safetyPolicyVersion,toolsetHash:e.toolsetHash,...e.toolTurnsHash!==void 0?{toolTurnsHash:e.toolTurnsHash}:{},temperature:e.temperature,
|
|
191
220
|
seed:e.seed,storedAtMs:this.now()});}invalidateEpoch(e){let n=0;for(let r=this.records.length-1;r>=0;r--)this.records[r].knowledgeEpoch===e&&(this.records.splice(r,1),n++);return n}get size(){return this.
|
|
192
|
-
records.length}};var
|
|
221
|
+
records.length}};var Sa=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()>
|
|
193
222
|
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(
|
|
194
|
-
o);}this.entradas.set(e,{valor:n,vence:this.now()+r});}get size(){return this.entradas.size}};var
|
|
195
|
-
|
|
196
|
-
let r=
|
|
197
|
-
return Number.isInteger(t)?String(t):String(Math.round(t*1e9)/1e9)}function
|
|
223
|
+
o);}this.entradas.set(e,{valor:n,vence:this.now()+r});}get size(){return this.entradas.size}};var Ko=class{resolvers=[];register(e){return this.resolvers.push(e),this}try(e){for(let n of this.resolvers)try{let r=n.try(e);if(r)return r}catch{}return null}get size(){return this.resolvers.length}},
|
|
224
|
+
cp={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]??up(t.normalizedText))?.trim();if(!n)return null;
|
|
225
|
+
let r=dp(n);return r===null||!Number.isFinite(r)?null:{text:lp(r),data:{value:r},resolver:"arithmetic"}}};function up(t){return /^[0-9+\-*/%.()\s]+$/.test(t.trim())&&/[+\-*/%]/.test(t)?t.trim():null}function lp(t){
|
|
226
|
+
return Number.isInteger(t)?String(t):String(Math.round(t*1e9)/1e9)}function dp(t){let e=t.match(/\d+\.?\d*|[+\-*/%()]/g);if(!e||e.join("")!==t.replace(/\s+/g,""))return null;let n=[],r=[],o={"+":1,"-":1,
|
|
198
227
|
"*":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===
|
|
199
228
|
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&&
|
|
200
229
|
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),
|
|
201
|
-
s=true;}for(;r.length;){let a=r.pop();if(a==="("||!i(a))return null}return n.length===1?n[0]:null}function
|
|
202
|
-
|
|
230
|
+
s=true;}for(;r.length;){let a=r.pop();if(a==="("||!i(a))return null}return n.length===1?n[0]:null}function Ta(){return new Ko().register(cp)}var pp=/\b(compare|versus|\bvs\b|difference between|both|and then|after that|which is (?:better|cheaper|faster)|compar[ae]|diferencia entre)\b/i,Ca=/\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,
|
|
231
|
+
fp=/\b(summarize|rewrite|translate|classify|extract|reformat|fix|convert|the following|below|above|this text|resume|reescribe|traduce|clasifica)\b/i,tr=class{classifier;maxRounds;constructor(e={}){this.
|
|
203
232
|
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.
|
|
204
|
-
test(r))return
|
|
205
|
-
.8,"self-contained transformation",0);let i=this.classifier?.classify(r);return i&&i.confidence>=.75?
|
|
206
|
-
e"?
|
|
207
|
-
d question",Math.min(this.maxRounds,2)):
|
|
208
|
-
"SINGLE_RETRIEVAL"?1:t==="MULTI_HOP_RETRIEVAL"?Math.min(e,2):0}function
|
|
209
|
-
us-4-5-20251101","claude-sonnet-4-5-20250929","claude-haiku-4-5-20251001"],
|
|
210
|
-
name:"tool_search_tool_bm25"},regex:{type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"}},
|
|
211
|
-
function
|
|
233
|
+
test(r))return Fe("TOOL_ACTION",.9,"imperative + write tool available",0);if(n==="off")return Fe("NO_RETRIEVAL",1,"retrieval disabled by caller",0);if(fp.test(r)&&!Ca.test(r))return Fe("NO_RETRIEVAL",
|
|
234
|
+
.8,"self-contained transformation",0);let i=this.classifier?.classify(r);return i&&i.confidence>=.75?Fe(i.executionClass,i.confidence,"local classifier",mp(i.executionClass,this.maxRounds)):n==="singl\
|
|
235
|
+
e"?Fe("SINGLE_RETRIEVAL",.7,"caller hint: single",1):n==="multi"?Fe("MULTI_HOP_RETRIEVAL",.7,"caller hint: multi",Math.min(this.maxRounds,2)):pp.test(r)?Fe("MULTI_HOP_RETRIEVAL",.7,"comparison/compoun\
|
|
236
|
+
d question",Math.min(this.maxRounds,2)):Ca.test(r)?Fe("SINGLE_RETRIEVAL",.65,"single factual lookup",1):Fe("NO_RETRIEVAL",.5,"no retrieval signal (conservative default)",0)}};function mp(t,e){return t===
|
|
237
|
+
"SINGLE_RETRIEVAL"?1:t==="MULTI_HOP_RETRIEVAL"?Math.min(e,2):0}function Fe(t,e,n,r){return {executionClass:t,confidence:e,reason:n,rounds:r}}var hp=["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\
|
|
238
|
+
us-4-5-20251101","claude-sonnet-4-5-20250929","claude-haiku-4-5-20251001"],Ea={herramientas:10,tokensDeEsquemas:1e4},Pa=5,gp={regex:200,bm25:500},Ra=1e4,nr={bm25:{type:"tool_search_tool_bm25_20251119",
|
|
239
|
+
name:"tool_search_tool_bm25"},regex:{type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"}},bp="bvsala_contract";function Da(t){let e=t.lastIndexOf("/");return (e>=0?t.slice(e+1):t).toLowerCase()}
|
|
240
|
+
function Go(t){let e=r=>r.replace(/-\d{8}$/,""),n=e(Da(t));return hp.some(r=>e(r)===n)}function _a(t){let e={modo:"off",siempreCargadas:[],variante:"bm25"};if(t===void 0)return e;let n=r=>r==="off"||r===
|
|
212
241
|
"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(
|
|
213
|
-
r=>typeof r=="string"))]:[],variante:t.variant==="regex"?"regex":"bm25"}}function
|
|
242
|
+
r=>typeof r=="string"))]:[],variante:t.variant==="regex"?"regex":"bm25"}}function Zo(t){return !t.some(e=>Array.isArray(e.intents)&&e.intents.length>0)&&!t.some(e=>typeof e.risk=="string")}function Ia(t){
|
|
214
243
|
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===
|
|
215
244
|
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 \
|
|
216
|
-
Responses and Agents APIs, not for Chat Completions, which is what the OpenAI-compatible adapter speaks");if(
|
|
245
|
+
Responses and Agents APIs, not for Chat Completions, which is what the OpenAI-compatible adapter speaks");if(!Go(t.modelo))return r(`${Da(t.modelo)} is not in the provider's tool search model compatib\
|
|
217
246
|
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\
|
|
218
|
-
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=
|
|
219
|
-
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!==
|
|
220
|
-
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>
|
|
221
|
-
`${c.length} tools to defer, over the provider's limit of ${
|
|
247
|
+
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=nr[n];if(t.herramientas.some(y=>y.id===o.name))
|
|
248
|
+
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!==bp),a=new Set(s),c=t.herramientas.filter(y=>!a.has(y.
|
|
249
|
+
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>Ra)return r(
|
|
250
|
+
`${c.length} tools to defer, over the provider's limit of ${Ra}`,l);if(e.modo==="always")return {aplicar:true,variante:n,...l,razon:`toolSearch "always": ${c.length} tool(s) deferred behind the provider'\
|
|
222
251
|
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\
|
|
223
|
-
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<
|
|
252
|
+
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<Ea.herramientas&&d<=Ea.tokensDeEsquemas)return r(`${t.herramientas.
|
|
224
253
|
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/
|
|
225
|
-
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,
|
|
226
|
-
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 ${
|
|
254
|
+
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,Pa).reduce((y,k)=>y+k,0),f=m*p*u,v=p*g+h*gp[n],b={ahorroDelPrefijo:f,costeDeUnaBusqueda:v};
|
|
255
|
+
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 ${Pa} largest definition\
|
|
227
256
|
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\
|
|
228
257
|
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; \
|
|
229
|
-
the layer credits nothing for it`}}function
|
|
230
|
-
this.maxTools=e.maxTools??8,this.scoreIntentMatch=e.scoreIntentMatch??
|
|
231
|
-
reason:"no tools provided",setIsStable:true}
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
258
|
+
the layer credits nothing for it`}}function Aa(t,e,n){return n||Zo(t)?[...t]:t.filter(r=>e||r.risk==="read")}var Yo=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});}},rr=class{maxTools;scoreIntentMatch;learningTurns;freezer;constructor(e={}){
|
|
259
|
+
this.maxTools=e.maxTools??8,this.scoreIntentMatch=e.scoreIntentMatch??vp,this.learningTurns=e.learningTurns??16,this.freezer=e.freezer??new Yo;}passthrough(e){return !e||e.length===0?{tools:[],droppedIds:[],
|
|
260
|
+
reason:"no tools provided",setIsStable:true}:{tools:[...e],droppedIds:[],reason:`router off: caller tools passed through whole (${e.length}/${e.length}; risk gating is the caller's responsibility while \
|
|
261
|
+
routing is off)`,setIsStable:true}}select(e,n,r,o){if(!n||n.length===0)return {tools:[],droppedIds:[],reason:"no tools provided",setIsStable:true};if(Zo(n)){let f=this.passthrough(n);return {...f,reason:`ca\
|
|
262
|
+
talogue declares no \`intents\` and no \`risk\`: nothing to select on, passed through whole (${f.tools.length}/${n.length}). Declare ToolDescriptor.intents/risk to enable pruning`}}let i=r==="TOOL_ACT\
|
|
263
|
+
ION",s=n.filter(f=>i||f.risk==="read"),a=f=>i&&f.risk!=="read",c=s.filter(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),
|
|
264
|
+
d=c.map(f=>({tool:f,score:this.scoreIntentMatch(e,f)})).filter(f=>f.score>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))].
|
|
265
|
+
map(f=>({tool:f})).map(f=>f.tool).sort((f,v)=>f.id<v.id?-1:f.id>v.id?1:0);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(x=>y.has(
|
|
266
|
+
x.id));this.freezer.record(o,f.ids,v);let T=new Set(k.map(x=>x.id));return {tools:k,droppedIds:n.filter(x=>!T.has(x.id)).map(x=>x.id),reason:`frozen tool set after ${this.learningTurns} turns (${k.length}\
|
|
267
|
+
/${n.length}): it no longer depends on this request's text, so the prefix cache survives`,setIsStable:true}}let b=[...new Set([...f?.ids??[],...h.map(y=>y.id)])].sort().slice(0,this.maxTools);this.freezer.
|
|
268
|
+
record(o,b,v);}let m=new Set(h.map(f=>f.id)),g=n.filter(f=>!m.has(f.id)).map(f=>f.id);return {tools:h,droppedIds:g,reason:`selected ${h.length}/${n.length} by intent match (writes ${i?"allowed":"blocked"}\
|
|
269
|
+
)`,setIsStable:g.length===0}}};function vp(t,e){let n=Wn(t),r=0;for(let o of Array.isArray(e.intents)?e.intents:[]){let i=Wn(o);i&&(n.includes(i)?r+=2:i.split(/\s+/).some(s=>s.length>3&&n.includes(s))&&
|
|
270
|
+
(r+=1));}return r}function yp(t){let e=new Set,n=[];for(let r of t){let o=r.hash??xp(r.text);e.has(o)||(e.add(o),n.push(r));}return n}function kp(t,e={maxDocuments:5}){let n=e.minDocuments??1,r=[...t].sort((s,a)=>(a.score??
|
|
242
271
|
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(
|
|
243
|
-
s);else break}return i}async function
|
|
244
|
-
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=
|
|
245
|
-
(r=await e.reranker.rerank(t.query,r));let i=
|
|
246
|
-
...t.userPreferences},decisions:[...t.decisions],openItems:[...t.openItems],evidenceRefs:[...t.evidenceRefs]};for(let[r,o]of Object.entries(e.set??{}))r==="userPreferences"&&
|
|
247
|
-
o):n.confirmedFacts[r]=o;for(let[r,o]of Object.entries(e.append??{})){let i=
|
|
248
|
-
|
|
249
|
-
${r}`});let o=t.history.slice(-e);return n.push(...o,t.current),n}function
|
|
272
|
+
s);else break}return i}async function Oa(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};
|
|
273
|
+
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=yp(r),e.reranker&&
|
|
274
|
+
(r=await e.reranker.rerank(t.query,r));let i=kp(r,{maxDocuments:t.maxDocuments});return {docs:i,rounds:n,retrievedCount:o,keptCount:i.length}}function xp(t){return t.trim().replace(/\s+/g," ").toLowerCase()}function bb(){return {goals:[],confirmedFacts:{},userPreferences:{},decisions:[],openItems:[],evidenceRefs:[]}}function vb(t,e){let n={goals:[...t.goals],confirmedFacts:{...t.confirmedFacts},userPreferences:{
|
|
275
|
+
...t.userPreferences},decisions:[...t.decisions],openItems:[...t.openItems],evidenceRefs:[...t.evidenceRefs]};for(let[r,o]of Object.entries(e.set??{}))r==="userPreferences"&&Cp(o)?Object.assign(n.userPreferences,
|
|
276
|
+
o):n.confirmedFacts[r]=o;for(let[r,o]of Object.entries(e.append??{})){let i=Sp(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],
|
|
277
|
+
Tp(n,r);return n}function yb(t){let e=t.rawTurns??3,n=[],r=wp(t.state);r&&n.push({role:"system",content:`Conversation state:
|
|
278
|
+
${r}`});let o=t.history.slice(-e);return n.push(...o,t.current),n}function wp(t){let e=[];return t.goals.length&&e.push(`goals: ${t.goals.join("; ")}`),Object.keys(t.confirmedFacts).length&&e.push(`fa\
|
|
250
279
|
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(
|
|
251
280
|
"; ")}`),t.openItems.length&&e.push(`open: ${t.openItems.join("; ")}`),e.join(`
|
|
252
|
-
`)}function
|
|
253
|
-
for(let n of ["goals","decisions","openItems","evidenceRefs"]){let r=t[n].indexOf(e);r>=0&&t[n].splice(r,1);}}function
|
|
254
|
-
`).filter(c=>c.trim().length>0).map(c=>({indent:
|
|
255
|
-
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=
|
|
256
|
-
match(/^\[(\d+)\]:\s*(.*)$/);if(u){let l=u[2];return Number(u[1])===0||l.trim()===""?[]:
|
|
257
|
-
function
|
|
281
|
+
`)}function Sp(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 Tp(t,e){
|
|
282
|
+
for(let n of ["goals","decisions","openItems","evidenceRefs"]){let r=t[n].indexOf(e);r>=0&&t[n].splice(r,1);}}function Cp(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Ma={format:"json-compact",supports(){return true},encode(t){return JSON.stringify(t)},instruction(){return ""}};function La(t,e={}){let n=e.delimiter??",",r=e.indent??" ",i=t.split(`
|
|
283
|
+
`).filter(c=>c.trim().length>0).map(c=>({indent:Ep(c,r),content:c.slice($a(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=Ot(
|
|
284
|
+
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=Ot(g.content,n),v={};l.forEach((b,y)=>{v[b]=pn(f[y]??"null");}),p.push(v);}return p}let u=s.content.
|
|
285
|
+
match(/^\[(\d+)\]:\s*(.*)$/);if(u){let l=u[2];return Number(u[1])===0||l.trim()===""?[]:Ot(l,n).map(pn)}}let[a]=ja(i,0,0,n);return a}function $a(t,e){let n=0;for(;t.startsWith(e,n);)n+=e.length;return n}
|
|
286
|
+
function Ep(t,e){return $a(t,e)/e.length}function ja(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=Pp(s.content,r);if(!a){i++;continue}let{key:c,
|
|
258
287
|
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&&
|
|
259
|
-
i<t.length;d++,i++){let p=t[i];if(p.indent!==n+1)break;let h=
|
|
260
|
-
i]}function
|
|
261
|
-
let i=Number(r[2]),s=r[3];return i===0||s.trim()===""?{key:
|
|
262
|
-
o[1]),s=o[2];return s===""?{key:i,kind:{type:"object"}}:{key:i,kind:{type:"scalar",value:
|
|
263
|
-
'"'?(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
|
|
264
|
-
'"'):t==="null"?null:t==="true"?true:t==="false"?false:/^-?\d+$/.test(t)||/^-?\d*\.\d+$/.test(t)?Number(t):t}function
|
|
265
|
-
'"'):e}function
|
|
266
|
-
`)}function
|
|
267
|
-
e))
|
|
268
|
-
join(o);r.push(`${s}${a}[${e.length}]: ${d}`);return}let c=
|
|
269
|
-
return}r.push(`${s}${a}[${e.length}]:`);let u=n+1,l=i.repeat(u);for(let d of e)if(
|
|
270
|
-
r.push(`${l}${i}${g}`);}}function
|
|
271
|
-
o))return null;let i=Object.keys(o);if(i.slice().sort().join("\0")!==r)return null;for(let s of i)if(!
|
|
288
|
+
i<t.length;d++,i++){let p=t[i];if(p.indent!==n+1)break;let h=Ot(p.content,r),m={};u.columns.forEach((g,f)=>{m[g]=pn(h[f]??"null");}),l.push(m);}o[c]=l;}else {let[l,d]=ja(t,i+1,n+1,r);o[c]=l,i=d;}}return [o,
|
|
289
|
+
i]}function Pp(t,e){let n=t.match(/^([^[:]+)\[(\d+)\]\{(.*)\}:\s*$/);if(n)return {key:or(n[1]),kind:{type:"table",count:Number(n[2]),columns:Ot(n[3],e)}};let r=t.match(/^([^[:]+)\[(\d+)\]:\s*(.*)$/);if(r){
|
|
290
|
+
let i=Number(r[2]),s=r[3];return i===0||s.trim()===""?{key:or(r[1]),kind:{type:"emptyArray"}}:{key:or(r[1]),kind:{type:"inlineArray",values:Ot(s,e).map(pn)}}}let o=t.match(/^([^:]+):\s*(.*)$/);if(o){let i=or(
|
|
291
|
+
o[1]),s=o[2];return s===""?{key:i,kind:{type:"object"}}:{key:i,kind:{type:"scalar",value:pn(s)}}}return null}function Ot(t,e){let n=[],r="",o=false;for(let i=0;i<t.length;i++){let s=t[i];o?s==='"'?t[i+1]===
|
|
292
|
+
'"'?(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 pn(t){return t.startsWith('"')&&t.endsWith('"')&&t.length>=2?t.slice(1,-1).replace(/""/g,
|
|
293
|
+
'"'):t==="null"?null:t==="true"?true:t==="false"?false:/^-?\d+$/.test(t)||/^-?\d*\.\d+$/.test(t)?Number(t):t}function or(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/""/g,
|
|
294
|
+
'"'):e}function Rp(t,e={}){let n=e.delimiter??",",r=e.indent??" ",o=[];return ei(null,t,0,o,n,r),o.join(`
|
|
295
|
+
`)}function ei(t,e,n,r,o,i){let s=i.repeat(n),a=t===null?"":`${_p(t)}`;if(Array.isArray(e)){Dp(a,e,n,r,o,i);return}if(Xo(e)){t!==null&&r.push(`${s}${a}:`);let c=t===null?n:n+1;for(let[u,l]of Object.entries(
|
|
296
|
+
e))ei(u,l,c,r,o,i);return}r.push(`${s}${a}: ${ir(e,o)}`);}function Dp(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(Qo)){let d=e.map(p=>ir(p,o)).
|
|
297
|
+
join(o);r.push(`${s}${a}[${e.length}]: ${d}`);return}let c=sr(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=>ir(p[m],o)).join(o);r.push(`${d}${h}`);}
|
|
298
|
+
return}r.push(`${s}${a}[${e.length}]:`);let u=n+1,l=i.repeat(u);for(let d of e)if(Qo(d))r.push(`${l}- ${ir(d,o)}`);else {let p=[];ei(null,d,0,p,o,i);let[h,...m]=p;r.push(`${l}- ${h??""}`);for(let g of m)
|
|
299
|
+
r.push(`${l}${i}${g}`);}}function sr(t){if(t.length===0)return null;let e=t[0];if(!Xo(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(!Xo(
|
|
300
|
+
o))return null;let i=Object.keys(o);if(i.slice().sort().join("\0")!==r)return null;for(let s of i)if(!Qo(o[s]))return null}return n}function _p(t){return /^[A-Za-z_][A-Za-z0-9_]*$/.test(t)?t:Na(t)}function ir(t,e){
|
|
272
301
|
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(`
|
|
273
|
-
`)||n.includes('"')||n!==n.trim()||/^(true|false|null)$/.test(n)||/^-?\d/.test(n)?
|
|
274
|
-
"number"||typeof t=="boolean"}function
|
|
275
|
-
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
|
|
276
|
-
encode(e){return
|
|
277
|
-
`)},instruction(){return "Data is CSV: first line is the header row; each subsequent line is one record."}};function
|
|
278
|
-
'""')}"`:e}var
|
|
302
|
+
`)||n.includes('"')||n!==n.trim()||/^(true|false|null)$/.test(n)||/^-?\d/.test(n)?Na(n):n}function Na(t){return `"${t.replace(/"/g,'""')}"`}function Qo(t){return t===null||typeof t=="string"||typeof t==
|
|
303
|
+
"number"||typeof t=="boolean"}function Xo(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\
|
|
304
|
+
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 Ap(t={}){return {format:"compact-rows",supports(){return true},
|
|
305
|
+
encode(e){return Rp(e,t)},instruction(){return Ip},decode(e){return La(e,t)}}}var Ba=Ap();var qa={format:"csv",supports(t){return Array.isArray(t)&&sr(t)!==null},encode(t){let e=t,n=sr(e),r=n.map(Fa).join(","),o=e.map(i=>n.map(s=>Fa(i[s])).join(","));return [r,...o].join(`
|
|
306
|
+
`)},instruction(){return "Data is CSV: first line is the header row; each subsequent line is one record."}};function Fa(t){if(t==null)return "";let e=String(t);return /[",\n]/.test(e)?`"${e.replace(/"/g,
|
|
307
|
+
'""')}"`:e}var ar=class{tokenizer;serializers;minSavingsTokens;minSavingsRatio;qualityPenalty;constructor(e){this.tokenizer=e.tokenizer,this.serializers=e.serializers??[Ma,Ba,qa],this.minSavingsTokens=e.minimumSavingsTokens??
|
|
279
308
|
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(
|
|
280
|
-
e))continue;let l=u.encode(e);if(u.format!=="json-compact"&&!
|
|
309
|
+
e))continue;let l=u.encode(e);if(u.format!=="json-compact"&&!Op(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);
|
|
281
310
|
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];
|
|
282
|
-
return u?
|
|
311
|
+
return u?za(u,s,"json baseline unavailable"):{chosen:"json-compact",encoded:JSON.stringify(e),instruction:"",candidateTokens:s,instructionOverheadTokens:0,reason:"no serializer supported payload; defa\
|
|
283
312
|
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&&
|
|
284
|
-
d>=this.minSavingsRatio&&u.total<a.total&&(a=u,c=`${u.format} saved ${l} tokens (${(d*100).toFixed(1)}%) vs json`);}return
|
|
285
|
-
n)}catch{return false}}function
|
|
286
|
-
length)return false;for(let s=0;s<t.length;s++)if(!
|
|
287
|
-
call(e,s)||!
|
|
288
|
-
string":return "string";case "number":return "number";case "boolean":return "boolean";default:return}}function
|
|
289
|
-
e.type??
|
|
290
|
-
message:"expected boolean"});break;case "null":t!==null&&r.push({path:n,message:"expected null"});break;}}function
|
|
313
|
+
d>=this.minSavingsRatio&&u.total<a.total&&(a=u,c=`${u.format} saved ${l} tokens (${(d*100).toFixed(1)}%) vs json`);}return za(a,s,c)}};function Op(t,e,n){if(!t.decode)return false;try{return ti(t.decode(e),
|
|
314
|
+
n)}catch{return false}}function ti(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.
|
|
315
|
+
length)return false;for(let s=0;s<t.length;s++)if(!ti(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.
|
|
316
|
+
call(e,s)||!ti(t[s],e[s]))return false;return true}function za(t,e,n){return {chosen:t.format,encoded:t.encoded,instruction:t.instruction,candidateTokens:e,instructionOverheadTokens:t.instructionTokens,reason:n}}function he(t,e,n="$"){let r=[];return ni(t,e,n,r),{valid:r.length===0,errors:r}}function Mp(t){if(Array.isArray(t))return "array";if(t===null)return "null";switch(typeof t){case "object":return "object";case "\
|
|
317
|
+
string":return "string";case "number":return "number";case "boolean":return "boolean";default:return}}function ni(t,e,n,r){switch(e.enum&&!e.enum.some(i=>Bp(i,t))&&r.push({path:n,message:"value not in enum"}),
|
|
318
|
+
e.type??Mp(t)){case "object":Lp(t,e,n,r);break;case "array":$p(t,e,n,r);break;case "string":jp(t,e,n,r);break;case "number":case "integer":Np(t,e,n,r);break;case "boolean":typeof t!="boolean"&&r.push({path:n,
|
|
319
|
+
message:"expected boolean"});break;case "null":t!==null&&r.push({path:n,message:"expected null"});break;}}function Lp(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t)){r.push({path:n,
|
|
291
320
|
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(
|
|
292
321
|
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&&
|
|
293
|
-
|
|
294
|
-
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)=>
|
|
322
|
+
ni(o[i],s,`${n}.${i}`,r);}function $p(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\
|
|
323
|
+
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)=>ni(o,e.items,`${n}[${i}]`,r));}function jp(t,e,n,r){if(typeof t!=
|
|
295
324
|
"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.
|
|
296
325
|
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\
|
|
297
|
-
sion: ${e.pattern}`});}o&&!o.test(t)&&r.push({path:n,message:"string does not match pattern"});}}function
|
|
326
|
+
sion: ${e.pattern}`});}o&&!o.test(t)&&r.push({path:n,message:"string does not match pattern"});}}function Np(t,e,n,r){if(typeof t!="number"||Number.isNaN(t)){r.push({path:n,message:"expected number"});return}
|
|
298
327
|
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.
|
|
299
|
-
minimum&&r.push({path:n,message:`number below minimum ${e.minimum}`});}function
|
|
300
|
-
e,n,r),r}};function
|
|
301
|
-
.${r}`,n);}t.type==="array"&&(t.maxItems==null&&n.push(`${e}: array should set maxItems to bound output`),t.items&&
|
|
302
|
-
tring should set maxLength or use an enum`);}function
|
|
303
|
-
ate + repair"}}function
|
|
304
|
-
return r<n?{compress:false,reason:`net saving ${r} < ${n} min`}:{compress:true,reason:`net saving ${r} tokens`}}function
|
|
328
|
+
minimum&&r.push({path:n,message:`number below minimum ${e.minimum}`});}function Bp(t,e){return t===e?true:typeof t!=typeof e?false:t&&e&&typeof t=="object"?JSON.stringify(t)===JSON.stringify(e):false}var cr=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 ri(
|
|
329
|
+
e,n,r),r}};function ri(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??{}))ri(o,`${e}\
|
|
330
|
+
.${r}`,n);}t.type==="array"&&(t.maxItems==null&&n.push(`${e}: array should set maxItems to bound output`),t.items&&ri(t.items,`${e}[]`,n)),t.type==="string"&&t.maxLength==null&&!t.enum&&n.push(`${e}: s\
|
|
331
|
+
tring should set maxLength or use an enum`);}function Va(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\
|
|
332
|
+
ate + repair"}}function zb(t=()=>true){return {id:"provider-native",supports:t}}function oi(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;
|
|
333
|
+
return r<n?{compress:false,reason:`net saving ${r} < ${n} min`}:{compress:true,reason:`net saving ${r} tokens`}}function Gb(t){return {async compress(e){let n=e.protectedSpans??[],r=e.text,o=[];n.forEach((c,u)=>{
|
|
305
334
|
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,
|
|
306
335
|
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.
|
|
307
|
-
originalTokens,protectedSpans:n.length,fidelityPassed:false,skipped:true,reason:"protected span lost during compression; fell back to original"}}}}var
|
|
308
|
-
compressedTokens:0,protectedSpans:(t.protectedSpans??[]).length,fidelityPassed:true,skipped:true,reason:"no compressor configured (noop)"}}};function
|
|
336
|
+
originalTokens,protectedSpans:n.length,fidelityPassed:false,skipped:true,reason:"protected span lost during compression; fell back to original"}}}}var Zb={async compress(t){return {compressed:t.text,originalTokens:0,
|
|
337
|
+
compressedTokens:0,protectedSpans:(t.protectedSpans??[]).length,fidelityPassed:true,skipped:true,reason:"no compressor configured (noop)"}}};function Ua(t,e){let n=s=>s.toLowerCase().replace(/[.,;:!¡?¿()[\]{}"«»…]/g,
|
|
309
338
|
" ").replace(/\s+/g," ").trim(),o=n((s=>{let a=new Set,c=[];for(let u of s.split(`
|
|
310
339
|
`)){let l=u.trim();l&&a.has(l)||(l&&a.add(l),c.push(u));}return c.join(`
|
|
311
|
-
`)})(t)),i=n(e);return !(!
|
|
312
|
-
let e=t.replace(
|
|
340
|
+
`)})(t)),i=n(e);return !(!Jo(un(o),un(i))||dn(ln(o))!==dn(ln(i)))}var ii=["ansi","carriage-return","json","repeated-lines"],Fp=256,qp=/\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)|[ -/]+[0-~]|[@-_])/g;function zp(t){if(!t.includes("\x1B"))return null;
|
|
341
|
+
let e=t.replace(qp,"");return e.length<t.length?e:null}function Vp(t){let e="";for(let n of t.split("\r"))e=n+e.slice(n.length);return e}function Up(t){if(!t.includes("\r")||t.includes(`\r
|
|
313
342
|
`))return null;let e=t.split(`
|
|
314
|
-
`).map(n=>n.includes("\r")?
|
|
315
|
-
`);return e.length<t.length?e:null}var
|
|
316
|
-
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}
|
|
317
|
-
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
|
|
318
|
-
[previous line repeated ${t} more times]`,
|
|
319
|
-
`)){let r=
|
|
320
|
-
`)}function
|
|
321
|
-
`);if(e.length<
|
|
343
|
+
`).map(n=>n.includes("\r")?Vp(n):n).join(`
|
|
344
|
+
`);return e.length<t.length?e:null}var Hp=t=>t===32||t===9||t===10||t===13;function Wp(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=[],
|
|
345
|
+
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}Hp(u)&&(c>i&&o.push(e.slice(i,c)),i=c+1);}i<e.length&&o.push(e.slice(i));let a=o.
|
|
346
|
+
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 Ja=/^\[previous line repeated (\d+) more times\]$/,Jp=t=>`\
|
|
347
|
+
[previous line repeated ${t} more times]`,Ha=3;function Kp(t){let e=[];for(let n of t.split(`
|
|
348
|
+
`)){let r=Ja.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(`
|
|
349
|
+
`)}function Gp(t){let e=t.split(`
|
|
350
|
+
`);if(e.length<Ha||e.some(i=>Ja.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=Jp(c);if(c+1>=Ha&&c*(s.length+1)>u.length+1)n.push(
|
|
322
351
|
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(`
|
|
323
|
-
`);return
|
|
324
|
-
o=t,i=[];for(let a of
|
|
325
|
-
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
|
|
326
|
-
applied:[],originalChars:t.length,compactChars:t.length,reason:e}}var
|
|
327
|
-
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=>
|
|
352
|
+
`);return Kp(o)!==t?null:o.length<t.length?o:null}var Zp={ansi:zp,"carriage-return":Up,json:Wp,"repeated-lines":Gp};function Ka(t,e={}){let n=new Set(e.transforms??ii),r=Math.max(1,e.minSavedChars??256),
|
|
353
|
+
o=t,i=[];for(let a of ii){if(!n.has(a))continue;let c=Zp[a](o);c!=null&&c.length<o.length&&(o=c,i.push(a));}let s=t.length-o.length;return i.length===0?Wa(t,"nothing to compact"):s<r?Wa(t,`compaction w\
|
|
354
|
+
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 Wa(t,e){return {text:t,changed:false,
|
|
355
|
+
applied:[],originalChars:t.length,compactChars:t.length,reason:e}}var Yp=new Set(["path","paths","file","files","filepath","filename","absolutepath","relativepath","targetfile","notebookpath"]);function Qp(t){
|
|
356
|
+
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=>Yp.has(n.toLowerCase().replace(/[_-]/g,"")))}function Ga(t,e={}){let n=new Map,
|
|
328
357
|
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,
|
|
329
|
-
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&&
|
|
330
|
-
argumentos)){i.vistasDeFichero+=1;return}let l=
|
|
331
|
-
`),o=
|
|
332
|
-
options.data??
|
|
358
|
+
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&&Qp(c?.
|
|
359
|
+
argumentos)){i.vistasDeFichero+=1;return}let l=Ka(s.content,e);l.changed&&i.compactados.push({indice:a,texto:l.text,aplicadas:l.applied,enLaCola:a>r});}),i}var Za=new WeakSet;function Ya(t){Za.add(t);}function si(t){return typeof t=="object"&&t!==null&&Za.has(t)}var ai=class{id="mock";options;constructor(e={}){this.options=e,Ya(this);}async generate(e,n){let r=e.messages.map(c=>c.content).join(`
|
|
360
|
+
`),o=It.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+=It.count(c);}let i,s=false;if(e.schema){let c=this.
|
|
361
|
+
options.data??ur(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,It.count(i));return {text:i,usage:{
|
|
333
362
|
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.
|
|
334
|
-
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
|
|
335
|
-
enum[0];switch(t.type){case "object":{let e={};for(let n of t.required??[]){let r=t.properties?.[n];e[n]=r?
|
|
336
|
-
array":return t.items?[
|
|
337
|
-
t)}function
|
|
338
|
-
Number(e[2]);return n>5||n===5&&r>=6}function
|
|
339
|
-
return
|
|
340
|
-
|
|
341
|
-
ni"
|
|
342
|
-
"gpt-5.4"
|
|
343
|
-
"gpt-5.4-mini"
|
|
344
|
-
outputPer1k:.015,largo:{estandar:{inputPer1k:.01,cachedInputPer1k:.001,outputPer1k:.045},tier:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225}}}),"gpt-5.6-luna"
|
|
363
|
+
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 ur(t){if(t.enum&&t.enum.length>0)return t.
|
|
364
|
+
enum[0];switch(t.type){case "object":{let e={};for(let n of t.required??[]){let r=t.properties?.[n];e[n]=r?ur(r):null;}for(let[n,r]of Object.entries(t.properties??{}))n in e||(e[n]=ur(r));return e}case "\
|
|
365
|
+
array":return t.items?[ur(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 iv(t){return new ai(
|
|
366
|
+
t)}function ci(t){let e=t.toLowerCase(),n=e.lastIndexOf("/");return n>=0?e.slice(n+1):e}function Qa(t){let e=/^gpt-(\d+)(?:\.(\d+))?(?![\d.])/.exec(t);if(!e)return false;let n=Number(e[1]),r=e[2]===void 0?0:
|
|
367
|
+
Number(e[2]);return n>5||n===5&&r>=6}function Qe(t){let e=ci(t);return e.startsWith("gpt-")||e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4")?Qa(e)?1.25:1:e.startsWith("gemini")?1:1.25}function fn(t){
|
|
368
|
+
return Qa(ci(t))?1.25:1}function ui(t){let e=t.toLowerCase();return e.startsWith("claude")||e.startsWith("anthropic/")||ci(e).startsWith("claude")?2:Qe(t)}var Xp="https://developers.openai.com/api/docs/pricing",ef="https://ai.google.dev/gemini-api/docs/pricing",li="2026-09-27",B=t=>({...t,fuente:Xp,consultado:li}),Me=t=>({...t,fuente:ef,consultado:li}),
|
|
369
|
+
tf="https://platform.claude.com/docs/en/about-claude/pricing",ie=t=>({...t,fuente:tf,consultado:li}),nf={openai:{flex:{"gpt-5":B({inputPer1k:625e-6,cachedInputPer1k:625e-7,outputPer1k:.005}),"gpt-5-mi\
|
|
370
|
+
ni":B({inputPer1k:125e-6,cachedInputPer1k:125e-7,outputPer1k:.001}),"gpt-5-nano":B({inputPer1k:25e-6,cachedInputPer1k:25e-7,outputPer1k:2e-4}),"gpt-5.2":B({inputPer1k:875e-6,cachedInputPer1k:875e-7,outputPer1k:.007}),
|
|
371
|
+
"gpt-5.4":B({inputPer1k:.00125,cachedInputPer1k:13e-5,outputPer1k:.0075,largo:{estandar:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225},tier:{inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.01125}}}),
|
|
372
|
+
"gpt-5.4-mini":B({inputPer1k:375e-6,cachedInputPer1k:375e-7,outputPer1k:.00225}),"gpt-5.4-nano":B({inputPer1k:1e-4,cachedInputPer1k:1e-5,outputPer1k:625e-6}),"gpt-5.5":B({inputPer1k:.0025,cachedInputPer1k:25e-5,
|
|
373
|
+
outputPer1k:.015,largo:{estandar:{inputPer1k:.01,cachedInputPer1k:.001,outputPer1k:.045},tier:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225}}}),"gpt-5.6-luna":B({inputPer1k:1e-4,cachedInputPer1k:1e-5,
|
|
345
374
|
cacheWritePer1k:125e-6,outputPer1k:6e-4,largo:{estandar:{inputPer1k:4e-4,cachedInputPer1k:4e-5,cacheWritePer1k:5e-4,outputPer1k:.0018},tier:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,
|
|
346
|
-
outputPer1k:9e-4}}}),"gpt-5.6-sol"
|
|
347
|
-
tier:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.015}},vigenteHasta:"2026-11-21"}),"gpt-5.6-terra"
|
|
348
|
-
largo:{estandar:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.018},tier:{inputPer1k:.002,cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.009}}}),o3
|
|
349
|
-
cachedInputPer1k:25e-5,outputPer1k:.004}),"o4-mini"
|
|
350
|
-
largo:{estandar:{inputPer1k:.02,cachedInputPer1k:.002,cacheWritePer1k:.025,outputPer1k:.075},tier:{inputPer1k:.01,cachedInputPer1k:.001,cacheWritePer1k:.0125,outputPer1k:.0375}}}),"gpt-6-sol"
|
|
375
|
+
outputPer1k:9e-4}}}),"gpt-5.6-sol":B({inputPer1k:.002,cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.01,largo:{estandar:{inputPer1k:.008,cachedInputPer1k:8e-4,cacheWritePer1k:.01,outputPer1k:.03},
|
|
376
|
+
tier:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.015}},vigenteHasta:"2026-11-21"}),"gpt-5.6-terra":B({inputPer1k:.001,cachedInputPer1k:1e-4,cacheWritePer1k:.00125,outputPer1k:.006,
|
|
377
|
+
largo:{estandar:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.018},tier:{inputPer1k:.002,cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.009}}}),o3:B({inputPer1k:.001,
|
|
378
|
+
cachedInputPer1k:25e-5,outputPer1k:.004}),"o4-mini":B({inputPer1k:55e-5,cachedInputPer1k:138e-6,outputPer1k:.0022}),"gpt-6-astra":B({inputPer1k:.005,cachedInputPer1k:5e-4,cacheWritePer1k:.00625,outputPer1k:.025,
|
|
379
|
+
largo:{estandar:{inputPer1k:.02,cachedInputPer1k:.002,cacheWritePer1k:.025,outputPer1k:.075},tier:{inputPer1k:.01,cachedInputPer1k:.001,cacheWritePer1k:.0125,outputPer1k:.0375}}}),"gpt-6-sol":B({inputPer1k:.001,
|
|
351
380
|
cachedInputPer1k:1e-4,cacheWritePer1k:.00125,outputPer1k:.005,largo:{estandar:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.015},tier:{inputPer1k:.002,cachedInputPer1k:2e-4,
|
|
352
|
-
cacheWritePer1k:.0025,outputPer1k:.0075}}}),"gpt-6-luna"
|
|
353
|
-
outputPer1k:75e-5},tier:{inputPer1k:1e-4,cachedInputPer1k:1e-5,cacheWritePer1k:125e-6,outputPer1k:375e-6}}})},batch:{"gpt-6-astra"
|
|
354
|
-
largo:{estandar:{inputPer1k:.02,cachedInputPer1k:.002,cacheWritePer1k:.025,outputPer1k:.075},tier:{inputPer1k:.01,cachedInputPer1k:.001,cacheWritePer1k:.0125,outputPer1k:.0375}}}),"gpt-6-sol"
|
|
381
|
+
cacheWritePer1k:.0025,outputPer1k:.0075}}}),"gpt-6-luna":B({inputPer1k:5e-5,cachedInputPer1k:5e-6,cacheWritePer1k:625e-7,outputPer1k:25e-5,largo:{estandar:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,
|
|
382
|
+
outputPer1k:75e-5},tier:{inputPer1k:1e-4,cachedInputPer1k:1e-5,cacheWritePer1k:125e-6,outputPer1k:375e-6}}})},batch:{"gpt-6-astra":B({inputPer1k:.005,cachedInputPer1k:5e-4,cacheWritePer1k:.00625,outputPer1k:.025,
|
|
383
|
+
largo:{estandar:{inputPer1k:.02,cachedInputPer1k:.002,cacheWritePer1k:.025,outputPer1k:.075},tier:{inputPer1k:.01,cachedInputPer1k:.001,cacheWritePer1k:.0125,outputPer1k:.0375}}}),"gpt-6-sol":B({inputPer1k:.001,
|
|
355
384
|
cachedInputPer1k:1e-4,cacheWritePer1k:.00125,outputPer1k:.005,largo:{estandar:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.015},tier:{inputPer1k:.002,cachedInputPer1k:2e-4,
|
|
356
|
-
cacheWritePer1k:.0025,outputPer1k:.0075}}}),"gpt-6-luna"
|
|
357
|
-
outputPer1k:75e-5},tier:{inputPer1k:1e-4,cachedInputPer1k:1e-5,cacheWritePer1k:125e-6,outputPer1k:375e-6}}}),"gpt-5.6-sol"
|
|
385
|
+
cacheWritePer1k:.0025,outputPer1k:.0075}}}),"gpt-6-luna":B({inputPer1k:5e-5,cachedInputPer1k:5e-6,cacheWritePer1k:625e-7,outputPer1k:25e-5,largo:{estandar:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,
|
|
386
|
+
outputPer1k:75e-5},tier:{inputPer1k:1e-4,cachedInputPer1k:1e-5,cacheWritePer1k:125e-6,outputPer1k:375e-6}}}),"gpt-5.6-sol":B({inputPer1k:.002,cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.01,
|
|
358
387
|
largo:{estandar:{inputPer1k:.008,cachedInputPer1k:8e-4,cacheWritePer1k:.01,outputPer1k:.03},tier:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.015}},vigenteHasta:"2026-11-21"}),
|
|
359
|
-
"gpt-5.6-terra"
|
|
360
|
-
cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.009}}}),"gpt-5.6-luna"
|
|
361
|
-
cacheWritePer1k:5e-4,outputPer1k:.0018},tier:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,outputPer1k:9e-4}}}),"gpt-5.5"
|
|
362
|
-
estandar:{inputPer1k:.01,cachedInputPer1k:.001,outputPer1k:.045},tier:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225}}}),"gpt-5.4"
|
|
363
|
-
largo:{estandar:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225},tier:{inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.01125}}}),"gpt-5.4-mini"
|
|
364
|
-
outputPer1k:.00225}),"gpt-5.4-nano"
|
|
365
|
-
cachedInputPer1k:625e-7,outputPer1k:.005}),"gpt-5-mini"
|
|
366
|
-
4.1"
|
|
367
|
-
pt-4o-mini"
|
|
368
|
-
{inputPer1k:.01,outputPer1k:.04})}},anthropic:{batch:{"claude-fable-5-1":
|
|
369
|
-
cacheWritePer1k:.00625,outputPer1k:.025}),"claude-fable-5":
|
|
370
|
-
cacheWritePer1k:.00625,outputPer1k:.025}),"claude-opus-5-5":
|
|
371
|
-
cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-8":
|
|
372
|
-
cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-6":
|
|
373
|
-
cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4":
|
|
374
|
-
cacheWritePer1k:.00125,outputPer1k:.005}),"claude-sonnet-4-6":
|
|
375
|
-
cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-sonnet-4":
|
|
376
|
-
cacheWritePer1k:625e-6,outputPer1k:.0025}),"claude-3-5-haiku":
|
|
377
|
-
outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.5-flash":
|
|
378
|
-
cachedInputPer1k:2e-5}),"gemini-3.1-pro-preview":
|
|
379
|
-
outputPer1k:.009,cachedInputPer1k:4e-4}}}),"gemini-2.5-pro":
|
|
380
|
-
inputPer1k:.00125,outputPer1k:.0075,cachedInputPer1k:25e-5}}}),"gemini-2.5-flash":
|
|
381
|
-
cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.6-flash":
|
|
382
|
-
outputPer1k:75e-5,cachedInputPer1k:125e-7}),"gemini-3-flash-preview":
|
|
383
|
-
t}function
|
|
384
|
-
opic":/^(gpt-|o[1-9](-|$))/.test(o)?"openai":o.startsWith("gemini")?"google":o.startsWith("claude-")?"anthropic":null}function
|
|
385
|
-
if(
|
|
386
|
-
inputPer1k*
|
|
387
|
-
null?{servido:t,factor:null,conDescuento:false}:{servido:t,factor:e,conDescuento:e<1}}var
|
|
388
|
-
"number"&&Number.isFinite(t);function
|
|
389
|
-
standard-rate-tier"};let n=t.uso;if(n.complete===false||!
|
|
390
|
-
return {ok:false,motivo:"incomplete-usage"};let r=
|
|
391
|
-
motivo:"no-tier-price"};let s=Math.max(0,n.inputTokens),a=
|
|
388
|
+
"gpt-5.6-terra":B({inputPer1k:.001,cachedInputPer1k:1e-4,cacheWritePer1k:.00125,outputPer1k:.006,largo:{estandar:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.018},tier:{inputPer1k:.002,
|
|
389
|
+
cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.009}}}),"gpt-5.6-luna":B({inputPer1k:1e-4,cachedInputPer1k:1e-5,cacheWritePer1k:125e-6,outputPer1k:6e-4,largo:{estandar:{inputPer1k:4e-4,cachedInputPer1k:4e-5,
|
|
390
|
+
cacheWritePer1k:5e-4,outputPer1k:.0018},tier:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,outputPer1k:9e-4}}}),"gpt-5.5":B({inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.015,largo:{
|
|
391
|
+
estandar:{inputPer1k:.01,cachedInputPer1k:.001,outputPer1k:.045},tier:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225}}}),"gpt-5.4":B({inputPer1k:.00125,cachedInputPer1k:13e-5,outputPer1k:.0075,
|
|
392
|
+
largo:{estandar:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225},tier:{inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.01125}}}),"gpt-5.4-mini":B({inputPer1k:375e-6,cachedInputPer1k:375e-7,
|
|
393
|
+
outputPer1k:.00225}),"gpt-5.4-nano":B({inputPer1k:1e-4,cachedInputPer1k:1e-5,outputPer1k:625e-6}),"gpt-5.2":B({inputPer1k:875e-6,cachedInputPer1k:875e-7,outputPer1k:.007}),"gpt-5":B({inputPer1k:625e-6,
|
|
394
|
+
cachedInputPer1k:625e-7,outputPer1k:.005}),"gpt-5-mini":B({inputPer1k:125e-6,cachedInputPer1k:125e-7,outputPer1k:.001}),"gpt-5-nano":B({inputPer1k:25e-6,cachedInputPer1k:25e-7,outputPer1k:2e-4}),"gpt-\
|
|
395
|
+
4.1":B({inputPer1k:.001,outputPer1k:.004}),"gpt-4.1-mini":B({inputPer1k:2e-4,outputPer1k:8e-4}),"gpt-4.1-nano":B({inputPer1k:5e-5,outputPer1k:2e-4}),"gpt-4o":B({inputPer1k:.00125,outputPer1k:.005}),"g\
|
|
396
|
+
pt-4o-mini":B({inputPer1k:75e-6,outputPer1k:3e-4}),o3:B({inputPer1k:.001,outputPer1k:.004}),"o4-mini":B({inputPer1k:55e-5,outputPer1k:.0022}),"o3-mini":B({inputPer1k:55e-5,outputPer1k:.0022}),"o3-pro":B(
|
|
397
|
+
{inputPer1k:.01,outputPer1k:.04})}},anthropic:{batch:{"claude-fable-5-1":ie({inputPer1k:.005,cachedInputPer1k:125e-6,cacheWritePer1k:.00625,outputPer1k:.025}),"claude-mythos-5-1":ie({inputPer1k:.005,cachedInputPer1k:125e-6,
|
|
398
|
+
cacheWritePer1k:.00625,outputPer1k:.025}),"claude-fable-5":ie({inputPer1k:.005,cachedInputPer1k:5e-4,cacheWritePer1k:.00625,outputPer1k:.025}),"claude-mythos-5":ie({inputPer1k:.005,cachedInputPer1k:5e-4,
|
|
399
|
+
cacheWritePer1k:.00625,outputPer1k:.025}),"claude-opus-5-5":ie({inputPer1k:.002,cachedInputPer1k:1e-4,cacheWritePer1k:.0025,outputPer1k:.01}),"claude-opus-5":ie({inputPer1k:.0025,cachedInputPer1k:25e-5,
|
|
400
|
+
cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-8":ie({inputPer1k:.0025,cachedInputPer1k:25e-5,cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-7":ie({inputPer1k:.0025,cachedInputPer1k:25e-5,
|
|
401
|
+
cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-6":ie({inputPer1k:.0025,cachedInputPer1k:25e-5,cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-5":ie({inputPer1k:.0025,cachedInputPer1k:25e-5,
|
|
402
|
+
cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4":ie({inputPer1k:.0075,cachedInputPer1k:75e-5,cacheWritePer1k:.009375,outputPer1k:.0375}),"claude-sonnet-5":ie({inputPer1k:.001,cachedInputPer1k:1e-4,
|
|
403
|
+
cacheWritePer1k:.00125,outputPer1k:.005}),"claude-sonnet-4-6":ie({inputPer1k:.0015,cachedInputPer1k:15e-5,cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-sonnet-4-5":ie({inputPer1k:.0015,cachedInputPer1k:15e-5,
|
|
404
|
+
cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-sonnet-4":ie({inputPer1k:.0015,cachedInputPer1k:15e-5,cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-haiku-4-5":ie({inputPer1k:5e-4,cachedInputPer1k:5e-5,
|
|
405
|
+
cacheWritePer1k:625e-6,outputPer1k:.0025}),"claude-3-5-haiku":ie({inputPer1k:4e-4,cachedInputPer1k:4e-5,cacheWritePer1k:5e-4,outputPer1k:.002})}},google:{flex:{"gemini-3.7-flash":Me({inputPer1k:375e-6,
|
|
406
|
+
outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.5-flash":Me({inputPer1k:75e-5,outputPer1k:.0045,cachedInputPer1k:8e-5}),"gemini-3.5-flash-lite":Me({inputPer1k:15e-5,outputPer1k:.00125,
|
|
407
|
+
cachedInputPer1k:2e-5}),"gemini-3.1-pro-preview":Me({inputPer1k:.001,outputPer1k:.006,cachedInputPer1k:2e-4,largo:{estandar:{inputPer1k:.004,outputPer1k:.018,cachedInputPer1k:4e-4},tier:{inputPer1k:.002,
|
|
408
|
+
outputPer1k:.009,cachedInputPer1k:4e-4}}}),"gemini-2.5-pro":Me({inputPer1k:625e-6,outputPer1k:.005,cachedInputPer1k:125e-6,largo:{estandar:{inputPer1k:.0025,outputPer1k:.015,cachedInputPer1k:25e-5},tier:{
|
|
409
|
+
inputPer1k:.00125,outputPer1k:.0075,cachedInputPer1k:25e-5}}}),"gemini-2.5-flash":Me({inputPer1k:15e-5,outputPer1k:.00125,cachedInputPer1k:3e-5}),"gemini-3.8-flash":Me({inputPer1k:375e-6,outputPer1k:.001875,
|
|
410
|
+
cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.6-flash":Me({inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.1-flash-lite":Me({inputPer1k:125e-6,
|
|
411
|
+
outputPer1k:75e-5,cachedInputPer1k:125e-7}),"gemini-3-flash-preview":Me({inputPer1k:25e-5,outputPer1k:.0015,cachedInputPer1k:5e-5})}}};function Xe(t){let e=t.lastIndexOf("/");return e>=0?t.slice(e+1):
|
|
412
|
+
t}function mn(t){let e=t.toLowerCase(),n=e.indexOf("/"),r=n>0?e.slice(0,n):"",o=Xe(e);return r==="openai"||r==="azure-openai"?"openai":r==="google"||r==="google-vertex"?"google":r==="anthropic"?"anthr\
|
|
413
|
+
opic":/^(gpt-|o[1-9](-|$))/.test(o)?"openai":o.startsWith("gemini")?"google":o.startsWith("claude-")?"anthropic":null}function rf(t){return Date.parse(`${t}T23:59:59.999Z`)}function hn(t,e,n,r=Date.now()){
|
|
414
|
+
if(Ze(n)===void 0)return;let o=_t(n);if(o===void 0)return;let i=nf[t]?.[e],s=i?i[o]:void 0;if(s&&!(s.vigenteHasta&&r>rf(s.vigenteHasta)))return s}function lr(t){let e=Ze(t);if(e)return {...e,cacheWritePer1k:e.
|
|
415
|
+
inputPer1k*Qe(Xe(t))}}var Xa={flex:.5,default:1,auto:1,priority:1,fast:1,scale:1,standard:1,batch:.5},ec=Math.min(...Object.values(Xa).filter(t=>t<1)),Mt="flex";function di(t){if(t==null||t==="")return null;let e=Xa[t];return e==
|
|
416
|
+
null?{servido:t,factor:null,conDescuento:false}:{servido:t,factor:e,conDescuento:e<1}}var dr=1e10;function pi(t){let e=Math.floor(t*dr)/dr;return e>t&&(e=(Math.floor(t*dr)-1)/dr),e<=0?0:e}var pr=t=>typeof t==
|
|
417
|
+
"number"&&Number.isFinite(t);function fr(t){let e=di(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:"\
|
|
418
|
+
standard-rate-tier"};let n=t.uso;if(n.complete===false||!pr(n.inputTokens)||!pr(n.outputTokens)||n.cachedInputTokens!=null&&!pr(n.cachedInputTokens)||n.cacheWriteInputTokens!=null&&!pr(n.cacheWriteInputTokens))
|
|
419
|
+
return {ok:false,motivo:"incomplete-usage"};let r=lr(t.modelo);if(!r)return {ok:false,motivo:"no-standard-price"};let o=t.origen??mn(t.modelo),i=o?hn(o,e.servido,t.modelo,t.ahoraMs):void 0;if(!i)return {ok:false,
|
|
420
|
+
motivo:"no-tier-price"};let s=Math.max(0,n.inputTokens),a=Qe(Xe(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&&
|
|
392
421
|
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.
|
|
393
422
|
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"]]},
|
|
394
423
|
{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??
|
|
395
|
-
b.inputPer1k,"cache write":b.inputPer1k*a,output:b.outputPer1k}:void 0,k=(
|
|
396
|
-
T=new Set,
|
|
397
|
-
void 0&&
|
|
398
|
-
std-
|
|
399
|
-
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"&&
|
|
400
|
-
tier was read from a response header whose values the provider does not document"),b&&
|
|
401
|
-
t the difference between the two published rate cards":"")),v){let
|
|
402
|
-
its prompt cache, so those tokens are priced at the smallest per-token difference they could have had`);}T.size>0&&
|
|
403
|
-
e tokens add nothing`);let
|
|
424
|
+
b.inputPer1k,"cache write":b.inputPer1k*a,output:b.outputPer1k}:void 0,k=(I,F)=>{let z=F?y[I]:m[I],U=g[I];return U===void 0?{std:z,aplicado:z}:F?{std:z,aplicado:m[I]>0?z*(U/m[I]):z}:{std:z,aplicado:U}},
|
|
425
|
+
T=new Set,x=I=>{let F=0,z=0;for(let U of f){if(U.tokens<=0)continue;let ee=U.posibles[0],K=k(ee,I);for(let N of U.posibles.slice(1)){let Te=k(N,I);Te.std-Te.aplicado<K.std-K.aplicado&&(ee=N,K=Te);}g[ee]===
|
|
426
|
+
void 0&&U.posibles.length===1&&T.add(ee),F+=U.tokens/1e3*K.std,z+=U.tokens/1e3*K.aplicado;}return {std:F,aplicado:z}},P=x(false),M=P.std-P.aplicado,A=P.std,w=P.aplicado,S=M,C=false;if(b){let I=x(true);A=I.std;let F=I.
|
|
427
|
+
std-I.aplicado;C=F>M,S=Math.min(F,M),w=C?I.std-S:I.aplicado;}if(!(S>0))return {ok:false,motivo:"no-difference"};let E=pi(S);if(E<=0)return {ok:false,motivo:"no-difference"};let _=[];if(t.origen===null?_.push("\
|
|
428
|
+
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"&&_.push("the served \
|
|
429
|
+
tier was read from a response header whose values the provider does not document"),b&&_.push("priced from your costModels: your standard rate times the published tier-to-standard ratio"+(C?", capped a\
|
|
430
|
+
t the difference between the two published rate cards":"")),v){let I=[...c?[]:["read from"],...u?[]:["written to"]].join(" or ");_.push(`the provider's usage did not say how many input tokens were ${I}\
|
|
431
|
+
its prompt cache, so those tokens are priced at the smallest per-token difference they could have had`);}T.size>0&&_.push(`the provider publishes no ${[...T].join(" or ")} price for this tier, so thos\
|
|
432
|
+
e tokens add nothing`);let L=_.length===0;return {ok:true,importe:E,basis:L?"measured":"estimated",costeEstandar:A,costeAplicado:w,factorEfectivo:w/A,motivoBasis:L?`the provider's own usage for this call\
|
|
404
433
|
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\
|
|
405
|
-
led at the batch rate card)":""):`estimated: ${
|
|
434
|
+
led at the batch rate card)":""):`estimated: ${_.join("; ")}`,consultado:i.consultado}}function tc(t,e,n){let r=e??mn(t);return r!==null&&hn(r,"batch",t,n)!==void 0}var of="slower and variable: OpenAI\
|
|
406
435
|
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\
|
|
407
|
-
short the request returns 429 and is not charged. Do not put a deferrable request on a user-facing path.",
|
|
436
|
+
short the request returns 429 and is not charged. Do not put a deferrable request on a user-facing path.",sf='slower and variable: Google targets minutes for the Flex tier ("Minutes (1\u201315 min target)\
|
|
408
437
|
", 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\
|
|
409
|
-
he server side. Do not put a deferrable request on a user-facing path.',
|
|
438
|
+
he server side. Do not put a deferrable request on a user-facing path.',af="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\
|
|
410
439
|
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\
|
|
411
|
-
n a user-facing path."
|
|
440
|
+
n a user-facing path.",cf="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.",nc="this provider\
|
|
412
441
|
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 \
|
|
413
|
-
request/response call (with the built-in Anthropic and OpenAI providers, layer.batches.submit() sends such requests there)";function
|
|
414
|
-
google"?
|
|
415
|
-
st on a user-facing path.`}var
|
|
416
|
-
return {minimumCacheTokens:
|
|
417
|
-
0),n),o=Math.min(Math.max(0,t.uso.cacheWriteInputTokens??0),n-r),i=n-r-o;if(n<
|
|
418
|
-
cacheWritePer1k,a=i/1e3*t.fila.inputPer1k;return {importe:
|
|
419
|
-
"https:"||e.port!==""?null:
|
|
420
|
-
function
|
|
421
|
-
null?
|
|
422
|
-
n")return;let r=n.call(t);return r==="oficial"||r==="no-oficial"?r:void 0}catch{return}}function
|
|
423
|
-
return typeof t=="object"&&t!==null?
|
|
424
|
-
hash="",e.toString().replace(/\/+$/,"")}catch{return t.replace(/\/+$/,"")}}function
|
|
425
|
-
l: a batch request path must be relative to the provider base (got "${t}")`);return t}var
|
|
442
|
+
request/response call (with the built-in Anthropic and OpenAI providers, layer.batches.submit() sends such requests there)";function rc(t,e=null){return t==null||t===""?cf:t===Mt?e==="openai"?of:e==="\
|
|
443
|
+
google"?sf:af:`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\
|
|
444
|
+
st on a user-facing path.`}var oc=1024;function gt(t,e){return e==="openai"&&mn(Xe(t))==="openai"&&Qe(Xe(t))>1}function fi(t){let e=Ze(t);if(!e||!(e.inputPer1k>0))return null;let n=(e.cachedInputPer1k??e.inputPer1k)/e.inputPer1k;
|
|
445
|
+
return {minimumCacheTokens:oc,cacheReadMultiplier:n,cacheWriteMultiplier:Qe(Xe(t))}}function ic(t){let e=t.consultado??Eo,n=Math.max(0,t.uso.inputTokens),r=Math.min(Math.max(0,t.uso.cachedInputTokens??
|
|
446
|
+
0),n),o=Math.min(Math.max(0,t.uso.cacheWriteInputTokens??0),n-r),i=n-r-o;if(n<oc||i<=0)return {importe:0,costeEstandar:0,costeAplicado:0,tokensOrdinarios:Math.max(0,i),consultado:e};let s=i/1e3*t.fila.
|
|
447
|
+
cacheWritePer1k,a=i/1e3*t.fila.inputPer1k;return {importe:pi(s-a),costeEstandar:s,costeAplicado:a,tokensOrdinarios:i,consultado:e}}var sc=new Set;function we(t,e){sc.has(t)||(sc.add(t),console.warn(e));}var uf={"api.anthropic.com":"anthropic","api.openai.com":"openai","generativelanguage.googleapis.com":"google"};function gn(t){if(typeof t!="string")return null;try{let e=new URL(t);return e.protocol!==
|
|
448
|
+
"https:"||e.port!==""?null:uf[e.hostname.toLowerCase()]??null}catch{return null}}function mr(t){return gn(t)!==null?"oficial":"no-oficial"}var ac=Symbol.for("@bivelio/savings-layer:provider-origin");function bn(t){return {esquemaEnFormatoNativo:false,esquemaEstricto:false,esquemaPorPrompt:false,piezasDelAdaptador:t}}var lf=2;function Lt(t){return lf*(t??[]).filter(e=>e.parameters==null).length}var hr=new WeakMap;
|
|
449
|
+
function $t(t,e){return hr.set(t,e),t}function gr(t){return typeof t=="object"&&t!==null?hr.get(t):void 0}var cc=new WeakMap;function uc(t,e){cc.set(t,e);}function bt(t){return typeof t=="object"&&t!==
|
|
450
|
+
null?cc.get(t):void 0}var lc=new WeakMap;function br(t,e){lc.set(t,e);}function dc(t){if(typeof t!="object"||t===null)return;let e=lc.get(t);if(e!==void 0)return e;try{let n=t[ac];if(typeof n!="functio\
|
|
451
|
+
n")return;let r=n.call(t);return r==="oficial"||r==="no-oficial"?r:void 0}catch{return}}function pc(t,e){let n=hr.get(t);return n&&hr.set(e,n),e}var fc=new WeakMap;function mc(t,e){fc.set(t,e);}function mi(t){
|
|
452
|
+
return typeof t=="object"&&t!==null?fc.get(t):void 0}var hc=new WeakSet;function gc(t){typeof t=="object"&&t!==null&&hc.add(t);}function df(t){return hc.has(t)}function vt(t,e,n){df(t)||we(e,n);}var bc=new WeakMap;function vr(t,e){bc.set(t,e);}function vc(t){return typeof t=="object"&&t!==null?bc.get(t):void 0}function yr(t){try{let e=new URL(t);return e.username="",e.password="",e.search="",e.
|
|
453
|
+
hash="",e.toString().replace(/\/+$/,"")}catch{return t.replace(/\/+$/,"")}}function kr(t){if(!t.startsWith("/")||t.startsWith("//")||/^\/*[a-z][a-z0-9+.-]*:/i.test(t))throw new Error(`[bvsala] interna\
|
|
454
|
+
l: a batch request path must be relative to the provider base (got "${t}")`);return t}var hi=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(
|
|
426
455
|
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,
|
|
427
456
|
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(
|
|
428
457
|
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.
|
|
429
458
|
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),
|
|
430
459
|
i=e.slice(r+1),i.charCodeAt(0)===32&&(i=i.slice(1))),o){case "data":this.datos+=i+`
|
|
431
460
|
`;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":
|
|
432
|
-
this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};async function*
|
|
433
|
-
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
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
i))
|
|
461
|
+
this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};async function*xr(t){let e=new hi;if(typeof t=="string"){yield*e.push(t),yield*e.
|
|
462
|
+
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 pf(t,e){return e==="max_tokens"?/\bmax_tokens\b/i.test(t)&&/max_completion_tokens/i.test(t)&&/unsupported|not supported|unrecognized|unknown parameter|use 'max_completion_tokens'/i.test(t):/max_completion_tokens/i.
|
|
463
|
+
test(t)&&/unsupported|not supported|unrecognized|unknown (parameter|field|argument)|extra (inputs|fields) (are )?not permitted|not permitted/i.test(t)}function et(t){if(t==null||typeof t!="object")return true;
|
|
464
|
+
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.map(String):[];if(o.some(s=>!i.includes(s)))return false;
|
|
465
|
+
for(let s of Object.values(n))if(!et(s))return false}if(e.items!==void 0&&!et(e.items))return false;for(let o of ["anyOf","oneOf","allOf"]){let i=e[o];if(Array.isArray(i)&&i.some(s=>!et(s)))return false}let r=e.$defs??
|
|
466
|
+
e.definitions;return !(r&&typeof r=="object"&&Object.values(r).some(o=>!et(o)))}function ff(t){return !/response_format/i.test(t)||/invalid schema/i.test(t)?false:/invalid parameter|not supported|unsupported|unrecognized request argument|unknown parameter/i.
|
|
467
|
+
test(t)}function mf(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:
|
|
468
|
+
`+JSON.stringify(t)}var hf=/(^|\.)api\.openai\.com$|\.openai\.azure\.com$/i;function gi(t,e,n){return e??bf(n)?t.replace(/^[^/]+\//,""):t}function gf(t){let e=gn(t);return e==="openai"||e==="google"?e:
|
|
469
|
+
null}var yc="x-gemini-service-tier";function kc(t,e){try{let n=t.headers?.get?.(e);return typeof n=="string"&&n.trim()!==""?n.trim():void 0}catch{return}}function bi(t,e,n){if(e.explicitCacheWrites!==
|
|
470
|
+
true||!gt(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\
|
|
471
|
+
ser"||o.role==="tool")&&typeof o.content=="string"&&o.content!==""?{puntos:1,indice:r-1}:{puntos:0,indice:-1}}function bf(t){try{return hf.test(new URL(t).hostname)}catch{return false}}var xc=class{id;opts;fetchImpl;sinResponseFormat=new Set;streamOptionsRejected=false;campoDeTopeAprendido=new Map;origen;constructor(e){
|
|
472
|
+
this.opts=e,this.id=`openai-compatible:${e.baseUrl}`,this.fetchImpl=e.fetchImpl??fetch,this.origen=gf(e.baseUrl),uc(this,this.origen),br(this,mr(e.baseUrl));let n=(o,i)=>o.schema!=null&&!this.sinResponseFormat.
|
|
473
|
+
has(i),r=o=>gi(o,this.opts.stripProviderPrefix,this.opts.baseUrl);vr(this,{protocolo:"openai",origen:this.origen,endpoint:yr(e.baseUrl),cuerpo:o=>{let i=r(o.model);return this.construirCuerpo(i,o,n(o,
|
|
474
|
+
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(/\/$/,"")}${kr(o)}`,{method:i.method,headers:{...i.json!==
|
|
445
475
|
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.
|
|
446
|
-
form}:{},...i.signal?{signal:i.signal}:{}})});}async generate(e,n){let r=
|
|
447
|
-
enviar(r,e,i,void 0,o);
|
|
448
|
-
Model "${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
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
leer(s,e,i,r)}async*generateStream(e,n={}){if(e.schema!=null||e.deferrable===true){let
|
|
452
|
-
e.model,this.opts.stripProviderPrefix,this.opts.baseUrl),o=n.signal,i=!this.streamOptionsRejected,
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
"
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
c
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
a}
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
476
|
+
form}:{},...i.signal?{signal:i.signal}:{}})});}async generate(e,n){let r=gi(e.model,this.opts.stripProviderPrefix,this.opts.baseUrl),o=n?.signal,i=e.schema!=null&&!this.sinResponseFormat.has(r),s=await this.
|
|
477
|
+
enviar(r,e,i,void 0,o);for(let a=0;a<2&&!s.ok&&!(s.status!==400&&s.status!==422);a++){let c=await Sr(s);if(s.status===400&&i&&ff(c))this.sinResponseFormat.add(r),vt(this,`sin-response-format:${r}`,`[b\
|
|
478
|
+
vsala] Model "${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\
|
|
479
|
+
go straight 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\
|
|
480
|
+
the native guarantee, use a model with structured outputs (gpt-4o or later).`),i=false;else if(!this.corregirCampoDeTope(r,e,s.status,c))throw new Error(`provider ${s.status}: ${c}`);s=await this.enviar(
|
|
481
|
+
r,e,i,void 0,o);}if(!s.ok){let a=await Sr(s);throw new Error(`provider ${s.status}: ${a}`)}return this.leer(s,e,i,r)}async*generateStream(e,n={}){if(e.schema!=null||e.deferrable===true){let w=await this.
|
|
482
|
+
generate(e);w.text!==""&&(yield {type:"text",delta:w.text}),yield {type:"done",response:w};return}let r=gi(e.model,this.opts.stripProviderPrefix,this.opts.baseUrl),o=n.signal,i=!this.streamOptionsRejected,
|
|
483
|
+
s=i,a=w=>this.enviar(r,e,false,{includeUsage:w,...o?{signal:o}:{}}),c=await a(s);for(let w=0;w<2&&!c.ok&&!(c.status!==400&&c.status!==422);w++){let S=await Sr(c);if(this.corregirCampoDeTope(r,e,c.status,
|
|
484
|
+
S)){c=await a(s);continue}if(!s||c.status!==422&&!/stream_options|include_usage/i.test(S))throw new Error(`provider ${c.status}: ${S}`);if(this.opts.requireUsage)throw new Error(`provider ${c.status}:\
|
|
485
|
+
this endpoint rejects stream_options, so a streamed answer would carry no usage and requireUsage is set. ${S}`);s=false,c=await a(false);}if(i&&!s&&c.ok&&(this.streamOptionsRejected=true,vt(this,`sin-stream-o\
|
|
486
|
+
ptions:${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 `generate()` for a me\
|
|
487
|
+
asured figure, or an endpoint that reports usage when streaming.")),!c.ok)throw new Error(`provider ${c.status}: ${await Sr(c)}`);if((c.headers.get("content-type")??"").includes("application/json")){let w=await this.
|
|
488
|
+
leer(c,e,false,r);w.text!==""&&(yield {type:"text",delta:w.text}),yield {type:"done",response:w};return}let u=c.body,l=u&&typeof u.getReader=="function"?u:await c.text(),d="",p=new Map,h,m,g,f=false,v="";for await(let w of xr(
|
|
489
|
+
l)){if(w.data==="[DONE]")break;let S;try{S=JSON.parse(w.data);}catch{continue}if(S===null||typeof S!="object")continue;if(S.error!=null){let _=S.error,L=typeof _.message=="string"?_.message:JSON.stringify(
|
|
490
|
+
S.error);throw new Error(`provider stream error: ${L}`)}let C=S.choices?.[0],E=C?.delta;(wr(E?.reasoning_content)||wr(E?.reasoning))&&(f=true),typeof E?.content=="string"&&E.content!==""&&(d+=E.content,
|
|
491
|
+
yield {type:"text",delta:E.content}),typeof E?.refusal=="string"&&(v+=E.refusal);for(let _ of E?.tool_calls??[]){let L=typeof _.index=="number"?_.index:0,I=p.get(L)??{args:""};!I.id&&typeof _.id=="stri\
|
|
492
|
+
ng"&&_.id!==""&&(I.id=_.id);let F=_.function?.name;!I.name&&typeof F=="string"&&F!==""&&(I.name=F),typeof _.function?.arguments=="string"&&(I.args+=_.function.arguments),p.set(L,I);}C?.finish_reason!=null&&
|
|
493
|
+
(h=C.finish_reason),S.usage!=null&&typeof S.usage=="object"&&(m=S.usage),typeof S.service_tier=="string"&&S.service_tier!==""&&(g=S.service_tier);}if(h===void 0)throw new Error("provider stream ended b\
|
|
494
|
+
efore completion (no finish_reason)");let b=typeof m?.prompt_tokens!="number",y=typeof m?.completion_tokens!="number";if(this.opts.requireUsage&&(b||y))throw new Error(Tc(m?.prompt_tokens,m?.completion_tokens));
|
|
495
|
+
let k=wc(m,f),T=Sc(m),x={inputTokens:m?.prompt_tokens??0,outputTokens:m?.completion_tokens??0,...m?.prompt_tokens_details?.cached_tokens!=null?{cachedInputTokens:m.prompt_tokens_details.cached_tokens}:
|
|
496
|
+
{},...T!==void 0?{cacheWriteInputTokens:T}:{},...k!==void 0?{reasoningTokens:k}:{},...b||y?{complete:false}:{}},P=[...p.entries()].sort((w,S)=>w[0]-S[0]).map(([,w])=>({...w.id?{id:w.id}:{},name:w.name??"",
|
|
497
|
+
arguments:w.args})).filter(w=>w.name!==""),M=g?"cuerpo":void 0;!g&&this.origen==="google"&&(g=kc(c,yc),g&&(M="cabecera"));let A=bi(r,e,this.origen);yield {type:"done",response:$t({text:d,...P.length>0?
|
|
498
|
+
{toolCalls:P}:{},finishReason:h,...v!==""?{refusal:v}:{},...g?{servedServiceTier:g}:{},usage:x,structuredNatively:false,raw:m??null},{...bn(Lt(e.tools)),origen:this.origen,...M?{tierLeidoDe:M}:{},...A?{cacheExplicita:{
|
|
499
|
+
puntos:A.puntos}}:{}})};}campoDeTope(e){return this.opts.maxTokensParam??this.campoDeTopeAprendido.get(e)??(this.origen==="openai"?"max_completion_tokens":"max_tokens")}corregirCampoDeTope(e,n,r,o){if(this.
|
|
500
|
+
opts.maxTokensParam!==void 0||n.maxOutputTokens==null||this.campoDeTopeAprendido.has(e))return false;let i=this.campoDeTope(e);if(!pf(o,i))return false;let s=i==="max_tokens"?"max_completion_tokens":"max_toke\
|
|
501
|
+
ns";return this.campoDeTopeAprendido.set(e,s),vt(this,`campo-de-tope:${this.opts.baseUrl}:${e}`,`[bvsala] This endpoint rejects \`${i}\` for model "${e}" with a ${r}, so the output cap is sent as \`${s}\
|
|
502
|
+
\` instead (the rejected request was not billed; the model is noted and the following requests go straight there). To choose the field yourself, set \`maxTokensParam\` on OpenAICompatibleProvider.`),true}async enviar(e,n,r,o,i){
|
|
503
|
+
let s=this.construirCuerpo(e,n,r,o);return await this.fetchImpl(`${this.opts.baseUrl.replace(/\/$/,"")}/chat/completions`,{method:"POST",headers:{"content-type":"application/json",...this.opts.apiKey?
|
|
504
|
+
{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){let i=n.messages.map(c=>c.role===
|
|
505
|
+
"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>0?{role:"assistant",content:c.
|
|
506
|
+
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=bi(e,n,this.origen);if(s?.puntos===
|
|
507
|
+
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:mf(n.schema)});let a={model:e,messages:i};if(n.maxOutputTokens!=
|
|
508
|
+
null&&(a[this.campoDeTope(e)]=n.maxOutputTokens),n.temperature!=null&&(a.temperature=n.temperature),n.seed!=null&&(a.seed=n.seed),n.promptCacheKey!=null&&(a.prompt_cache_key=n.promptCacheKey),n.deferrable===
|
|
509
|
+
true&&(a.service_tier=Mt),s&&(a.prompt_cache_options={mode:"explicit"}),n.schema&&r){let c=et(n.schema);c||vt(this,"strict-incompatible","[bvsala] The response contract does not meet OpenAI's `strict` m\
|
|
510
|
+
ode (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 is still guided and the lay\
|
|
511
|
+
er 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",json_schema:{name:"bvsala_\
|
|
512
|
+
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}:{},parameters:c.parameters??
|
|
513
|
+
{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,e,n,r,o,this.opts.requireUsage===
|
|
514
|
+
true)}leerJson(e,n,r,o,i,s){let a=e.choices?.[0]?.message,c=a?.content??"",u=typeof a?.refusal=="string"&&a.refusal!==""?a.refusal:void 0,l=(a?.tool_calls??[]).map(x=>({...x.id?{id:x.id}:{},name:x.function?.
|
|
515
|
+
name??"",arguments:x.function?.arguments??""})).filter(x=>x.name!==""),d=e.usage??{},p=d.prompt_tokens??0,h=d.completion_tokens??0,m=typeof d.prompt_tokens!="number",g=typeof d.completion_tokens!="num\
|
|
516
|
+
ber";if(s&&(m||g))throw new Error(Tc(d.prompt_tokens,d.completion_tokens));let f=e.choices?.[0]?.finish_reason,v=typeof e.service_tier=="string"&&e.service_tier!==""?e.service_tier:void 0,b=v?"cuerpo":
|
|
517
|
+
void 0;!v&&this.origen==="google"&&n&&(v=kc(n,yc),v&&(b="cabecera"));let y=Sc(d),k=bi(i,r,this.origen),T=wc(d,wr(a?.reasoning_content)||wr(a?.reasoning));return $t({text:c,...l.length>0?{toolCalls:l}:
|
|
518
|
+
{},...f?{finishReason:f}:{},...u!==void 0?{refusal:u}:{},...v?{servedServiceTier:v}:{},...r.deferrable===true?{requestedServiceTier:Mt}:{},usage:{inputTokens:p,outputTokens:h,...d.prompt_tokens_details?.
|
|
519
|
+
cached_tokens!=null?{cachedInputTokens:d.prompt_tokens_details.cached_tokens}:{},...y!==void 0?{cacheWriteInputTokens:y}:{},...T!==void 0?{reasoningTokens:T}:{},...m||g?{complete:false}:{}},structuredNatively:r.
|
|
520
|
+
schema!=null&&o,raw:e},{esquemaEnFormatoNativo:r.schema!=null&&o,esquemaEstricto:r.schema!=null&&o&&et(r.schema),esquemaPorPrompt:r.schema!=null&&!o,piezasDelAdaptador:Lt(r.tools),origen:this.origen,...b?
|
|
521
|
+
{tierLeidoDe:b}:{},...k?{cacheExplicita:{puntos:k.puntos}}:{}})}};function wc(t,e){let n=t?.completion_tokens_details?.reasoning_tokens;if(!(typeof n!="number"||!Number.isInteger(n)||n<0)&&!(n===0&&e))
|
|
522
|
+
return n}function Sc(t){let e=t?.prompt_tokens_details?.cache_write_tokens;return typeof e=="number"&&Number.isInteger(e)&&e>=0?e:void 0}function wr(t){return typeof t=="string"&&t!==""}function Tc(t,e){
|
|
523
|
+
return `provider returned incomplete usage (prompt=${t??"absent"}, completion=${e??"absent"}); cannot measure cost. For gateways/streaming, ensure usage reporting is enabled.`}async function Sr(t){try{
|
|
524
|
+
return (await t.text()).slice(0,500)}catch{return "<no body>"}}function Cc(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:
|
|
525
|
+
`+JSON.stringify(t)}function Ec(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.
|
|
491
526
|
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=[],
|
|
492
|
-
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
|
|
493
|
-
bytes:4*1024*1024,porEntrada:64*1024,claves:4096},
|
|
527
|
+
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 vf={
|
|
528
|
+
bytes:4*1024*1024,porEntrada:64*1024,claves:4096},Tr=class{constructor(e=vf){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(
|
|
494
529
|
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>
|
|
495
530
|
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.
|
|
496
|
-
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
|
|
497
|
-
if(n===null||typeof n!="object")continue;let r=n;if(r.type!=="compaction")continue;e.iteraciones++,e.input+=
|
|
498
|
-
let o=r.cache_creation,i=
|
|
499
|
-
Math.min(s,a);}return e.iteraciones>0?e:null}function
|
|
531
|
+
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 jt=t=>typeof t=="number"&&Number.isFinite(t)&&t>0?t:0;function Pc(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){
|
|
532
|
+
if(n===null||typeof n!="object")continue;let r=n;if(r.type!=="compaction")continue;e.iteraciones++,e.input+=jt(r.input_tokens),e.output+=jt(r.output_tokens),e.cacheRead+=jt(r.cache_read_input_tokens);
|
|
533
|
+
let o=r.cache_creation,i=jt(o?.ephemeral_5m_input_tokens),s=jt(o?.ephemeral_1h_input_tokens),a=typeof r.cache_creation_input_tokens=="number"?jt(r.cache_creation_input_tokens):i+s;e.cacheWrite+=a,e.cacheWrite1h+=
|
|
534
|
+
Math.min(s,a);}return e.iteraciones>0?e:null}function vi(t,e,n){let r=t??{},o=Pc(r.iterations),i=Rc(r.cache_read_input_tokens,o?.cacheRead),s=Rc(r.cache_creation_input_tokens,o?.cacheWrite),a=r.cache_creation?.ephemeral_1h_input_tokens,c=typeof a==
|
|
500
535
|
"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!=
|
|
501
536
|
"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||
|
|
502
|
-
p||o?{}:{reasoningTokens:0},...d||p?{complete:false}:{}},entradaAusente:d,salidaAusente:p}}function
|
|
503
|
-
function
|
|
504
|
-
{},...n,...r?{cache_creation:r}:{}}}function
|
|
505
|
-
tool_calls";case "refusal":return "content_filter";default:return t}}var
|
|
537
|
+
p||o?{}:{reasoningTokens:0},...d||p?{complete:false}:{}},entradaAusente:d,salidaAusente:p}}function Rc(t,e){return e?(t??0)+e:t}function yi(t){let e=t?.service_tier;return typeof e=="string"&&e!==""?e:void 0}
|
|
538
|
+
function ki(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??
|
|
539
|
+
{},...n,...r?{cache_creation:r}:{}}}function xi(t){return t==="thinking"||t==="redacted_thinking"}function wi(t){switch(t){case "end_turn":return "stop";case "max_tokens":return "length";case "tool_use":return "\
|
|
540
|
+
tool_calls";case "refusal":return "content_filter";default:return t}}var yf=new Set([null,"cyber","general_harms"]);function Si(t){if(t.stopReason!=="refusal")return false;let e=t.stopDetails;if(e===null||typeof e!=
|
|
541
|
+
"object"||Array.isArray(e))return false;let n=e;if(n.type!=="refusal"||!("category"in n))return false;let r=n.category;return !(r!==null&&typeof r!="string"||!yf.has(r)||t.bloques!==0||t.outputTokens!==0||Array.
|
|
542
|
+
isArray(t.iterations)&&t.iterations.length>1)}var Cr=4,tt="bvsala_contract",kf={"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\
|
|
506
543
|
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\
|
|
507
544
|
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\
|
|
508
545
|
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\
|
|
@@ -510,38 +547,39 @@ ct. This exchange has a call without its result, a result for a call that turn d
|
|
|
510
547
|
. 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\
|
|
511
548
|
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\
|
|
512
549
|
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\
|
|
513
|
-
urn of the conversation to keep the native tool loop."},
|
|
514
|
-
fetchImpl=e.fetchImpl??fetch,
|
|
515
|
-
anthropic",origen:
|
|
550
|
+
urn of the conversation to keep the native tool loop."},Dc=class{id;opts;fetchImpl;busquedas=new Tr;constructor(e={}){this.opts=e,this.id=`anthropic:${e.baseUrl??"https://api.anthropic.com/v1"}`,this.
|
|
551
|
+
fetchImpl=e.fetchImpl??fetch,mc(this,Er(e.baseUrl)?"oficial":"compatible"),br(this,mr(e.baseUrl??"https://api.anthropic.com/v1"));let n=this.opts.baseUrl??"https://api.anthropic.com/v1";vr(this,{protocolo:"\
|
|
552
|
+
anthropic",origen:Pf(n),endpoint:yr(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(/\/$/,"")}${kr(r)}`;return this.fetchImpl(
|
|
516
553
|
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.
|
|
517
|
-
opts.headers},...o.json!==void 0?{body:JSON.stringify(o.json)}:{},...o.signal?{signal:o.signal}:{}})}});}modeloEnElCable(e){return this.opts.stripProviderPrefix??
|
|
518
|
-
""):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
|
|
519
|
-
r.esquemaPorPrompt,r.reenviadas)}async*generateStream(e,n={}){if(e.schema!=null||e.deferrable===true){let
|
|
520
|
-
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
|
|
521
|
-
"application/json")){let
|
|
522
|
-
body,a=s&&typeof s.getReader=="function"?s:await i.text(),c="",u=new Map,l,d,p=false,h=false,m,g=false,
|
|
523
|
-
continue;let
|
|
524
|
-
"content_block_start"){let
|
|
525
|
-
{},json:"",...
|
|
526
|
-
if(
|
|
527
|
-
number"?u.get(S.index):void 0;
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
(
|
|
531
|
-
entries()].sort((
|
|
532
|
-
"tool_use")
|
|
533
|
-
{}:
|
|
534
|
-
{},...
|
|
535
|
-
|
|
536
|
-
"
|
|
537
|
-
|
|
554
|
+
opts.headers},...o.json!==void 0?{body:JSON.stringify(o.json)}:{},...o.signal?{signal:o.signal}:{}})}});}modeloEnElCable(e){return this.opts.stripProviderPrefix??Er(this.opts.baseUrl)?e.replace(/^[^/]+\//,
|
|
555
|
+
""):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 Oc(o)}`);return this.leer(o,e,r.contratoNativo,r.turnoAnadido,
|
|
556
|
+
r.esquemaPorPrompt,r.reenviadas)}async*generateStream(e,n={}){if(e.schema!=null||e.deferrable===true){let w=await this.generate(e);w.text!==""&&(yield {type:"text",delta:w.text}),yield {type:"done",response:w};
|
|
557
|
+
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 Oc(i)}`);if((i.headers.get("content-type")??"").includes(
|
|
558
|
+
"application/json")){let w=await this.leer(i,e,r.contratoNativo,r.turnoAnadido,r.esquemaPorPrompt,r.reenviadas);w.text!==""&&(yield {type:"text",delta:w.text}),yield {type:"done",response:w};return}let s=i.
|
|
559
|
+
body,a=s&&typeof s.getReader=="function"?s:await i.text(),c="",u=new Map,l,d,p=false,h=false,m,g,f=0,v=false,b,y;for await(let w of xr(a)){let S;try{S=JSON.parse(w.data);}catch{continue}if(S===null||typeof S!="\
|
|
560
|
+
object")continue;let C=w.event!=="message"?w.event:S.type??w.event;if(C==="message_start")l=S.message?.usage??l,typeof S.message?.id=="string"&&S.message.id!==""&&(b=S.message.id),y=S.message?.diagnostics;else if(C===
|
|
561
|
+
"content_block_start"){f+=1;let E=S.content_block;xi(E?.type)&&(v=true),typeof S.index=="number"&&E&&u.set(S.index,{tipo:E.type??"",...typeof E.id=="string"?{id:E.id}:{},...typeof E.name=="string"?{name:E.
|
|
562
|
+
name}:{},json:"",...E.content!==void 0?{content:E.content}:{},...e.toolSearch&&(E.type==="server_tool_use"||E.type==="tool_search_tool_result")?{crudo:E}:{}});}else if(C==="content_block_delta"){let E=S.
|
|
563
|
+
delta;if(E?.type==="text_delta"&&typeof E.text=="string"&&E.text!=="")c+=E.text,yield {type:"text",delta:E.text};else if(E?.type==="input_json_delta"&&typeof E.partial_json=="string"){let _=typeof S.index==
|
|
564
|
+
"number"?u.get(S.index):void 0;_&&(_.json+=E.partial_json);}}else if(C==="message_delta")p=true,m=S.delta?.stop_reason??m,S.delta&&"stop_details"in S.delta&&(g=S.delta.stop_details),S.usage&&(d=ki(d,S.usage));else if(C===
|
|
565
|
+
"message_stop"){h=true;break}else if(C==="error")throw new Error(`provider stream error: ${S.error?.type}: ${S.error?.message}`)}if(!h&&!p)throw new Error("provider stream ended before completion (no me\
|
|
566
|
+
ssage_delta)");let k=ki(l,d),x=(p?vi(k,d?.output_tokens,v):void 0)?.usage??{inputTokens:0,outputTokens:0,complete:false};if(this.opts.requireUsage&&x.complete===false)throw new Error(Ac(p?k.input_tokens:void 0,
|
|
567
|
+
p?d?.output_tokens:void 0));let P=[...u.entries()].sort((w,S)=>w[0]-S[0]).map(([,w])=>w).filter(w=>w.tipo==="tool_use"&&w.name!==tt).map(w=>({...w.id?{id:w.id}:{},name:w.name??"",arguments:Ef(w.json)})).
|
|
568
|
+
filter(w=>w.name!==""),M=yi(k),A=e.toolSearch?Ic([...u.entries()].sort((w,S)=>w[0]-S[0]).map(([,w])=>({type:w.tipo,name:w.name,content:w.content})),r.reenviadas):void 0;if(e.toolSearch){let w=[];for(let[
|
|
569
|
+
,S]of [...u.entries()].sort((C,E)=>C[0]-E[0]))if(S.tipo==="tool_use")w.push({type:"tool_use",id:S.id,name:S.name});else if(S.tipo==="tool_search_tool_result"&&S.crudo)w.push(S.crudo);else if(S.tipo==="\
|
|
570
|
+
server_tool_use"&&S.crudo){let C=S.json===""?S.crudo.input??{}:Cf(S.json);C!==void 0&&w.push({...S.crudo,input:C});}this.recordarBusquedas(w);}yield {type:"done",response:$t({text:c,...P.length>0?{toolCalls:P}:
|
|
571
|
+
{},...m?{finishReason:wi(m)}:{},...p&&Si({stopReason:m,stopDetails:g,bloques:f,outputTokens:d?.output_tokens,iterations:k.iterations})?{unbilledRefusal:true}:{},...M?{servedServiceTier:M}:{},...A?{toolSearch:A}:
|
|
572
|
+
{},...b?{providerMessageId:b}:{},...this.diagnosticoDe(e,y),usage:x,structuredNatively:false,raw:{usage:k,stop_reason:m}},bn((r.turnoAnadido?1:0)+Lt(e.tools)))};}async enviar(e,n){let r=(this.opts.baseUrl??
|
|
573
|
+
"https://api.anthropic.com/v1").replace(/\/$/,"");return await this.fetchImpl(`${r}/messages`,{method:"POST",headers:{"content-type":"application/json","anthropic-version":this.opts.apiVersion??"2023-\
|
|
574
|
+
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,
|
|
575
|
+
finDelPrefijo:i,prefijoEnSystem:s,turnoAnadido:a}=xf(e,n?.anteponer,m=>this.avisar(`anthropic-herramientas-${m}`,kf[m]));if(o.length===0)throw new Error("anthropic: the request has no user/assistant m\
|
|
538
576
|
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}:
|
|
539
|
-
{},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({...
|
|
540
|
-
toolSearch.variant]});}let u=false,l=false,d=false;if(e.schema){let m=c.length>0,g=c.some(v=>v.name===
|
|
541
|
-
upado",`[bvsala] One of your tools is already named \`${
|
|
577
|
+
{},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({...nr[e.
|
|
578
|
+
toolSearch.variant]});}let u=false,l=false,d=false;if(e.schema){let m=c.length>0,g=c.some(v=>v.name===tt),f=et(e.schema);g?(r.push({type:"text",text:Cc(e.schema)}),l=true,this.avisar("anthropic-contrato-nombre-oc\
|
|
579
|
+
upado",`[bvsala] One of your tools is already named \`${tt}\`, so the output contract cannot travel as a tool without colliding with it (duplicate tool names are a provider error). The schema is sent a\
|
|
542
580
|
s prompt text instead, which is measurably more expensive on this API. Rename that tool to get the cheaper path.`)):(!f&&!m&&this.avisar("anthropic-strict-incompatible","[bvsala] The response contract\
|
|
543
581
|
does not meet `strict` 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 sti\
|
|
544
|
-
ll guided and the layer still validates, but the guarantee comes from the layer, not the provider."),u=f&&!m,c.push({name:
|
|
582
|
+
ll guided and the layer still validates, but the guarantee comes from the layer, not the provider."),u=f&&!m,c.push({name:tt,description:m?"Return the final answer in the required shape. Use the other\
|
|
545
583
|
tools first if you need data; call this one instead of writing the answer as text.":"Return the final answer in the required shape.",input_schema:e.schema,...u?{strict:true}:{}}),m&&(d=this.opts.forceAnswerThroughTool!==
|
|
546
584
|
false,this.avisar("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 t\
|
|
547
585
|
hat exact tool, 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 a\
|
|
@@ -549,63 +587,64 @@ nswer through SOME tool \u2014 yours or the contract \u2014 and can no longer re
|
|
|
549
587
|
because the model may pick one of your tools and defer the final answer to the next turn.':", not forced (`forceAnswerThroughTool: false`). The guarantee is the layer's, not the provider's (`constrai\
|
|
550
588
|
nts.backend: \"none\"`), and if the model answers in prose the layer pays a second full call to repair it \u2014 on this API that second call re-pays the whole tool-use overhead.")+" Dropping either t\
|
|
551
589
|
he tools or the 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};
|
|
552
|
-
r.length>0&&(p.system=r),e.temperature!=null&&(p.temperature=e.temperature),c.length>0&&(p.tools=c),u?p.tool_choice={type:"tool",name:
|
|
590
|
+
r.length>0&&(p.system=r),e.temperature!=null&&(p.temperature=e.temperature),c.length>0&&(p.tools=c),u?p.tool_choice={type:"tool",name:tt}:d&&(p.tool_choice={type:"any"}),e.deferrable===true&&this.avisar(
|
|
553
591
|
"anthropic-sin-tier-diferible","[bvsala] This request was declared deferrable, but the Anthropic Messages API has NO cheaper synchronous tier: its `service_tier` chooses between priority capacity (mor\
|
|
554
592
|
e expensive) and standard, 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 fi\
|
|
555
|
-
t a request/response call: send such requests with layer.batches.submit() instead.");let h=this.marcarCache(e,r,o,i,s);return e.cacheDiagnostics&&
|
|
556
|
-
cacheDiagnostics.previousMessageId}),this.opts.automaticCache===true&&e.cachePlacement==null&&e.stablePrefixMessages!=null&&h<Math.min(this.opts.maxCacheBreakpoints??
|
|
557
|
-
meral"}),{body:p,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=
|
|
593
|
+
t a request/response call: send such requests with layer.batches.submit() instead.");let h=this.marcarCache(e,r,o,i,s);return e.cacheDiagnostics&&Er(this.opts.baseUrl)&&(p.diagnostics={previous_message_id:e.
|
|
594
|
+
cacheDiagnostics.previousMessageId}),this.opts.automaticCache===true&&e.cachePlacement==null&&e.stablePrefixMessages!=null&&h<Math.min(this.opts.maxCacheBreakpoints??Cr,Cr)&&(p.cache_control={type:"ephe\
|
|
595
|
+
meral"}),{body:p,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=nr[e.
|
|
558
596
|
toolSearch.variant].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.
|
|
559
597
|
para(c);if(!u)return;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.
|
|
560
|
-
includes(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!==
|
|
561
|
-
length!==0&&this.busquedas.recordar(n,
|
|
562
|
-
|
|
598
|
+
includes(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!==tt).map(r=>r.id).filter(r=>typeof r=="string"&&r!=="");n.
|
|
599
|
+
length!==0&&this.busquedas.recordar(n,Ec(e));}avisar(e,n){vt(this,e,n);}marcarCache(e,n,r,o,i){if(e.promptCacheKey!=null,e.stablePrefixMessages==null)return 0;let s=Math.min(this.opts.maxCacheBreakpoints??
|
|
600
|
+
Cr,Cr);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.
|
|
563
601
|
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){
|
|
564
|
-
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||!
|
|
602
|
+
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||!Er(this.opts.baseUrl))return {};if(n===void 0)return {};
|
|
565
603
|
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!="\
|
|
566
604
|
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){
|
|
567
|
-
let c=e.content??[],u=c.some(k=>
|
|
568
|
-
stringify(k.input??{})})).filter(k=>k.name!==""),p=c.find(k=>k.type==="tool_use"&&k.name===
|
|
569
|
-
u);if(s&&(f||v))throw new Error(
|
|
570
|
-
...e.stop_reason?{finishReason:
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
let
|
|
580
|
-
|
|
581
|
-
type:"
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
let e
|
|
596
|
-
t
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
new Uint8Array(
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
o
|
|
605
|
+
let c=e.content??[],u=c.some(k=>xi(k.type)),l=c.filter(k=>k.type==="text").map(k=>k.text??"").join(""),d=c.filter(k=>k.type==="tool_use"&&k.name!==tt).map(k=>({...k.id?{id:k.id}:{},name:k.name??"",arguments:JSON.
|
|
606
|
+
stringify(k.input??{})})).filter(k=>k.name!==""),p=c.find(k=>k.type==="tool_use"&&k.name===tt),h=p?JSON.stringify(p.input??{}):l,m=e.usage,{usage:g,entradaAusente:f,salidaAusente:v}=vi(m,m?.output_tokens,
|
|
607
|
+
u);if(s&&(f||v))throw new Error(Ac(m?.input_tokens,m?.output_tokens));let b=yi(m),y=n.toolSearch?Ic(c,a):void 0;return n.toolSearch&&this.recordarBusquedas(c),$t({text:h,...d.length>0?{toolCalls:d}:{},
|
|
608
|
+
...e.stop_reason?{finishReason:wi(e.stop_reason)}:{},...Si({stopReason:e.stop_reason,stopDetails:e.stop_details,bloques:Array.isArray(e.content)?e.content.length:0,outputTokens:m?.output_tokens,iterations:m?.
|
|
609
|
+
iterations})?{unbilledRefusal:true}:{},...b?{servedServiceTier:b}:{},usage:g,structuredNatively:n.schema!=null&&r,...y?{toolSearch:y}:{},...typeof e.id=="string"&&e.id!==""?{providerMessageId:e.id}:{},...this.
|
|
610
|
+
diagnosticoDe(n,e.diagnostics),raw:e},{...bn((o?1:0)+Lt(n.tools)),esquemaPorPrompt:i})}};function xf(t,e,n){let r=[],o=[],i=t.stablePrefixMessages??0,s,a=0,c=true,u=Tf(t),l=new Set,d=t.messages,p=g=>{if(g>=
|
|
611
|
+
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}]}),p(f));};for(let g=0;g<
|
|
612
|
+
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?"sin-pareja":"sin-ids"),
|
|
613
|
+
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";)k+=1;let x=wf(y,d.
|
|
614
|
+
slice(g+1,k),u,l);if("llamadas"in x){o.push({role:"assistant",content:[...v??[],...b,...x.llamadas]}),p(g);let P={role:"user",content:[]};o.push(P),x.resultados.forEach((M,A)=>{P.content.push(M),p(g+1+
|
|
615
|
+
A);}),g=k-1;continue}n(x.motivo);}let T=v?[...v,...b]:b;T.length>0&&(o.push({role:"assistant",content:T}),p(g));for(let x=g+1;x<k;x++)h(d[x],x);g=k-1;}let m=false;return o.length>0&&o[0].role==="assistant"&&
|
|
616
|
+
(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}}function wf(t,e,n,r){
|
|
617
|
+
if(t.some(c=>!c.id)||e.some(c=>!c.toolCallId))return {motivo:"sin-ids"};let o=t.map(c=>_c(c.id)),i=new Set(o);if(i.size!==o.length||o.some(c=>r.has(c)))return {motivo:"sin-pareja"};let s=e.map(c=>_c(c.toolCallId));
|
|
618
|
+
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=>Sf(c.arguments));if(a.some(c=>c===void 0))return {motivo:"sin-pareja"};if(t.some(c=>!n.
|
|
619
|
+
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)=>({type:"tool_result",tool_use_id:s[u],
|
|
620
|
+
...c.content!==""?{content:c.content}:{},...c.isError===true?{is_error:true}:{}}))}}function _c(t){return t.replace(/[^a-zA-Z0-9_-]/g,"_")}function Sf(t){let e=n=>typeof n=="object"&&n!==null&&!Array.isArray(
|
|
621
|
+
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 Tf(t){let e=new Set((t.tools??[]).map(r=>r.id));if(!t.toolSearch)
|
|
622
|
+
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!=="tool_search_tool_result")continue;let i=o.
|
|
623
|
+
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 Er(t){try{return /(^|\.)api\.anthropic\.com$/i.test(new URL(
|
|
624
|
+
t??"https://api.anthropic.com/v1").hostname)}catch{return false}}function Ic(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("tool_search_too\
|
|
625
|
+
l"))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)typeof a?.
|
|
626
|
+
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 Cf(t){
|
|
627
|
+
try{return JSON.parse(t)}catch{return}}function Ef(t){try{return JSON.stringify(JSON.parse(t===""?"{}":t))}catch{return t}}function Ac(t,e){return `provider returned incomplete usage (input=${t??"absen\
|
|
628
|
+
t"}, output=${e??"absent"}); cannot measure cost.`}async function Oc(t){try{return (await t.text()).slice(0,500)}catch{return "<no body>"}}function Pf(t){return gn(t)==="anthropic"?"anthropic":null}var vn=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.
|
|
629
|
+
now()-this.start}all(){return this.events}};var nt=class extends Error{status;constructor(e,n){super(e),this.name="LicenseError",n&&(this.status=n);}};function Ti(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function Pr(t,e=""){if(typeof t!="number"){let n=e&&
|
|
630
|
+
`"${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 Re(t,e,n=""){
|
|
631
|
+
let r=Ti(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):
|
|
632
|
+
new TypeError(u)}return t}function Ci(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 Lc(t,e){Re(t,void 0,"digestInt\
|
|
633
|
+
o() output");let n=e.outputLen;if(t.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function yn(...t){for(let e=0;e<t.length;e++)t[e].fill(0);}function Rr(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var $c=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Rf=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Dr(t){if(Re(t),$c)return t.toHex();
|
|
634
|
+
let e="";for(let n=0;n<t.length;n++)e+=Rf[t[n]];return e}var qe={_0:48,_9:57,A:65,F:70,a:97,f:102};function Mc(t){if(t>=qe._0&&t<=qe._9)return t-qe._0;if(t>=qe.A&&t<=qe.F)return t-(qe.A-10);if(t>=qe.a&&
|
|
635
|
+
t<=qe.f)return t-(qe.a-10)}function kn(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if($c)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?
|
|
636
|
+
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=Mc(t.charCodeAt(
|
|
637
|
+
i)),a=Mc(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 Ei(...t){let e=0;for(let r=0;r<t.length;r++){let o=t[r];Re(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 jc(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 Nc(t=32){
|
|
638
|
+
Pr(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(
|
|
639
|
+
`"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}var Bc=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});var _r=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=
|
|
640
|
+
new Uint8Array(e),this.view=Rr(this.buffer);}update(e){Ci(this),Re(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=Rr(e);for(;o<=i-s;s+=
|
|
641
|
+
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){Ci(this),
|
|
642
|
+
Lc(e,this),this.finished=true;let{buffer:n,view:r,blockLen:o,isLE:i}=this,{pos:s}=this;n[s++]=128,yn(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(
|
|
643
|
+
o-8,BigInt(this.length*8),i),this.process(r,0);let a=Rr(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\
|
|
605
644
|
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.
|
|
606
|
-
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
|
|
607
|
-
o=new Uint32Array(n);for(let i=0;i<n;i++){let{h:s,l:a}=
|
|
608
|
-
n+r+o+(t/2**32|0)|0,
|
|
645
|
+
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 se=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Ir=BigInt(4294967295),Fc=BigInt(32);function Df(t,e=false){return e?{h:Number(t&Ir),l:Number(t>>Fc&Ir)}:{h:Number(t>>Fc&Ir)|0,l:Number(t&Ir)|0}}function qc(t,e=false){let n=t.length,r=new Uint32Array(n),
|
|
646
|
+
o=new Uint32Array(n);for(let i=0;i<n;i++){let{h:s,l:a}=Df(t[i],e);[r[i],o[i]]=[s,a];}return [r,o]}var Pi=(t,e,n)=>t>>>n,Ri=(t,e,n)=>t<<32-n|e>>>n,yt=(t,e,n)=>t>>>n|e<<32-n,kt=(t,e,n)=>t<<32-n|e>>>n,xn=(t,e,n)=>t<<64-n|e>>>n-32,wn=(t,e,n)=>t>>>n-32|e<<64-n;function Le(t,e,n,r){let o=(e>>>0)+(r>>>0);return {h:t+n+(o/2**32|0)|0,l:o|0}}var zc=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Vc=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Uc=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Hc=(t,e,n,r,o)=>e+
|
|
647
|
+
n+r+o+(t/2**32|0)|0,Wc=(t,e,n,r,o)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(o>>>0),Jc=(t,e,n,r,o,i)=>e+n+r+o+i+(t/2**32|0)|0;var Kc=qc(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242",
|
|
609
648
|
"0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc6\
|
|
610
649
|
8b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","\
|
|
611
650
|
0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3\
|
|
@@ -613,158 +652,158 @@ c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a6
|
|
|
613
652
|
x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5d\
|
|
614
653
|
efb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0x\
|
|
615
654
|
eada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c1\
|
|
616
|
-
00d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),
|
|
655
|
+
00d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),If=Kc[0],Af=Kc[1],rt=new Uint32Array(80),ot=new Uint32Array(80),Di=class extends _r{constructor(e){
|
|
617
656
|
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=
|
|
618
657
|
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<
|
|
619
|
-
16;y++,n+=4)
|
|
620
|
-
|
|
621
|
-
Gh:g,Gl:f,Hh:v,Hl:b}=this;for(let y=0;y<80;y++){let k=
|
|
622
|
-
|
|
623
|
-
let
|
|
624
|
-
0),{h:d,l:p}=
|
|
625
|
-
m,g,f,v,b);}roundClean(){
|
|
626
|
-
0;Dh=
|
|
627
|
-
xpected boolean, got type="+typeof t)}return t}function
|
|
628
|
-
"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
|
|
629
|
-
function
|
|
630
|
-
return
|
|
631
|
-
"expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function
|
|
658
|
+
16;y++,n+=4)rt[y]=e.getUint32(n),ot[y]=e.getUint32(n+=4);for(let y=16;y<80;y++){let k=rt[y-15]|0,T=ot[y-15]|0,x=yt(k,T,1)^yt(k,T,8)^Pi(k,T,7),P=kt(k,T,1)^kt(k,T,8)^Ri(k,T,7),M=rt[y-2]|0,A=ot[y-2]|0,w=yt(
|
|
659
|
+
M,A,19)^xn(M,A,61)^Pi(M,A,6),S=kt(M,A,19)^wn(M,A,61)^Ri(M,A,6),C=Uc(P,S,ot[y-7],ot[y-16]),E=Hc(C,x,w,rt[y-7],rt[y-16]);rt[y]=E|0,ot[y]=C|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,
|
|
660
|
+
Gh:g,Gl:f,Hh:v,Hl:b}=this;for(let y=0;y<80;y++){let k=yt(d,p,14)^yt(d,p,18)^xn(d,p,41),T=kt(d,p,14)^kt(d,p,18)^wn(d,p,41),x=d&h^~d&g,P=p&m^~p&f,M=Wc(b,T,P,Af[y],ot[y]),A=Jc(M,v,k,x,If[y],rt[y]),w=M|0,
|
|
661
|
+
S=yt(r,o,28)^xn(r,o,34)^xn(r,o,39),C=kt(r,o,28)^wn(r,o,34)^wn(r,o,39),E=r&i^r&a^i&a,_=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}=Le(u|0,l|0,A|0,w|0),u=a|0,l=c|0,a=i|0,c=s|0,i=r|0,s=o|0;
|
|
662
|
+
let L=zc(w,C,_);r=Vc(L,A,S,E),o=L|0;}(({h:r,l:o}=Le(this.Ah|0,this.Al|0,r|0,o|0))),{h:i,l:s}=Le(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Le(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=Le(this.Dh|0,this.Dl|0,u|0,l|
|
|
663
|
+
0),{h:d,l:p}=Le(this.Eh|0,this.El|0,d|0,p|0),{h,l:m}=Le(this.Fh|0,this.Fl|0,h|0,m|0),{h:g,l:f}=Le(this.Gh|0,this.Gl|0,g|0,f|0),{h:v,l:b}=Le(this.Hh|0,this.Hl|0,v|0,b|0),this.set(r,o,i,s,a,c,u,l,d,p,h,
|
|
664
|
+
m,g,f,v,b);}roundClean(){yn(rt,ot);}destroy(){this.destroyed=true,yn(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}},_i=class extends Di{Ah=se[0]|0;Al=se[1]|0;Bh=se[2]|0;Bl=se[3]|0;Ch=se[4]|0;Cl=se[5]|
|
|
665
|
+
0;Dh=se[6]|0;Dl=se[7]|0;Eh=se[8]|0;El=se[9]|0;Fh=se[10]|0;Fl=se[11]|0;Gh=se[12]|0;Gl=se[13]|0;Hh=se[14]|0;Hl=se[15]|0;constructor(){super(64);}};var Ar=jc(()=>new _i,Bc(3));var X=(t,e,n)=>Re(t,e,n),Ai=Pr,Oi=Dr,$e=(...t)=>Ei(...t),Gc=t=>kn(t),Lr=Ti,Zc=t=>Nc(t),Mr=BigInt(0),Ii=BigInt(1);function Nt(t,e=""){if(typeof t!="boolean"){let n=e&&`"${e}" `;throw new TypeError(n+"e\
|
|
666
|
+
xpected boolean, got type="+typeof t)}return t}function Of(t){if(typeof t=="bigint"){if(!Or(t))throw new RangeError("positive bigint expected, got "+t)}else Ai(t);return t}function ze(t,e=""){if(typeof t!=
|
|
667
|
+
"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 Yc(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?Mr:BigInt("0x"+t)}function Mi(t){return Yc(Dr(t))}function Ve(t){return Yc(Dr(Sn(Re(t)).reverse()))}
|
|
668
|
+
function Li(t,e){if(Pr(e),e===0)throw new RangeError("zero length");t=Of(t);let n=t.toString(16);if(n.length>e*2)throw new RangeError("number too large");return kn(n.padStart(e*2,"0"))}function Qc(t,e){
|
|
669
|
+
return Li(t,e).reverse()}function Xc(t,e){if(t=X(t),e=X(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 Sn(t){return Uint8Array.from(X(t))}var Or=t=>typeof t=="bigint"&&Mr<=t;function Mf(t,e,n){return Or(t)&&Or(e)&&Or(n)&&e<=t&&t<n}function $i(t,e,n,r){if(!Mf(e,n,r))throw new RangeError(
|
|
670
|
+
"expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function ji(t){if(t<Mr)throw new Error("expected non-negative bigint, got "+t);let e;for(e=0;t>Mr;t>>=Ii,e+=1);return e}var eu=t=>(Ii<<BigInt(t))-Ii;function xt(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(
|
|
632
671
|
`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.
|
|
633
|
-
entries(i).forEach(([a,c])=>r(a,c,s));o(e,false),o(n,true);}var
|
|
634
|
-
|
|
635
|
-
o number");if(e<=
|
|
636
|
-
"invert: does not exist");return
|
|
637
|
-
e),o}function
|
|
638
|
-
e.ONE)),o=n(e,r),i=n(e,e.neg(r)),s=(t+
|
|
639
|
-
eql(u.sqr(d),c),v=u.cmov(l,d,f);return
|
|
640
|
-
1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return
|
|
641
|
-
"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++,
|
|
642
|
-
"Cannot find square root");let v=
|
|
643
|
-
t,e)&
|
|
644
|
-
reduce((r,o)=>(r[o]="function",r),e);if(
|
|
645
|
-
|
|
646
|
-
i=e;for(;n>
|
|
647
|
-
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
|
|
648
|
-
let n=
|
|
649
|
-
|
|
672
|
+
entries(i).forEach(([a,c])=>r(a,c,s));o(e,false),o(n,true);}var Ni=()=>{throw new Error("not implemented")};var ae=BigInt(0),re=BigInt(1),wt=BigInt(2),ou=BigInt(3),iu=BigInt(4),su=BigInt(5),Lf=BigInt(7),au=BigInt(8),$f=BigInt(9),cu=BigInt(16);function Z(t,e){if(e<=ae)throw new Error("mod: expected positive \
|
|
673
|
+
modulus, got "+e);let n=t%e;return n>=ae?n:e+n}function De(t,e,n){if(e<ae)throw new Error("pow2: expected non-negative exponent, got "+e);let r=t;for(;e-- >ae;)r*=r,r%=n;return r}function tu(t,e){if(t===ae)throw new Error("invert: expected non-zer\
|
|
674
|
+
o number");if(e<=ae)throw new Error("invert: expected positive modulus, got "+e);let n=Z(t,e),r=e,o=ae,s=re;for(;n!==ae;){let u=r/n,l=r-n*u,d=o-s*u;r=n,n=l,o=s,s=d;}if(r!==re)
|
|
675
|
+
throw new Error("invert: does not exist");return Z(o,e)}function Bi(t,e,n){let r=t;if(!r.eql(r.sqr(e),n))throw new Error("Cannot find square root")}function uu(t,e){let n=t,r=(n.ORDER+re)/iu,o=n.pow(e,
|
|
676
|
+
r);return Bi(n,o,e),o}function jf(t,e){let n=t,r=(n.ORDER-su)/au,o=n.mul(e,wt),i=n.pow(o,r),s=n.mul(e,i),a=n.mul(n.mul(s,wt),i),c=n.mul(s,n.sub(a,n.ONE));return Bi(n,c,e),c}function Nf(t){let e=Br(t),
|
|
677
|
+
n=lu(t),r=n(e,e.neg(e.ONE)),o=n(e,r),i=n(e,e.neg(r)),s=(t+Lf)/cu;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.
|
|
678
|
+
cmov(h,p,g);let f=u.eql(u.sqr(d),c),v=u.cmov(l,d,f);return Bi(u,v,c),v})}function lu(t){if(t<ou)throw new Error("sqrt is not defined for small field");let e=t-re,n=0;for(;e%wt===ae;)e/=wt,n++;let r=wt,
|
|
679
|
+
o=Br(t);for(;nu(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return uu;let i=o.pow(r,e),s=(e+re)/wt;return function(c,u){let l=c;if(l.is0(u))return u;
|
|
680
|
+
if(nu(l,u)!==1)throw new Error("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++,
|
|
681
|
+
f=l.sqr(f),g===d)throw new Error("Cannot find square root");let v=re<<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 Bf(t){return t%iu===ou?uu:t%au===su?jf:t%cu===
|
|
682
|
+
$f?Nf(t):lu(t)}var Ue=(t,e)=>(Z(t,e)&re)===re,Ff=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function du(t){let e={ORDER:"bigint",
|
|
683
|
+
BYTES:"number",BITS:"number"},n=Ff.reduce((r,o)=>(r[o]="function",r),e);if(xt(t,n),ze(t.BYTES,"BYTES"),ze(t.BITS,"BITS"),t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.
|
|
684
|
+
ORDER<=re)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function qf(t,e,n){let r=t;if(n<ae)throw new Error("invalid exponent, negatives unsupported");if(n===ae)return r.ONE;
|
|
685
|
+
if(n===re)return e;let o=r.ONE,i=e;for(;n>ae;)n&re&&(o=r.mul(o,i)),i=r.sqr(i),n>>=re;return o}function Nr(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]=
|
|
686
|
+
a,r.mul(a,c)),r.ONE),s=r.inv(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 nu(t,e){let n=t,r=(n.ORDER-re)/wt,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 zf(t,e){if(e!==void 0&&Ai(e),t<=ae)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);
|
|
687
|
+
let n=ji(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 ru=new WeakMap,
|
|
688
|
+
jr=class{ORDER;BITS;BYTES;isLE;ZERO=ae;ONE=re;_lengths;_mod;constructor(e,n={}){if(e<=re)throw new Error("invalid field: expected ORDER > 1, got "+e);let r;this.isLE=false,n!=null&&typeof n=="object"&&(typeof n.
|
|
650
689
|
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.
|
|
651
|
-
freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:i}=
|
|
652
|
-
048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=i,Object.freeze(this);}create(e){return
|
|
653
|
-
"+typeof e);return
|
|
654
|
-
e*e,this.ORDER)}add(e,n){return
|
|
655
|
-
return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return
|
|
656
|
-
isLE?
|
|
657
|
-
: 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
|
|
658
|
-
|
|
659
|
-
freeze(
|
|
660
|
-
throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function
|
|
661
|
-
shiftBy:s}}function
|
|
662
|
-
isNeg:p,isNegF:h,offsetF:u}}var
|
|
663
|
-
e.ZERO,this.Fn=e.Fn,this.bits=n;}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>
|
|
690
|
+
freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:i}=zf(e,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2\
|
|
691
|
+
048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=i,Object.freeze(this);}create(e){return Z(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got\
|
|
692
|
+
"+typeof e);return ae<=e&&e<this.ORDER}is0(e){return e===ae}isValidNot0(e){return !this.is0(e)&&this.isValid(e)}isOdd(e){return (e&re)===re}neg(e){return Z(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return Z(
|
|
693
|
+
e*e,this.ORDER)}add(e,n){return Z(e+n,this.ORDER)}sub(e,n){return Z(e-n,this.ORDER)}mul(e,n){return Z(e*n,this.ORDER)}pow(e,n){return qf(this,e,n)}div(e,n){return Z(e*tu(n,this.ORDER),this.ORDER)}sqrN(e){
|
|
694
|
+
return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return tu(e,this.ORDER)}sqrt(e){let n=ru.get(this);return n||ru.set(this,n=Bf(this.ORDER)),n(this,e)}toBytes(e){return this.
|
|
695
|
+
isLE?Qc(e,this.BYTES):Li(e,this.BYTES)}fromBytes(e,n=false){X(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\
|
|
696
|
+
: 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?Ve(e):
|
|
697
|
+
Mi(e);if(a&&(c=Z(c,s)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Nr(this,e)}cmov(e,n,r){return Nt(r,"condition"),r?n:e}};Object.
|
|
698
|
+
freeze(jr.prototype);function Br(t,e={}){return new jr(t,e)}var Fr=BigInt(0),Vi=BigInt(1);function pu(t,e){let n=e.negate();return t?n:e}function zr(t,e){let n=Nr(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function gu(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)
|
|
699
|
+
throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Fi(t,e){gu(t,e);let n=Math.ceil(e/t)+1,r=2**(t-1),o=2**t,i=eu(t),s=BigInt(t);return {windows:n,windowSize:r,mask:i,maxNumber:o,
|
|
700
|
+
shiftBy:s}}function fu(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+=Vi);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,
|
|
701
|
+
isNeg:p,isNegF:h,offsetF:u}}var qi=new WeakMap,bu=new WeakMap;function zi(t){return bu.get(t)||1}function mu(t){if(t!==Fr)throw new Error("invalid wNAF")}var qr=class{BASE;ZERO;Fn;bits;constructor(e,n){this.BASE=e.BASE,this.ZERO=
|
|
702
|
+
e.ZERO,this.Fn=e.Fn,this.bits=n;}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>Fr;)n&Vi&&(r=r.add(o)),o=o.double(),n>>=Vi;return r}precomputeWindow(e,n){let{windows:r,windowSize:o}=Fi(n,this.bits),i=[],
|
|
664
703
|
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,
|
|
665
|
-
s=
|
|
666
|
-
ZERO){let i=
|
|
667
|
-
get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),
|
|
668
|
-
e);return i===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),n,o)}createCache(e,n){
|
|
669
|
-
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>
|
|
670
|
-
let o=
|
|
671
|
-
freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:i}}function
|
|
672
|
-
let n=e,r=
|
|
673
|
-
sqrt(o.div(g,f))}}catch{return {isValid:false,value:
|
|
674
|
-
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,
|
|
704
|
+
s=Fi(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:u,isZero:l,isNeg:d,isNegF:p,offsetF:h}=fu(r,a,s);r=c,l?i=i.add(pu(p,n[h])):o=o.add(pu(d,n[u]));}return mu(r),{p:o,f:i}}wNAFUnsafe(e,n,r,o=this.
|
|
705
|
+
ZERO){let i=Fi(e,this.bits);for(let s=0;s<i.windows&&r!==Fr;s++){let{nextN:a,offset:c,isZero:u,isNeg:l}=fu(r,s,i);if(r=a,!u){let d=n[c];o=o.add(l?d.negate():d);}}return mu(r),o}getPrecomputes(e,n,r){let o=qi.
|
|
706
|
+
get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),qi.set(n,o))),o}cached(e,n,r){let o=zi(e);return this.wNAF(o,this.getPrecomputes(o,e,r),n)}unsafe(e,n,r,o){let i=zi(
|
|
707
|
+
e);return i===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),n,o)}createCache(e,n){gu(n,this.bits),bu.set(e,n),qi.delete(e);}hasCache(e){return zi(e)!==1}};function hu(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return du(e),e}else return Br(t,{isLE:n})}function vu(t,e,n={},r){if(r===void 0&&(r=t==="edwar\
|
|
708
|
+
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>Fr))throw new Error(`CURVE.${c} must be positive bigint`)}
|
|
709
|
+
let o=hu(e.p,n.Fp,r),i=hu(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.
|
|
710
|
+
freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:i}}function yu(t,e){return function(r){let o=t(r);return {secretKey:o,publicKey:e(o)}}}var it=BigInt(0),oe=BigInt(1),Ui=BigInt(2),Vf=BigInt(8);function Uf(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 ku(t,e={}){
|
|
711
|
+
let n=e,r=vu("edwards",t,n,n.FpFnLE),{Fp:o,Fn:i}=r,s=r.CURVE,{h:a}=s;xt(n,{},{uvRatio:"function"});let c=Ui<<BigInt(i.BYTES*8)-oe,u=g=>o.create(g),l=n.uvRatio===void 0?(g,f)=>{try{return {isValid:!0,value:o.
|
|
712
|
+
sqrt(o.div(g,f))}}catch{return {isValid:false,value:it}}}:n.uvRatio;if(!Uf(o,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function d(g,f,v=false){let b=v?oe:it;return $i("coordinate "+g,
|
|
713
|
+
f,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,oe,u(s.Gx*s.Gy));static ZERO=new h(it,oe,oe,it);static Fp=o;static Fn=i;X;Y;Z;T;constructor(f,v,b,y){
|
|
675
714
|
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{
|
|
676
|
-
x:v,y:b}=f||{};return d("x",v),d("y",b),new h(v,b,
|
|
677
|
-
o.ORDER
|
|
678
|
-
"bad point: x=0 and x_0=1");return
|
|
679
|
-
return m.createCache(this,f),v||this.multiply(
|
|
680
|
-
|
|
681
|
-
p(f);let{X:v,Y:b,Z:y}=this,{X:k,Y:T,Z:
|
|
682
|
-
let{a:f}=s,{X:v,Y:b,Z:y}=this,k=u(v*v),T=u(b*b),
|
|
683
|
-
Y:k,Z:T,T:
|
|
684
|
-
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=>
|
|
685
|
-
if(!i.isValid(f))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return f===
|
|
686
|
-
return m.unsafe(this,s.n).is0()}toAffine(f){let v=this,b=f,{X:y,Y:k,Z:T}=v,
|
|
687
|
-
was invalid");return {x:P,y:
|
|
688
|
-
return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let m=new
|
|
689
|
-
this.ep=e;}static fromBytes(e){
|
|
690
|
-
return this.ep.toAffine(e)}toHex(){return
|
|
715
|
+
x:v,y:b}=f||{};return d("x",v),d("y",b),new h(v,b,oe,u(v*b))}static fromBytes(f,v=false){let b=o.BYTES,{a:y,d:k}=s;f=Sn(X(f,b,"point")),Nt(v,"zip215");let T=Sn(f),x=f[b-1];T[b-1]=x&-129;let P=Ve(T),M=v?c:
|
|
716
|
+
o.ORDER;$i("point.y",P,it,M);let A=u(P*P),w=u(A-oe),S=u(k*A-y),{isValid:C,value:E}=l(w,S);if(!C)throw new Error("bad point: invalid y coordinate");let _=(E&oe)===oe,L=(x&128)!==0;if(!v&&E===it&&L)throw new Error(
|
|
717
|
+
"bad point: x=0 and x_0=1");return L!==_&&(E=u(-E)),h.fromAffine({x:E,y:P})}static fromHex(f,v=false){return h.fromBytes(Gc(f),v)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(f=8,v=true){
|
|
718
|
+
return m.createCache(this,f),v||this.multiply(Ui),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:x}=f,P=u(y*y),M=u(k*k),A=u(T*T),w=u(A*A),
|
|
719
|
+
S=u(P*v),C=u(A*u(S+M)),E=u(w+u(b*u(P*M)));if(C!==E)throw new Error("bad point: equation left != right (1)");let _=u(y*k),L=u(T*x);if(_!==L)throw new Error("bad point: equation left != right (2)")}equals(f){
|
|
720
|
+
p(f);let{X:v,Y:b,Z:y}=this,{X:k,Y:T,Z:x}=f,P=u(v*x),M=u(k*y),A=u(b*x),w=u(T*y);return P===M&&A===w}is0(){return this.equals(h.ZERO)}negate(){return new h(u(-this.X),this.Y,this.Z,u(-this.T))}double(){
|
|
721
|
+
let{a:f}=s,{X:v,Y:b,Z:y}=this,k=u(v*v),T=u(b*b),x=u(Ui*u(y*y)),P=u(f*k),M=v+b,A=u(u(M*M)-k-T),w=P+T,S=w-x,C=P-T,E=u(A*S),_=u(w*C),L=u(A*C),I=u(S*w);return new h(E,_,I,L)}add(f){p(f);let{a:v,d:b}=s,{X:y,
|
|
722
|
+
Y:k,Z:T,T:x}=this,{X:P,Y:M,Z:A,T:w}=f,S=u(y*P),C=u(k*M),E=u(x*b*w),_=u(T*A),L=u((y+k)*(P+M)-S-C),I=_-E,F=_+E,z=u(C-v*S),U=u(L*I),ee=u(F*z),K=u(L*z),N=u(I*F);return new h(U,ee,N,K)}subtract(f){return p(
|
|
723
|
+
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=>zr(h,y));return zr(h,[v,b])[0]}multiplyUnsafe(f){
|
|
724
|
+
if(!i.isValid(f))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return f===it?h.ZERO:this.is0()||f===oe?this:m.unsafe(this,f,v=>zr(h,v))}isSmallOrder(){return this.clearCofactor().
|
|
725
|
+
is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(f){let v=this,b=f,{X:y,Y:k,Z:T}=v,x=v.is0();b==null&&(b=x?Vf:o.inv(T));let P=u(y*b),M=u(k*b),A=o.mul(T,b);if(x)return {x:it,y:oe};if(A!==oe)
|
|
726
|
+
throw new Error("invZ was invalid");return {x:P,y:M}}clearCofactor(){return a===oe?this:this.multiplyUnsafe(a)}toBytes(){let{x:f,y:v}=this.toAffine(),b=o.toBytes(v);return b[b.length-1]|=f&oe?128:0,b}toHex(){
|
|
727
|
+
return Oi(this.toBytes())}toString(){return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let m=new qr(h,i.BITS);return i.BITS>=8&&h.BASE.precompute(8),Object.freeze(h.prototype),Object.freeze(h),h}var Vr=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){
|
|
728
|
+
this.ep=e;}static fromBytes(e){Ni();}static fromHex(e){Ni();}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity();}toAffine(e){
|
|
729
|
+
return this.ep.toAffine(e)}toHex(){return Oi(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){
|
|
691
730
|
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.
|
|
692
|
-
ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,n){return this.ep.precompute(e,n),this}};function
|
|
693
|
-
equired');let r=e,o=n;
|
|
694
|
-
outputLen,l=2*a.BYTES;if(u!==void 0&&(
|
|
695
|
-
C=>C:o.adjustScalarBytes,h=o.domain===void 0?(C,
|
|
696
|
-
let
|
|
697
|
-
C),
|
|
698
|
-
"context"),!!i)))}function y(C,
|
|
699
|
-
if(!c.isValid(
|
|
700
|
-
!!k.zip215:
|
|
701
|
-
|
|
702
|
-
is0()}let
|
|
703
|
-
try{return !!t.fromBytes(C,
|
|
704
|
-
|
|
705
|
-
|
|
731
|
+
ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,n){return this.ep.precompute(e,n),this}};function xu(t,e,n={}){if(typeof e!="function")throw new Error('"hash" function param is r\
|
|
732
|
+
equired');let r=e,o=n;xt(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.
|
|
733
|
+
outputLen,l=2*a.BYTES;if(u!==void 0&&(ze(u,"hash.outputLen"),u!==l))throw new Error(`hash.outputLen must be ${l}, got ${u}`);let d=o.randomBytes===void 0?Zc:o.randomBytes,p=o.adjustScalarBytes===void 0?
|
|
734
|
+
C=>C:o.adjustScalarBytes,h=o.domain===void 0?(C,E,_)=>{if(Nt(_,"phflag"),E.length||_)throw new Error("Contexts/pre-hash are not supported");return C}:o.domain;function m(C){return c.create(Ve(C))}function g(C){
|
|
735
|
+
let E=P.secretKey;X(C,P.secretKey,"secretKey");let _=X(r(C),2*E,"hashedSecretKey"),L=p(_.slice(0,E)),I=_.slice(E,2*E),F=m(L);return {head:L,prefix:I,scalar:F}}function f(C){let{head:E,prefix:_,scalar:L}=g(
|
|
736
|
+
C),I=s.multiply(L),F=I.toBytes();return {head:E,prefix:_,scalar:L,point:I,pointBytes:F}}function v(C){return f(C).pointBytes}function b(C=Uint8Array.of(),...E){let _=$e(...E);return m(r(h(_,X(C,void 0,
|
|
737
|
+
"context"),!!i)))}function y(C,E,_={}){C=X(C,void 0,"message"),i&&(C=i(C));let{prefix:L,scalar:I,pointBytes:F}=f(E),z=b(_.context,L,C),U=s.multiply(z).toBytes(),ee=b(_.context,U,F,C),K=c.create(z+ee*I);
|
|
738
|
+
if(!c.isValid(K))throw new Error("sign failed: invalid s");let N=$e(U,c.toBytes(K));return X(N,P.signature,"result")}let k={zip215:o.zip215};function T(C,E,_,L=k){let{context:I}=L,F=L.zip215===void 0?
|
|
739
|
+
!!k.zip215:L.zip215,z=P.signature;C=X(C,z,"signature"),E=X(E,void 0,"message"),_=X(_,P.publicKey,"publicKey"),F!==void 0&&Nt(F,"zip215"),i&&(E=i(E));let U=z/2,ee=C.subarray(0,U),K=Ve(C.subarray(U,z)),
|
|
740
|
+
N,Te,Y;try{N=t.fromBytes(_,F),Te=t.fromBytes(ee,F),Y=s.multiplyUnsafe(K);}catch{return false}if(!F&&N.isSmallOrder())return false;let Et=b(I,ee,_,E);return Te.add(N.multiplyUnsafe(Et)).subtract(Y).clearCofactor().
|
|
741
|
+
is0()}let x=a.BYTES,P={secretKey:x,publicKey:x,signature:2*x,seed:x};function M(C){return C=C===void 0?d(P.seed):C,X(C,P.seed,"seed")}function A(C){return Lr(C)&&C.length===P.secretKey}function w(C,E){
|
|
742
|
+
try{return !!t.fromBytes(C,E===void 0?k.zip215:E)}catch{return false}}let S={getExtendedPublicKey:f,randomSecretKey:M,isValidSecretKey:A,isValidPublicKey:w,toMontgomery(C){let{y:E}=t.fromBytes(C),_=P.publicKey,
|
|
743
|
+
L=_===32;if(!L&&_!==57)throw new Error("only defined for 25519 and 448");let I=L?a.div(oe+E,oe-E):a.div(E-oe,E+oe);return a.toBytes(I)},toMontgomerySecret(C){let E=P.secretKey;X(C,E);let _=r(C.subarray(
|
|
744
|
+
0,E));return p(_).subarray(0,E)}};return Object.freeze(P),Object.freeze(S),Object.freeze({keygen:yu(M,v),getPublicKey:v,sign:y,verify:T,utils:S,Point:t,lengths:P})}var Jf=BigInt(0),He=BigInt(1),Su=BigInt(2);var Kf=BigInt(5),Gf=BigInt(8),Bt=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Gi={p:Bt,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Gf,
|
|
706
745
|
a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6d\
|
|
707
|
-
c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function
|
|
708
|
-
i*t%i,c=
|
|
709
|
-
return t[0]&=248,t[31]&=127,t[31]|=64,t}var
|
|
710
|
-
s=
|
|
711
|
-
"1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var
|
|
712
|
-
fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),
|
|
713
|
-
|
|
714
|
-
oint expected")}init(e){return new t(e)}static fromBytes(e){
|
|
715
|
-
let a=i(s*s),c=i(
|
|
716
|
-
"invalid ristretto255 encoding 2");return new t(new
|
|
717
|
-
u=s(c*c),{value:l}=
|
|
718
|
-
g)}equals(e){this.assertSame(e);let{X:n,Y:r}=this.ep,{X:o,Y:i}=e.ep,s=u=>
|
|
719
|
-
|
|
746
|
+
c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Zf(t){let e=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),i=Bt,a=t*t%
|
|
747
|
+
i*t%i,c=De(a,Su,i)*a%i,u=De(c,He,i)*t%i,l=De(u,Kf,i)*u%i,d=De(l,e,i)*l%i,p=De(d,n,i)*d%i,h=De(p,r,i)*p%i,m=De(h,o,i)*h%i,g=De(m,o,i)*h%i,f=De(g,e,i)*l%i;return {pow_p_5_8:De(f,Su,i)*t%i,b2:a}}function Yf(t){
|
|
748
|
+
return t[0]&=248,t[31]&=127,t[31]|=64,t}var Wi=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Zi(t,e){let n=Bt,r=Z(e*e*e,n),o=Z(r*r*e,n),i=Zf(t*o).pow_p_5_8,
|
|
749
|
+
s=Z(t*r*i,n),a=Z(e*s*s,n),c=s,u=Z(s*Wi,n),l=a===t,d=a===Z(-t,n),p=a===Z(-t*Wi,n);return l&&(s=c),(d||p)&&(s=u),Ue(s,n)&&(s=Z(-s,n)),{isValid:l||d,value:s}}var at=ku(Gi,{uvRatio:Zi}),st=at.Fp,Eu=at.Fn;function Qf(t){return xu(at,Ar,Object.assign({adjustScalarBytes:Yf,zip215:true},t))}var Pu=Qf({});var Ji=Wi;BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");var em=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt(
|
|
750
|
+
"1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var Tu=t=>Zi(He,t),rm=BigInt("0x7\
|
|
751
|
+
fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Ki=t=>st.create(Ve(t)&rm);var ct=class t extends Vr{static BASE=new t(
|
|
752
|
+
at.BASE);static ZERO=new t(at.ZERO);static Fp=st;static Fn=Eu;constructor(e){super(e);}static fromAffine(e){return new t(at.fromAffine(e))}assertSame(e){if(!(e instanceof t))throw new Error("RistrettoP\
|
|
753
|
+
oint expected")}init(e){return new t(e)}static fromBytes(e){Re(e,32);let{a:n,d:r}=Gi,o=Bt,i=k=>st.create(k),s=Ki(e);if(!Xc(st.toBytes(s),e)||Ue(s,o))throw new Error("invalid ristretto255 encoding 1");
|
|
754
|
+
let a=i(s*s),c=i(He+n*a),u=i(He-n*a),l=i(c*c),d=i(u*u),p=i(n*r*l-d),{isValid:h,value:m}=Tu(i(p*d)),g=i(m*u),f=i(m*g*p),v=i((s+s)*g);Ue(v,o)&&(v=i(-v));let b=i(c*f),y=i(v*b);if(!h||Ue(y,o)||b===Jf)throw new Error(
|
|
755
|
+
"invalid ristretto255 encoding 2");return new t(new at(v,b,He,y))}static fromHex(e){return t.fromBytes(kn(e))}toBytes(){let{X:e,Y:n,Z:r,T:o}=this.ep,i=Bt,s=f=>st.create(f),a=s(s(r+n)*s(r-n)),c=s(e*n),
|
|
756
|
+
u=s(c*c),{value:l}=Tu(s(a*u)),d=s(l*a),p=s(l*c),h=s(d*p*o),m;if(Ue(o*h,i)){let f=s(n*Ji),v=s(e*Ji);e=f,n=v,m=s(d*em);}else m=p;Ue(e*h,i)&&(n=s(-n));let g=s((r-n)*m);return Ue(g,i)&&(g=s(-g)),st.toBytes(
|
|
757
|
+
g)}equals(e){this.assertSame(e);let{X:n,Y:r}=this.ep,{X:o,Y:i}=e.ep,s=u=>st.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(ct.BASE);Object.freeze(
|
|
758
|
+
ct.ZERO);Object.freeze(ct.prototype);Object.freeze(ct);var Ru=`-----BEGIN PUBLIC KEY-----
|
|
720
759
|
MCowBQYDK2VwAyEAWBiklf0kmDIVmM7nMiCxwiEAkwQIiqWGuRiRDJonsFY=
|
|
721
|
-
-----END PUBLIC KEY-----`;function
|
|
722
|
-
length%4?"=".repeat(4-e.length%4):"";return
|
|
723
|
-
function
|
|
724
|
-
function
|
|
725
|
-
oken"};let n=t.split("."),r=n[0],o=n[1],i=n[2],s;try{s=JSON.parse(
|
|
726
|
-
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=
|
|
727
|
-
return {ok:false,reason:"invalid public key"}}let u=false;try{u=
|
|
728
|
-
{ok:false,reason:"bad signature"}}function
|
|
729
|
-
n.payloadBytes))}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function
|
|
730
|
-
active":e<=r?"grace":"expired"}function
|
|
731
|
-
{reason:i.reason}:{}};let s=i.payload,a=n.nowSeconds??Math.floor(Date.now()/1e3),c=
|
|
732
|
-
if(o.header?.typ!==
|
|
760
|
+
-----END PUBLIC KEY-----`;function Du(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 Yi(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.
|
|
761
|
+
length%4?"=".repeat(4-e.length%4):"";return Du(e+n)}function im(t){let e=t.replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=Du(e);return n.subarray(n.length-32)}var sm=new TextEncoder,_u=new TextDecoder;
|
|
762
|
+
function am(t){return typeof t=="object"&&t!==null&&"keys"in t}function Ft(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 cm=/^[A-Za-z0-9_-]+$/;
|
|
763
|
+
function Iu(t){let e=t.split(".");return e.length===3&&e.every(n=>cm.test(n))}function Qi(t){return t===""?"empty":Iu(t)?"token":"malformed"}function Xi(t,e){if(!Iu(t))return {ok:false,reason:"malformed t\
|
|
764
|
+
oken"};let n=t.split("."),r=n[0],o=n[1],i=n[2],s;try{s=JSON.parse(_u.decode(Yi(r)));}catch{return {ok:false,reason:"header is not valid JSON"}}let a;if(am(e)){let l=typeof s.kid=="string"?s.kid:e.defaultKid,
|
|
765
|
+
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=im(a),c.length!==32)return {ok:!1,reason:"invalid public key"}}catch{
|
|
766
|
+
return {ok:false,reason:"invalid public key"}}let u=false;try{u=Pu.verify(Yi(i),sm.encode(`${r}.${o}`),c);}catch{return {ok:false,reason:"signature verification error"}}return u?{ok:true,header:s,payloadBytes:Yi(o)}:
|
|
767
|
+
{ok:false,reason:"bad signature"}}function qt(t,e){let n=Xi(t,e);if(!n.ok||!n.payloadBytes)return {signatureValid:false,...n.reason?{reason:n.reason}:{}};try{return {signatureValid:!0,payload:JSON.parse(_u.decode(
|
|
768
|
+
n.payloadBytes))}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function es(t,e,n){if(n?.has(t.jti))return "revoked";let r=t.expires_at+t.grace_days*86400;return e<=t.expires_at?"\
|
|
769
|
+
active":e<=r?"grace":"expired"}function Ny(t,e,n={}){let r=Ft(t);if(Qi(r)==="empty")return {status:"none",reason:"empty"};let i=qt(r,e);if(!i.signatureValid||!i.payload)return {status:"invalid",...i.reason?
|
|
770
|
+
{reason:i.reason}:{}};let s=i.payload,a=n.nowSeconds??Math.floor(Date.now()/1e3),c=es(s,a,n.revoked);return c==="revoked"?{status:c,payload:s,reason:"license revoked"}:{status:c,payload:s}}var Au="BVSALA-REVOC",um=300,lm=new TextDecoder;function Ou(t,e,n={}){let r=u=>({ok:false,seq:-1,asOf:0,revoked:new Set,reason:u}),o=Xi(t,e);if(!o.ok||!o.payloadBytes)return r(o.reason??"bad signature");
|
|
771
|
+
if(o.header?.typ!==Au)return r(`unexpected token type "${String(o.header?.typ??"")}" (want ${Au})`);let i;try{i=JSON.parse(lm.decode(o.payloadBytes));}catch{return r("payload is not valid JSON")}if(typeof i.
|
|
733
772
|
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.
|
|
734
|
-
nowSeconds??Math.floor(Date.now()/1e3),c=n.maxSkewSeconds
|
|
773
|
+
nowSeconds??Math.floor(Date.now()/1e3),c=n.maxSkewSeconds??um;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 zt=class{_seq=-1;_asOf=0;_lastContactAt=0;set=new Set;get seq(){
|
|
735
774
|
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.
|
|
736
775
|
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&&
|
|
737
|
-
(this._asOf=e.asOf),r||o}};function
|
|
738
|
-
c?.features??[]),l=()=>{if(s==="empty")return "none";if(!c)return "invalid";let p=
|
|
776
|
+
(this._asOf=e.asOf),r||o}};function Ur(t,e,n){let r=()=>Math.floor((n.now?n.now():Date.now())/1e3),o=n.startedAt??r(),i=Ft(t),s=Qi(i),a=s==="token"?qt(i,e):{signatureValid:false,reason:s},c=a.signatureValid?a.payload:void 0,u=new Set(
|
|
777
|
+
c?.features??[]),l=()=>{if(s==="empty")return "none";if(!c)return "invalid";let p=es(c,r(),n.revocation.snapshot());if(n.maxStalenessSeconds!=null&&(p==="active"||p==="grace")){let h=c.expires_at+c.grace_days*
|
|
739
778
|
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(
|
|
740
|
-
p),isActive:()=>d(),status:l,reason:()=>c?void 0:a.reason,refreshAfter:()=>{if(c)return Math.min(c.expires_at,r()+86400)}}}function
|
|
779
|
+
p),isActive:()=>d(),status:l,reason:()=>c?void 0:a.reason,refreshAfter:()=>{if(c)return Math.min(c.expires_at,r()+86400)}}}function Mu(t,e,n){return Ur(t,e,{revocation:new zt,...n?{now:n}:{}})}var Vt={pollIntervalSeconds:900,floorSeconds:300,maxIntervalSeconds:3600,jitterRatio:.1,maxSkewSeconds:300,requestTimeoutMs:3e4},Lu=3,dm=12;function pm(t){let e=t.random??Math.random,n;if(t.consecutiveFailures>
|
|
741
780
|
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:
|
|
742
|
-
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
|
|
781
|
+
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 fm=10,Hr=class{constructor(e){this.opts=e;}opts;timer=null;controller=null;consecutiveFailures=0;stopped=false;started=false;lastEtag=null;consecutive304=0;now(){
|
|
743
782
|
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();
|
|
744
783
|
if(!e){this.avisar("sin-fetch","[bv-sala] no global fetch available; revocation call-home disabled (offline). License expiry is still enforced from the token."),this.opts.onEvent?.({type:"no-fetch"});
|
|
745
|
-
return}let n=new AbortController;this.controller=n;let r=this.opts.requestTimeoutMs
|
|
784
|
+
return}let n=new AbortController;this.controller=n;let r=this.opts.requestTimeoutMs??Vt.requestTimeoutMs,o=setTimeout(()=>n.abort(),r);o.unref?.();let i={accept:"application/json"};this.lastEtag&&(i["\
|
|
746
785
|
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.now()),this.opts.onEvent?.(
|
|
747
|
-
{type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=
|
|
748
|
-
ions 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=
|
|
749
|
-
opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds
|
|
786
|
+
{type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=fm&&(this.consecutive304=0,this.lastEtag=null);return}if(this.consecutive304=0,!s.ok)throw new Error(`revocat\
|
|
787
|
+
ions 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=Ou(c.list,this.opts.publicKeyPem,{minSeq:this.
|
|
788
|
+
opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??Vt.maxSkewSeconds});if(!u.ok){let d=u.reason??"rejected";this.opts.onEvent?.({type:"rejected",reason:d}),this.avisar(`r\
|
|
750
789
|
echazada:${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. Check ${this.opts.url}.`);
|
|
751
790
|
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.snapshot().size}:{type:"\
|
|
752
791
|
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(){return !!(this.opts.
|
|
753
|
-
silenceWarnings??this.opts.silenciarAvisos)}avisar(e,n){this.callado()||
|
|
754
|
-
|
|
792
|
+
silenceWarnings??this.opts.silenciarAvisos)}avisar(e,n){this.callado()||we(`poller:${this.opts.url}:${e}`,n);}avisarFalloDeRed(e){if(this.callado())return;let n=this.consecutiveFailures;if(n<Lu||(n-Lu)%
|
|
793
|
+
dm!==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 revocations sti\
|
|
755
794
|
ll 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(){if(this.stopped)
|
|
756
|
-
return;let e=
|
|
757
|
-
opts.pollIntervalSeconds
|
|
795
|
+
return;let e=pm({refreshAfter:this.opts.getRefreshAfter?.(),nowSeconds:this.now(),consecutiveFailures:this.consecutiveFailures,floorSeconds:this.opts.floorSeconds??Vt.floorSeconds,pollIntervalSeconds:this.
|
|
796
|
+
opts.pollIntervalSeconds??Vt.pollIntervalSeconds,maxIntervalSeconds:this.opts.maxIntervalSeconds??Vt.maxIntervalSeconds,jitterRatio:this.opts.jitterRatio??Vt.jitterRatio,...this.opts.random?{random:this.
|
|
758
797
|
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.
|
|
759
|
-
controller?.abort();}};var
|
|
798
|
+
controller?.abort();}};var Cn=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=
|
|
760
799
|
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.
|
|
761
800
|
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.
|
|
762
801
|
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??
|
|
763
802
|
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.
|
|
764
803
|
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.
|
|
765
804
|
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\
|
|
766
|
-
er ${this.options.serviceAccountKey}`,[
|
|
767
|
-
`the server responded ${o.status}`)):o.status===401||o.status===403?(
|
|
805
|
+
er ${this.options.serviceAccountKey}`,[Un]:`${this.options.surface??"sdk"}/${Be}`},body:JSON.stringify(r)});o.ok?this.fallosSeguidos=0:o.status>=500?(this.fallosSeguidos++,this.requeue(n),this.avisarDeFallo(
|
|
806
|
+
`the server responded ${o.status}`)):o.status===401||o.status===403?(we(`metering-auth-${o.status}`,`[bv-sala] usage reporting is being rejected with HTTP ${o.status} at ${this.options.url}. Check 'se\
|
|
768
807
|
rviceAccountKey' (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?.(
|
|
769
808
|
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.
|
|
770
809
|
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||
|
|
@@ -776,207 +815,209 @@ tokens.compressedInput,baselineOutputTokens:n.tokens.baselineOutput,actualOutput
|
|
|
776
815
|
eliminatedInputFloorCost!==void 0&&Number.isFinite(n.cost.eliminatedInputFloorCost)&&n.cost.eliminatedInputFloorCost>0&&n.tokens.eliminatedInput>0?{eliminatedInputFloorCost:n.cost.eliminatedInputFloorCost}:
|
|
777
816
|
{},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}$/.
|
|
778
817
|
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.
|
|
779
|
-
attribution.sessionId}:{},...n.attribution?.agentId?{agentId:n.attribution.agentId}:{}}}};function
|
|
780
|
-
]";return new RegExp(`-${e}{8,10}-${e}{5}$`).test(t)}function
|
|
781
|
-
t.NETLIFY)}async function
|
|
782
|
-
if(t.KUBERNETES_SERVICE_HOST||
|
|
783
|
-
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
|
|
784
|
-
ONS","GITLAB_CI","CIRCLECI","TRAVIS","JENKINS_URL","BUILDKITE","TF_BUILD","TEAMCITY_VERSION","BITBUCKET_BUILD_NUMBER","CODEBUILD_BUILD_ID","HEROKU_TEST_RUN_ID","DRONE"];function
|
|
785
|
-
return false;for(let e of
|
|
818
|
+
attribution.sessionId}:{},...n.attribution?.agentId?{agentId:n.attribution.agentId}:{}}}};function Wr(){return globalThis.process}function mm(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\
|
|
819
|
+
]";return new RegExp(`-${e}{8,10}-${e}{5}$`).test(t)}function hm(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??
|
|
820
|
+
t.NETLIFY)}async function gm(){if(Wr()?.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 bm(t,e=gm){
|
|
821
|
+
if(t.KUBERNETES_SERVICE_HOST||hm(t))return;let n=t.HOSTNAME??t.COMPUTERNAME??await e();if(!(!n||mm(n)))return n}async function vm(){let t=Wr();if(!t||!t.env)return;let e=t.env,n=await bm(e),r=[t.platform,
|
|
822
|
+
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 ym=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTI\
|
|
823
|
+
ONS","GITLAB_CI","CIRCLECI","TRAVIS","JENKINS_URL","BUILDKITE","TF_BUILD","TEAMCITY_VERSION","BITBUCKET_BUILD_NUMBER","CODEBUILD_BUILD_ID","HEROKU_TEST_RUN_ID","DRONE"];function ts(){let t=Wr()?.env;if(!t)
|
|
824
|
+
return false;for(let e of ym){let n=t[e];if(n&&n!=="false"&&n!=="0")return true}return false}async function km(t,e){let n=globalThis.crypto,r=new TextEncoder;if(n?.subtle)try{let s=await n.subtle.importKey("raw",
|
|
786
825
|
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}\
|
|
787
|
-
|${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
|
|
788
|
-
if(!r)return;let o=await
|
|
789
|
-
new
|
|
790
|
-
|
|
791
|
-
|
|
826
|
+
|${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 ns(t){let n=Wr()?.env?.BVSALA_SEAT_ID;if(n&&xm.test(n))return n;let r=await vm();
|
|
827
|
+
if(!r)return;let o=await km(t,r);if(o)return `m-${o.slice(0,32)}`}var xm=/^[A-Za-z0-9._:/-]{1,128}$/;var $u={inputPer1k:5e-4,outputPer1k:.0015,cachedInputPer1k:5e-5};function ju(t){return {exactCache:t.exactCache??new Kn,semanticCache:t.semanticCache,singleflight:t.singleflight??new Gn,resolvers:t.resolvers??Ta(),router:t.router??new tr,toolSelector:t.toolSelector??
|
|
828
|
+
new rr,formatSelector:t.formatSelector??new ar({tokenizer:t.tokenizer}),schemaRegistry:t.schemaRegistry??new cr,constraintBackends:t.constraintBackends??[]}}function J(t){let e=t.maxOutputTokens,n=t.response?.maxOutputTokens;return e==null?n??void 0:n==null?e:Math.min(e,n)}function rs(t){let e=t.response?.maxOutputTokens??256,n=t.maxOutputTokens;return n==
|
|
829
|
+
null?e:Math.min(e,n)}function os(t){let e=t.maxOutputTokens;if(e!==void 0&&(typeof e!="number"||!Number.isInteger(e)||e<=0))throw new TypeError(`[bvsala] request.maxOutputTokens must be a positive int\
|
|
830
|
+
eger (got ${String(e)}).`)}var Se=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\
|
|
831
|
+
ted before any provider request was sent"),this.name="StreamAbortedError",this.requestSent=e;}},Jr=class extends Error{job;notSubmitted;constructor(e,n,r,o){super(e,o),this.name="BatchSubmitError",this.
|
|
832
|
+
job=n,this.notSubmitted=r;}};var wm={"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.\
|
|
792
833
|
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\
|
|
793
834
|
.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,
|
|
794
835
|
"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\
|
|
795
|
-
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,"
|
|
796
|
-
"
|
|
797
|
-
|
|
798
|
-
/^qwq/,/^qwen3/,/^glm-(4\.[5-9]|[5-9])/,/magistral/];function
|
|
799
|
-
return "unclassified-model";let o=
|
|
836
|
+
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,"gemini-3.8-flash":true,"gemini-3.7-flash":true,"gemini-3.6-flas\
|
|
837
|
+
h":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},Sm=new Set(["claude\
|
|
838
|
+
-opus-4-7","claude-opus-4-8"]),Tm=[/^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($|[-_.])/,
|
|
839
|
+
/^qwq/,/^qwen3/,/^glm-(4\.[5-9]|[5-9])/,/magistral/];function Nu(t){let e=t.lastIndexOf("/"),n=(e>=0?t.slice(e+1):t).toLowerCase();if(Tm.some(i=>i.test(n)))return "reasoning-model";let r=_t(t);if(r===void 0)
|
|
840
|
+
return "unclassified-model";let o=wm[r];if(o===true)return "reasoning-model";if(o!==false)return "unclassified-model";if(Sm.has(r))return "temperature-ignored"}var is={minimumCacheTokens:1024,cacheReadMultiplier:.5,cacheWriteMultiplier:1},Bu={minimumCacheTokens:1024,cacheReadMultiplier:.1,cacheWriteMultiplier:1.25},Cm=[["claude-fable-5-1",512],["claude-mytho\
|
|
800
841
|
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",
|
|
801
|
-
4096],["claude-3-5-haiku",2048]];function
|
|
802
|
-
n)),c=a*i*r.cacheReadMultiplier+(1-a)*i*r.cacheWriteMultiplier;return s+c}function
|
|
842
|
+
4096],["claude-3-5-haiku",2048]];function ss(t){for(let[e,n]of Cm)if(t===e||t.startsWith(`${e}-`))return {...Bu,minimumCacheTokens:n};return Bu}var as={minimumCacheTokens:1024,cacheReadMultiplier:.1,cacheWriteMultiplier:1};var Fu={minimumCacheTokens:1024,cacheReadMultiplier:1,cacheWriteMultiplier:1};function Kr(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,
|
|
843
|
+
n)),c=a*i*r.cacheReadMultiplier+(1-a)*i*r.cacheWriteMultiplier;return s+c}function cs(t){let e=Kr(t.originalTokens,t.stablePrefixTokens,t.prefixHitRate,t.tier),n=Kr(t.compressedTokens,0,0,t.tier)+(t.compressorCostTokens??
|
|
803
844
|
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}\
|
|
804
845
|
< ${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*
|
|
805
846
|
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\
|
|
806
|
-
es not touch the cache tier";return {comprimir:r>0,costeComprimido:n,costeSinComprimir:e,ganancia:r,razon:a}}function
|
|
807
|
-
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
|
|
808
|
-
totalTokens?null:1)}var
|
|
809
|
-
1)*e}estado(e){return this.estados.get(e)}decidir(e,n){let r=
|
|
810
|
-
{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 ${
|
|
847
|
+
es not touch the cache tier";return {comprimir:r>0,costeComprimido:n,costeSinComprimir:e,ganancia:r,razon:a}}function qu(t){let e=o=>cs({...t,prefixHitRate:o}).ganancia;if(e(0)<=0||e(1)>0)return null;let n=0,
|
|
848
|
+
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 Em(t){let e=qu({originalTokens:t.totalTokens,compressedTokens:t.totalTokens,stablePrefixTokens:t.stablePrefixTokens,tier:t.tier});return e??(Kr(t.totalTokens,t.stablePrefixTokens,0,t.tier)<=t.
|
|
849
|
+
totalTokens?null:1)}var Gr=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-
|
|
850
|
+
1)*e}estado(e){return this.estados.get(e)}decidir(e,n){let r=Em(n),o=this.estados.get(e),i=Pm(o);return n.stablePrefixTokens<=0?{marcar:false,razon:"no stable prefix to cache",umbral:r,observada:i}:r==null?
|
|
851
|
+
{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 ${Ut(i)} did not reach the ${Ut(
|
|
811
852
|
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 \
|
|
812
|
-
is only observable on requests that were marked`,umbral:r,observada:i}:i!=null&&i>r?{marcar:true,razon:`measured hit rate ${
|
|
813
|
-
razon:`prefix-cache marking OFF: measured hit rate ${
|
|
814
|
-
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
|
|
815
|
-
if(!t)return null;let e=t.tokensLeidos+t.tokensEscritos;return e<=0?t.marcadas>0?0:null:t.tokensLeidos/e}function
|
|
816
|
-
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
|
|
817
|
-
return
|
|
818
|
-
"";return `${t.role}${t.name??""}${t.toolCallId??""}${e}${t.content}${n}`}function
|
|
819
|
-
let e=0;for(;e<t.length&&t[e].role==="system";)e+=1;return e}function
|
|
820
|
-
tardias:0},"1h":{resueltas:0,reutilizadas:0,tardias:0}}}var
|
|
853
|
+
is only observable on requests that were marked`,umbral:r,observada:i}:i!=null&&i>r?{marcar:true,razon:`measured hit rate ${Ut(i)} beats the ${Ut(r)} break-even`,umbral:r,observada:i}:(o.apagada=true,{marcar:false,
|
|
854
|
+
razon:`prefix-cache marking OFF: measured hit rate ${Ut(i)} did not reach the ${Ut(r)} break-even, so marking was costing money`,umbral:r,observada:i})}registrar(e,n){let r=this.estados.get(e)??{marcadas:0,
|
|
855
|
+
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 Pm(t){
|
|
856
|
+
if(!t)return null;let e=t.tokensLeidos+t.tokensEscritos;return e<=0?t.marcadas>0?0:null:t.tokensLeidos/e}function Ut(t){return t==null?"n/a":`${(t*100).toFixed(1)}%`}var Ht={"5m":3e5,"30m":18e5,"1h":36e5},_e=["5m","30m","1h"],Uu=20;function zu(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.
|
|
857
|
+
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 Vu(t){
|
|
858
|
+
return zu(t,0).toString(36)+"."+zu(t,2654435769).toString(36)}function Rm(t){let e=t.toolCalls?.length?t.toolCalls.map(r=>`${r.id??""}${r.name}${r.arguments}`).join(""):"",n=t.isError===true?"error":
|
|
859
|
+
"";return `${t.role}${t.name??""}${t.toolCallId??""}${e}${t.content}${n}`}function Hu(t,e){let n=[Vu(`bvsala-prefijo\0${t}`)];for(let r of e)n.push(Vu(`${n[n.length-1]}${Rm(r)}`));return n}function hs(t){
|
|
860
|
+
let e=0;for(;e<t.length&&t[e].role==="system";)e+=1;return e}function us(){return {"5m":0,"30m":0,"1h":0}}function ls(){return {"5m":{resueltas:0,reutilizadas:0,tardias:0},"30m":{resueltas:0,reutilizadas:0,
|
|
861
|
+
tardias:0},"1h":{resueltas:0,reutilizadas:0,tardias:0}}}var Zr=1,Wu=1440*6e4;function gs(t){return `bvsala:cache-breakpoints:v${Zr}:${t}`}var Jt=class{clases=new Map;porHuella=new Map;maxPorClase;maxClases;prediccionesMinimas;confirmacionMinima;memoria;constructor(e={}){
|
|
821
862
|
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??
|
|
822
863
|
.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!==
|
|
823
|
-
e||a.indice!==s)continue;let c=Math.max(0,r-a.escrita);c>
|
|
864
|
+
e||a.indice!==s)continue;let c=Math.max(0,r-a.escrita);c>Ht["1h"]||(this.resolverReutilizada(o,a,c),i={tipo:a.tipo,indice:s,huecoMs:c,...a.posicionDelProveedor!==void 0?{posicionDelProveedor:a.posicionDelProveedor}:
|
|
824
865
|
{},...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","\
|
|
825
866
|
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,
|
|
826
867
|
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.
|
|
827
|
-
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
|
|
828
|
-
void 0)return;let o=n.ttl??"5m";if(n.huecoMs>
|
|
868
|
+
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 _e)n.pendientes[o][l]+=1;}}verificar(e,n,r){if(n.posicionDelProveedor===
|
|
869
|
+
void 0)return;let o=n.ttl??"5m";if(n.huecoMs>Ht[o])return;let i=this.estadoDe(e);i.predichas+=1,r>=n.posicionDelProveedor*.98&&(i.confirmadas+=1),i.predichas>=this.prediccionesMinimas&&i.confirmadas/i.
|
|
829
870
|
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["\
|
|
830
|
-
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:
|
|
831
|
-
i["30m"]),en1h:
|
|
832
|
-
return this.porHuella.size}exportarClase(e){let r=this.clases.get(e)??this.estadoVacio(),o=r.cabeza,i=c=>
|
|
833
|
-
u=>r.pendientes[c][u]),a={v:
|
|
834
|
-
huella,c.tipo,c.indice,c.escrita,c.contadas,0,c.posicionDelProveedor??null,c.ttl??null,c.idDelProveedor??null]),cur:
|
|
871
|
+
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:ds(i["5m"]),en30m:ds(
|
|
872
|
+
i["30m"]),en1h:ds(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(){
|
|
873
|
+
return this.porHuella.size}exportarClase(e){let r=this.clases.get(e)??this.estadoVacio(),o=r.cabeza,i=c=>_e.map(u=>{let l=r.contadores[c][u];return [l.resueltas,l.reutilizadas,l.tardias]}),s=c=>_e.map(
|
|
874
|
+
u=>r.pendientes[c][u]),a={v:Zr,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.
|
|
875
|
+
huella,c.tipo,c.indice,c.escrita,c.contadas,0,c.posicionDelProveedor??null,c.ttl??null,c.idDelProveedor??null]),cur:_e.map(c=>Math.max(0,r.cursores[c]-o)),pr:r.predichas,co:r.confirmadas,off:r.apagada};
|
|
835
876
|
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>
|
|
836
|
-
|
|
837
|
-
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!==
|
|
877
|
+
Zr)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.
|
|
878
|
+
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!==Zr||e.clase!==n)return null;let r=i=>typeof i==
|
|
838
879
|
"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<
|
|
839
|
-
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=
|
|
880
|
+
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=_e[c];o.contadores[i][h]={resueltas:l,reutilizadas:d,tardias:p},o.pendientes[i][h]=
|
|
840
881
|
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!==
|
|
841
882
|
"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&&
|
|
842
883
|
!(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}:
|
|
843
|
-
{},...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[
|
|
844
|
-
!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:
|
|
884
|
+
{},...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[_e[i]]=s;}return !r(e.pr)||
|
|
885
|
+
!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:ls(),H:ls(),T:ls()},pendientes:{S:us(),H:us(),T:us()},cola:[],
|
|
845
886
|
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.
|
|
846
887
|
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(
|
|
847
|
-
s.huella);}this.clases.delete(r);}return n}descartar(e){let n=this.clases.get(e.clase);
|
|
848
|
-
1<<o);}),e.descartada=true;}resolverReutilizada(e,n,r){
|
|
849
|
-
1,r<=
|
|
850
|
-
e.cabeza);for(;i<e.cola.length&&n-e.cola[i].escrita>
|
|
888
|
+
s.huella);}this.clases.delete(r);}return n}descartar(e){let n=this.clases.get(e.clase);_e.forEach((r,o)=>{e.contadas&1<<o||(n&&(n.pendientes[e.tipo][r]=Math.max(0,n.pendientes[e.tipo][r]-1)),e.contadas|=
|
|
889
|
+
1<<o);}),e.descartada=true;}resolverReutilizada(e,n,r){_e.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+=
|
|
890
|
+
1,r<=Ht[o]&&(s.reutilizadas+=1),o==="1h"&&r<=Ht["1h"]&&r>Ht["5m"]&&(s.tardias+=1),n.contadas|=1<<i;}),this.reducirSiHaceFalta(e.contadores[n.tipo]);}vencer(e,n){for(_e.forEach((r,o)=>{let i=Math.max(e.cursores[r],
|
|
891
|
+
e.cabeza);for(;i<e.cola.length&&n-e.cola[i].escrita>Ht[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+=
|
|
851
892
|
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),
|
|
852
|
-
e.cabeza+=1;}if(e.cabeza>1024&&e.cabeza*2>e.cola.length){e.cola.splice(0,e.cabeza);for(let r of
|
|
853
|
-
(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
|
|
854
|
-
0}function
|
|
855
|
-
0,i-s),Math.min(1,i+s)]}function
|
|
856
|
-
o=t.primaDeUnaHora!=null&&t.primaDeUnaHora>r?t.primaDeUnaHora:null,i=
|
|
893
|
+
e.cabeza+=1;}if(e.cabeza>1024&&e.cabeza*2>e.cola.length){e.cola.splice(0,e.cabeza);for(let r of _e)e.cursores[r]-=e.cabeza;e.cabeza=0;}}reducirSiHaceFalta(e){for(let n of _e)e[n].resueltas>=this.memoria&&
|
|
894
|
+
(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 ds(t){return t.resueltas>0?t.reutilizadas/t.resueltas:
|
|
895
|
+
0}function ps(t,e){let n=t-e;return n>0?Math.max(0,(t-1)/n):1}function fs(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(
|
|
896
|
+
0,i-s),Math.min(1,i+s)]}function ms(t,e,n,r,o){return e+n>=o&&fs(t,e+n)[0]>r?true:e>=o&&fs(t,e)[1]<r?false:null}function Ju(t){let e=t.muestrasMinimas??5,n=t.tramo.cacheReadMultiplier,r=t.tramo.cacheWriteMultiplier,
|
|
897
|
+
o=t.primaDeUnaHora!=null&&t.primaDeUnaHora>r?t.primaDeUnaHora:null,i=ps(r,n),s=o!=null?ps(o,n):null,a={historial:true,cola:false,ttl:"5m",razon:"",equilibrio:i};if(t.estadistica.apagada)return {...a,razon:`\
|
|
857
898
|
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\
|
|
858
|
-
n reuse measurement here`};let c=b=>({en5m:
|
|
899
|
+
n reuse measurement here`};let c=b=>({en5m:ms(b.k5m,b.muestras5m,b.pendientes5m,i,e),en1h:s!=null?ms(b.k1h,b.muestras1h,b.pendientes1h,s,e):null}),u=[],l=t.estadistica.H,d=t.estadistica.T,p=c(l),h=c(d),
|
|
859
900
|
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,
|
|
860
|
-
u.push(`history re-sent only ${m(l)} (break-even ${
|
|
901
|
+
u.push(`history re-sent only ${m(l)} (break-even ${Wt(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\
|
|
861
902
|
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\
|
|
862
|
-
en ${
|
|
863
|
-
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 ${
|
|
864
|
-
0){let[
|
|
865
|
-
tokens then beats the extra premium on the ${P} written now`));}}return {historial:g,cola:f,ttl:v,razon:u.join("; "),equilibrio:i}}function
|
|
866
|
-
t.tramo.cacheReadMultiplier),r=t.estadistica.T,o=t.estadistica.H,i=(a,c,u)=>
|
|
903
|
+
en ${Wt(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.
|
|
904
|
+
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 ${Wt(s)}), while 5 min does not pay`);else if(k.en5m===true&&y.muestras1h>=e&&T>
|
|
905
|
+
0){let[x]=fs(y.kTardias,y.muestras1h+y.pendientes1h),P=Math.max(0,T-t.lecturaPrevista()),M=x*(r-n)*T,A=(o-r)*P;M>A&&(v="1h",u.push(`1h TTL: at least ${Wt(x)} of re-sends come after 5 min; re-reading ${T}\
|
|
906
|
+
tokens then beats the extra premium on the ${P} written now`));}}return {historial:g,cola:f,ttl:v,razon:u.join("; "),equilibrio:i}}function Ku(t){let e=t.muestrasMinimas??5,n=ps(t.tramo.cacheWriteMultiplier,
|
|
907
|
+
t.tramo.cacheReadMultiplier),r=t.estadistica.T,o=t.estadistica.H,i=(a,c,u)=>ms(a,c,u,n,e)===false;if(t.estadistica.apagada)return {explicita:false,historial:true,razon:`provider default kept: the provider's co\
|
|
867
908
|
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:`\
|
|
868
|
-
provider default kept: continued ${r.k30m}/${r.muestras30m} within 30 min, not clearly below the ${
|
|
869
|
-
explicita:true,historial:s,razon:`explicit mode: continued only ${r.k30m}/${r.muestras30m} within 30 min (break-even ${
|
|
870
|
-
istory":"system header"}`,equilibrio:n}}function
|
|
871
|
-
if(!t||!e)return null;let r=
|
|
909
|
+
provider default kept: continued ${r.k30m}/${r.muestras30m} within 30 min, not clearly below the ${Wt(n)} break-even`,equilibrio:n};let s=!t.hayHistorial||!i(o.k30m,o.muestras30m,o.pendientes30m);return {
|
|
910
|
+
explicita:true,historial:s,razon:`explicit mode: continued only ${r.k30m}/${r.muestras30m} within 30 min (break-even ${Wt(n)}), so the question is not written; breakpoint at the ${s?"end of the stable h\
|
|
911
|
+
istory":"system header"}`,equilibrio:n}}function Wt(t){return `${(t*100).toFixed(1)}%`}var Gu=.5;function Dm(t,e){return e.inputPer1k<=0||e.outputPer1k<=0?null:Math.max(t.inputPer1k/e.inputPer1k,t.outputPer1k/e.outputPer1k)}function _m(t){return 1-t}function Im(t,e=Gu){return e-t}function Zu(t,e,n=Gu){
|
|
912
|
+
if(!t||!e)return null;let r=Dm(t,e);if(r==null||!Number.isFinite(r))return null;let o=_m(r),i=Im(r,n),s=i>0,a=c=>`${(c*100).toFixed(1)}%`;return {r,equilibrio:o,escaladoMaximo:i,viable:s,razon:s?`the c\
|
|
872
913
|
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\
|
|
873
|
-
o escalations it cannot reach the ${a(n)} target, so this pair is not worth the quality risk`}}var
|
|
874
|
-
ude-opus-4":"claude-haiku-4-5","claude-sonnet-4":"claude-haiku-4-5","claude-3-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
e)}decidir(e,n){let r=this.estados.get(e),o=
|
|
914
|
+
o escalations it cannot reach the ${a(n)} target, so this pair is not worth the quality risk`}}var bs={"gpt-4":"gpt-4o","gpt-4-turbo":"gpt-4o-mini","gpt-4o":"gpt-4o-mini","gpt-4.1":"gpt-4.1-mini","cla\
|
|
915
|
+
ude-opus-4":"claude-haiku-4-5","claude-sonnet-4":"claude-haiku-4-5","claude-3-5-sonnet":"claude-3-5-haiku"};function Am(t){return Object.keys(t).sort((e,n)=>n.length-e.length||e.localeCompare(n))}function Yu(t,e=bs){
|
|
916
|
+
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){for(let n of Am(e))if(t.startsWith(n)&&t.charAt(
|
|
917
|
+
n.length)==="-"&&/^\d{4}/.test(t.slice(n.length+1)))return e[n]}var Yr=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(
|
|
918
|
+
e)}decidir(e,n){let r=this.estados.get(e),o=Mm(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\
|
|
878
919
|
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}\
|
|
879
920
|
); 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(
|
|
880
921
|
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)}\
|
|
881
922
|
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,
|
|
882
|
-
n&&(r.escaladas+=1),this.estados.set(e,r);}};function
|
|
883
|
-
for(let r of
|
|
923
|
+
n&&(r.escaladas+=1),this.estados.set(e,r);}};function Mm(t){return !t||t.enrutadas<=0?null:t.escaladas/t.enrutadas}var Lm=["enum","pattern","maximum","minimum","maxLength","minLength","maxItems","minItems"];function $m(t){return t?vs(t)?"value-constrained":"structural":"none"}function vs(t,e=0){if(e>12)return false;let n=t;
|
|
924
|
+
for(let r of Lm)if(n[r]!==void 0)return true;if(t.properties){for(let r of Object.values(t.properties))if(vs(r,e+1))return true}return !!(t.items&&vs(t.items,e+1))}function Qu(t){let e=$m(t.schema),n=(t.tools??
|
|
884
925
|
[]).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\
|
|
885
926
|
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\
|
|
886
927
|
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 \
|
|
887
|
-
content has somewhere to fall":"output contract checks shape only: a well-formed answer with wrong content passes"}}function
|
|
928
|
+
content has somewhere to fall":"output contract checks shape only: a well-formed answer with wrong content passes"}}function ys(t){let e=[];if(e.push("non-empty"),t.texto.trim()==="")return {acepta:false,
|
|
888
929
|
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 \
|
|
889
930
|
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\
|
|
890
931
|
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,
|
|
891
|
-
motivo:"the cheap model's answer is not valid JSON",comprobaciones:e}}let r=
|
|
892
|
-
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
|
|
893
|
-
JSON.parse(t),r=JSON.parse(e);}catch{return {divergen:false,motivo:"not comparable (at least one answer is not JSON)"}}let o=
|
|
894
|
-
le facts (free prose only)"}:
|
|
895
|
-
of a false valid \u2014 it is a reason to look, never a verdict"}}var
|
|
896
|
-
an")n.push(`b:${t}`);else if(typeof t=="string"){let r=t.trim();r.length>0&&r.length<=
|
|
897
|
-
t")for(let r of Object.keys(t).sort())
|
|
898
|
-
, because a number nobody can check is not a number at all but a promise, and this product exists to stop making those. ";function
|
|
899
|
-
0,t)}function
|
|
900
|
-
"object":t.items?"array":void 0)){case "string":return t.maxLength!=null?{valor:
|
|
901
|
-
{valor:Math.trunc(t.maximum)}:void 0;case "number":return;case "array":{if(t.maxItems==null||!t.items)return;let n=
|
|
902
|
-
ject":{if(t.additionalProperties!==false||!t.properties)return;let n={};for(let[r,o]of Object.entries(t.properties)){let i=
|
|
903
|
-
t);return e?JSON.stringify(e.valor):null}function
|
|
904
|
-
let o=r.minimumSavingsTokens??
|
|
932
|
+
motivo:"the cheap model's answer is not valid JSON",comprobaciones:e}}let r=he(n,t.schema);return r.valid?{acepta:true,motivo:"the cheap model's answer satisfies the output contract",comprobaciones:e}:{
|
|
933
|
+
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 Xu(t,e){let n,r;try{n=
|
|
934
|
+
JSON.parse(t),r=JSON.parse(e);}catch{return {divergen:false,motivo:"not comparable (at least one answer is not JSON)"}}let o=Qr(n),i=Qr(r);return o.length===0&&i.length===0?{divergen:false,motivo:"no comparab\
|
|
935
|
+
le facts (free prose only)"}:Nm(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 \
|
|
936
|
+
of a false valid \u2014 it is a reason to look, never a verdict"}}var jm=40;function Qr(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\
|
|
937
|
+
an")n.push(`b:${t}`);else if(typeof t=="string"){let r=t.trim();r.length>0&&r.length<=jm&&n.push(`s:${r.toLowerCase()}`);}else if(Array.isArray(t))for(let r of t)Qr(r,e+1,n);else if(t&&typeof t=="objec\
|
|
938
|
+
t")for(let r of Object.keys(t).sort())Qr(t[r],e+1,n);return n.sort()}function Nm(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 el="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\
|
|
939
|
+
, because a number nobody can check is not a number at all but a promise, and this product exists to stop making those. ";function Bm(t){if(t<=0)return "";let e=el;for(;e.length<t;)e+=el;return e.slice(
|
|
940
|
+
0,t)}function Fm(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 ks(t){if(t.enum&&t.enum.length>0)return {valor:Fm(t.enum)};switch(t.type??(t.properties?
|
|
941
|
+
"object":t.items?"array":void 0)){case "string":return t.maxLength!=null?{valor:Bm(t.maxLength)}:void 0;case "boolean":return {valor:false};case "null":return {valor:null};case "integer":return t.maximum!=null?
|
|
942
|
+
{valor:Math.trunc(t.maximum)}:void 0;case "number":return;case "array":{if(t.maxItems==null||!t.items)return;let n=ks(t.items);return n?{valor:Array.from({length:t.maxItems},()=>n.valor)}:void 0}case "ob\
|
|
943
|
+
ject":{if(t.additionalProperties!==false||!t.properties)return;let n={};for(let[r,o]of Object.entries(t.properties)){let i=ks(o);if(!i)return;n[r]=i.valor;}return {valor:n}}default:return}}function qm(t){let e=ks(
|
|
944
|
+
t);return e?JSON.stringify(e.valor):null}function tl(t,e){let n=qm(t);return n===null?null:e(n)}var Xr=16,nl=64,zm=8,Vm="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 rl(t,e,n,r={}){
|
|
945
|
+
let o=r.minimumSavingsTokens??zm,i;try{if(Ss(t,0))return {applied:!1,reason:"schema has a pattern; no witness can be synthesised to prove the round trip"};i=Cs(t,0);}catch(w){return {applied:false,reason:w instanceof
|
|
905
946
|
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;
|
|
906
|
-
if(!s)return {applied:false,reason:"nothing to compact"};let a=
|
|
907
|
-
i.compact)),h=d-p,m=Number.POSITIVE_INFINITY;for(let
|
|
947
|
+
if(!s)return {applied:false,reason:"nothing to compact"};let a=w=>Kt(w,s,true),c=w=>Kt(w,s,false),u=Gm(t),l=Um(t,i.compact,s,u);if(!l.ok)return {applied:false,reason:l.reason};let d=e(JSON.stringify(t)),p=e(JSON.stringify(
|
|
948
|
+
i.compact)),h=d-p,m=Number.POSITIVE_INFINITY;for(let w of u){let S=e(JSON.stringify(w))-e(JSON.stringify(a(w)));S<m&&(m=S);}Number.isFinite(m)||(m=0);let g=w=>w/1e3*n.inputPer1k,f=w=>w/1e3*n.outputPer1k,
|
|
908
949
|
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.
|
|
909
950
|
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\
|
|
910
|
-
e model, not of the schema: ${
|
|
911
|
-
chmarks/ab-live.ts) and pass it in`};let
|
|
912
|
-
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 P=g(h)+f(
|
|
913
|
-
n.inputPer1k:h,
|
|
914
|
-
ut tokens ($${v.toFixed(9)}): the compact contract saves ${h} input tokens and the measured output delta is ${
|
|
915
|
-
1)} input tokens equivalent): the compact contract saves ${h} input tokens and the measured output delta is ${
|
|
916
|
-
codedEnumValues:i.coded,schemaTokensOriginal:d,schemaTokensCompact:p,modelledShapeSavingTokens:m,measuredOutputDeltaTokens:
|
|
917
|
-
function
|
|
918
|
-
ok:false,reason:"compact witness does not validate against the compact schema"};if(!
|
|
919
|
-
ject"||t.type==null&&t.properties!=null}function
|
|
920
|
-
ng")?null:e}function
|
|
951
|
+
e model, not of the schema: ${Vm}. 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\
|
|
952
|
+
chmarks/ab-live.ts) and pass it in`};let x=T.deltaTokens;if(x<0)return {applied:false,reason:`the measured output delta is ${x} tokens: this model writes MORE from a compact contract (${T.procedencia}). T\
|
|
953
|
+
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 P=g(h)+f(x),M=n.inputPer1k>0?P*1e3/
|
|
954
|
+
n.inputPer1k:h,A=`+${x} tokens (${x>0?"the model wrote LESS":"no measured change"}), ${T.procedencia}`;return P<v?{applied:false,reason:`net saving $${P.toFixed(9)}/request is below the floor of ${o} inp\
|
|
955
|
+
ut tokens ($${v.toFixed(9)}): the compact contract saves ${h} input tokens and the measured output delta is ${A}; break-even at ${y}`}:{applied:true,reason:`net saving $${P.toFixed(9)}/request (${M.toFixed(
|
|
956
|
+
1)} input tokens equivalent): the compact contract saves ${h} input tokens and the measured output delta is ${A}; break-even at ${y}`,plan:{compactSchema:i.compact,expand:c,compact:a,renamedKeys:i.renamed,
|
|
957
|
+
codedEnumValues:i.coded,schemaTokensOriginal:d,schemaTokensCompact:p,modelledShapeSavingTokens:m,measuredOutputDeltaTokens:x,outputDeltaProvenance:T.procedencia,breakEvenOutputDeltaTokens:b,netSavingUsd:P}}}
|
|
958
|
+
function Um(t,e,n,r){for(let o of r){if(!he(o,t).valid)return {ok:false,reason:"synthesised witness does not satisfy the caller's own schema; nothing can be proven"};let i=Kt(o,n,true);if(!he(i,e).valid)return {
|
|
959
|
+
ok:false,reason:"compact witness does not validate against the compact schema"};if(!Ts(Kt(i,n,false),o))return {ok:false,reason:"round trip is not the identity"}}return {ok:true}}function ol(t){return t.type==="ob\
|
|
960
|
+
ject"||t.type==null&&t.properties!=null}function il(t){return t.type==="array"||t.type==null&&t.items!=null}function Hm(t){let e=t.enum;return !e||e.length===0||e.length>nl||!e.every(n=>typeof n=="stri\
|
|
961
|
+
ng")?null:e}function Cs(t,e){if(e>Xr)throw new RangeError("schema too deep");let n=Hm(t);if(n){if(t.minLength!=null)return {compact:t,renamed:0,coded:0};let r=sl(n,true);if(!r)return {compact:t,renamed:0,
|
|
921
962
|
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,
|
|
922
|
-
enumBack:i},renamed:0,coded:o}}return
|
|
923
|
-
let r=0,o=0,i=new Map,s=new Map;for(let[p,h]of n){let m=
|
|
963
|
+
enumBack:i},renamed:0,coded:o}}return ol(t)?Wm(t,e):il(t)?Jm(t,e):{compact:t,renamed:0,coded:0}}function Wm(t,e){let n=Object.entries(t.properties??{});if(n.length===0)return {compact:t,renamed:0,coded:0};
|
|
964
|
+
let r=0,o=0,i=new Map,s=new Map;for(let[p,h]of n){let m=Cs(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=sl(n.map(([p])=>p),false));
|
|
924
965
|
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[
|
|
925
|
-
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
|
|
926
|
-
if(!t.items)return {compact:t,renamed:0,coded:0};let n=
|
|
966
|
+
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 Jm(t,e){
|
|
967
|
+
if(!t.items)return {compact:t,renamed:0,coded:0};let n=Cs(t.items,e+1);return {compact:{...t,items:n.compact},...n.node?{node:{items:n.node}}:{},renamed:n.renamed,coded:n.coded}}function sl(t,e){let n=[
|
|
927
968
|
...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&&
|
|
928
|
-
!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
|
|
929
|
-
t;if(e.items&&Array.isArray(t))return t.map(i=>
|
|
930
|
-
u);i[c]=l?
|
|
931
|
-
r,0));return n}function
|
|
932
|
-
if(n>
|
|
933
|
-
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?
|
|
969
|
+
!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 Kt(t,e,n){let r=n?e.enumFwd:e.enumBack;if(r&&typeof t=="string")return r.get(t)??
|
|
970
|
+
t;if(e.items&&Array.isArray(t))return t.map(i=>Kt(i,e.items,n));let o=n?e.keysFwd:e.keysBack;if((o||e.props)&&Km(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(
|
|
971
|
+
u);i[c]=l?Kt(a,l,n):a;}return i}return t}function Km(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Gm(t){let e=Math.min(nl,Math.max(1,xs(t,0))),n=[];for(let r=0;r<e;r++)n.push(ws(t,
|
|
972
|
+
r,0));return n}function xs(t,e){if(e>Xr)return 0;let n=t.enum?.length??0;for(let r of Object.values(t.properties??{}))n=Math.max(n,xs(r,e+1));return t.items&&(n=Math.max(n,xs(t.items,e+1))),n}function ws(t,e,n){
|
|
973
|
+
if(n>Xr)return null;if(t.enum&&t.enum.length>0)return t.enum[Math.min(e,t.enum.length-1)];if(ol(t)){let r={};for(let[o,i]of Object.entries(t.properties??{}))r[o]=ws(i,e,n+1);return r}if(il(t)){if(t.maxItems===
|
|
974
|
+
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?ws(i,e,n+1):null)}switch(t.type){case "string":{if(t.maxLength===0)return "";
|
|
934
975
|
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===
|
|
935
|
-
"integer"?Math.round(r):r}case "boolean":return true;case "null":return null;default:return null}}function
|
|
936
|
-
values(t.properties??{}))if(
|
|
937
|
-
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(!
|
|
938
|
-
return false;for(let s of o)if(!Object.prototype.hasOwnProperty.call(e,s)||!
|
|
939
|
-
enums)",pares:8}},
|
|
976
|
+
"integer"?Math.round(r):r}case "boolean":return true;case "null":return null;default:return null}}function Ss(t,e){if(e>Xr)throw new RangeError("schema too deep");if(t.pattern!=null)return true;for(let n of Object.
|
|
977
|
+
values(t.properties??{}))if(Ss(n,e+1))return true;return !!(t.items&&Ss(t.items,e+1))}function Ts(t,e){if(t===e)return true;if(t===null||e===null||typeof t!="object"||typeof e!="object")return false;let n=Array.
|
|
978
|
+
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(!Ts(t[s],e[s]))return false;return true}let o=Object.keys(t),i=Object.keys(e);if(o.length!==i.length)
|
|
979
|
+
return false;for(let s of o)if(!Object.prototype.hasOwnProperty.call(e,s)||!Ts(t[s],e[s]))return false;return true}var Zm="2026-08-14",al={"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 \
|
|
980
|
+
enums)",pares:8}},Ym=Ro(al);function Qm(t){return Po(al,Ym,t)}var eo=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&&
|
|
940
981
|
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,
|
|
941
|
-
origen:"remembered",procedencia:`measured by the caller on an earlier request for this contract on ${e}`};let i=
|
|
942
|
-
Velio on ${e} (${
|
|
943
|
-
r=
|
|
944
|
-
n)}:${
|
|
945
|
-
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=
|
|
982
|
+
origen:"remembered",procedencia:`measured by the caller on an earlier request for this contract on ${e}`};let i=Qm(e);return i?{deltaTokens:i.deltaTokens,origen:"catalogue",procedencia:`measured by Bi\
|
|
983
|
+
Velio on ${e} (${Zm}, ${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.]",Xm=new TextEncoder;function eh(t){return Xm.encode(t).length}function th(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;
|
|
984
|
+
r=Es(o);}catch{r=n;}return `${t} ${r}`}function Es(t){return t===null||typeof t!="object"?JSON.stringify(t)??"null":Array.isArray(t)?`[${t.map(Es).join(",")}]`:`{${Object.keys(t).sort().map(n=>`${JSON.stringify(
|
|
985
|
+
n)}:${Es(t[n])}`).join(",")}}`}function cl(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=[],
|
|
986
|
+
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=th(d,p);h!==null&&
|
|
946
987
|
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.
|
|
947
|
-
get(u);if(l===void 0||s.get(l)===u)continue;let d=
|
|
948
|
-
(r,o)=>n.has(o)?{...r,content:
|
|
949
|
-
o==="google"||o==="google-vertex"?
|
|
988
|
+
get(u);if(l===void 0||s.get(l)===u)continue;let d=eh(t[u].content);d<1024||(a.push(u),c+=d);}return {indices:a,bytesOriginales:c}}function ul(t,e){if(e.length===0)return t;let n=new Set(e);return t.map(
|
|
989
|
+
(r,o)=>n.has(o)?{...r,content:Ps}:r)}function to(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"?is:o==="anthropic"?ss(i):
|
|
990
|
+
o==="google"||o==="google-vertex"?as:/^(gpt-|o[1-9](-|$)|chatgpt)/.test(i)?is:i.startsWith("claude")?ss(i):i.startsWith("gemini")?as:Fu}function ll(t){let e=t.prefix!=null,n=cs({originalTokens:t.originalTokens,
|
|
950
991
|
compressedTokens:t.compressedTokens,stablePrefixTokens:t.prefix?.stableTokens??0,prefixHitRate:t.prefix?.hitRate??0,tier:t.tier,...t.compressorCostTokens!=null?{compressorCostTokens:t.compressorCostTokens}:
|
|
951
992
|
{}});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.
|
|
952
|
-
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
|
|
993
|
+
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 pl(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),
|
|
953
994
|
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\
|
|
954
995
|
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\
|
|
955
996
|
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,
|
|
956
|
-
costeDeDosLlamadas:i,ganancia:s,perdidaSiDegrada:a,razon:u}}function
|
|
957
|
-
0,
|
|
958
|
-
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
|
|
959
|
-
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
|
|
960
|
-
"number"&&Number.isInteger(t)&&t>=0;function
|
|
961
|
-
return "simulated-provider";if(t.origen==="no-oficial")return "unofficial-origin";let e=t.usoPrimario;if(!e||e.complete===false||!
|
|
962
|
-
usoReparacion;if(n&&(n.complete===false||!
|
|
963
|
-
layer-changed-request";if(t.codebookAplicado)return "codebook";if(t.tokensDelSondeo!==0||t.sondeoAplicado)return "tool-discovery";if(t.busquedaNativa===true)return "native-tool-
|
|
964
|
-
esquemaNativo||t.esquemaPorPrompt))return "schema-in-prompt";if(t.hayEsquema&&!t.esquemaEnFormatoNativo)return "schema-not-verbatim";if(t.hayEsquema&&!t.esquemaEstricto)return "
|
|
965
|
-
t.modeloPedido)return "cheaper-model-served";if(!t.cacheable)return "not-cacheable";let r=
|
|
966
|
-
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?
|
|
967
|
-
max(0,t.mensajesDeLaCapa)+Math.max(0,t.piezasDelAdaptador)+(t.hayEsquema?1:0),...i!==void 0?{reasoningTokens:i}:{},requestFingerprint:t.huella(),textSha256:
|
|
968
|
-
|
|
969
|
-
o=n.reasoningTokens;return n.v===2&&typeof n.inputTokens=="number"&&Number.isInteger(n.inputTokens)&&n.inputTokens>0&&
|
|
970
|
-
"number"&&r>0&&r<1)&&
|
|
971
|
-
inputTokens,outputTokens:n.outputTokens,...r!==void 0?{tierFactor:r}:{},layerInsertions:n.layerInsertions,...o!==void 0?{reasoningTokens:o}:{},requestFingerprint:n.
|
|
972
|
-
|
|
973
|
-
return "reasoning-not-reported";if(t.reasoningTokens!==0)return "reasoning-reported"}function
|
|
974
|
-
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.
|
|
975
|
-
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,
|
|
976
|
-
|
|
977
|
-
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.
|
|
978
|
-
a=
|
|
979
|
-
at,inputTokens:t.inputTokens,outputTokens:t.outputTokens,creditedInputTokens:i,creditedOutputTokens:c,cachedInputPer1k:o,outputPer1k:r.outputPer1k,tierFactor:u}}}var
|
|
997
|
+
costeDeDosLlamadas:i,ganancia:s,perdidaSiDegrada:a,razon:u}}function fl(t){let n=(t.description??(Array.isArray(t.intents)?t.intents.join("; "):"")).trim().split(/\r?\n/,1)[0]??"",r=n.length>dl?n.slice(
|
|
998
|
+
0,dl-1).trimEnd()+"\u2026":n;return {id:t.id,intents:t.intents,risk:t.risk,...r?{description:r}:{}}}var dl=200;function ml(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.
|
|
999
|
+
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 hl(t,e){
|
|
1000
|
+
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 rh=2;function Rs(t){return ne(ve({messages:t.messages,structuredData:t.structuredData??null,tools:t.tools??[],schema:t.response?.schema??null}))}function gl(t){return t.temperature===0}
|
|
1001
|
+
var ut=t=>typeof t=="number"&&Number.isInteger(t)&&t>=0;function oh(t,e){if(ut(t.reasoningTokens)){if(!e)return t.reasoningTokens;if(ut(e.reasoningTokens))return t.reasoningTokens+e.reasoningTokens}}function bl(t){
|
|
1002
|
+
if(t.contadorSimulado)return "simulated-provider";if(t.origen==="no-oficial")return "unofficial-origin";let e=t.usoPrimario;if(!e||e.complete===false||!ut(e.inputTokens)||e.inputTokens<=0||!ut(e.outputTokens))
|
|
1003
|
+
return "no-usage";let n=t.usoReparacion;if(n&&(n.complete===false||!ut(n.outputTokens)))return "no-usage";if(t.eliminatedInput!==0||t.compressedInput!==0||t.elididoLocal!==0||Math.abs(t.sentLocalSinSondeo-
|
|
1004
|
+
t.baselineInput)>rh)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\
|
|
1005
|
+
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 "\
|
|
1006
|
+
schema-not-strict";if(t.modeloServido!==t.modeloPedido)return "cheaper-model-served";if(!t.cacheable)return "not-cacheable";let r=di(t.tierServido),o=r?.conDescuento&&r.factor!=null&&r.factor>0&&r.factor<
|
|
1007
|
+
1?r.factor:void 0,i=oh(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?
|
|
1008
|
+
{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:ne(t.
|
|
1009
|
+
textoServido)}}var no=t=>typeof t=="string"&&t.length>0;function vl(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))
|
|
1010
|
+
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&&ut(n.outputTokens)&&typeof n.at=="number"&&
|
|
1011
|
+
Number.isFinite(n.at)&&(r===void 0||typeof r=="number"&&r>0&&r<1)&&ut(n.layerInsertions)&&(o===void 0||ut(o))&&no(n.requestId)&&no(n.model)&&no(n.requestFingerprint)&&no(n.textSha256)?{v:2,requestId:n.
|
|
1012
|
+
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.
|
|
1013
|
+
requestFingerprint,textSha256:n.textSha256,...typeof n.cacheKey=="string"?{cacheKey:n.cacheKey}:{}}:"malformed"}function ih(t,e){if(!e.determinista)return "sampled";if(e.salidaDelModelo!==void 0)return e.
|
|
1014
|
+
salidaDelModelo;if(t.reasoningTokens===void 0)return "reasoning-not-reported";if(t.reasoningTokens!==0)return "reasoning-reported"}function yl(t,e){if(e.textoServidoSha256!==t.textSha256)return {ok:false,reason:"\
|
|
1015
|
+
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.
|
|
1016
|
+
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,
|
|
1017
|
+
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<
|
|
1018
|
+
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.
|
|
1019
|
+
max(0,e.topeDeSalida):Number.POSITIVE_INFINITY,a=ih(t,e),c=a===void 0?Math.floor(.95*Math.min(t.outputTokens,s)):0,u=Math.min(1,t.tierFactor??1,e.diferible?ec:1);return {ok:true,...a!==void 0?{outputNotCredited:a}:
|
|
1020
|
+
{},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 En={done:true,value:void 0},Pn=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){
|
|
980
1021
|
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);},
|
|
981
1022
|
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.
|
|
982
1023
|
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.
|
|
@@ -985,54 +1026,80 @@ terminado)return;let r=e.toolCalls?.length??0,o=this.primerEventoAt??(n.vivo&&r>
|
|
|
985
1026
|
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(){
|
|
986
1027
|
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.
|
|
987
1028
|
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)
|
|
988
|
-
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(
|
|
989
|
-
esperas.splice(0);if(n){n.reject(e);for(let o of r)o.resolve(
|
|
990
|
-
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(
|
|
1029
|
+
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(En);}fallarCola(e){this.cerrada=true;let[n,...r]=this.
|
|
1030
|
+
esperas.splice(0);if(n){n.reject(e);for(let o of r)o.resolve(En);}else this.errorPendiente={valor:e};}siguiente(){if(this.consumidorSalio)return Promise.resolve(En);let e=this.cola.shift();if(e)return Promise.
|
|
1031
|
+
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(En):new Promise((n,r)=>{this.esperas.
|
|
991
1032
|
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(),
|
|
992
|
-
this.consumidorSalio=true,this.cola.length=0,Promise.resolve(
|
|
993
|
-
"fail_open"?"fail_open":"provider"}}function
|
|
994
|
-
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
|
|
995
|
-
hechos,n=
|
|
1033
|
+
this.consumidorSalio=true,this.cola.length=0,Promise.resolve(En))}}};function sh(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===
|
|
1034
|
+
"fail_open"?"fail_open":"provider"}}function ah(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!==
|
|
1035
|
+
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 kl(t){let e=t.
|
|
1036
|
+
hechos,n=sh(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,
|
|
996
1037
|
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\
|
|
997
1038
|
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.
|
|
998
1039
|
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){
|
|
999
1040
|
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.
|
|
1000
|
-
embedder,factGuard:"passed",...i.calibration?{calibration:{...i.calibration}}:{}};}let o=
|
|
1041
|
+
embedder,factGuard:"passed",...i.calibration?{calibration:{...i.calibration}}:{}};}let o=ah(t.cascada);return o&&(r.cascade=o),r}function xl(t){return {source:"coalesced",sharedFrom:t==null?"provider":t.
|
|
1001
1042
|
source==="coalesced"?t.sharedFrom??"provider":t.source,...t?.schema?{schema:{...t.schema}}:{},...t?.repair?{repair:{...t.repair}}:{},...t?.truncation?{truncation:{...t.truncation}}:{},...t?.cacheMatch?
|
|
1002
|
-
{cacheMatch:
|
|
1043
|
+
{cacheMatch:ch(t.cacheMatch)}:{},...t?.cascade?{cascade:{...t.cascade}}:{}}}function ch(t){return t.kind==="semantic"&&t.calibration?{...t,calibration:{...t.calibration}}:{...t}}var uh="i(?:'m| am)? ?(?:"+["can't","cannot","can not","won't","will not","shouldn't","should not","unable to","not able to","not going to","not in a position to","not comfortable","don't feel comfort\
|
|
1044
|
+
able","do not feel comfortable","'d rather not","would rather not","don't think i can","do not think i can"].join("|")+")",lh="(?:help(?! but)|assist|provide|comply|fulfil|fulfill|create|write|generat\
|
|
1045
|
+
e|produce|give|share|support|engage|participate|answer|respond|discuss|offer|continue|draft|facilitate|contribute|go along|go into|walk you through|explain how|describe how|tell you how|teach|instruct\
|
|
1046
|
+
|encourage|condone|endorse|promote|role-?play|pretend|do that|do this|do so|with that|with this|with your request|with this request|that request|this request)",dh="i(?:'ll| will| must| need to|'d| wou\
|
|
1047
|
+
ld)?(?: have to)? ?(?:respectfully |politely )?decline",ph="(?:(?:that|this|it)(?:'s| is) not something i(?:'m| am)? ?(?:can|will|able to|comfortable)|(?:it|that|this)(?:'s| is| would be| would not be\
|
|
1048
|
+
| wouldn't be) (?:not )?(?:appropriate|ethical|responsible) for me to|i(?:'m| am) not sure (?:that )?it(?:'s| is| would be) appropriate)",fh="(?:(?:i'm |i am |i'm really |i am really |i'm so |really |\
|
|
1049
|
+
so )?sorry|i apologi[sz]e|my apologies|apologies|unfortunately|regrettably|i'm afraid|i am afraid|as an ai|as a language model|as an assistant|i understand|i appreciate|thank you for|thanks for|while \
|
|
1050
|
+
i understand|while i appreciate)",j="\\p{L}*",mh="no (?:puedo|voy a|me es posible|estoy en condiciones de|me siento c\xF3mod[oa])",hh=`(?:ayudar${j}|asistir${j}|proporcionar${j}|facilitar${j}|dar${j}|\
|
|
1051
|
+
ofrecer${j}|crear${j}|escribir${j}|generar${j}|compartir${j}|cumplir|responder${j}|colaborar|participar|atender${j}|hacer eso|hacerlo|con eso|con esto|con esa|con esta|con tu)`,gh="(?:lo siento|lo lam\
|
|
1052
|
+
ento|siento|lamento|disculpa|disculpe|perd\xF3n|perdona|lamentablemente|desafortunadamente|me temo que|como (?:una )?(?:ia|inteligencia artificial|modelo de lenguaje|asistente)|entiendo)",bh="no (?:pu\
|
|
1053
|
+
c|et puc|us puc|em sento c\xF2mod[ea]|estic en condicions de)",vh=`(?:ajudar${j}|assistir${j}|proporcionar${j}|facilitar${j}|donar${j}|oferir${j}|crear${j}|escriure${j}|generar${j}|compartir${j}|compl\
|
|
1054
|
+
ir|respondre${j}|col\xB7laborar|participar|fer aix\xF2|fer-ho|amb aix\xF2|amb aquesta|amb la teva)`,yh="(?:ho sento|ho lamento|em sap greu|disculpa|disculpeu|perdona|malauradament|lamentablement|disso\
|
|
1055
|
+
rtadament|com a (?:ia|intel\xB7lig\xE8ncia artificial|model de llenguatge|assistent)|entenc)",kh="(?:je ne (?:peux|pourrai|pourrais|vais|souhaite)(?: malheureusement)? pas|je ne suis pas en mesure d[e\
|
|
1056
|
+
']|je refuse d[e'])",xh="(?:aider|assister|fournir|r\xE9pondre|cr\xE9er|\xE9crire|g\xE9n\xE9rer|partager|donner|proposer|participer|expliquer comment|acc\xE9der \xE0|satisfaire|faire cela|faire \xE7a|le faire)",
|
|
1057
|
+
wh="(?:d\xE9sol\xE9e?|je suis d\xE9sol\xE9e?|je regrette|malheureusement|h\xE9las|je comprends|en tant qu'(?:ia|intelligence artificielle|mod\xE8le de langage|assistant))",Sh="(?:ich (?:kann|werde|dar\
|
|
1058
|
+
f|m\xF6chte)|(?:kann|werde|darf|m\xF6chte) ich)(?: \\p{L}+){0,4}? (?:nicht|keine\\p{L}*)(?: \\p{L}+){0,3}?",Th="(?:helfen|unterst\xFCtzen|bereitstellen|geben|erstellen|schreiben|generieren|beantworten|li\
|
|
1059
|
+
efern|nachkommen|teilen|anbieten|erkl\xE4ren|behilflich sein)",Ch="(?:es tut mir leid|tut mir leid|entschuldigung|entschuldige|leider|bedauerlicherweise|ich verstehe|als (?:eine )?(?:ki|k\xFCnstliche int\
|
|
1060
|
+
elligenz|sprachmodell|assistent))",Eh="non (?:posso|sono in grado di|riesco a|mi sento a mio agio (?:a|nel))",Ph=`(?:aiutar${j}|assister${j}|fornir${j}|crear${j}|scriver${j}|generar${j}|condivider${j}\
|
|
1061
|
+
|risponder${j}|dar${j}|offrir${j}|soddisfare|partecipare|farlo|fare questo|con questo|con questa)`,Rh="(?:mi dispiace|spiacente|purtroppo|sfortunatamente|capisco|come (?:un'?\\s?)?(?:ia|intelligenza ar\
|
|
1062
|
+
tificiale|modello linguistico|assistente))",Dh="n\xE3o (?:posso|consigo|vou|sou capaz de|estou em condi\xE7\xF5es de|me sinto confort\xE1vel (?:em|a))",_h=`(?:ajudar${j}|auxiliar${j}|assistir${j}|forn\
|
|
1063
|
+
ecer${j}|criar${j}|escrever${j}|gerar${j}|compartilhar${j}|partilhar${j}|dar${j}|oferecer${j}|responder${j}|atender${j}|cumprir|participar|fazer isso|com isso|com esse|com essa)`,Ih="(?:desculpe|descu\
|
|
1064
|
+
lpa|sinto muito|lamento|infelizmente|entendo|compreendo|como (?:uma? )?(?:ia|intelig\xEAncia artificial|modelo de linguagem|assistente))",Gt="(?:[\\s,]+[\\p{L}'\u2019-]+){0,4}?[\\s,]+",Sl=[`${uh}${Gt}${lh}`,
|
|
1065
|
+
dh,ph,`${mh}${Gt}${hh}`,"lamento no poder",`${bh}${Gt}${vh}`,`${kh}${Gt}${xh}`,`${Sh} ${Th}`,`${Eh}${Gt}${Ph}`,`${Dh}${Gt}${_h}`].join("|"),Ah=[fh,gh,yh,wh,Ch,Rh,Ih].join("|"),Oh=new RegExp(`^(?:${Sl}\
|
|
1066
|
+
)(?![\\p{L}])`,"u"),Mh=new RegExp(`^(?:${Ah})(?![\\p{L}])`,"u"),wl=new RegExp(`(?:^|[^\\p{L}'])(?:${Sl})(?![\\p{L}])`,"u");function Lh(t){return t.slice(0,4*300).replace(/[‘’ʼ`´]/g,"'").toLowerCase().
|
|
1067
|
+
replace(/\s+/g," ").trim().replace(/^[\s*#>_"'«“¿¡(\[-]+/u,"").trim()}function $h(t){let e=[...t.matchAll(/[.!?。](?:\s|$)/g)],n=e.length>=2?e[1].index+1:t.length;return t.slice(0,Math.min(n,240))}
|
|
1068
|
+
function ro(t){if(typeof t!="string"||t==="")return null;let e=Lh(t);if(e==="")return null;let n=$h(e);return Oh.test(n)?"opens-with-refusal":Mh.test(n)&&wl.test(n)?"apology-then-refusal":e.length<=300&&
|
|
1069
|
+
wl.test(e)?"short-refusal":null}function oo(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,
|
|
1003
1070
|
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==
|
|
1004
|
-
"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
|
|
1005
|
-
n=Math.round(e*100)/100;return n===0?"<0.01%":Number.isInteger(n)?`${n}%`:`${n.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}%`}function
|
|
1071
|
+
"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 jh(t){let e=t*100,
|
|
1072
|
+
n=Math.round(e*100)/100;return n===0?"<0.01%":Number.isInteger(n)?`${n}%`:`${n.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}%`}function Tl(t){let e=jh(t);return `[bvsala] Verification sampling is ON \
|
|
1006
1073
|
(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\
|
|
1007
1074
|
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\
|
|
1008
|
-
your statement or any commission.`}function
|
|
1009
|
-
\` must be a number from 0 to 1 and \`verification.maxCheckCostUsd\`, when set, a positive number (got sampleRate ${e}); verification sampling is OFF.`}var
|
|
1075
|
+
your statement or any commission.`}function Cl(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\
|
|
1076
|
+
\` must be a number from 0 to 1 and \`verification.maxCheckCostUsd\`, when set, a positive number (got sampleRate ${e}); verification sampling is OFF.`}var El="[bvsala] Verification sampling is set, b\
|
|
1010
1077
|
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\
|
|
1011
|
-
g/usage` \u2014 or pass `verification.onCheck` to receive them yourself. No request will be sent twice until then.",
|
|
1012
|
-
request was not affected.";function
|
|
1013
|
-
{tools:[...t.tools]}:{},...t.response?.schema?{schema:t.response.schema}:{},...t
|
|
1014
|
-
|
|
1078
|
+
g/usage` \u2014 or pass `verification.onCheck` to receive them yourself. No request will be sent twice until then.",Pl="[bvsala] verification sampling hit an internal error and skipped a request; your\
|
|
1079
|
+
request was not affected.";function Rl(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?
|
|
1080
|
+
{tools:[...t.tools]}:{},...t.response?.schema?{schema:t.response.schema}:{},...J(t)!=null?{maxOutputTokens:J(t)}:{},...t.temperature!==void 0?{temperature:t.temperature}:{},...t.seed!==void 0?{seed:t.
|
|
1081
|
+
seed}:{}}}function Dl(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==="\
|
|
1015
1082
|
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===
|
|
1016
1083
|
"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>
|
|
1017
1084
|
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?
|
|
1018
|
-
{estrato:"tokens_compressed"}:{estrato:"unchanged"}}function
|
|
1019
|
-
i*1e10)/1e10}var
|
|
1085
|
+
{estrato:"tokens_compressed"}:{estrato:"unchanged"}}function _l(t,e){if(!(e>0))return false;if(e>=1)return true;let n=ne(`${t}:verification-sample`);return Number.parseInt(n.slice(0,13),16)/2**52<e}function Il(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(
|
|
1086
|
+
i*1e10)/1e10}var Nh=32,Bh=6e5;function Fh(t){return new Date(t).toISOString().slice(0,10)}var io=class{tasa;tope;onCheck;waitUntil;provider;precio;contrato;now;sumidero;avisar;enVuelo=new Set;cerrado=false;constructor(e){
|
|
1020
1087
|
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,
|
|
1021
|
-
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=
|
|
1022
|
-
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:
|
|
1023
|
-
e),precios:l,estrato:s.estrato};}let c=this.now();this.sumidero.contar?.(
|
|
1024
|
-
excluida};return {...n,report:{...o,verification:u}}}catch{return this.avisar("verificacion-fallo-interno",
|
|
1088
|
+
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=_l(o.requestId,this.tasa),s=Dl({request:e,result:n,
|
|
1089
|
+
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:Rl(
|
|
1090
|
+
e),precios:l,estrato:s.estrato};}let c=this.now();this.sumidero.contar?.(Fh(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.
|
|
1091
|
+
excluida};return {...n,report:{...o,verification:u}}}catch{return this.avisar("verificacion-fallo-interno",Pl),n}}cerrar(){this.cerrado=true;let e=[...this.enVuelo];this.enVuelo.clear();for(let n of e)if(!n.
|
|
1025
1092
|
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.
|
|
1026
1093
|
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??
|
|
1027
|
-
0,outputTokens:i.tokens.actualOutput},prices:{inputPer1k:s.inputPer1k,...s.cachedInputPer1k!==void 0?{cachedInputPer1k:s.cachedInputPer1k}:{},outputPer1k:s.outputPer1k}};if(this.enVuelo.size>=
|
|
1094
|
+
0,outputTokens:i.tokens.actualOutput},prices:{inputPer1k:s.inputPer1k,...s.cachedInputPer1k!==void 0?{cachedInputPer1k:s.cachedInputPer1k}:{},outputPer1k:s.outputPer1k}};if(this.enVuelo.size>=Nh){this.
|
|
1028
1095
|
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(()=>{
|
|
1029
|
-
try{l.abortar.abort();}catch{}this.resolverVuelo(l,{...a,outcome:"check_failed"});},
|
|
1096
|
+
try{l.abortar.abort();}catch{}this.resolverVuelo(l,{...a,outcome:"check_failed"});},Bh),l.reloj.unref?.(),setTimeout(()=>{if(l.decidido)return;let d;try{d=Promise.resolve(this.provider.generate(o.peticion,
|
|
1030
1097
|
{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(
|
|
1031
1098
|
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??
|
|
1032
1099
|
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==
|
|
1033
|
-
"string"?/^[a-z_]{1,32}$/.test(d)?d:"other":void 0;return {...e,outcome:"paired",naive:{cost:
|
|
1100
|
+
"string"?/^[a-z_]{1,32}$/.test(d)?d:"other":void 0;return {...e,outcome:"paired",naive:{cost:Il({inputTokens:s,outputTokens:a,cachedInputTokens:l},o),inputTokens:s,cachedInputTokens:l,outputTokens:a,...p!==
|
|
1034
1101
|
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.
|
|
1035
|
-
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
|
|
1102
|
+
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 Ds=true,Bl=new WeakSet;function qh(t){typeof t=="object"&&t!==null&&Bl.add(t);}function Ml(t){return typeof t=="object"&&t!==null&&Bl.has(t)}function Ll(t,e){switch(t){case "none":return zh();case "inv\
|
|
1036
1103
|
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\
|
|
1037
1104
|
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 \
|
|
1038
1105
|
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\
|
|
@@ -1040,71 +1107,72 @@ status: invalid)":"BiVelio license key is not valid (it does not verify). Check
|
|
|
1040
1107
|
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\
|
|
1041
1108
|
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\
|
|
1042
1109
|
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\
|
|
1043
|
-
license is not active. See https://savings.bivelio.com/dashboard/account${t?` (license status: ${t})`:""}`}}function
|
|
1110
|
+
license is not active. See https://savings.bivelio.com/dashboard/account${t?` (license status: ${t})`:""}`}}function zh(){return "BiVelio license required: none was configured. Pass { licenseKey } \u2014 t\
|
|
1044
1111
|
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\
|
|
1045
|
-
cense status: none)"}function
|
|
1046
|
-
path at all \u2014 pass { licenseKey } instead, from https://savings.bivelio.com/dashboard/install (license status: invalid)"}var
|
|
1047
|
-
this.config=e,e.silenceWarnings===true&&
|
|
1048
|
-
verjaDeCascada=new
|
|
1049
|
-
precio:o=>this.precioConocido(o),contrato:(o,i)=>
|
|
1050
|
-
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.
|
|
1051
|
-
generateOptimized(e,n);}catch(o){if(o instanceof
|
|
1052
|
-
return this.conVerificacion(e,r,"optimizado")}generateStream(e,n={},r){let o;try{o=new
|
|
1053
|
-
r),o.handle}async ejecutarStream(e,n,r){try{if(r&&await r,n.abortado)throw new
|
|
1054
|
-
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
|
|
1055
|
-
a instanceof
|
|
1056
|
-
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){
|
|
1057
|
-
o);}}conPalancasPorDefecto(e){let n=this.config.priceLevers
|
|
1058
|
-
...r??{},...o?{deferrable:true}:{},...i?{standalone:true}:{}}}}motivoDeEntregaEntera(e){return e.
|
|
1059
|
-
generateStream!="function"?"provider-without-streaming":null}async llamarProveedor(e,n){n.llamadas+=
|
|
1060
|
-
usage.complete===false&&(n.sinContador+=1),r}async llamarProveedorEnStream(e,n,r){if(r.senal.aborted)
|
|
1061
|
-
e,{signal:r.senal})){if(r.senal.aborted)break;if(s.type==="text")s.delta!==""&&(o+=s.delta,
|
|
1062
|
-
falloDelProveedor=true,s)}if(!i)throw r.senal.aborted?new
|
|
1063
|
-
i.usage.complete===false&&(n.sinContador+=1),i.text!==o&&(this.avisar(`stream-texto-distinto:${this.
|
|
1064
|
-
|
|
1065
|
-
i,{...i,text:o})),r.sirvioEnVivo=true,i}decidirMarcadoDeCache(e,n,r,o,i,s,a,c=null){let u=e.savings?.
|
|
1066
|
-
mensajesDePrefijo:0,cacheWriteMultiplier:1,explicita:l,explicitaPorColocador:false,colocacion:null},
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
prefix-cache","skipped",{reason:"savings.toolDiscovery is on: which schemas travel is decided by
|
|
1070
|
-
share a prefix fingerprint. Marking would pay the 1.25x write premium for a prefix that cannot
|
|
1071
|
-
"auto"&&!l){let k=this.colocarConEspejo(e,n,r,o,s,p,a,c);if("marcado"in k)return k.marcado;h=k.
|
|
1072
|
-
m,o.tools),e),f=this.tokensFor(this.assemblePromptText(r,o.tools),e),v=
|
|
1073
|
-
decidir(b,{totalTokens:f,stablePrefixTokens:g,tier:u??p});return a.record("prefix-cache",
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
this.
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
d
|
|
1085
|
-
|
|
1086
|
-
confirmadas}/${k.predichas}`,...T});let
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1112
|
+
cense status: none)"}function Vh(){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 \
|
|
1113
|
+
path at all \u2014 pass { licenseKey } instead, from https://savings.bivelio.com/dashboard/install (license status: invalid)"}var ao=class{deps;config;now;generateId;contratosQueIncumplen;verjaDeCache=new Gr;espejoDeCache=new Jt;verjaDeCascada;memoriaDelCodebook=new eo;referenciasDeLider=new WeakMap;noReproducibles=new WeakSet;negativasSinCobro=new WeakSet;comprobador;constructor(e,n={}){
|
|
1114
|
+
this.config=e,e.silenceWarnings===true&&gc(e.provider),this.deps=ju(e),this.now=e.now??(()=>Date.now()),this.generateId=e.generateId??(()=>rn()),this.contratosQueIncumplen=e.constraintMemory??new Set,this.
|
|
1115
|
+
verjaDeCascada=new Yr(e.modelCascade?.exploration!=null?{exploracion:e.modelCascade.exploration}:{});let r=oo(e.verification);this.comprobador=r.activo&&n.verificacion?new io({ajustes:r,provider:e.provider,
|
|
1116
|
+
precio:o=>this.precioConocido(o),contrato:(o,i)=>Uh(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(
|
|
1117
|
+
e,n,r):n}cerrarVerificacion(){this.comprobador?.cerrar();}async generate(e){this.assertLicensed(),os(e),e=this.conPalancasPorDefecto(e);let n={llamadas:0,falloDelProveedor:false,sinContador:0},r;try{r=await this.
|
|
1118
|
+
generateOptimized(e,n);}catch(o){if(o instanceof nt||this.config.failOpen===false||n.falloDelProveedor||n.llamadas>0||Ml(o))throw o;return this.conVerificacion(e,await this.failOpenDirect(e,o),"fail-open")}
|
|
1119
|
+
return this.conVerificacion(e,r,"optimizado")}generateStream(e,n={},r){let o;try{o=new Pn(this.now,n?.signal);}catch(i){let s=new Pn(this.now);return s.fallar(i),s.handle}return this.ejecutarStream(e,o,
|
|
1120
|
+
r),o.handle}async ejecutarStream(e,n,r){try{if(r&&await r,n.abortado)throw new Se(!1);e=this.conPalancasPorDefecto(e);let o=this.motivoDeEntregaEntera(e);if(o){let a=await this.generate(e);n.completar(
|
|
1121
|
+
a,{vivo:!1,motivo:o});return}this.assertLicensed(),os(e),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
|
|
1122
|
+
nt||a instanceof Se)throw a;if(n.sumidero.senal.aborted)throw new Se(i.llamadas>0);if(this.config.failOpen===!1||i.falloDelProveedor||i.llamadas>0||Ml(a))throw a;let c=this.conVerificacion(e,await this.
|
|
1123
|
+
failOpenDirect(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){
|
|
1124
|
+
n.fallar(o);}}conPalancasPorDefecto(e){let n=this.config.priceLevers,r=e.savings,o=n?.deferrable===true&&r?.deferrable===void 0,i=n?.standalone===true&&r?.standalone===void 0,s=this.config.semanticCacheDefault,
|
|
1125
|
+
a=s!==void 0&&s!==false&&r?.semanticCache===void 0;return !o&&!i&&!a?e:{...e,savings:{...r??{},...o?{deferrable:true}:{},...i?{standalone:true}:{},...a?{semanticCache:s}:{}}}}motivoDeEntregaEntera(e){return e.
|
|
1126
|
+
response?.schema!=null?"output-contract":e.savings?.deferrable===true?"deferrable":typeof this.config.provider.generateStream!="function"?"provider-without-streaming":null}async llamarProveedor(e,n){n.llamadas+=
|
|
1127
|
+
1;let r;try{r=await this.config.provider.generate(e);}catch(o){throw n.falloDelProveedor=true,o}return r.usage.complete===false&&(n.sinContador+=1),r}async llamarProveedorEnStream(e,n,r){if(r.senal.aborted)
|
|
1128
|
+
throw new Se(n.llamadas>0);n.llamadas+=1;let o="",i;try{for await(let s of this.config.provider.generateStream(e,{signal:r.senal})){if(r.senal.aborted)break;if(s.type==="text")s.delta!==""&&(o+=s.delta,
|
|
1129
|
+
r.texto(s.delta));else if(s.type==="done"){i=s.response;break}}}catch(s){throw r.senal.aborted?new Se(true):(n.falloDelProveedor=true,s)}if(!i)throw r.senal.aborted?new Se(true):(n.falloDelProveedor=true,new Error(
|
|
1130
|
+
`provider "${this.config.provider.id}" stream ended without a final response`));return r.proveedorTermino(),i.usage.complete===false&&(n.sinContador+=1),i.text!==o&&(this.avisar(`stream-texto-distinto:${this.
|
|
1131
|
+
config.provider.id}`,`[bvsala] provider "${this.config.provider.id}" streamed text that differs from its final response; the streamed text is what the caller received, so it is what is reported and ca\
|
|
1132
|
+
ched. Its generateStream must end with a done whose response.text equals the concatenated deltas.`),i=pc(i,{...i,text:o})),r.sirvioEnVivo=true,i}decidirMarcadoDeCache(e,n,r,o,i,s,a,c=null){let u=e.savings?.
|
|
1133
|
+
standalone===true&>(n,bt(this.config.provider))?fi(n):null,l=u!==null,d={marcar:false,huella:"",claveDeVerja:"",mensajesDePrefijo:0,cacheWriteMultiplier:1,explicita:l,explicitaPorColocador:false,colocacion:null},
|
|
1134
|
+
p=_s(n,this.config.compressionEconomics);if(!p)return a.record("prefix-cache","skipped",{reason:`no cache read discount for model "${n}" (unrecognised provider, or a declared tier that does not discou\
|
|
1135
|
+
nt reads): not claiming a cacheable prefix`}),d;if(!o.setIsStable)return a.record("prefix-cache","skipped",{reason:"the tool SET is selected per request; tools render first, so the prefix cannot hit. \
|
|
1136
|
+
Pruning wins here (it is a measured saving); pass the tools you want fixed."}),d;if(i)return a.record("prefix-cache","skipped",{reason:"savings.toolDiscovery is on: which schemas travel is decided by \
|
|
1137
|
+
a non-deterministic probe, so the tool block \u2014 which renders first \u2014 varies across requests that would share a prefix fingerprint. Marking would pay the 1.25x write premium for a prefix that cannot hi\
|
|
1138
|
+
t. Turn tool discovery off to reclaim the prefix cache."}),d;let h=null;if(this.config.cacheBreakpoints==="auto"&&!l){let k=this.colocarConEspejo(e,n,r,o,s,p,a,c);if("marcado"in k)return k.marcado;h=k.
|
|
1139
|
+
observacion;}if(s<=0)return {...d,colocacion:h};let m=r.slice(0,s),g=this.tokensFor(this.assemblePromptText(m,o.tools),e),f=this.tokensFor(this.assemblePromptText(r,o.tools),e),v=ne(ve({model:n,tools:(o.
|
|
1140
|
+
tools??[]).map(k=>k.id),prefijo:m.map(k=>`${k.role}:${k.content}`)})),b=l?`${v}|explicit`:v,y=this.verjaDeCache.decidir(b,{totalTokens:f,stablePrefixTokens:g,tier:u??p});return a.record("prefix-cache",
|
|
1141
|
+
y.marcar?"marked":"skipped",{reason:y.razon,stablePrefixTokens:g,breakEvenHitRate:y.umbral,observedHitRate:y.observada,...l?{mode:"explicit"}:{}}),y.marcar?{marcar:true,huella:v,claveDeVerja:b,mensajesDePrefijo:s,
|
|
1142
|
+
cacheWriteMultiplier:p.cacheWriteMultiplier,explicita:l,explicitaPorColocador:false,colocacion:h}:{...d,colocacion:h}}colocarConEspejo(e,n,r,o,i,s,a,c=null){let{tramoOpenAI:u,conPrima:l}=this.primasDelColocador(
|
|
1143
|
+
e,n,s);if(!l&&!u)return {observacion:null};let d=hs(r),p=Math.max(d,Math.min(i,r.length)),h=r.length,m=c?.huellas??this.huellasDelColocador(e,n,r,o.tools),g=m[d],f=c?.clase===g?c:null,v=f?.espejo??this.
|
|
1144
|
+
espejoDeCache,b=this.now(),y=v.observar(g,m,b),k=v.estadistica(g,b),T=f?{mirrorStore:f.estado}:{},x={S:d,...p>d?{H:p}:{},T:h},P=U=>this.tokensFor(this.assemblePromptText(r.slice(0,U),o.tools),e),M={clase:g,
|
|
1145
|
+
huellas:m,tramos:x,coincidencia:y,enviada:b,...f?{conAlmacen:true}:{}};if(u){let U=Ku({estadistica:k,tramo:u,hayHistorial:p>d});a.record("prefix-cache-placement",U.explicita?"explicit":"provider-default",
|
|
1146
|
+
{reason:U.razon,breakEvenReuseRate:U.equilibrio,continuedWithin30m:k.T.en30m,samples:k.T.muestras30m,...T});let ee={...M,cola:!U.explicita,ttl:"5m",ultimo:U.explicita?null:"T",indiceDelUltimo:U.explicita?
|
|
1147
|
+
null:h};if(!U.explicita)return {observacion:ee};let K=U.historial?p:d;if(K<=0)return {marcado:{marcar:false,huella:"",claveDeVerja:"",mensajesDePrefijo:0,cacheWriteMultiplier:1,explicita:true,explicitaPorColocador:true,
|
|
1148
|
+
colocacion:{...ee,ultimo:null,indiceDelUltimo:null}}};let N=K===d?"S":"H",Te=`${g}|explicit|${N}`,Y=this.verjaDeCache.decidir(Te,{totalTokens:P(h),stablePrefixTokens:P(K),tier:u});return a.record("pre\
|
|
1149
|
+
fix-cache",Y.marcar?"marked":"skipped",{reason:Y.razon,breakEvenHitRate:Y.umbral,observedHitRate:Y.observada,mode:"explicit"}),{marcado:{marcar:Y.marcar,huella:Y.marcar?this.huellaDelPrefijo(n,o.tools,
|
|
1150
|
+
r,K):"",claveDeVerja:Y.marcar?Te:"",mensajesDePrefijo:Y.marcar?K:0,cacheWriteMultiplier:1,explicita:true,explicitaPorColocador:true,colocacion:{...ee,ultimo:Y.marcar?N:null,indiceDelUltimo:Y.marcar?K:null}}}}
|
|
1151
|
+
let A={S:d>0?P(d):0,H:p>d?P(p):0,T:P(h)},w=ui(n),S=Ju({estadistica:k,tramo:s,primaDeUnaHora:w>s.cacheWriteMultiplier?w:null,tokens:A,hayHistorial:p>d,lecturaPrevista:()=>y?P(y.indice):0}),C=S.historial&&
|
|
1152
|
+
p>d?p:d,E=S.cola?"T":C>0?C===p&&p>d?"H":"S":null,_=S.cola?h:C>0?C:null;a.record("prefix-cache-placement",E??"none",{reason:S.razon||"fixed placement",boundary:C===0?"none":C===d?"system":"history",tail:S.
|
|
1153
|
+
cola,ttl:S.ttl,breakEvenReuseRate:S.equilibrio,historyReusedWithin5m:k.H.en5m,continuedWithin5m:k.T.en5m,samples:k.T.muestras5m,providerConfirmedReads:`${k.confirmadas}/${k.predichas}`,...T});let L={...M,
|
|
1154
|
+
cola:S.cola,ttl:S.ttl,ultimo:null,indiceDelUltimo:null};if(E==null||_==null)return {marcado:{marcar:false,huella:"",claveDeVerja:"",mensajesDePrefijo:0,cacheWriteMultiplier:1,explicita:false,explicitaPorColocador:false,
|
|
1155
|
+
colocacion:L}};let I=S.ttl==="1h"?{...s,cacheWriteMultiplier:w}:s,F=`${g}|${C===0?"-":C===d?"S":"H"}${S.cola?"+T":""}@${S.ttl}`,z=this.verjaDeCache.decidir(F,{totalTokens:A.T,stablePrefixTokens:S.cola?
|
|
1156
|
+
A.T:C===d?A.S:A.H,tier:I});return a.record("prefix-cache",z.marcar?"marked":"skipped",{reason:z.razon,stablePrefixTokens:S.cola?A.T:C===d?A.S:A.H,breakEvenHitRate:z.umbral,observedHitRate:z.observada}),
|
|
1157
|
+
z.marcar?{marcado:{marcar:true,huella:this.huellaDelPrefijo(n,o.tools,r,C),claveDeVerja:F,mensajesDePrefijo:C,cacheWriteMultiplier:s.cacheWriteMultiplier,explicita:false,explicitaPorColocador:false,colocacion:{
|
|
1158
|
+
...L,ultimo:E,indiceDelUltimo:_}}}:{marcado:{marcar:false,huella:"",claveDeVerja:"",mensajesDePrefijo:0,cacheWriteMultiplier:1,explicita:false,explicitaPorColocador:false,colocacion:L}}}apuntarEnElEspejo(e,n,r,o=this.
|
|
1091
1159
|
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;
|
|
1092
|
-
if(a&&l&&s.coincidencia&&d!==void 0&&s.indiceDelUltimo>=d&&s.indiceDelUltimo-d<
|
|
1160
|
+
if(a&&l&&s.coincidencia&&d!==void 0&&s.indiceDelUltimo>=d&&s.indiceDelUltimo-d<Uu){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.
|
|
1093
1161
|
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,
|
|
1094
1162
|
...!m&&g?{cacheMissReason:g.missReason,...g.missedInputTokens!==void 0?{cacheMissedInputTokensEstimate:g.missedInputTokens}:{}}:{},...h.apagada&&!p.apagada?{reason:`the provider's counter confirmed on\
|
|
1095
1163
|
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?
|
|
1096
1164
|
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,
|
|
1097
|
-
s=e.colocacion,a=
|
|
1098
|
-
return}let u=new
|
|
1099
|
-
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),
|
|
1100
|
-
could not write the placement store (${
|
|
1101
|
-
true&&
|
|
1102
|
-
e,n,r,o.tools),d=l[
|
|
1103
|
-
huellas:l,espejo:p,estado:h}}primasDelColocador(e,n,r){let o=
|
|
1104
|
-
let i=
|
|
1165
|
+
s=e.colocacion,a=gs(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 (${Nl(l)}), so this request was not recorded`});
|
|
1166
|
+
return}let u=new Jt;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\
|
|
1167
|
+
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),Wu);}catch(l){r.record("prefix-cache-placement","store-error",{reason:`\
|
|
1168
|
+
could not write the placement store (${Nl(l)})`});}}async cargarEspejo(e,n,r,o,i){if(this.config.cacheBreakpoints!=="auto"||!o.setIsStable||i)return null;let s=bt(this.config.provider);if(e.savings?.standalone===
|
|
1169
|
+
true&>(n,s))return null;let a=_s(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(
|
|
1170
|
+
e,n,r,o.tools),d=l[hs(r)],p=new Jt,h;try{let m=await this.config.cacheBreakpointStore.get(gs(d));h=m==null?"empty":p.importarClase(d,m)==="loaded"?"loaded":"unreadable";}catch{h="unavailable";}return {clase:d,
|
|
1171
|
+
huellas:l,espejo:p,estado:h}}primasDelColocador(e,n,r){let o=bt(this.config.provider),i=e.savings?.standalone===void 0&>(n,o);return {tramoOpenAI:i?fi(n):null,conPrima:r.cacheWriteMultiplier>1&&!i}}huellasDelColocador(e,n,r,o){
|
|
1172
|
+
let i=ve({model:n,tools:(o??[]).map(s=>s.id),schema:e.response?.schema??null});return Hu(i,r)}huellaDelPrefijo(e,n,r,o){return ne(ve({model:e,tools:(n??[]).map(i=>i.id),prefijo:r.slice(0,o).map(i=>`${i.
|
|
1105
1173
|
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 \
|
|
1106
|
-
cascade is off",fuerza:"none",bucket:"",economia:null,observada:null,muestras:0,precioBarato:null,tasaDeMuestreo:0};if(s==="off")return a;let c=
|
|
1107
|
-
this.config.modelCascade?.pairs??
|
|
1174
|
+
cascade is off",fuerza:"none",bucket:"",economia:null,observada:null,muestras:0,precioBarato:null,tasaDeMuestreo:0};if(s==="off")return a;let c=Qu({schema:e.response?.schema,tools:e.tools}),u=Yu(e.model,
|
|
1175
|
+
this.config.modelCascade?.pairs??bs),l=this.precioConocido(e.model,i),d=u?this.precioConocido(u,i):void 0,p=Zu(d,l),h=ne(ve({tenant:n.tenantId,scope:n.authorizationScope,contract:n.contractId,schema:n.
|
|
1108
1176
|
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.
|
|
1109
1177
|
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":
|
|
1110
1178
|
"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 } })\
|
|
@@ -1118,496 +1186,509 @@ er its meaning, so a well-formed answer with wrong content is served and counted
|
|
|
1118
1186
|
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,
|
|
1119
1187
|
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.
|
|
1120
1188
|
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.
|
|
1121
|
-
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
|
|
1122
|
-
n)}throw e?new
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
now
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
i.
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
this.
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
this.
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1189
|
+
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 nt(Ll(n,r),
|
|
1190
|
+
n)}throw e?new nt(Vh(),"invalid"):new nt(Ll("none"),"none")}avisar(e,n){this.config.silenceWarnings||we(e,n);}avisarDeTruncado(e,n,r,o,i){let s=J(e),a=In(e)||"(no contractId)",c=i?" The layer has NOTED\
|
|
1191
|
+
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 cut off, the task do\
|
|
1192
|
+
es 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 know in advance how much\
|
|
1193
|
+
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 Anthropic API requires \`max_\
|
|
1194
|
+
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 this model (what its \`m\
|
|
1195
|
+
axLength\`/\`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 bounds CHARACTERS, whi\
|
|
1196
|
+
ch 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 model is writing more th\
|
|
1197
|
+
an its own schema permits (no structured mode enforces \`maxLength\`).${c}`;this.avisar(`salida-truncada:${a}:${n}`,`[bvsala] The response was cut off after exhausting \`maxOutputTokens\`${s!=null?` (${s}\
|
|
1198
|
+
)`:""} 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 it would be cut off again\
|
|
1199
|
+
, a paid call for the same failure.${u}`);}avisarDePalancasSinConfigurar(e){this.config.silenceWarnings||((e.compression===true||e.compression==="auto")&&!this.config.compressor&&this.avisar("palanca-sin\
|
|
1200
|
+
-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 report, `report.compression`\
|
|
1201
|
+
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 should decide to pay for: p\
|
|
1202
|
+
lug it in with `createSavingsLayer({ compressor })`, any object with `compress({ text })`. If your plan does not include `long_context_compression`, that feature is needed too. The rest of the layer k\
|
|
1203
|
+
eeps saving as usual."),e.semanticCache&&!this.deps.semanticCache&&this.avisar("palanca-sin-cache-semantica",'[bv-sala] `savings.semanticCache` was requested but this layer has no semantic cache, so e\
|
|
1204
|
+
very 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 provider: plug it in with `cre\
|
|
1205
|
+
ateSavingsLayer({ semanticCache: new InMemorySemanticCache({ embed }) })`. The exact cache and the rest of the layer keep working.'),this.deps.semanticCache&&e.semanticCache===void 0&&this.config.semanticCacheDefault===
|
|
1206
|
+
void 0&&this.avisar("cache-semantica-sin-pedir","[bv-sala] This layer was given a `semanticCache`, but this request does not ask for it, so the semantic cache was neither consulted nor written: every \
|
|
1207
|
+
reworded question is paid to the provider and a calibrating cache collects no labels. Passing the cache to `createSavingsLayer` does not switch it on. Ask for it per request with `savings: { semanticC\
|
|
1208
|
+
ache: true }`, or on every request with `createSavingsLayer({ semanticCache, semanticCacheDefault: true })` \u2014 preferably with a cache built with `calibration`. If you switch it on per request on purpo\
|
|
1209
|
+
se, set `semanticCacheDefault: false` to say so and this warning goes away."));}async generateOptimized(e,n={llamadas:0,falloDelProveedor:false,sinContador:0},r=null){this.assertLicensed();let o=new vn(this.
|
|
1210
|
+
now),i=new At,s=jo(e),a=Jn(s),c=e.savings??{};this.avisarDePalancasSinConfigurar(c),c.semanticCache&&c.semanticCache!=="include-agentic"&&this.deps.semanticCache&&$l(s,a)&&this.avisar("semantica-agent\
|
|
1211
|
+
ica-apagada",'[bv-sala] `savings.semanticCache` is on, but this request is agentic (it declares tools, carries tool calls or results, or holds more than one user turn), so the semantic cache was neith\
|
|
1212
|
+
er 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 under the similarity score cannot see that. The exact cache is un\
|
|
1213
|
+
affected. To include agentic requests, set `savings.semanticCache: "include-agentic"` after measuring it on your own traffic.');let u=this.now(),l=this.decidirCascada(e,s,c,o,u),d=this.costModelFor(l.
|
|
1214
|
+
modeloServido,u);o.record("canonicalize","done",{tenant:s.tenantId,contract:s.contractId}),o.record("policy",a.reasons.join("; ")||"no restrictions",{allowExactCache:a.allowExactCache,allowSemanticCache:a.
|
|
1215
|
+
allowSemanticCache});let p=this.tokensFor(this.assembleBaselinePrompt(e),e),h=rs(e),m,g=()=>m??=Rs(e);if(i.baselineInput=p,i.baselineOutput=h,i.baselineTools=e.tools?.length??0,c.deterministicResolvers!==
|
|
1216
|
+
false){let y=this.deps.resolvers.try(s);if(y)return i.avoidCall(p,this.tokensFor(y.text,e)),o.record("resolver",y.resolver,{avoided:true}),this.finish(e,s,{text:y.text,data:y.data,storedAtMs:this.now()},"d\
|
|
1217
|
+
eterministic",i,d,o,Dn(),_n(),void 0,void 0,void 0,void 0,void 0,this.informeDeCascada(l,{servedModel:e.model}))}let f=No(s,{servedModel:l.modeloServido});if(a.allowExactCache&&c.exactCache!==false){let y=await this.
|
|
1218
|
+
deps.exactCache.get(f),k=y?ro(y.text):null;k!==null&&o.record("exact-cache","ignored: the stored answer reads as a refusal written as text (text_refusal); it is not replayed",{skipReason:"text_refusal",
|
|
1219
|
+
rule:k});let T=k===null?y:null;if(T){let x=this.creditoPorReferencia(vl(T.meta),{request:e,cascada:l,toggles:c,huella:g,texto:T.text,claveLeida:f,calidad:()=>{let P=e.response?.schema;return !P||he(T.data,
|
|
1220
|
+
P).valid}});return x.ok?i.avoidCallByReference(x.credit):(i.avoidCall(p,this.tokensFor(T.text,e)),i.referenceRejected=x.reason),o.record("exact-cache","hit",{ageMs:this.now()-T.storedAtMs,basis:x.ok?"\
|
|
1221
|
+
reference":"estimated",...x.ok?{}:{referenceRejected:x.reason},...x.ok&&x.outputNotCredited?{outputNotCredited:x.outputNotCredited}:{}}),this.finish(e,s,T,"exact",i,d,o,Dn(),_n(),this.now()-T.storedAtMs,
|
|
1222
|
+
void 0,void 0,void 0,void 0,this.informeDeCascada(l))}o.record("exact-cache","miss");}let v=la(s,{servedModel:l.modeloServido,deferrable:c.deferrable===true,toolDiscovery:c.toolDiscovery===true,...J(e)!=null?
|
|
1223
|
+
{maxOutputTokens:J(e)}:{}}),b=async()=>{try{return await this.expensivePath(n,e,s,a,c,i,d,o,f,p,l,r,u)}catch(y){throw (n.falloDelProveedor||n.llamadas>0)&&qh(y),y}};if(a.allowSingleflight&&c.singleflight!==
|
|
1224
|
+
false){if(r){let T=this.deps.singleflight,x=typeof T.join=="function"?T.join(v):void 0;if(x){let P=await x;return this.noReproducibles.has(P)?(o.record("singleflight","not coalesced: the answer in flight\
|
|
1225
|
+
cannot be replayed"),b()):(o.record("singleflight","coalesced",{key:v}),this.asCoalescedFollower(P,p,this.tokensFor(P.text??"",e),d,e))}return o.record("singleflight","skipped (streaming: a streamed \
|
|
1226
|
+
request never leads)"),b()}let{value:y,coalesced:k}=await this.deps.singleflight.run(v,b);if(k&&this.noReproducibles.has(y))return o.record("singleflight","not coalesced: the answer in flight cannot b\
|
|
1227
|
+
e replayed"),b();if(k){o.record("singleflight","coalesced",{key:v});let T=this.creditoPorReferencia(this.referenciasDeLider.get(y)??"absent",{request:e,cascada:l,toggles:c,huella:g,texto:y.text??"",claveLeida:void 0,
|
|
1228
|
+
calidad:()=>y.report.constraints.structurallyValid!==false&&y.report.qualityStatus!=="rejected"});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){
|
|
1229
|
+
let m=this.entitled("semantic_cache"),g=null;if(i.semanticCache&&i.semanticCache!=="include-agentic"&&this.deps.semanticCache&&$l(r,o)&&c.record("semantic-cache",'skipped: agentic traffic (default); s\
|
|
1230
|
+
et savings.semanticCache: "include-agentic" to include it'),o.allowSemanticCache&&i.semanticCache&&this.deps.semanticCache&&!m&&c.record("semantic-cache","degraded: feature not included in this licens\
|
|
1231
|
+
e"),o.allowSemanticCache&&i.semanticCache&&this.deps.semanticCache&&m){let R=this.deps.semanticCache,O=R.calibrated?await R.lookup(r,{agentic:o.isAgentic}):{hit:await R.find(r),probe:null},q=O.hit?ro(
|
|
1232
|
+
O.hit.record.answer.text):null;q!==null&&c.record("semantic-cache","ignored: the stored answer reads as a refusal written as text (text_refusal); it is not replayed",{skipReason:"text_refusal",rule:q});
|
|
1233
|
+
let H=q===null?O.hit:null;if(g=O.probe,H)return s.avoidCall(l,this.tokensFor(H.record.answer.text,n)),c.record("semantic-cache","hit",{confidence:H.confidence,similarity:H.similarity}),this.finish(n,r,
|
|
1234
|
+
H.record.answer,"semantic",s,a,c,Dn(),_n(),H.ageMs,H.confidence,void 0,void 0,void 0,this.informeDeCascada(d,{servedModel:n.model}),void 0,void 0,void 0,{semantico:H});c.record("semantic-cache","miss",
|
|
1235
|
+
g?{calibration:g.reason,score:g.score}:void 0);}let f=i.router===false,v=f?Dn():this.deps.router.classify(r);c.record("router",v.executionClass,{confidence:v.confidence,reason:v.reason});let b=this.planearBusquedaNativa(
|
|
1236
|
+
n,i,v.executionClass,f,d,a,c),y=b?b.seleccion:f?this.deps.toolSelector.passthrough(n.tools):this.deps.toolSelector.select(r.normalizedText,n.tools,v.executionClass,r.toolsetHash);if(b||this.avisarDeHerramientasPodadas(
|
|
1237
|
+
n,y,d.modeloServido),s.actualTools=y.tools.length,y.droppedIds.length){let R=new Set(y.droppedIds),O=(n.tools??[]).filter(q=>R.has(q.id)).reduce((q,H)=>q+this.tokensFor(so(H),n),0);s.eliminate(O),c.record(
|
|
1238
|
+
"tool-selector",y.reason,{dropped:y.droppedIds,eliminatedTokens:O});}s.baselineRetrieval=this.config.retriever?v.rounds:0;let k=await Oa({execution:v.executionClass,query:r.normalizedText,maxRounds:n.retrieval?.
|
|
1239
|
+
maxRounds??v.rounds,maxDocuments:n.retrieval?.maxDocuments??5},{...this.config.retriever?{retriever:this.config.retriever}:{},...this.config.reranker?{reranker:this.config.reranker}:{}});s.actualRetrieval=
|
|
1240
|
+
k.rounds,k.retrievedCount>0&&c.record("retrieval",`kept ${k.keptCount}/${k.retrievedCount}`,{rounds:k.rounds});let T=_n(),x=[...n.messages],P=As(n.messages),M=false,A=k.docs.length>0?{role:"system",content:`\
|
|
1241
|
+
Retrieved context \u2014 answer using only this evidence and cite sources by [id]:
|
|
1169
1242
|
|
|
1170
|
-
`+k.docs.map((
|
|
1171
|
-
${
|
|
1243
|
+
`+k.docs.map((R,O)=>`[${R.source??R.id??`doc${O+1}`}]
|
|
1244
|
+
${R.text}`).join(`
|
|
1172
1245
|
|
|
1173
|
-
`)}:null,
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
`:"")+T.encoded}),c.record("serialization",T.chosen,{reason:T.reason,jsonTokens:
|
|
1177
|
-
disabled; sent compact JSON"});}if(
|
|
1178
|
-
{},
|
|
1179
|
-
{}},
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
this.assemblePromptText(
|
|
1183
|
-
compressorCostTokens});
|
|
1184
|
-
xe
|
|
1185
|
-
s.compressionReport={originalTokens:
|
|
1186
|
-
let
|
|
1187
|
-
record("elision","applied",{elided:
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
indice],
|
|
1191
|
-
(
|
|
1192
|
-
compactados.length,before:
|
|
1193
|
-
cacheReadMultiplier:
|
|
1194
|
-
|
|
1195
|
-
null;
|
|
1196
|
-
schemaTokensCompact:
|
|
1197
|
-
breakEvenOutputDeltaTokens:
|
|
1198
|
-
deps.constraintBackends):{backend:"none",reason:"no output contract"};c.record("constraints",
|
|
1199
|
-
!b,
|
|
1200
|
-
e.llamadas>0);let
|
|
1201
|
-
{},...
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
resent?.
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
let
|
|
1214
|
-
true,
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
let
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
"
|
|
1222
|
-
"
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
n,
|
|
1239
|
-
`
|
|
1240
|
-
`),
|
|
1246
|
+
`)}:null,w=In(n),S=J(n),C=S!=null?Math.floor(S*3.2):null,E=this.contratosQueIncumplen.has(w)?Is(n.response?.schema,"",C):"";if(E&&An(x,{role:"system",content:`JSON limits (not API-enforced): ${E}`}),n.
|
|
1247
|
+
structuredData!==void 0){let R=JSON.stringify(n.structuredData),O=this.tokensFor(R,n);if(i.serialization!==false){T=this.deps.formatSelector.choose(n.structuredData,{model:n.model,...n.tokenizer?{tokenizer:n.
|
|
1248
|
+
tokenizer}:{}});let q=this.tokensFor(T.encoded+T.instruction,n);s.compress(O,q),An(x,{role:"system",content:(T.instruction?T.instruction+`
|
|
1249
|
+
`:"")+T.encoded}),c.record("serialization",T.chosen,{reason:T.reason,jsonTokens:O,chosenTokens:q});}else An(x,{role:"system",content:R}),c.record("serialization","json-compact",{reason:"format selector\
|
|
1250
|
+
disabled; sent compact JSON"});}if(A&&An(x,A),(i.compression===true||i.compression==="auto")&&o.allowCompression&&this.config.compressor&&this.entitled("long_context_compression")){let R=this.config.compressionEconomics??
|
|
1251
|
+
{},O=to(n.model,R),q={compressorCostTokens:R.compressorCostTokens??0,...R.minimumContextTokens!=null?{minimumContextTokens:R.minimumContextTokens}:{},...R.minimumNetTokens!=null?{minimumNetTokens:R.minimumNetTokens}:
|
|
1252
|
+
{}},H=0,te=0;for(let de of x)de.role==="system"?H+=1:te+=this.tokensFor(de.content,n);let Ke=this.tokensFor(this.assemblePromptText(x,y.tools),n),le=oi({...q,contextTokens:te,projectedEliminable:te}),
|
|
1253
|
+
ue=0,G=0,Ae=false,Ee=le.reason;if(le.compress){let de=[];for(let Q of x){if(Q.role==="system"){de.push(Q);continue}let en=this.tokensFor(Q.content,n),tn=await this.config.compressor.compress({text:Q.content}),
|
|
1254
|
+
Xs=!tn.skipped&&tn.fidelityPassed&&Ua(Q.content,tn.compressed),ea=Xs?this.tokensFor(tn.compressed,n):en;Xs&&ea<en?(de.push({...Q,content:tn.compressed}),ue+=en,G+=ea):de.push(Q);}let Ge=this.tokensFor(
|
|
1255
|
+
this.assemblePromptText(de,y.tools),n),xe=oi({...q,contextTokens:te,projectedEliminable:ue-G}),zn=ll({originalTokens:Ke,compressedTokens:Ge,tier:O,...R.prefix?{prefix:R.prefix}:{},compressorCostTokens:q.
|
|
1256
|
+
compressorCostTokens});G>=ue?Ee="no fidelity-passed net reduction":xe.compress?zn.comprimir?(Ae=true,Ee=zn.razon,M=de.slice(0,P).some((Q,en)=>Q.content!==x[en]?.content),x=de,s.compress(ue,G)):Ee=zn.razon:
|
|
1257
|
+
Ee=xe.reason;}Ae||(ue=0,G=0),c.record("compression",Ae?"applied":"skipped",{reason:Ee,before:ue,after:G,contextTokens:te,promptTokens:Ke,cacheTierMinimum:O.minimumCacheTokens,protectedSystemMessages:H,
|
|
1258
|
+
prefixRewritten:M}),s.compressionReport={originalTokens:ue,compressedTokens:G,protectedSpans:H,fidelityPassed:true};}if(i.elision!==false&&o.allowElision&&this.entitled("tool_result_elision")){let R=cl(x);if(R.
|
|
1259
|
+
indices.length>0){let O=this.tokensFor(Ps,n),q=0;for(let H of R.indices){let te=this.tokensFor(x[H].content,n);q+=Math.max(0,te-O);}(R.indices.some(H=>H<P)&&(M=true),x=ul(x,R.indices),s.eliminate(q),
|
|
1260
|
+
s.elididoLocal+=q),c.record("elision","applied",{elided:R.indices.length,eliminatedTokens:q,grossBytes:R.bytesOriginales,live:Ds});}else c.record("elision","skipped",{reason:"no old/large t\
|
|
1261
|
+
ool_result over the age\xD7size threshold"});}let _=Xh(this.config.toolOutputCompaction,i.toolOutputCompaction);if(_&&!this.entitled("long_context_compression")&&c.record("tool-output-compaction","degr\
|
|
1262
|
+
aded: feature not included in this license"),_&&o.allowCompression&&this.entitled("long_context_compression")){let R=Ga(x,_),O=0,q=0,H=0,te=0,Ke={};if(R.compactados.length>0){let ue=x.slice();for(let G of R.
|
|
1263
|
+
compactados){let Ae=x[G.indice],Ee=this.tokensFor(Ae.content,n),de=this.tokensFor(G.texto,n);ue[G.indice]={...Ae,content:G.texto},O+=Ee,q+=de,G.enLaCola?H+=Math.max(0,Ee-de):te+=Math.max(0,Ee-de);for(let Ge of G.
|
|
1264
|
+
aplicadas)Ke[Ge]=(Ke[Ge]??0)+1;}x=ue,s.compress(O,q),s.compactedLocal+=Math.max(0,O-q);}let le=to(n.model,this.config.compressionEconomics);c.record("tool-output-compaction",R.compactados.length>0?"appl\
|
|
1265
|
+
ied":"skipped",{compacted:R.compactados.length,before:O,after:q,tailSavedTokens:H,replayedSavedTokens:te,transforms:Ke,fileViewsKeptVerbatim:R.vistasDeFichero,exceptedTools:R.exceptuados,cacheWriteMultiplier:le.
|
|
1266
|
+
cacheWriteMultiplier,cacheReadMultiplier:le.cacheReadMultiplier,note:"counted in tokens.compressedInput only; never priced into savings or commission. each tail token saved is one token fewer written \
|
|
1267
|
+
now and re-read on every later turn"});}let L=n.response?.schema,I=L&&i.outputCodebook===true?rl(L,R=>this.tokensFor(R,n),a,{evidencia:this.memoriaDelCodebook.resolver(d.modeloServido,In(n),i.outputCodebookMeasuredOutputDeltaTokens)}):
|
|
1268
|
+
null;I&&c.record("output-codebook",I.applied?"applied":"skipped",{reason:I.reason,...I.applied?{renamedKeys:I.plan.renamedKeys,codedEnumValues:I.plan.codedEnumValues,schemaTokensOriginal:I.plan.schemaTokensOriginal,
|
|
1269
|
+
schemaTokensCompact:I.plan.schemaTokensCompact,modelledShapeSavingTokens:I.plan.modelledShapeSavingTokens,measuredOutputDeltaTokens:I.plan.measuredOutputDeltaTokens,outputDeltaProvenance:I.plan.outputDeltaProvenance,
|
|
1270
|
+
breakEvenOutputDeltaTokens:I.plan.breakEvenOutputDeltaTokens,netSavingUsd:I.plan.netSavingUsd,pricedForModel:d.modeloServido}:{}});let F=I?.applied?I.plan.compactSchema:L,z=F?Va(d.modeloServido,F,this.
|
|
1271
|
+
deps.constraintBackends):{backend:"none",reason:"no output contract"};c.record("constraints",z.backend,{reason:z.reason});let U=b?{tools:b.prefijo,setIsStable:y.setIsStable}:y,ee=i.toolDiscovery===true&&
|
|
1272
|
+
!b,K=this.config.cacheBreakpointStore?await this.cargarEspejo(n,d.modeloServido,x,U,ee):null,N=this.decidirMarcadoDeCache(n,d.modeloServido,x,U,ee,M?As(x,true):P,c,K),Te=this.now();if(p?.senal.aborted)throw new Se(
|
|
1273
|
+
e.llamadas>0);let Y=b?this.sinDescubrimientoPorBusquedaNativa(i,y.tools,c):await this.descubrirHerramientas(e,n,i,y.tools,x,s,a,c),Et=Y.tools;s.actualTools=Et.length;let $n={messages:x,...Et.length?{tools:Et}:
|
|
1274
|
+
{},...F?{schema:F}:{},...J(n)!=null?{maxOutputTokens:J(n)}:{},...n.temperature!=null?{temperature:n.temperature}:{},...n.seed!=null?{seed:n.seed}:{},...i.deferrable?{deferrable:true}:{},...N.explicita?{
|
|
1275
|
+
explicitCacheWrites:true}:{},...b?{toolSearch:b.plan}:{},constraintBackend:z.backend},jn={model:d.modeloServido,...$n,...N.marcar?{stablePrefixMessages:N.mensajesDePrefijo,promptCacheKey:N.huella,...N.colocacion&&
|
|
1276
|
+
!N.explicita&&(N.colocacion.cola||N.colocacion.ttl!=="5m")?{cachePlacement:{tail:N.colocacion.cola,ttl:N.colocacion.ttl}}:{},...this.config.cacheMissDiagnostics===true&&N.colocacion?{cacheDiagnostics:{previousMessageId:N.
|
|
1277
|
+
colocacion.coincidencia?.idDelProveedor??null}}:{}}:{}},D,Js=false,cd={...e};try{D=p?await this.llamarProveedorEnStream(jn,e,p):await this.llamarProveedor(jn,e);}catch(R){if(!this.respaldaFaltaDeCapacidad(
|
|
1278
|
+
i,R,p))throw R;Object.assign(e,cd),Js=true,c.record("deferred-tier","capacity-fallback",{error:R instanceof Error?R.message.slice(0,200):String(R),reason:'the cheaper tier had no capacity; repeated once\
|
|
1279
|
+
at the standard tier and price, as configured with priceLevers.onCapacityError: "standard"'});let{deferrable:O,...q}=jn;D=await this.llamarProveedor(q,e);}let ud=gr(D),ld=D.servedServiceTier;b&&c.record(
|
|
1280
|
+
"tool-search","provider",{searches:D.toolSearch?.searches??null,loaded:D.toolSearch?.loaded??[],errors:D.toolSearch?.errors??0,resentResults:D.toolSearch?.resent?.results??0,resentTools:D.toolSearch?.
|
|
1281
|
+
resent?.tools??[],reason:D.toolSearch?"what the provider's tool search did in this call; its cost is in the provider's counter and credited to no ledger":"the adapter did not report what the search di\
|
|
1282
|
+
d"}),s.actualLlm+=1;let wo=R=>{if(!I?.applied)return R;let O=We(R);return O.ok?JSON.stringify(I.plan.expand(O.value)):R},fe=wo(D.text),je=D.usage,dd=D.unbilledRefusal===true,Ks={...D.providerMessageId?{
|
|
1283
|
+
id:D.providerMessageId}:{},...D.cacheDiagnostics?{diagnostico:D.cacheDiagnostics}:{}},pt=false;if(d.enruta){let R=ys({texto:fe,schema:L,finishReason:D.finishReason,pidioHerramientas:(D.toolCalls?.length??
|
|
1284
|
+
0)>0});this.verjaDeCascada.registrar(d.bucket,!R.acepta),c.record("model-cascade",R.acepta?"accepted":"escalating",{servedModel:d.modeloServido,reason:R.motivo,checks:R.comprobaciones}),R.acepta||(pt=
|
|
1285
|
+
true,s.cascadeAttempt(D.usage,D.unbilledRefusal===true?{inputPer1k:0,outputPer1k:0,cachedInputPer1k:0}:d.precioBarato??a,N.marcar&&N.cacheWriteMultiplier>1?1:fn(d.modeloServido)),s.actualLlm+=1,D=await this.
|
|
1286
|
+
llamarProveedor({model:n.model,...$n},e),fe=wo(D.text));}let Ie=pt?n.model:d.modeloServido,Qt=pt?this.costModelFor(n.model,h):a;s.actualInput+=D.usage.inputTokens,s.actualOutput+=D.usage.outputTokens,D.
|
|
1287
|
+
unbilledRefusal===true&&s.unbilledCall(D.usage);let pd=D.usage,fd=D.servedServiceTier,md=D.structuredNatively===true,Nn=gr(D),hd=dc(this.config.provider),Gs;I?.applied&&c.record("output-codebook",We(D.text).
|
|
1288
|
+
ok?"expanded":"not-expanded (response was not JSON)",We(D.text).ok?{localOutputTokensCompact:this.tokensFor(D.text,n),localOutputTokensExpanded:this.tokensFor(fe,n),creditedLedger:"none",note:"local c\
|
|
1289
|
+
ount of the served answer in both shapes; not credited to any ledger"}:{}),L&&z.backend==="provider-native"&&D.structuredNatively===false&&(z={backend:"none",reason:"provider did not enforce the contract\
|
|
1290
|
+
natively; the schema travelled in the prompt and the layer is the only validator"},c.record("constraints","none",{downgradedFrom:"provider-native",reason:z.reason})),s.sentInputLocal=this.tokensFor(this.
|
|
1291
|
+
assemblePromptText(x,Et),n),s.removedInputLocal=Math.max(0,l-s.sentInputLocal-s.elididoLocal-s.compactedLocal);let gd=s.sentInputLocal;s.sentInputLocal+=Y.tokensLocalesDelSondeo,s.estimatorExact=this.
|
|
1292
|
+
estimatorEsExacto(n),D.usage.cachedInputTokens&&s.providerCached(D.usage.cachedInputTokens);let Zs=fn(Ie),bd=!pt&&N.marcar&&N.cacheWriteMultiplier>1;if(Zs>1&&!bd&&D.unbilledRefusal!==true&&(D.usage.cacheWriteInputTokens??
|
|
1293
|
+
0)>0&&s.providerCacheWritePremium(D.usage.cacheWriteInputTokens??0,Zs,Qt),N.marcar&&je.complete===false)c.record("prefix-cache","not measured: the provider reported no usage for this call");else if(N.marcar&&
|
|
1294
|
+
dd)c.record("prefix-cache","not measured: the marked call was a refusal the provider does not bill");else if(N.marcar){let R=Math.max(0,je.cacheWriteInputTokens??0),O=Math.min(R,Math.max(0,je.cacheWrite1hInputTokens??
|
|
1295
|
+
(N.colocacion?.ttl==="1h"?R:0)));s.cacheWritePremium(R-O,N.cacheWriteMultiplier,d.precioBarato??a),O>0&&s.cacheWritePremium(O,ui(d.modeloServido),d.precioBarato??a),this.verjaDeCache.registrar(N.claveDeVerja,
|
|
1296
|
+
je),c.record("prefix-cache","measured",{cacheRead:je.cachedInputTokens??0,cacheWritePremiumTokens:je.cacheWriteInputTokens??0,...O>0?{cacheWrite1hTokens:O}:{}});}N.colocacion?.conAlmacen?await this.apuntarEnElAlmacen(
|
|
1297
|
+
N,je,c,Ks):N.colocacion&&this.apuntarEnElEspejo(N,je,c,this.espejoDeCache,Ks);let Pt=null;if(d.modo==="shadow"&&d.elegible&&d.candidato&&d.precioBarato&&Yh(u,d.tasaDeMuestreo))try{let R=await this.llamarProveedor(
|
|
1298
|
+
{model:d.candidato,...$n},e);s.actualLlm+=1;let O=s.extraCostUsd;s.cascadeAttempt(R.usage,d.precioBarato,fn(d.candidato));let q=wo(R.text),H=ys({texto:q,schema:L,finishReason:R.finishReason,pidioHerramientas:(R.
|
|
1299
|
+
toolCalls?.length??0)>0});this.verjaDeCascada.registrar(d.bucket,!H.acepta);let te=H.acepta?Xu(q,fe):null;Pt={coste:s.extraCostUsd-O,divergio:te?te.divergen:null},c.record("model-cascade",H.acepta?"sa\
|
|
1300
|
+
mple accepted":"sample escalated",{candidateModel:d.candidato,reason:H.motivo,sampleCost:Pt.coste,...te?{diverged:te.divergen,divergence:te.motivo}:{},note:"measurement only: this answer was NEVER ser\
|
|
1301
|
+
ved. The escalation rate it feeds is a money figure, not a quality one"});}catch(R){c.record("model-cascade","sample failed (measurement only; the answer is unaffected)",{error:R instanceof Error?R.message:
|
|
1302
|
+
String(R)});}let Bn=fe,ft=true,Ne={},mt=(D.toolCalls?.length??0)>0;if(mt&&(ft=null,L&&c.record("validation","n/a: model requested tool calls (the output contract applies to the final answer)")),L&&!mt){let R=We(
|
|
1303
|
+
fe),O=R.ok?he(R.value,L):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},q=false;R.ok&&R.rescatado!=null&&O.valid&&(fe=R.rescatado,q=true,c.record("validation","rescued-locally",{reason:"the model \
|
|
1304
|
+
wrapped valid JSON in prose or a markdown fence; it was extracted locally instead of paying a repair call"})),!O.valid&&Qh(O.errors)&&this.contratosQueIncumplen.add(In(n));let H=D.finishReason==="leng\
|
|
1305
|
+
th",te=jl(D),Ke=!O.valid&&O.errors.some(le=>/not a valid regular expression/.test(le.message));if(!O.valid&&Ke)c.record("validation","repair-skipped",{reason:"schema defect (uncompilable pattern); no \
|
|
1306
|
+
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 no response can satisfy it. \
|
|
1307
|
+
NOT retried (it would be a paid call for the same failure). Fix the schema's `pattern`."),Ne.reparacion={outcome:"skipped",skipReason:"schema_defect"};else if(!O.valid&&te)c.record("validation","repai\
|
|
1308
|
+
r-skipped",{reason:(D.refusal!==void 0?"the provider refused the request (a refusal message instead of an answer)":"the provider refused the request (finish reason content_filter)")+"; a repair on the\
|
|
1309
|
+
same model would be refused, and may be billed, again",model:Ie}),Ne.reparacion={outcome:"skipped",skipReason:"provider_refusal"};else if(!O.valid&&H){let le=tl(L,Ae=>this.tokensFor(Ae,n)),ue=J(n)??null,
|
|
1310
|
+
G=le!==null&&ue!=null&&le<=ue;G&&this.contratosQueIncumplen.add(In(n)),c.record("validation","repair-skipped",{reason:"output truncated by maxOutputTokens; a retry with the same cap would truncate aga\
|
|
1311
|
+
in",maxOutputTokens:J(n)??null,outputTokens:D.usage.outputTokens,model:Ie,...le!==null?{schemaAllowsTokens:le}:{},learnedValueLimits:G}),this.avisarDeTruncado(n,Ie,D.usage.outputTokens,le,G),Ne.reparacion=
|
|
1312
|
+
{outcome:"skipped",skipReason:"output_truncated"};}else if(!O.valid&&z.backend==="none"){let le=O.errors.slice(0,5).map(Q=>`- ${Q.path}: ${Q.message}`).join(`
|
|
1313
|
+
`),ue=[{role:"user",content:`Your previous reply did not satisfy the required JSON contract.
|
|
1241
1314
|
|
|
1242
1315
|
Previous reply:
|
|
1243
|
-
${
|
|
1316
|
+
${fe}
|
|
1244
1317
|
|
|
1245
1318
|
Problems found:
|
|
1246
|
-
${
|
|
1319
|
+
${le}
|
|
1247
1320
|
|
|
1248
|
-
Return ONLY the corrected JSON object. Keep the same content; fix only what is listed.`}],
|
|
1249
|
-
round(
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
servedTier
|
|
1263
|
-
generateId(),
|
|
1264
|
-
elididoLocal,sentLocalSinSondeo:
|
|
1265
|
-
esquemaEnFormatoNativo:
|
|
1266
|
-
model,modeloServido:
|
|
1267
|
-
i.exactCache!==false;typeof
|
|
1268
|
-
reasoningTokens}:{},exactCache:
|
|
1269
|
-
|
|
1270
|
-
provider answer carries content this layer cannot replay"
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
"
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1321
|
+
Return ONLY the corrected JSON object. Keep the same content; fix only what is listed.`}],G=this.tokensFor(this.assemblePromptText(ue),n),Ae=s.sentInputLocal>0?s.actualInput/s.sentInputLocal:1,Ee=Math.
|
|
1322
|
+
round(Ae*G),de=Math.min(D.usage.outputTokens,J(n)??Number.POSITIVE_INFINITY),Ge=Ee/1e3*Qt.inputPer1k+de/1e3*Qt.outputPer1k,xe=this.config.skipRepairAboveBaseline?s.estimateCost(Qt):void 0;if(xe!=null&&
|
|
1323
|
+
xe.baselineEstimate>0&&xe.actual+Ge>xe.baselineEstimate&&xe!=null)c.record("validation","repair-skipped",{reason:"repairing would cost more than not using the layer at all; the invalid answer is serve\
|
|
1324
|
+
d as-is and reported as invalid",errors:O.errors,baselineUsd:xe.baselineEstimate,actualUsd:xe.actual,repairEstimateUsd:Ge}),this.avisar("reparacion-mas-cara-que-el-baseline",`[bvsala] The answer did n\
|
|
1325
|
+
ot satisfy the output contract, and repairing it would have cost MORE than sending this request without the layer at all (baseline ~$${xe.baselineEstimate}, already spent ~$${xe.actual}, repair ~$${Ge.
|
|
1326
|
+
toFixed(6)}). The repair was skipped and the invalid answer is returned with \`constraints.structurallyValid: false\` \u2014 check it before using it. This combination is usually a request carrying both tool\
|
|
1327
|
+
s and an output contract; see the adapter warning for the cheaper shapes.`),Ne.reparacion={outcome:"skipped",skipReason:"would_cost_more_than_no_layer"};else {s.retries=1,c.record("validation","repair-\
|
|
1328
|
+
attempt",{errors:O.errors}),D=await this.llamarProveedor({model:Ie,messages:ue,schema:L,...J(n)!=null?{maxOutputTokens:J(n)}:{}},e),Gs=D.usage,s.actualLlm+=1,s.actualInput+=D.usage.inputTokens,s.actualOutput+=
|
|
1329
|
+
D.usage.outputTokens,s.repairOutput+=D.usage.outputTokens,s.repairInput+=D.usage.inputTokens,D.unbilledRefusal===true&&s.unbilledCall(D.usage),s.sentInputLocal+=G,fe=D.text;let Q=We(fe);O=Q.ok?he(Q.value,
|
|
1330
|
+
L):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},Q.ok&&(Bn=Q.value,Q.rescatado!=null&&O.valid&&(fe=Q.rescatado)),Ne.reparacion={outcome:O.valid?"repaired":"still_invalid"};}}else R.ok&&(Bn=R.
|
|
1331
|
+
value);ft=O.valid,!O.valid&&Ne.reparacion===void 0&&(Ne.reparacion={outcome:"skipped",skipReason:"decode_time_constraint"}),Ne.validacion={resultado:O.valid?"passed":"failed",errores:O.errors.length,desenvuelto:q},
|
|
1332
|
+
c.record("validation",ft?"valid":"invalid");}let vd=this.now()-Te,yd=Jh(Bn),Rt={text:fe,data:Bn,rendered:yd,storedAtMs:this.now()},me=this.informeDeDiferido(i,D,Ie,Js),Ce=this.informeDeEscrituras(i,ud,
|
|
1333
|
+
je,ld,d.modeloServido,N.marcar,N.explicitaPorColocador);Ce&&c.record("cache-writes",Ce.mode,{breakpoints:Ce.breakpoints,...Ce.avoidedWritePremium?{avoidedWritePremium:Ce.avoidedWritePremium.amount,basis:"\
|
|
1334
|
+
estimated"}:{},creditedLedger:"none",reason:Ce.reason}),me&&c.record("deferred-tier",me.credited?"credited":"not-credited",{...me.requestedTier?{requestedTier:me.requestedTier}:{},...me.servedTier?{servedTier:me.
|
|
1335
|
+
servedTier}:{},creditedLedger:"none",reason:me.reason});let kd=Y.aplicado,So=D.finishReason==="length",Fn=D.replayable===false,To=jl(D),qn=To||mt?null:ro(fe),Dt=ft!==false&&!mt&&!kd&&!So&&!Fn&&!To&&qn===null,
|
|
1336
|
+
Ys=this.generateId(),ge;try{ge=bl({contadorSimulado:si(this.config.provider),origen:hd,usoPrimario:pd,usoReparacion:Gs,tierServido:fd,eliminatedInput:s.eliminatedInput,compressedInput:s.compressedInput,
|
|
1337
|
+
elididoLocal:s.elididoLocal,sentLocalSinSondeo:gd,baselineInput:l,codebookAplicado:I?.applied===!0,tokensDelSondeo:Y.tokensLocalesDelSondeo,sondeoAplicado:Y.aplicado,busquedaNativa:b!==null,hayEsquema:L!=
|
|
1338
|
+
null,esquemaNativo:md,esquemaEnFormatoNativo:Nn?.esquemaEnFormatoNativo===!0&&F===L,esquemaEstricto:Nn?.esquemaEstricto===!0,esquemaPorPrompt:Nn?.esquemaPorPrompt===!0,piezasDelAdaptador:Nn?.piezasDelAdaptador??
|
|
1339
|
+
0,modeloPedido:n.model,modeloServido:Ie,cacheable:Dt,mensajesDeLaCapa:x.length-n.messages.length,requestId:Ys,at:this.now(),textoServido:fe,huella:()=>Rs(n)});}catch{ge="fingerprint-failed";}let Qs=Dt&&
|
|
1340
|
+
o.allowExactCache&&i.exactCache!==false;typeof ge=="object"?c.record("reference","written",{inputTokens:ge.inputTokens,outputTokens:ge.outputTokens,layerInsertions:ge.layerInsertions,...ge.reasoningTokens!==
|
|
1341
|
+
void 0?{reasoningTokens:ge.reasoningTokens}:{},exactCache:Qs}):c.record("reference","not-written",{reason:ge});try{Dt||c.record("cache-write",mt?"skipped: tool-call turn (an action request must not be\
|
|
1342
|
+
replayed from cache)":ft===!1?"skipped: response fails its output contract":So?'skipped: answer cut off by the output cap (finish_reason "length"); replaying half an answer would bill it as a 100% av\
|
|
1343
|
+
oided call':Fn?"skipped: the provider answer carries content this layer cannot replay":To?'skipped: the provider refused (stop_reason "refusal" / finish_reason "content_filter" / a refusal message); a\
|
|
1344
|
+
refusal is not an answer, and replaying it would credit an avoided call the provider may not have billed':qn!==null?"skipped: the answer reads as a refusal written as text (text_refusal); it was meas\
|
|
1345
|
+
ured and served as usual, but a refusal is not an answer to replay or to credit as an avoided call":"skipped: answered with a reduced tool view (tool discovery), so it must not be replayed",qn!==null&&
|
|
1346
|
+
!mt&&ft!==!1&&!So&&!Fn?{skipReason:"text_refusal",rule:qn}:void 0);let R=pt?No(r,{servedModel:Ie}):u;if(Qs){let q=this.config.exactCacheTtlMs??864e5,H=o.maxCacheAgeMs==null?q:Math.min(q,o.maxCacheAgeMs);
|
|
1347
|
+
await this.deps.exactCache.set(R,typeof ge=="object"?{...Rt,meta:{...Rt.meta??{},reference:{...ge,cacheKey:R}}}:Rt,H);}let O=Ie!==n.model;Dt&&!O&&o.allowSemanticCache&&i.semanticCache&&this.deps.semanticCache?
|
|
1348
|
+
await this.deps.semanticCache.store(r,Rt):Dt&&O&&i.semanticCache&&c.record("cache-write","semantic write skipped: a cheaper model answered, and this cache keys on the model the caller asked for"),g&&this.
|
|
1349
|
+
deps.semanticCache&&(Dt&&!O&&o.allowSemanticCache&&i.semanticCache?(c.record("semantic-calibration","label requested",{reason:g.reason,score:g.score}),this.deps.semanticCache.observe(g,Rt)):c.record("\
|
|
1350
|
+
semantic-calibration","no label: the cache would not store this answer"));}catch(R){c.record("cache-write","failed (non-fatal; answer already served)",{error:R instanceof Error?R.message:String(R)});}s.
|
|
1351
|
+
callsWithoutUsage=e.sinContador;let Xt=D.unbilledRefusal===true;Xt&&(s.servedUnbilledRefusal=true,c.record("cost","unbilled refusal: measured at 0, no saving credited",{reason:"the provider documents a re\
|
|
1352
|
+
fusal before any output in this category as not billed; its tokens stay counted, priced at 0, and nothing is credited against a request that cost nothing"}));let xd=Xt&&me?.credited?{...me.requestedTier?
|
|
1353
|
+
{requestedTier:me.requestedTier}:{},...me.servedTier?{servedTier:me.servedTier}:{},credited:false,creditedLedger:"none",latency:me.latency,reason:"the provider did not bill this call (a refusal it docume\
|
|
1354
|
+
nts as not billed), so no tier discount is credited"}:me,wd=Xt&&Ce?.avoidedWritePremium?{mode:Ce.mode,breakpoints:Ce.breakpoints,reason:Ce.reason}:Ce,ht=this.finish(n,r,Rt,"miss",s,Qt,c,v,T,void 0,void 0,
|
|
1355
|
+
ft,z.backend,vd,this.informeDeCascada(d,{servedModel:Ie,...d.enruta?{escalated:pt}:{},...d.elegible&&d.precioBarato&&!Xt?{estimatedSwapSaving:Zh(s,pt,d.precioBarato,this.costModelFor(n.model,h))}:{},...Pt?
|
|
1356
|
+
{sampled:true,sampleCost:St(Pt.coste),...Pt.divergio!==null?{divergedOnSample:Pt.divergio}:{}}:{},...s.cascadeInput>0||s.cascadeOutput>0?{cascadeInputTokens:s.cascadeInput,cascadeOutputTokens:s.cascadeOutput}:
|
|
1357
|
+
{}}),xd,Ys,wd,{...Ne,final:{...D.finishReason!==void 0?{finishReason:D.finishReason}:{},...J(n)!=null?{topeDelLlamante:J(n)}:{}}});return typeof ge=="object"&&this.referenciasDeLider.set(ht,ge),Fn&&this.
|
|
1358
|
+
noReproducibles.add(ht),Xt&&this.negativasSinCobro.add(ht),mt&&(ht.toolCalls=D.toolCalls),D.finishReason!==void 0&&(ht.finishReason=D.finishReason),D.refusal!==void 0&&(ht.refusal=D.refusal),ht}planearBusquedaNativa(e,n,r,o,i,s,a){
|
|
1359
|
+
let c=_a(n.toolSearch),u=e.tools??[];if(c.modo==="off"||u.length===0)return null;let l=Aa(u,r==="TOOL_ACTION",o),d=Ia({opciones:c,capacidad:mi(this.config.provider),modelo:i.modeloServido,herramientas:l.
|
|
1360
|
+
map(g=>({id:g.id,tokens:this.tokensFor(so(g),e)})),hayContrato:e.response?.schema!=null,cascadaActiva:i.modo!=="off",precio:s,lecturaDeCache:this.lecturaDeCacheDe(i.modeloServido,s)});if(a.record("too\
|
|
1283
1361
|
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?
|
|
1284
1362
|
{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),
|
|
1285
1363
|
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(
|
|
1286
|
-
g.id)),plan:{variant:d.variante,alwaysLoaded:d.siempreCargadas}}}lecturaDeCacheDe(e,n){let r=
|
|
1364
|
+
g.id)),plan:{variant:d.variante,alwaysLoaded:d.siempreCargadas}}}lecturaDeCacheDe(e,n){let r=_s(e,this.config.compressionEconomics)?.cacheReadMultiplier??1,o=n.cachedInputPer1k!=null&&n.inputPer1k>0?n.
|
|
1287
1365
|
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\
|
|
1288
|
-
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}}
|
|
1289
|
-
let o=e.tools??[];n.droppedIds.length===0
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
let u={tools:o,tokensLocalesDelSondeo:0,aplicado:false};if(r.toolDiscovery!==
|
|
1293
|
-
tokensFor(
|
|
1294
|
-
o.map(f=>({risk:f.risk,tokens:l(f)})),3),salidaFinal:n
|
|
1295
|
-
reason:p.razon,oneCall:p.costeDeUnaLlamada,twoCalls:p.costeDeDosLlamadas}),u;let h,m=this.tokensFor(this.
|
|
1296
|
-
|
|
1297
|
-
Error?f.message:String(f)}),u}s.actualLlm+=1,s.actualInput+=h.usage.inputTokens,
|
|
1298
|
-
(h.toolCalls??[]).map(f=>f.name),o,3);return g.reconocidos.length===0?(c.record(
|
|
1299
|
-
ignorados}:{}}),{tools:o,tokensLocalesDelSondeo:m,aplicado:false}):(c.record(
|
|
1300
|
-
length?{unknownNames:g.ignorados}:{}}),{tools:g.tools,tokensLocalesDelSondeo:m,
|
|
1301
|
-
elegible,reason:e.razon,verifier:e.fuerza,creditedLedger:"none",...e.candidato?
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
creditedLedger:"none",latency:"
|
|
1305
|
-
the cheaper tier
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
()":"";return {...u,reason:
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
h=
|
|
1321
|
-
void 0
|
|
1322
|
-
|
|
1323
|
-
tokensOrdinarios>0&&r.inputTokens>=1024?
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
than any tier discount on it"}}finish(e,n,r,o,i,s,a,c,u,l,d,p,h="
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
T=m!=null&&m.servedModel!==m.requestedModel;return {requestId:f??
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
providerCachedInput}:{}},cache:{result:r,...l!==void 0?{confidence:l}:
|
|
1336
|
-
{}}
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
...r!=="miss"?{freshnessPassed:!
|
|
1340
|
-
traces:s.all()}}async failOpenDirect(e,n){let r=new
|
|
1341
|
-
let o=new
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
1,o.actualLlm=1,o.actualInput=l.usage.inputTokens,o.actualOutput=l.usage.outputTokens,o.baselineInput=l.usage.
|
|
1345
|
-
l.usage.
|
|
1346
|
-
|
|
1347
|
-
length??0)>0;if(f&&(m=null),a&&!f){let b=
|
|
1348
|
-
e,s,"miss",o,i,r,
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
n.
|
|
1360
|
-
|
|
1361
|
-
|
|
1366
|
+
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}}avisarDeHerramientasPodadas(e,n,r){
|
|
1367
|
+
let o=e.tools??[];if(n.droppedIds.length===0)return;let i=mi(this.config.provider)!==void 0&&Go(r);this.avisar("herramientas-podadas-por-el-selector",`[bv-sala] The tool selector sent ${n.tools.length}\
|
|
1368
|
+
of ${o.length} tools, chosen by the \`intents\`/\`risk\` your tools declare: the model cannot call the other ${n.droppedIds.length} in that request (they are listed in the report's \`tool-selector\` tr\
|
|
1369
|
+
ace). A catalogue with no \`intents\` and no \`risk\`, or \`savings: { router: false }\`, is sent whole.`+(i?' This provider and model also support native tool search: `savings: { toolSearch: "auto" }\
|
|
1370
|
+
` sends every tool deferred and lets the model search, without breaking the prompt cache.':""));}async descubrirHerramientas(e,n,r,o,i,s,a,c){let u={tools:o,tokensLocalesDelSondeo:0,aplicado:false};if(r.toolDiscovery!==
|
|
1371
|
+
true)return u;if(o.length<2)return c.record("tool-discovery","skipped (nothing to discover)",{candidates:o.length}),u;let l=f=>this.tokensFor(so(f),n),d=o.map(fl),p=pl({promptTokens:this.tokensFor(this.
|
|
1372
|
+
assemblePromptText(i),n),esquemasCompletos:o.reduce((f,v)=>f+l(v),0),descriptoresLigeros:d.reduce((f,v)=>f+l(v),0),esquemasDeLaSegunda:hl(o.map(f=>({risk:f.risk,tokens:l(f)})),3),salidaFinal:rs(n),salidaDelSondeo:96,
|
|
1373
|
+
precio:a});if(!p.aplicar)return c.record("tool-discovery","skipped (not worth a second call)",{reason:p.razon,oneCall:p.costeDeUnaLlamada,twoCalls:p.costeDeDosLlamadas}),u;let h,m=this.tokensFor(this.
|
|
1374
|
+
assemblePromptText(i,d),n);try{h=await this.llamarProveedor({model:n.model,messages:i,tools:d,maxOutputTokens:96,...n.temperature!=null?{temperature:n.temperature}:{},...n.seed!=null?{seed:n.seed}:{}},
|
|
1375
|
+
e);}catch(f){return c.record("tool-discovery","failed (falling back to a single call with every schema)",{error:f instanceof Error?f.message:String(f)}),u}s.actualLlm+=1,s.actualInput+=h.usage.inputTokens,
|
|
1376
|
+
s.actualOutput+=h.usage.outputTokens,s.discoveryInput+=h.usage.inputTokens,s.discoveryOutput+=h.usage.outputTokens;let g=ml((h.toolCalls??[]).map(f=>f.name),o,3);return g.reconocidos.length===0?(c.record(
|
|
1377
|
+
"tool-discovery","degraded: probe named no known tool",{finishReason:h.finishReason??null,...g.ignorados.length?{unknownNames:g.ignorados}:{}}),{tools:o,tokensLocalesDelSondeo:m,aplicado:false}):(c.record(
|
|
1378
|
+
"tool-discovery","applied (two provider calls)",{chosen:g.reconocidos,sent:g.tools.map(f=>f.id),candidates:o.length,...g.ignorados.length?{unknownNames:g.ignorados}:{}}),{tools:g.tools,tokensLocalesDelSondeo:m,
|
|
1379
|
+
aplicado:true})}informeDeCascada(e,n={}){if(e.modo!=="off")return {mode:e.modo,servedModel:n.servedModel??e.modeloServido,eligible:e.elegible,reason:e.razon,verifier:e.fuerza,creditedLedger:"none",...e.candidato?
|
|
1380
|
+
{candidateModel:e.candidato}:{},...e.economia?{costRatio:Rn(e.economia.r),breakEvenEscalationRate:Rn(e.economia.equilibrio),targetEscalationRate:Rn(e.economia.escaladoMaximo)}:{},...e.bucket?{workload:e.
|
|
1381
|
+
bucket}:{},...e.observada!=null?{escalationRate:Rn(e.observada),escalationSamples:e.muestras}:{},...n,requestedModel:e.modeloPedido}}informeDeDiferido(e,n,r,o=false){if(e.deferrable!==true)return;let i=gr(
|
|
1382
|
+
n),s=i?.origen??null,a=n.servedServiceTier;if(o)return {...bt(this.config.provider)!==void 0?{requestedTier:Mt}:{},...a?{servedTier:a}:{},credited:false,capacityFallback:true,creditedLedger:"none",latency:"\
|
|
1383
|
+
the cheaper tier refused the request for lack of capacity, and it was repeated once at the standard tier: the wait is the refused attempt plus a standard-tier call.",reason:'the cheaper tier had no ca\
|
|
1384
|
+
pacity (HTTP 429 or 503), so, as configured with priceLevers.onCapacityError: "standard", the request was repeated once at the standard tier and price; the refused attempt is not counted as a call and\
|
|
1385
|
+
nothing is credited'};let c=n.requestedServiceTier,u={...c?{requestedTier:c}:{},...a?{servedTier:a}:{},credited:false,creditedLedger:"none",latency:rc(c,s),reason:""};if(!c)return {...u,reason:nc};let l=this.
|
|
1386
|
+
precioDelCliente(r),d=fr({modelo:r,uso:n.usage,tierServido:a,origen:s,...i?.tierLeidoDe?{tierLeidoDe:i.tierLeidoDe}:{},...l?{precioDelCliente:l}:{},ahoraMs:this.now()});if(!d.ok){let p=d.motivo==="no-\
|
|
1387
|
+
tier-price"&&s==="openai"&&tc(r,s,this.now())?"; this model's deferred discount is published for the provider's batch API instead: send such requests with layer.batches.submit()":"";return {...u,reason:Gh(
|
|
1388
|
+
d.motivo,c,a)+p}}return {...u,credited:true,discountRate:Rn(d.factorEfectivo),estimatedTierSaving:d.importe,tierSaving:{amount:d.importe,basis:d.basis,standardCost:St(d.costeEstandar),appliedCost:St(d.costeAplicado),
|
|
1389
|
+
pricesCheckedOn:d.consultado,basisReason:d.motivoBasis},reason:`the provider reports serving the "${a}" tier; this call's usage was priced at the standard and at the "${a}" published rate cards, compo\
|
|
1390
|
+
nent by component (${(d.factorEfectivo*100).toFixed(1)}% of standard). The discount stacks with provider prefix caching rather than replacing it`}}informeDeEscrituras(e,n,r,o,i,s,a=false){if(e.standalone!==
|
|
1391
|
+
true&&!a)return;let c=n?.cacheExplicita;if(!c){let f=bt(this.config.provider),v="the provider chose where to write its prompt cache, as it does by default";return {mode:"provider-default",breakpoints:0,reason:gt(
|
|
1392
|
+
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-cache control only exists on Op\
|
|
1393
|
+
enAI'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}" is not an OpenAI model\
|
|
1394
|
+
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 continuations of this traffic withi\
|
|
1395
|
+
n 30 minutes were measured below the write premium's break-even (see the prefix-cache-placement trace). `:"")+"Trade-off: repeats and continuations of this exact prompt lose the cache reads the provid\
|
|
1396
|
+
er default would have given them.",d=u===1?"explicit mode: the provider wrote its prompt cache only at the end of the stable prefix, so the rest of this request was billed at the input rate with no ca\
|
|
1397
|
+
che-write charge. "+l:(s?"explicit mode with no breakpoint: the message at the prefix boundary cannot carry one":"explicit mode with no breakpoint: there was no stable prefix worth writing, or the mea\
|
|
1398
|
+
sured hit rate on it did not pay for the write premium")+", so the provider neither wrote nor read its prompt cache for this request. "+l,p=o?hn("openai",o,i,this.now()):void 0,h=lr(i),m=p&&p.cacheWritePer1k!==
|
|
1399
|
+
void 0?{inputPer1k:p.inputPer1k,cacheWritePer1k:p.cacheWritePer1k,consultado:p.consultado}:h?{inputPer1k:h.inputPer1k,cacheWritePer1k:h.cacheWritePer1k,consultado:void 0}:void 0;if(!m||r.complete===false)
|
|
1400
|
+
return {mode:"explicit",breakpoints:u,reason:d};let g=ic({uso:r,fila:{inputPer1k:m.inputPer1k,cacheWritePer1k:m.cacheWritePer1k},...m.consultado?{consultado:m.consultado}:{}});return {mode:"explicit",breakpoints:u,
|
|
1401
|
+
avoidedWritePremium:{amount:g.importe,basis:"estimated",standardCost:St(g.costeEstandar),appliedCost:St(g.costeAplicado),pricesCheckedOn:g.consultado,basisReason:g.tokensOrdinarios>0&&r.inputTokens>=1024?
|
|
1402
|
+
"estimated: the provider default was not run for this request. This is the write premium the default would have charged on the tokens after the last breakpoint; it does not subtract the cache reads th\
|
|
1403
|
+
e default could have given a later repeat":"estimated: below the provider's minimum cacheable length (or with nothing written past the breakpoint) the default would not have charged a write premium ei\
|
|
1404
|
+
ther"},reason:d}}escriturasSinLlamada(e){if(e.savings?.standalone===true)return {mode:"provider-default",breakpoints:0,reason:"no provider call was made, so nothing was written to or read from the provid\
|
|
1405
|
+
er's prompt cache for this request"}}respaldaFaltaDeCapacidad(e,n,r){return e.deferrable!==true||r!==null||this.config.priceLevers?.onCapacityError!=="standard"||bt(this.config.provider)===void 0?false:n instanceof
|
|
1406
|
+
Error&&/^provider (429|503)\b/.test(n.message)}diferidoSinLlamada(e){if(e.savings?.deferrable===true)return {credited:false,creditedLedger:"none",latency:"not applicable: no provider call was made for this \
|
|
1407
|
+
request.",reason:"no provider call was made, so no processing tier was served and none is credited; the call was avoided outright, which is worth more than any tier discount on it"}}finish(e,n,r,o,i,s,a,c,u,l,d,p,h="\
|
|
1408
|
+
none",m=0,g,f,v,b,y){let k=e.response?.schema,T,x=p===null?null:p??(k?(()=>{let A=he(r.data,k);return T={resultado:A.valid?"passed":"failed",errores:A.errors.length,desenvuelto:false},A.valid})():true),P=T&&
|
|
1409
|
+
!y?.validacion?{...y,validacion:T}:y,M=this.buildReport(e,n,o,i,s,a,c,u,l,d,x,h,m,g,f??this.diferidoSinLlamada(e),v,b??this.escriturasSinLlamada(e),P);return {requestId:M.requestId,data:r.data,text:r.text,
|
|
1410
|
+
...r.rendered!==void 0?{rendered:r.rendered}:{},report:M}}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(),T=m!=null&&m.servedModel!==m.requestedModel;return {requestId:f??
|
|
1411
|
+
this.generateId(),model:m?.servedModel??e.model,calls:{baselineLlm:o.baselineLlm,actualLlm:o.actualLlm,avoidedLlm:o.avoidedLlm,baselineRetrieval:o.baselineRetrieval,actualRetrieval:o.actualRetrieval,baselineTools:o.
|
|
1412
|
+
baselineTools,actualTools:o.actualTools,retries:o.retries},tokens:{baselineInput:o.baselineInput,actualInput:o.actualInput,eliminatedInput:o.eliminatedInput,compressedInput:o.compressedInput,baselineOutput:o.
|
|
1413
|
+
publishedBaselineOutput,actualOutput:o.actualOutput,eliminatedOutput:o.eliminatedOutput,...o.providerCachedInput?{providerCachedInput:o.providerCachedInput}:{}},cache:{result:r,...l!==void 0?{confidence:l}:
|
|
1414
|
+
{},...u!==void 0?{ageMs:u}:{},...o.reference?{reference:{...o.reference}}:{},...o.referenceRejected?{referenceRejected:o.referenceRejected}:{}},routing:{executionClass:a.executionClass,confidence:a.confidence,
|
|
1415
|
+
rounds:o.actualRetrieval,reason:a.reason},serialization:{chosen:c.chosen,candidateTokens:c.candidateTokens,instructionOverheadTokens:c.instructionOverheadTokens},...o.compressionReport?{compression:o.
|
|
1416
|
+
compressionReport}:{},constraints:{backend:p,schemaVersion:n.schemaVersion,...d===null?{}:{structurallyValid:d}},qualityStatus:Kh(r,d,T),qualityLedger:kl({cacheResult:r,structurallyValid:d,backend:p,hayEsquema:e.
|
|
1417
|
+
response?.schema!=null,ageMs:u,cascada:m,hechos:b}),...m?{modelCascade:m}:{},...g?{deferred:g}:{},...v?{cacheWrites:v}:{},quality:{...r!=="miss"?{freshnessPassed:!Jn(n).requiresFreshData}:{},...r==="s\
|
|
1418
|
+
emantic"&&b?.semantico?{semanticScore:b.semantico.similarity}:{}},cost:y,latencyMs:{total:k,preprocessing:Math.max(0,k-h),provider:h},traces:s.all()}}async failOpenDirect(e,n){let r=new vn(this.now);r.
|
|
1419
|
+
record("fail-open","internal optimizer error \u2014 bypassed to a direct provider call",{error:n instanceof Error?n.message:String(n)});let o=new At,i=this.costModelFor(e.model),s;try{s=jo(e);}catch{s=
|
|
1420
|
+
{schemaVersion:e.response?.version??e.response?.contractId??"none"};}let a=e.response?.schema,c=[...e.messages];e.structuredData!==void 0&&An(c,{role:"system",content:JSON.stringify(e.structuredData)});
|
|
1421
|
+
let u=this.now(),l=await this.config.provider.generate({model:e.model,messages:c,...e.tools?.length?{tools:e.tools}:{},...a?{schema:a}:{},...J(e)!=null?{maxOutputTokens:J(e)}:{},...e.temperature!=null?
|
|
1422
|
+
{temperature:e.temperature}:{},...e.seed!=null?{seed:e.seed}:{}}),d=this.now()-u;o.baselineLlm=1,o.actualLlm=1,o.actualInput=l.usage.inputTokens,o.actualOutput=l.usage.outputTokens,o.baselineInput=l.usage.
|
|
1423
|
+
inputTokens,o.baselineOutput=l.usage.outputTokens,l.usage.cachedInputTokens&&o.providerCached(l.usage.cachedInputTokens),l.unbilledRefusal===true&&(o.unbilledCall(l.usage),o.servedUnbilledRefusal=true);let p=fn(
|
|
1424
|
+
e.model);p>1&&l.unbilledRefusal!==true&&(l.usage.cacheWriteInputTokens??0)>0&&o.providerCacheWritePremium(l.usage.cacheWriteInputTokens??0,p,i),l.usage.complete===false&&(o.callsWithoutUsage=1);let h=l.text,
|
|
1425
|
+
m=true,g={origen:"fail_open",final:{...l.finishReason!==void 0?{finishReason:l.finishReason}:{},...J(e)!=null?{topeDelLlamante:J(e)}:{}}},f=(l.toolCalls?.length??0)>0;if(f&&(m=null),a&&!f){let b=We(l.text),
|
|
1426
|
+
y=b.ok?he(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(e,s,"miss",o,i,r,Dn(),_n(),void 0,void 0,m,"\
|
|
1427
|
+
none",d,void 0,e.savings?.deferrable===true?{credited:false,creditedLedger:"none",latency:"unchanged: the fail-open path asks for no processing tier, so this request was scheduled exactly as an ordinary on\
|
|
1428
|
+
e.",reason:"the optimizer failed and this request went out on the direct fail-open path, which asks for no cheaper tier: that tier can be refused for lack of capacity, and trading availability for a d\
|
|
1429
|
+
iscount 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 failed and this request went out unchanged on t\
|
|
1430
|
+
he 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.text,...f?{toolCalls:l.toolCalls}:{},...l.
|
|
1431
|
+
finishReason!==void 0?{finishReason:l.finishReason}:{},...l.refusal!==void 0?{refusal:l.refusal}:{},report:v}}asCoalescedFollower(e,n,r,o,i,s={ok:false,reason:"absent"}){let a=new At;this.negativasSinCobro.
|
|
1432
|
+
has(e)&&(a.servedUnbilledRefusal=true),s.ok?a.avoidCallByReference(s.credit):(a.avoidCall(n,r),a.referenceRejected=s.reason);let c=a.estimateCost(o),u=this.generateId(),l=this.diferidoSinLlamada(i),d=l?
|
|
1433
|
+
{deferred:l}:{},p=this.escriturasSinLlamada(i),{deferred:h,streaming:m,cacheWrites:g,...f}=e.report;return {...e,requestId:u,report:{...f,requestId:u,calls:{...e.report.calls,actualLlm:0,avoidedLlm:1},
|
|
1434
|
+
tokens:{baselineInput:a.baselineInput,actualInput:a.actualInput,eliminatedInput:a.eliminatedInput,compressedInput:a.compressedInput,baselineOutput:a.publishedBaselineOutput,actualOutput:a.actualOutput,
|
|
1435
|
+
eliminatedOutput:a.eliminatedOutput,...a.providerCachedInput?{providerCachedInput:a.providerCachedInput}:{}},cache:{result:"singleflight",...a.reference?{reference:{...a.reference}}:a.referenceRejected?
|
|
1436
|
+
{referenceRejected:a.referenceRejected}:{}},...d,...p?{cacheWrites:p}:{},qualityLedger:xl(e.report.qualityLedger),cost:c}}}creditoPorReferencia(e,n){if(typeof e=="string")return {ok:false,reason:e};let r;
|
|
1437
|
+
try{r=n.calidad();}catch{r=false;}try{return yl(e,{ahoraMs:this.now(),modeloPedido:n.request.model,modeloServido:n.cascada.modeloServido,huella:n.huella(),textoServidoSha256:ne(n.texto),claveLeida:n.claveLeida,
|
|
1438
|
+
calidadOk:r,precio:this.precioDocumentado(n.request.model),determinista:gl(n.request),salidaDelModelo:Nu(n.request.model),topeDeSalida:J(n.request),diferible:n.toggles.deferrable===!0})}catch{return {ok:false,
|
|
1439
|
+
reason:"different-request"}}}assembleBaselinePrompt(e){return this.assemblePromptText(e.messages,e.tools,e.structuredData)}assemblePromptText(e,n,r){let o=e.map(i=>i.content);r!==void 0&&o.push(JSON.stringify(
|
|
1440
|
+
r));for(let i of n??[])o.push(so(i));return o.join(`
|
|
1362
1441
|
`)}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;
|
|
1363
1442
|
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(
|
|
1364
|
-
e)}precioConocido(e,n=this.now()){return this.precioDelCliente(e)??
|
|
1365
|
-
slice(o+1)];if(i)return i}}precioDocumentado(e){return this.precioDelCliente(e)??
|
|
1443
|
+
e)}precioConocido(e,n=this.now()){return this.precioDelCliente(e)??Vn(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.
|
|
1444
|
+
slice(o+1)];if(i)return i}}precioDocumentado(e){return this.precioDelCliente(e)??Ze(e,this.now())}costModelFor(e,n=this.now()){let r=this.precioConocido(e,n);return r||(this.config.defaultCostModel?this.
|
|
1366
1445
|
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. \
|
|
1367
|
-
Pass { costModels: { "${e}": { inputPer1k, outputPer1k } } }.`)
|
|
1368
|
-
n.value,t.schema).valid?"met":"missed"}function
|
|
1369
|
-
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=
|
|
1370
|
-
e.push(i);}return e}function
|
|
1371
|
-
n)o+=1;else if(c===r&&(o-=1,o===0))return t.slice(e,a+1)}}function
|
|
1372
|
-
dation";switch(t){case "deterministic":case "exact":return "exact";case "semantic":return "task_equivalent";default:return "not_verified"}}function
|
|
1446
|
+
Pass { costModels: { "${e}": { inputPer1k, outputPer1k } } }.`),$u))}};function Uh(t,e){if((e.toolCalls?.length??0)>0||!t.schema)return "none";let n=We(typeof e.text=="string"?e.text:"");return n.ok&&he(
|
|
1447
|
+
n.value,t.schema).valid?"met":"missed"}function We(t){try{return {ok:!0,value:JSON.parse(t)}}catch{}for(let e of Hh(t))try{return {ok:!0,value:JSON.parse(e),rescatado:e}}catch{continue}return {ok:false}}function Hh(t){
|
|
1448
|
+
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=Wh(t,o);i&&
|
|
1449
|
+
e.push(i);}return e}function Wh(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===
|
|
1450
|
+
n)o+=1;else if(c===r&&(o-=1,o===0))return t.slice(e,a+1)}}function Jh(t){return typeof t=="string"?t:JSON.stringify(t,null,2)}function Kh(t,e,n=false){if(e===false)return "rejected";if(n)return "bounded_degra\
|
|
1451
|
+
dation";switch(t){case "deterministic":case "exact":return "exact";case "semantic":return "task_equivalent";default:return "not_verified"}}function Gh(t,e,n){switch(t){case "no-served-tier":return `asked the \
|
|
1373
1452
|
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\
|
|
1374
1453
|
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\
|
|
1375
1454
|
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\
|
|
1376
1455
|
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\
|
|
1377
1456
|
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\
|
|
1378
|
-
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
|
|
1379
|
-
round(t*1e6)/1e6}function
|
|
1380
|
-
return
|
|
1381
|
-
return false;let n=t.original;return
|
|
1382
|
-
reason:"n/a (short-circuited)",rounds:0}}function
|
|
1457
|
+
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 Rn(t){return Math.
|
|
1458
|
+
round(t*1e6)/1e6}function St(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}function Zh(t,e,n,r){if(e)return St(-t.extraCostUsd);let o=i=>t.actualInput/1e3*i.inputPer1k+t.actualOutput/1e3*i.outputPer1k;
|
|
1459
|
+
return St(o(r)-o(n))}function Yh(t,e){if(!(e>0))return false;if(e>=1)return true;let n=ne(`${t}:cascade-sample`);return Number.parseInt(n.slice(0,13),16)/2**52<e}function $l(t,e){if(!e.isAgentic||e.allowSemanticCache)
|
|
1460
|
+
return false;let n=t.original;return Jn({...t,original:{...n,savings:{...n.savings??{},semanticCache:"include-agentic"}}}).allowSemanticCache}function Dn(){return {executionClass:"NO_RETRIEVAL",confidence:1,
|
|
1461
|
+
reason:"n/a (short-circuited)",rounds:0}}function _n(){return {chosen:"json-compact",encoded:"",instruction:"",candidateTokens:{},instructionOverheadTokens:0,reason:"no structured payload"}}function Is(t,e="",n=null){
|
|
1383
1462
|
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");
|
|
1384
1463
|
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!=
|
|
1385
|
-
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=
|
|
1386
|
-
f&&o.push(f);}if(r.items!==void 0){let m=
|
|
1387
|
-
0,200):""}function
|
|
1388
|
-
test(e.message))}function
|
|
1389
|
-
for(let n=t.length-1;n>=0;n--)if(t[n].role==="user"){t.splice(n,0,e);return}t.push(e);}function
|
|
1390
|
-
if(e){let n=0;for(;n<t.length&&t[n].role==="system";)n+=1;return n}for(let n=t.length-1;n>=0;n--)if(t[n].role==="user")return n;return
|
|
1391
|
-
function
|
|
1392
|
-
return {submit:(e,n)=>
|
|
1464
|
+
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=Is(g,e?`${e}.${m}`:m,n);
|
|
1465
|
+
f&&o.push(f);}if(r.items!==void 0){let m=Is(r.items,`${i} entries`,n);m&&o.push(m);}return o.join("; ")}function In(t){let e=t.response;return e?e.contractId??e.version??JSON.stringify(e.schema??{}).slice(
|
|
1466
|
+
0,200):""}function jl(t){return t.finishReason==="content_filter"||typeof t.refusal=="string"&&t.refusal!==""}function Qh(t){return t.some(e=>/exceeds maxItems|exceeds maxLength|match pattern|exceeds maximum|below minimum|below minLength|below minItems/.
|
|
1467
|
+
test(e.message))}function so(t){return JSON.stringify({type:"function",function:{name:t.id,...t.description?{description:t.description}:{},parameters:t.parameters??{type:"object",properties:{}}}})}function An(t,e){
|
|
1468
|
+
for(let n=t.length-1;n>=0;n--)if(t[n].role==="user"){t.splice(n,0,e);return}t.push(e);}function Xh(t,e){if(e===false)return null;let n=typeof t=="object"&&t!==null?t:{};return e===true||t?n:null}function As(t,e=false){
|
|
1469
|
+
if(e){let n=0;for(;n<t.length&&t[n].role==="system";)n+=1;return n}for(let n=t.length-1;n>=0;n--)if(t[n].role==="user")return n;return As(t,true)}function Nl(t){return t instanceof Error?t.name:typeof t}
|
|
1470
|
+
function _s(t,e){let n=to(t,e);return n.cacheReadMultiplier<1?n:null}var zl={anthropic:{peticiones:1e5,bytes:256e6},openai:{peticiones:5e4,bytes:2e8}},eg=/^[A-Za-z0-9_-]{1,64}$/,Vl="/v1/chat/completions",tg=new Set(["completed","failed","expired","cancelled"]);function Ul(t){
|
|
1471
|
+
return {submit:(e,n)=>ng(t,e,n??{}),status:(e,n)=>ug(t,e,n?.signal),results:(e,n)=>fg(t,e,n?.signal),cancel:(e,n)=>pg(t,e,n?.signal)}}function po(t){let e=vc(t.provider);if(!e)throw new Error("[bvsala]\
|
|
1393
1472
|
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===
|
|
1394
1473
|
"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\
|
|
1395
|
-
ini's own Files API). Nothing was sent.");return e}async function
|
|
1396
|
-
anthropic",s=new TextEncoder,a=e.map(({customId:m,request:g})=>{let f;try{f=r.cuerpo(
|
|
1397
|
-
params:f}:{custom_id:m,method:"POST",url:
|
|
1474
|
+
ini's own Files API). Nothing was sent.");return e}async function ng(t,e,n){t.exigirLicencia();let r=po(t);rg(e);let o=og(n.maxRequestsPerBatch,r.protocolo),i=n.cacheSharedPrefix===true&&r.protocolo==="\
|
|
1475
|
+
anthropic",s=new TextEncoder,a=e.map(({customId:m,request:g})=>{let f;try{f=r.cuerpo(ig(g,i));}catch(y){throw new TypeError(`[bvsala] batch request "${m}": ${co(y)}`)}let v=r.protocolo==="anthropic"?{custom_id:m,
|
|
1476
|
+
params:f}:{custom_id:m,method:"POST",url:Vl,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=sg(a,r.protocolo,o),u=[],
|
|
1398
1477
|
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,
|
|
1399
1478
|
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(
|
|
1400
|
-
t.now()).toISOString(),requests:p,schemas:u};for(let m=0;m<c.length;m++)try{let g=r.protocolo==="anthropic"?await
|
|
1401
|
-
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
|
|
1402
|
-
provider batch was created: ${
|
|
1403
|
-
.`,v,b,{cause:g})}return h}function
|
|
1404
|
-
n,r]of t.entries()){let o=r?.customId;if(typeof o!="string"||!
|
|
1479
|
+
t.now()).toISOString(),requests:p,schemas:u};for(let m=0;m<c.length;m++)try{let g=r.protocolo==="anthropic"?await ag(r,c[m],n.signal):await cg(r,c[m],n.signal);h.batchIds.push(g);}catch(g){let f=h.batchIds.
|
|
1480
|
+
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 Jr(f===0?`[bvsala] batch submission failed before any \
|
|
1481
|
+
provider batch was created: ${co(g)}.`:`[bvsala] batch submission failed after ${f} of ${c.length} provider batches were created: ${co(g)}. The created batches run and are billed; error.job holds them\
|
|
1482
|
+
.`,v,b,{cause:g})}return h}function rg(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[
|
|
1483
|
+
n,r]of t.entries()){let o=r?.customId;if(typeof o!="string"||!eg.test(o))throw new TypeError(`[bvsala] batch request #${n}: customId must be 1 to 64 letters, digits, "_" or "-" (got ${JSON.stringify(o)}\
|
|
1405
1484
|
).`);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.
|
|
1406
1485
|
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\
|
|
1407
1486
|
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]\
|
|
1408
|
-
batch request "${o}": structuredData is serialized by the layer's pipeline, which batches skip. Put the payload in the messages instead.`)}}function
|
|
1409
|
-
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
|
|
1410
|
-
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
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1487
|
+
batch request "${o}": structuredData is serialized by the layer's pipeline, which batches skip. Put the payload in the messages instead.`)}}function og(t,e){let n=zl[e].peticiones;if(t===void 0)return n;
|
|
1488
|
+
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 ig(t,e){let n=0;for(;n<t.messages.length&&
|
|
1489
|
+
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}:{},...J(t)!=null?{maxOutputTokens:J(
|
|
1490
|
+
t)}:{},...t.temperature!=null?{temperature:t.temperature}:{},...t.seed!=null?{seed:t.seed}:{},...e&&n>0?{stablePrefixMessages:n}:{}}}function sg(t,e,n){let r=zl[e],o=new Map;for(let a of t){let c=e===
|
|
1491
|
+
"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+d>r.bytes)throw new TypeError(`[bvsa\
|
|
1492
|
+
la] 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)&&(s.push(c),c=[],u=i),c.push(l),
|
|
1493
|
+
u+=d;}c.length>0&&s.push(c);}return s}async function ag(t,e,n){let r=await On(t,"/messages/batches",{method:"POST",json:{requests:e.map(o=>o.linea)},...n?{signal:n}:{}});return Ls(r,"Message Batch")}async function cg(t,e,n){
|
|
1494
|
+
let r=e.map(a=>JSON.stringify(a.linea)).join(`
|
|
1416
1495
|
`)+`
|
|
1417
|
-
`,o=new FormData;o.append("purpose","batch"),o.append("file",new Blob([r],{type:"application/jsonl"}),"bvsala-batch.jsonl");let i=await
|
|
1418
|
-
t,"/batches",{method:"POST",json:{input_file_id:
|
|
1419
|
-
r);let o=await
|
|
1420
|
-
o).length;r.push(t.protocolo==="anthropic"?
|
|
1421
|
-
estado:r,terminado:r==="ended",cancelando:r==="canceling",cuentas:{processing:
|
|
1422
|
-
let r=
|
|
1423
|
-
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(
|
|
1424
|
-
map(h=>
|
|
1425
|
-
{},...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
|
|
1496
|
+
`,o=new FormData;o.append("purpose","batch"),o.append("file",new Blob([r],{type:"application/jsonl"}),"bvsala-batch.jsonl");let i=await On(t,"/files",{method:"POST",form:o,...n?{signal:n}:{}}),s=await On(
|
|
1497
|
+
t,"/batches",{method:"POST",json:{input_file_id:Ls(i,"file"),endpoint:Vl,completion_window:"24h"},...n?{signal:n}:{}});return Ls(s,"batch")}async function ug(t,e,n){t.exigirLicencia();let r=po(t);$s(e,
|
|
1498
|
+
r);let o=await uo(r,e,n);return Hl(e,o)}async function uo(t,e,n){let r=[];for(let[o,i]of e.batchIds.entries()){let s=await On(t,js(t,i),{method:"GET",...n?{signal:n}:{}}),a=e.requests.filter(c=>c.batch===
|
|
1499
|
+
o).length;r.push(t.protocolo==="anthropic"?lg(i,s):dg(i,s,a));}return r}function lg(t,e){let n=ce(e),r=typeof n.processing_status=="string"?n.processing_status:"unknown",o=ce(n.request_counts);return {id:t,
|
|
1500
|
+
estado:r,terminado:r==="ended",cancelando:r==="canceling",cuentas:{processing:lt(o.processing),succeeded:lt(o.succeeded),errored:lt(o.errored),canceled:lt(o.canceled),expired:lt(o.expired)}}}function dg(t,e,n){
|
|
1501
|
+
let r=ce(e),o=typeof r.status=="string"?r.status:"unknown",i=ce(r.request_counts),s=lt(i.total)||n,a=lt(i.completed),c=lt(i.failed),u=Math.max(0,s-a-c),l=tg.has(o),d=o==="failed"?{processing:0,succeeded:0,
|
|
1502
|
+
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(ce(r.errors).data)?ce(r.errors).data.
|
|
1503
|
+
map(h=>ce(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}:
|
|
1504
|
+
{},...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 Hl(t,e){let n={
|
|
1426
1505
|
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,
|
|
1427
1506
|
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.
|
|
1428
|
-
estado}))}}async function
|
|
1429
|
-
{}});return
|
|
1430
|
-
r,`${
|
|
1431
|
-
ntent`,{method:"GET",...n?{signal:n}:{}});for await(let p of
|
|
1432
|
-
continue}let d=u.schema!==void 0?e.schemas[u.schema]:void 0;a.push(
|
|
1433
|
-
if(typeof r!="string"||t.has(r))return;let o=
|
|
1507
|
+
estado}))}}async function pg(t,e,n){t.exigirLicencia();let r=po(t);$s(e,r);let o=await uo(r,e,n);for(let i of o)i.terminado||i.cancelando||await On(r,`${js(r,i.id)}/cancel`,{method:"POST",...n?{signal:n}:
|
|
1508
|
+
{}});return Hl(e,await uo(r,e,n))}async function fg(t,e,n){t.exigirLicencia();let r=po(t);$s(e,r);let o=await uo(r,e,n),i=new Map;for(let u of o)if(u.terminado)if(r.protocolo==="anthropic"){let l=await Ms(
|
|
1509
|
+
r,`${js(r,u.id)}/results`,{method:"GET",...n?{signal:n}:{}});for await(let d of ql(l))mg(i,d);}else for(let l of [u.salida,u.errores]){if(!l)continue;let d=await Ms(r,`/files/${encodeURIComponent(l)}/co\
|
|
1510
|
+
ntent`,{method:"GET",...n?{signal:n}:{}});for await(let p of ql(d))hg(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;
|
|
1511
|
+
continue}let d=u.schema!==void 0?e.schemas[u.schema]:void 0;a.push(gg(t,r,u,d,i.get(u.customId),l,s));}return {ended:o.every(u=>u.terminado),items:a,summary:yg(e,a,c)}}function mg(t,e){let n=ce(e),r=n.custom_id;
|
|
1512
|
+
if(typeof r!="string"||t.has(r))return;let o=ce(n.result);switch(o.type){case "succeeded":t.set(r,{tipo:"ok",cuerpo:o.message});return;case "errored":{let i=ce(ce(o.error).error);t.set(r,{tipo:"errored",
|
|
1434
1513
|
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":
|
|
1435
|
-
t.set(r,{tipo:"expired"});return;default:return}}function
|
|
1514
|
+
t.set(r,{tipo:"expired"});return;default:return}}function hg(t,e){let n=ce(e),r=n.custom_id;if(typeof r!="string"||t.has(r))return;let o=n.error;if(o!=null){let u=ce(o),l=typeof u.code=="string"?u.code:
|
|
1436
1515
|
"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.
|
|
1437
|
-
message=="string"?u.message:"the provider reported an error"}});return}let i=
|
|
1438
|
-
let c=
|
|
1439
|
-
rror"}});}function
|
|
1516
|
+
message=="string"?u.message:"the provider reported an error"}});return}let i=ce(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}
|
|
1517
|
+
let c=ce(ce(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\
|
|
1518
|
+
rror"}});}function gg(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\
|
|
1440
1519
|
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\
|
|
1441
1520
|
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:"\
|
|
1442
1521
|
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\
|
|
1443
1522
|
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\
|
|
1444
1523
|
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\
|
|
1445
1524
|
-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"};}
|
|
1446
|
-
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 (${
|
|
1447
|
-
): nothing is credited`}}let d=
|
|
1525
|
+
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 (${co(b)}\
|
|
1526
|
+
): nothing is credited`}}let d=bg(l,r),p=c?l.servedServiceTier:"batch",h=e.origen==="anthropic"||e.origen==="openai"?e.origen:null,m=kg(t.costModels,n.model),g=fr({modelo:n.model,uso:l.usage,tierServido:p,
|
|
1448
1527
|
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?
|
|
1449
|
-
{finishReason:l.finishReason}:{},usage:l.usage,...p?{servedTier:p}:{}};if(!g.ok)return {...f,reason:
|
|
1528
|
+
{finishReason:l.finishReason}:{},usage:l.usage,...p?{servedTier:p}:{}};if(!g.ok)return {...f,reason:vg(g.motivo,p)};let v={amount:g.importe,basis:g.basis,standardCost:lo(g.costeEstandar),appliedCost:lo(
|
|
1450
1529
|
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\
|
|
1451
|
-
blished rate cards, component by component (${(g.factorEfectivo*100).toFixed(1)}% of standard)`}}function
|
|
1452
|
-
return n.ok?
|
|
1530
|
+
blished rate cards, component by component (${(g.factorEfectivo*100).toFixed(1)}% of standard)`}}function bg(t,e){if(!e||(t.toolCalls?.length??0)>0)return {};let n=We(typeof t.text=="string"?t.text:"");
|
|
1531
|
+
return n.ok?he(n.value,e).valid?{data:n.value,contract:"met"}:{contract:"missed"}:{contract:"missed"}}function vg(t,e){switch(t){case "no-served-tier":return "the provider reported no service tier for t\
|
|
1453
1532
|
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\
|
|
1454
1533
|
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 "\
|
|
1455
1534
|
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\
|
|
1456
1535
|
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\
|
|
1457
|
-
is credited";case "no-difference":return "this result's usage costs the same at both published rate cards: nothing is credited"}}var
|
|
1536
|
+
is credited";case "no-difference":return "this result's usage costs the same at both published rate cards: nothing is credited"}}var Fl=1e10;function yg(t,e,n){let r=0,o=0,i=0,s=0,a=0,c=0,u=0,l=0n,d=0,
|
|
1458
1537
|
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(
|
|
1459
|
-
Math.round(v.amount*
|
|
1538
|
+
Math.round(v.amount*Fl)),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\
|
|
1460
1539
|
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\
|
|
1461
1540
|
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,
|
|
1462
|
-
tierSaving:Number(l)/
|
|
1541
|
+
tierSaving:Number(l)/Fl,standardCost:lo(d),appliedCost:lo(p),basis:m,...h?{pricesCheckedOn:h}:{},creditedLedger:"none",reason:g}}function $s(t,e){let n=t;if(!n||n.kind!=="bvsala.batch"||n.version!==1||
|
|
1463
1542
|
!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] \
|
|
1464
1543
|
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 \
|
|
1465
|
-
layer's provider is ${e.protocolo} at ${e.endpoint}. Read it with a layer configured like the one that submitted it.`)}function
|
|
1466
|
-
e)}`:`/batches/${encodeURIComponent(e)}`}async function
|
|
1467
|
-
async function
|
|
1544
|
+
layer's provider is ${e.protocolo} at ${e.endpoint}. Read it with a layer configured like the one that submitted it.`)}function js(t,e){return t.protocolo==="anthropic"?`/messages/batches/${encodeURIComponent(
|
|
1545
|
+
e)}`:`/batches/${encodeURIComponent(e)}`}async function Ms(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}
|
|
1546
|
+
async function On(t,e,n){return await(await Ms(t,e,n)).json()}function Ls(t,e){let n=ce(t).id;if(typeof n!="string"||n==="")throw new Error(`the provider returned no ${e} id`);return n}async function*ql(t){
|
|
1468
1547
|
let e=t.body;if(!e||typeof e.getReader!="function"){for(let s of (await t.text()).split(`
|
|
1469
|
-
`)){let a=
|
|
1470
|
-
`);for(;c>=0;){let u=
|
|
1471
|
-
`);}}o+=r.decode();let i=
|
|
1472
|
-
"/");return r>=0?t[e.slice(r+1)]:void 0}function
|
|
1473
|
-
Error?t.message:String(t)}function
|
|
1474
|
-
e,this.pollIntervalMs=e.pollIntervalMs??
|
|
1475
|
-
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(){
|
|
1476
|
-
true,this.timer&&clearInterval(this.timer),this.timer=null,this.controller?.abort(),this.controller=null;}
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1548
|
+
`)){let a=Os(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(`
|
|
1549
|
+
`);for(;c>=0;){let u=Os(o.slice(0,c));u!==void 0&&(yield u),o=o.slice(c+1),c=o.indexOf(`
|
|
1550
|
+
`);}}o+=r.decode();let i=Os(o);i!==void 0&&(yield i);}function Os(t){let e=t.trim();if(e!=="")try{return JSON.parse(e)}catch{return}}function kg(t,e){if(!t)return;let n=t[e];if(n)return n;let r=e.indexOf(
|
|
1551
|
+
"/");return r>=0?t[e.slice(r+1)]:void 0}function ce(t){return typeof t=="object"&&t!==null?t:{}}function lt(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.floor(t):0}function co(t){return t instanceof
|
|
1552
|
+
Error?t.message:String(t)}function lo(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}function xg(t){try{let e=new URL(t);return e.username="",e.password="",e.search="",e.hash="",e.toString()}catch{return "the configured licenseServerUrl"}}var wg=36e5,Sg=7*86400,Tg=3e4,fo=class{opts;pollIntervalMs;refreshLeadSeconds;timer=null;enVuelo=false;parado=false;controller=null;credencialAvisada=new Set;currentExpiresAt;currentOrg;constructor(e){
|
|
1553
|
+
this.opts=e,this.pollIntervalMs=e.pollIntervalMs??wg,this.refreshLeadSeconds=e.refreshLeadSeconds??Sg;let n=qt(Ft(e.initialToken),e.publicKey);this.currentExpiresAt=n.signatureValid&&n.payload?n.payload.
|
|
1554
|
+
expires_at:0,this.currentOrg=n.signatureValid?n.payload?.org_id:void 0;}start(){this.timer||(this.checkNow(),this.timer=setInterval(()=>{this.checkNow();},this.pollIntervalMs),this.timer.unref?.());}stop(){
|
|
1555
|
+
this.parado=true,this.timer&&clearInterval(this.timer),this.timer=null,this.controller?.abort(),this.controller=null;}avisarCredencialRechazada(e){this.credencialAvisada.has(e)||(this.credencialAvisada.add(
|
|
1556
|
+
e),console.warn(`[bv-sala] automatic pickup of the renewed license is failing with HTTP ${e} at ${xg(this.opts.url)}. Check 'serviceAccountKey' (rotated? from another organization?) and 'licenseServer\
|
|
1557
|
+
Url': until this works, the token will NOT renew itself and the SDK will stop operating when the grace period ends. (This warning is not muted by 'silenceWarnings'.)`));}nowSeconds(){return Math.floor(
|
|
1558
|
+
(this.opts.now?this.opts.now():Date.now())/1e3)}async checkNow(){if(this.enVuelo||this.parado||this.currentExpiresAt-this.nowSeconds()>this.refreshLeadSeconds)return false;this.enVuelo=true;let e=new AbortController;
|
|
1559
|
+
this.controller=e;let n=setTimeout(()=>e.abort(),this.opts.requestTimeoutMs??Tg);n.unref?.();try{let o=await(this.opts.fetchImpl??globalThis.fetch.bind(globalThis))(this.opts.url,{signal:e.signal,headers:{
|
|
1560
|
+
authorization:`Bearer ${this.opts.serviceAccountKey}`,accept:"application/json"}});if(!o.ok)return (o.status===401||o.status===403||o.status===404)&&this.avisarCredencialRechazada(o.status),!1;this.credencialAvisada.
|
|
1561
|
+
clear();let i=await o.json();if(typeof i.token!="string")return !1;let s=Ft(i.token),a=qt(s,this.opts.publicKey);return !a.signatureValid||!a.payload||a.payload.expires_at<=this.currentExpiresAt||this.currentOrg&&
|
|
1562
|
+
a.payload.org_id!==this.currentOrg||this.opts.revocados?.snapshot().has(a.payload.jti)||this.parado?!1:(this.currentExpiresAt=a.payload.expires_at,this.currentOrg=a.payload.org_id,this.opts.onNewToken(
|
|
1563
|
+
s),!0)}catch{return false}finally{clearTimeout(n),this.controller===e&&(this.controller=null),this.enVuelo=false;}}};var Wl=2e3,Jl=200,Cg=200,Eg=10,Pg=1e7,Rg=5,Dg=48*3600*1e3,Ns=/^[A-Za-z0-9._:/-]{1,128}$/,Zt=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0,Mn=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=
|
|
1564
|
+
1e3;function _g(t,e={}){if(!Ns.test(t.requestId)||!Ns.test(t.requestedModel)||!Ns.test(t.servedModel)||typeof t.at!="number"||!Number.isFinite(t.at)||t.at<1e12)return null;let n=typeof e?.ahora=="numb\
|
|
1565
|
+
er"?e.ahora:Date.now();if(t.at>n+Dg)return null;let r=t.optimized;if(!Mn(r.cost)||!Zt(r.inputTokens)||!Zt(r.cachedInputTokens)||!Zt(r.outputTokens))return null;let o=t.prices;if(!Mn(o.inputPer1k)||!Mn(
|
|
1566
|
+
o.outputPer1k)||o.cachedInputPer1k!==void 0&&!Mn(o.cachedInputPer1k))return null;let i={basis:"verification",requestId:t.requestId,at:Math.floor(t.at),stratum:t.stratum,outcome:t.outcome,requestedModel:t.
|
|
1487
1567
|
requestedModel,servedModel:t.servedModel,cacheResult:t.cacheResult,optimizedCost:r.cost,optimizedInputTokens:r.inputTokens,optimizedCachedInputTokens:Math.min(r.cachedInputTokens,r.inputTokens),optimizedOutputTokens:r.
|
|
1488
|
-
outputTokens,inputPer1k:o.inputPer1k,...o.cachedInputPer1k!==void 0?{cachedInputPer1k:o.cachedInputPer1k}:{},outputPer1k:o.outputPer1k};if(t.outcome==="paired"){let s=t.naive;if(!s||!
|
|
1489
|
-
inputTokens)||!
|
|
1490
|
-
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
|
|
1491
|
-
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=
|
|
1492
|
-
push(n),this.pendientes.length>
|
|
1568
|
+
outputTokens,inputPer1k:o.inputPer1k,...o.cachedInputPer1k!==void 0?{cachedInputPer1k:o.cachedInputPer1k}:{},outputPer1k:o.outputPer1k};if(t.outcome==="paired"){let s=t.naive;if(!s||!Mn(s.cost)||!Zt(s.
|
|
1569
|
+
inputTokens)||!Zt(s.cachedInputTokens)||!Zt(s.outputTokens)||s.cachedInputTokens>s.inputTokens)return null;if(i.naiveCost=s.cost,i.naiveInputTokens=s.inputTokens,i.naiveCachedInputTokens=s.cachedInputTokens,
|
|
1570
|
+
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 mo=class{o;flushIntervalMs;pendientes=[];conteos=new Map;reintentos=[];inflight=null;timer;fallosSeguidos=0;ultimoFallo=Number.
|
|
1571
|
+
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=_g(e,{ahora:this.ahora()});}catch{n=null;}n&&(this.pendientes.
|
|
1572
|
+
push(n),this.pendientes.length>Wl&&this.pendientes.splice(0,this.pendientes.length-Wl),this.pendientes.length>=Jl&&this.flushSiToca());}flushSiToca(){return this.reintentos.length>0&&this.ahora()-this.
|
|
1493
1573
|
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();},
|
|
1494
1574
|
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();
|
|
1495
1575
|
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;
|
|
1496
|
-
if(this.pendientes.length===0&&this.conteos.size===0)return null;let n=this.pendientes.splice(0,
|
|
1497
|
-
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??
|
|
1498
|
-
fetch;if(e)for(let n=0;n<
|
|
1499
|
-
Bearer ${this.o.serviceAccountKey}`,"content-type":"application/json",[
|
|
1500
|
-
this.ahora(),this.reencolar(n),this.avisarDeFallo(`the server responded ${r.status}`),!1):r.status===401||r.status===403?(this.o.silenceWarnings||
|
|
1576
|
+
if(this.pendientes.length===0&&this.conteos.size===0)return null;let n=this.pendientes.splice(0,Jl),r=[];for(let[o,i]of this.conteos){if(r.length>=Cg)break;let[s="",a=""]=o.split("|"),c=Math.min(i,Pg);
|
|
1577
|
+
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??rn)(),samples:n,counts:r}}async hacerFlush(){let e=this.o.fetchImpl??globalThis.
|
|
1578
|
+
fetch;if(e)for(let n=0;n<Rg&&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:`\
|
|
1579
|
+
Bearer ${this.o.serviceAccountKey}`,"content-type":"application/json",[Un]:`sdk/${Be}`},body:JSON.stringify(n)});return r.ok?(this.fallosSeguidos=0,!0):r.status>=500?(this.fallosSeguidos++,this.ultimoFallo=
|
|
1580
|
+
this.ahora(),this.reencolar(n),this.avisarDeFallo(`the server responded ${r.status}`),!1):r.status===401||r.status===403?(this.o.silenceWarnings||we(`verification-auth-${r.status}`,`[bvsala] verificat\
|
|
1501
1581
|
ion 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):
|
|
1502
1582
|
(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 \
|
|
1503
1583
|
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.
|
|
1504
|
-
reintentos.unshift(e);this.reintentos.length>
|
|
1584
|
+
reintentos.unshift(e);this.reintentos.length>Eg;)this.reintentos.pop();}avisarDeFallo(e){if(this.o.silenceWarnings)return;let n=this.fallosSeguidos;n<3||(n-3)%12!==0||console.warn(`[bvsala] verificatio\
|
|
1505
1585
|
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,
|
|
1506
|
-
conteos:this.conteos.size,reintentos:this.reintentos.length}}};var
|
|
1586
|
+
conteos:this.conteos.size,reintentos:this.reintentos.length}}};var Ig=72*3600,Ag,Kl=new Set(Object.values(Hn).flatMap(t=>t.flatMap(e=>[e,`openai/${e}`]))),Gl="[bvsala] `gpt-tokenizer` is not installed, so token counts for OpenAI models are ESTIMATED with a built-\
|
|
1507
1587
|
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 \
|
|
1508
|
-
(`npm i gpt-tokenizer`) and the SDK loads it automatically.";function
|
|
1588
|
+
(`npm i gpt-tokenizer`) and the SDK loads it automatically.";function C1(t){let e=(h,m)=>{t.silenceWarnings!==true&&we(h,m);};t.licenseGate&&(e("licenseGate-ignorado","[bvsala] Ignoring the injected `lic\
|
|
1509
1589
|
enseGate`: in the published package a license is only accepted as a `licenseKey` verified against BiVelio's embedded public key. Get yours at https://savings.bivelio.com/dashboard/install"),t={...t,licenseGate:void 0});
|
|
1510
|
-
let r={...t,tokenizer:t.tokenizer??
|
|
1511
|
-
licenseServerUrl){let m=new
|
|
1512
|
-
b),isActive:()=>f.isActive(),status:()=>f.status(),reason:()=>f.reason()};let v=`${t.licenseServerUrl.replace(/\/+$/,"")}/licenses/revocations`;i=new
|
|
1590
|
+
let r={...t,tokenizer:t.tokenizer??Io},o=t.tokenizer==null&&t.exactTokenizer!==false?Ag??=Oo(Io).catch(()=>false):Promise.resolve(true),i,s;if(t.licenseKey&&!t.licenseGate){let h=Ru;if(t.
|
|
1591
|
+
licenseServerUrl){let m=new zt,g=b=>Ur(b,h,{revocation:m,...t.now?{now:t.now}:{},maxStalenessSeconds:t.licenseRevocation?.maxStalenessSeconds??Ig}),f=g(t.licenseKey);r.licenseGate={isEntitled:b=>f.isEntitled(
|
|
1592
|
+
b),isActive:()=>f.isActive(),status:()=>f.status(),reason:()=>f.reason()};let v=`${t.licenseServerUrl.replace(/\/+$/,"")}/licenses/revocations`;i=new Hr({url:v,publicKeyPem:h,snapshot:m,getRefreshAfter:()=>f.
|
|
1513
1593
|
refreshAfter?.(),...t.now?{nowSeconds:()=>Math.floor(t.now()/1e3)}:{},...t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.licensePollIntervalSeconds!=null?{pollIntervalSeconds:t.licensePollIntervalSeconds}:
|
|
1514
|
-
{},...t.silenceWarnings!=null?{silenceWarnings:t.silenceWarnings}:{},...t.licenseRevocation??{}}),i.start(),t.serviceAccountKey&&t.licenseRefresh?.enabled!==false&&(s=new
|
|
1594
|
+
{},...t.silenceWarnings!=null?{silenceWarnings:t.silenceWarnings}:{},...t.licenseRevocation??{}}),i.start(),t.serviceAccountKey&&t.licenseRefresh?.enabled!==false&&(s=new fo({url:`${t.licenseServerUrl.replace(
|
|
1515
1595
|
/\/+$/,"")}/api/license/current`,serviceAccountKey:t.serviceAccountKey,publicKey:h,initialToken:t.licenseKey,revocados:m,onNewToken:b=>{f=g(b);},...t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.now?
|
|
1516
1596
|
{now:t.now}:{},...t.licenseRefresh?.intervalMs!=null?{pollIntervalMs:t.licenseRefresh.intervalMs}:{},...t.licenseRefresh?.leadSeconds!=null?{refreshLeadSeconds:t.licenseRefresh.leadSeconds}:{}}),s.start());}else
|
|
1517
|
-
r.licenseGate=
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
t.
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
{},...t.metering?.
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
e
|
|
1535
|
-
|
|
1536
|
-
i
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
t)
|
|
1597
|
+
r.licenseGate=Mu(t.licenseKey,h,t.now);}t.cacheBreakpointStore&&t.cacheBreakpoints!=="auto"&&e("almacen-de-colocacion-sin-auto",'[bv-sala] `cacheBreakpointStore` was given but `cacheBreakpoints` is not\
|
|
1598
|
+
"auto", so the store is never read or written: it only holds the measurement of `cacheBreakpoints: "auto"`. Set `cacheBreakpoints: "auto"` to use it, or remove it.');let a=oo(t.verification);!a.activo&&
|
|
1599
|
+
a.motivo==="invalido"&&e("verificacion-invalida",Cl(t.verification));let c,u;if(a.activo){let h;if(t.serviceAccountKey&&t.metering?.enabled!==false)if(t.meteringUrl){let m=/^(.*)\/api\/metering\/usage\/?$/.
|
|
1600
|
+
exec(t.meteringUrl);m&&(h=`${m[1]}/api/metering/verification`);}else t.licenseServerUrl&&(h=`${t.licenseServerUrl.replace(/\/+$/,"")}/api/metering/verification`);if(!h&&!a.onCheck)e("verificacion-sin-d\
|
|
1601
|
+
estino",El);else {h&&t.serviceAccountKey&&(c=new mo({url:h,serviceAccountKey:t.serviceAccountKey,...t.meteringFetch?{fetchImpl:t.meteringFetch}:t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.now?{now:t.
|
|
1602
|
+
now}:{},...t.metering?.flushIntervalMs!=null?{flushIntervalMs:t.metering.flushIntervalMs}:{},...t.silenceWarnings!=null?{silenceWarnings:t.silenceWarnings}:{}}),c.start());let m=c;u={encolar:g=>m?.encolar(
|
|
1603
|
+
g),...m?{contar:(g,f)=>m.contar(g,f)}:{},enReposo:()=>m?.flushSiToca()},e(`verificacion-activa:${a.tasa}`,Tl(a.tasa));}}let l=new ao(r,u?{verificacion:u}:{}),d;if(t.serviceAccountKey&&t.metering?.enabled!==
|
|
1604
|
+
false){let h=t.meteringUrl??(t.licenseServerUrl?`${t.licenseServerUrl.replace(/\/+$/,"")}/api/metering/usage`:void 0);if(h||e("clave-de-servicio-sin-servidor",'[bvsala] `serviceAccountKey` is set but the\
|
|
1605
|
+
re is no `licenseServerUrl` (or `meteringUrl`): seat metering and automatic license renewal are OFF, so nothing will reach your dashboard and a renewed license will not be picked up. Add `licenseServe\
|
|
1606
|
+
rUrl: "https://savings.bivelio.com"` \u2014 or drop `serviceAccountKey` for a zero-network deployment.'),h){d=new Cn({url:h,serviceAccountKey:t.serviceAccountKey,surface:"sdk",...t.metering?.orgId?{orgId:t.
|
|
1607
|
+
metering.orgId}:{},...t.metering?.flushIntervalMs!=null?{flushIntervalMs:t.metering.flushIntervalMs}:{},...t.metering?.maxBatch!=null?{maxBatch:t.metering.maxBatch}:{},...t.metering?.maxBuffer!=null?{
|
|
1608
|
+
maxBuffer:t.metering.maxBuffer}:{},...t.meteringFetch?{fetchImpl:t.meteringFetch}:t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.now?{now:t.now}:{},...t.metering?.ci!=null?{ci:t.metering.ci}:{},...t.
|
|
1609
|
+
silenceWarnings!=null?{silenceWarnings:t.silenceWarnings}:{}});let m=t.metering?.ci??ts();if(t.metering?.seatId)d.setSeat(t.metering.seatId,m);else {let g=d;ns(t.serviceAccountKey).then(f=>g.setSeat(f,
|
|
1610
|
+
m)).catch(()=>{});}d.start();}}return {batches:Ul({provider:r.provider,...r.costModels?{costModels:r.costModels}:{},exigirLicencia:()=>l.exigirLicencia(),now:r.now??Date.now}),generate:async h=>{let m=await o,
|
|
1611
|
+
g=await l.generate(h);if(!m&&Kl.has(h.model)&&e("tokenizador-exacto-ausente",Gl),d)try{d.record(g.report);}catch{}return g},generateStream:(h,m)=>{let g=l.generateStream(h,m??{},o);return g.result.then(
|
|
1612
|
+
async f=>{if(d)try{d.record(f.report);}catch{}!await o&&Kl.has(h.model)&&e("tokenizador-exacto-ausente",Gl);},()=>{}),g},close:()=>{l.cerrarVerificacion(),c?.stop(),i?.stop(),s?.stop(),d?.stop();}}}function Bs(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.
|
|
1613
|
+
toFixed(10).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"");return e==="-0"?"0":e}function Zl(t,e){if(t==null)return "";if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`[bvsala] toCsv: \
|
|
1614
|
+
column "${e}" holds a non-finite number`);return Bs(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\
|
|
1615
|
+
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 Og(t,e){
|
|
1616
|
+
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=>Zl(o,o)).join(",")];for(let o of t)r.push(n.map(
|
|
1617
|
+
i=>Zl(o[i],i)).join(","));return r.map(o=>`${o}\r
|
|
1618
|
+
`).join("")}var Yl={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:"\
|
|
1619
|
+
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 Ql(t){let e=t.
|
|
1620
|
+
indexOf("/");return e>0?t.slice(0,e):void 0}function Fs(t){let e=Ql(t)?.toLowerCase();return e!==void 0&&Object.hasOwn(Yl,e)?Yl[e]:void 0}function Xl(t){return Fs(t)?.otel??Ql(t)}function ed(t){return Fs(
|
|
1621
|
+
t)?.nombre}function Tt(t){return Fs(t)?t.slice(t.indexOf("/")+1):t}var pe={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.\
|
|
1541
1622
|
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\
|
|
1542
|
-
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"},
|
|
1543
|
-
request_sent`;function
|
|
1544
|
-
actual)}function
|
|
1545
|
-
bivelio_basis:n.basis,bivelio_currency:e};
|
|
1623
|
+
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"},td="error.type",W="com.bivelio.",nd=`${W}stream.\
|
|
1624
|
+
request_sent`;function Je(t){return t==="measured"||t==="reference"||t==="estimated"}function Yt(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}function rd(t){return Yt(t.cost.baselineEstimate-t.cost.
|
|
1625
|
+
actual)}function V(t,e,n){(typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n))&&(t[e]=n);}function qs(t,e){let{cost:n,tokens:r,calls:o,cache:i}=t,s={bivelio_request_id:t.requestId,
|
|
1626
|
+
bivelio_basis:n.basis,bivelio_currency:e};Je(n.basis)&&(s.bivelio_baseline_cost=n.baselineEstimate,s.bivelio_actual_cost=n.actual,s[`bivelio_saved_${n.basis}`]=rd(t),s.bivelio_net_savings_ratio=n.netSavings),
|
|
1546
1627
|
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=
|
|
1547
1628
|
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];
|
|
1548
|
-
return s}function
|
|
1549
|
-
void 0&&
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
baseline`,i.baselineLlm),
|
|
1553
|
-
ctual_input`,o.actualInput),
|
|
1554
|
-
`${
|
|
1555
|
-
erence_request_id`,s.reference?.requestId),
|
|
1556
|
-
|
|
1557
|
-
on.metadata.${l}`]=typeof d=="number"?
|
|
1558
|
-
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
|
|
1559
|
-
"function"}function
|
|
1560
|
-
ngsLayer: `tracer` must be an OpenTelemetry Tracer, a TracerProvider or the `trace` object of the OpenTelemetry API")}function
|
|
1561
|
-
test(e)?e:"_OTHER"}function
|
|
1562
|
-
isFinite(c)&&(r[a]=c);};i(
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
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
|
|
1573
|
-
ust be "hour" or "day"`)}function
|
|
1574
|
-
USD"`)}function
|
|
1575
|
-
[bvsala] ${e}: invalid "at" for request ${String(t.report?.requestId)}: expected an ISO 8601 string, epoch milliseconds or a valid Date`);return r}function
|
|
1576
|
-
t/n)*n}function
|
|
1577
|
-
`[bvsala] ${r}: report ${n} has no finite number in ${e}`)}function
|
|
1578
|
-
la] ${n}: every record must be { at, report }`);let a=s.report,c=a.cost?.basis;if(c==="shadow")continue;if(!
|
|
1579
|
-
own cost basis`);let u=c,l=
|
|
1629
|
+
return s}function zs(t){let e={};return V(e,pe.modeloRespuesta,Tt(t.model)),Je(t.cost.basis)&&(V(e,pe.entrada,t.tokens.actualInput),V(e,pe.salida,t.tokens.actualOutput),t.tokens.providerCachedInput!==
|
|
1630
|
+
void 0&&V(e,pe.lecturaDeCache,t.tokens.providerCachedInput)),e}function ho(t,e){let n=e?.currency??"USD",{cost:r,tokens:o,calls:i,cache:s}=t,a={};V(a,`${W}request_id`,t.requestId),V(a,`${W}sdk.version`,
|
|
1631
|
+
Be),V(a,`${W}model.id`,t.model),V(a,`${W}model.requested_id`,t.modelCascade?.requestedModel),V(a,`${W}cost.basis`,r.basis),V(a,`${W}cost.currency`,n),Je(r.basis)&&(V(a,`${W}cost.baseline`,r.baselineEstimate),
|
|
1632
|
+
V(a,`${W}cost.actual`,r.actual),V(a,`${W}cost.saved.${r.basis}`,rd(t)),V(a,`${W}cost.net_savings_ratio`,r.netSavings),V(a,`${W}cost.eliminated_input_floor`,r.eliminatedInputFloorCost)),V(a,`${W}calls.\
|
|
1633
|
+
baseline`,i.baselineLlm),V(a,`${W}calls.actual`,i.actualLlm),V(a,`${W}calls.avoided`,i.avoidedLlm),V(a,`${W}calls.retries`,i.retries),V(a,`${W}tokens.baseline_input`,o.baselineInput),V(a,`${W}tokens.a\
|
|
1634
|
+
ctual_input`,o.actualInput),V(a,`${W}tokens.eliminated_input`,o.eliminatedInput),V(a,`${W}tokens.compressed_input`,o.compressedInput),V(a,`${W}tokens.provider_cached_input`,o.providerCachedInput),V(a,
|
|
1635
|
+
`${W}tokens.baseline_output`,o.baselineOutput),V(a,`${W}tokens.actual_output`,o.actualOutput),V(a,`${W}tokens.eliminated_output`,o.eliminatedOutput),V(a,`${W}cache.result`,s.result),V(a,`${W}cache.ref\
|
|
1636
|
+
erence_request_id`,s.reference?.requestId),V(a,`${W}cache.reference_rejected`,s.referenceRejected),V(a,`${W}quality.status`,t.qualityStatus),V(a,`${W}latency.preprocessing_ms`,t.latencyMs?.preprocessing),
|
|
1637
|
+
V(a,`${W}latency.provider_ms`,t.latencyMs?.provider);let u=e?.langfuse?.metadata||e?.datadog?.metadata?qs(t,n):void 0;if(u&&e?.langfuse?.metadata)for(let[l,d]of Object.entries(u))a[`langfuse.observati\
|
|
1638
|
+
on.metadata.${l}`]=typeof d=="number"?Bs(d):d;if(e?.langfuse?.cost&&n==="USD"&&Je(r.basis)&&Number.isFinite(r.actual)&&(a["langfuse.observation.cost_details"]=JSON.stringify({total:r.actual})),u&&e?.datadog?.
|
|
1639
|
+
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 Mg=2,Lg=2,$g="@bivelio/savings-layer";function jg(t,e,n){try{if(t.isRecording?.()===!1)return;let r=ho(e,n);n?.genAi&&Object.assign(r,zs(e)),t.setAttributes(r);}catch{}}function Vs(t){return typeof t==
|
|
1640
|
+
"function"}function Ng(t){let e=t;if(e&&Vs(e.startActiveSpan))return e;if(e&&Vs(e.getTracer)){let n=e.getTracer($g,Be);if(n&&Vs(n.startActiveSpan))return n}throw new TypeError("[bvsala] instrumentSavi\
|
|
1641
|
+
ngsLayer: `tracer` must be an OpenTelemetry Tracer, a TracerProvider or the `trace` object of the OpenTelemetry API")}function Bg(t){let e=t?.name;return typeof e=="string"&&/^[A-Za-z_$][\w$.-]{0,127}$/.
|
|
1642
|
+
test(e)?e:"_OTHER"}function Fg(t,e,n){let r={[pe.operacion]:"chat"},o=n??Xl(t.model);typeof o=="string"&&o!==""&&(r[pe.proveedor]=o),r[pe.modeloPedido]=Tt(t.model);let i=(a,c)=>{typeof c=="number"&&Number.
|
|
1643
|
+
isFinite(c)&&(r[a]=c);};i(pe.temperatura,t.temperature),i(pe.semilla,t.seed),i(pe.maxTokens,J(t)),e&&(r[pe.stream]=true);let s=t.context?.sessionId;return typeof s=="string"&&s!==""&&(r[pe.conversacion]=
|
|
1644
|
+
s),r}function od(t,e,n){try{if(t.isRecording?.()!==!1){let r=e.report,o={...zs(r),...ho(r,n)};typeof e.finishReason=="string"&&e.finishReason!==""&&(o[pe.motivosDeFin]=[e.finishReason]);let i=r.streaming;
|
|
1645
|
+
i?.delivery==="live"&&typeof i.firstEventMs=="number"&&Number.isFinite(i.firstEventMs)&&(o[pe.primerTrozo]=i.firstEventMs/1e3),t.setAttributes(o);}}catch{}finally{try{t.end();}catch{}}}function Us(t,e){
|
|
1646
|
+
try{if(t.isRecording?.()!==!1){let n={[td]:Bg(e)};e instanceof Se&&(n[nd]=e.requestSent),t.setAttributes(n),t.setStatus?.({code:Lg});}}catch{}finally{try{t.end();}catch{}}}function qg(t,e){let n=Ng(e?.tracer);
|
|
1647
|
+
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}")`);let r={...e.currency!==
|
|
1648
|
+
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=Fg(s,a,o);}catch{h=void 0;}let m=`ch\
|
|
1649
|
+
at ${zg(s)}`;try{n.startActiveSpan(m,{kind:Mg,...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},Us(g,v),v}try{
|
|
1650
|
+
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(s),(a,c)=>c.
|
|
1651
|
+
then(u=>(od(a,u,r),u),u=>{throw Us(a,u),u}))},generateStream(s,a){return i(s,true,()=>t.generateStream(s,a),(c,u)=>(u.result.then(l=>od(c,l,r),l=>Us(c,l)),u))},close(){t.close();}}}function zg(t){try{return typeof t.
|
|
1652
|
+
model=="string"?Tt(t.model):""}catch{return ""}}function Vg(t,e){let n=e?.currency??"USD",r={model:Tt(t.model),metadata:qs(t,n)};if(Je(t.cost.basis)){let{actualInput:o,actualOutput:i,providerCachedInput:s}=t.tokens,a={input:Math.max(0,o-(s??0)),output:i};
|
|
1653
|
+
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 id=["measured","reference","estimated","unmeasured"],Hs=36e5,sd=24*Hs;function go(t,e){if(t===void 0)return "day";if(t==="hour"||t==="day")return t;throw new TypeError(`[bvsala] ${e}: granularity m\
|
|
1654
|
+
ust be "hour" or "day"`)}function bo(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 "\
|
|
1655
|
+
USD"`)}function Ug(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(`\
|
|
1656
|
+
[bvsala] ${e}: invalid "at" for request ${String(t.report?.requestId)}: expected an ISO 8601 string, epoch milliseconds or a valid Date`);return r}function Hg(t,e){let n=e==="hour"?Hs:sd;return Math.floor(
|
|
1657
|
+
t/n)*n}function Wg(t,e){return t+(e==="hour"?Hs:sd)}function dt(t){return new Date(t).toISOString().replace(/\.\d{3}Z$/,"Z")}function ye(t,e,n,r){if(typeof t=="number"&&Number.isFinite(t))return t;throw new TypeError(
|
|
1658
|
+
`[bvsala] ${r}: report ${n} has no finite number in ${e}`)}function vo(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\
|
|
1659
|
+
la] ${n}: every record must be { at, report }`);let a=s.report,c=a.cost?.basis;if(c==="shadow")continue;if(!id.includes(c))throw new TypeError(`[bvsala] ${n}: report ${String(a.requestId)} has an unkn\
|
|
1660
|
+
own cost basis`);let u=c,l=Hg(Ug(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:Wg(l,e),modelo:a.model,basis:u,clave:d,extra:p,peticiones:0,llamadas:0,
|
|
1580
1661
|
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}},
|
|
1581
|
-
o.set(h,m));let g=String(a.requestId);m.peticiones+=1,m.llamadas+=
|
|
1582
|
-
|
|
1583
|
-
compressedInput+=
|
|
1584
|
-
Output",g,n),m.tokens.eliminatedOutput+=
|
|
1585
|
-
"tokens.providerCachedInput",g,n)),
|
|
1586
|
-
void 0&&(m.suelo=(m.suelo??0)+
|
|
1587
|
-
s.modelo>a.modelo?1:0)||i(s.basis)-i(a.basis)||(s.clave<a.clave?-1:s.clave>a.clave?1:0))}function
|
|
1588
|
-
measured:t.basis==="measured"?n:null,reference:t.basis==="reference"?n:null,estimated:t.basis==="estimated"?n:null,suelo:e&&t.suelo!==void 0?
|
|
1589
|
-
keys(t).sort().map(e=>[e,t[e]]))}function
|
|
1590
|
-
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
|
|
1662
|
+
o.set(h,m));let g=String(a.requestId);m.peticiones+=1,m.llamadas+=ye(a.calls?.actualLlm,"calls.actualLlm",g,n),m.evitadas+=ye(a.calls?.avoidedLlm,"calls.avoidedLlm",g,n);let f=a.tokens;if(m.tokens.baselineInput+=
|
|
1663
|
+
ye(f?.baselineInput,"tokens.baselineInput",g,n),m.tokens.actualInput+=ye(f?.actualInput,"tokens.actualInput",g,n),m.tokens.eliminatedInput+=ye(f?.eliminatedInput,"tokens.eliminatedInput",g,n),m.tokens.
|
|
1664
|
+
compressedInput+=ye(f?.compressedInput,"tokens.compressedInput",g,n),m.tokens.baselineOutput+=ye(f?.baselineOutput,"tokens.baselineOutput",g,n),m.tokens.actualOutput+=ye(f?.actualOutput,"tokens.actual\
|
|
1665
|
+
Output",g,n),m.tokens.eliminatedOutput+=ye(f?.eliminatedOutput,"tokens.eliminatedOutput",g,n),f.providerCachedInput!==void 0&&(m.tokens.providerCachedInput=(m.tokens.providerCachedInput??0)+ye(f.providerCachedInput,
|
|
1666
|
+
"tokens.providerCachedInput",g,n)),Je(u)){let v=ye(a.cost.baselineEstimate,"cost.baselineEstimate",g,n),b=ye(a.cost.actual,"cost.actual",g,n);m.baseline+=v,m.actual+=b,m.ahorro+=v-b,a.cost.eliminatedInputFloorCost!==
|
|
1667
|
+
void 0&&(m.suelo=(m.suelo??0)+ye(a.cost.eliminatedInputFloorCost,"cost.eliminatedInputFloorCost",g,n));}}let i=s=>id.indexOf(s);return [...o.values()].sort((s,a)=>s.inicio-a.inicio||(s.modelo<a.modelo?-1:
|
|
1668
|
+
s.modelo>a.modelo?1:0)||i(s.basis)-i(a.basis)||(s.clave<a.clave?-1:s.clave>a.clave?1:0))}function yo(t){let e=Je(t.basis),n=Yt(t.ahorro);return {baseline:e?Yt(t.baseline):null,actual:e?Yt(t.actual):null,
|
|
1669
|
+
measured:t.basis==="measured"?n:null,reference:t.basis==="reference"?n:null,estimated:t.basis==="estimated"?n:null,suelo:e&&t.suelo!==void 0?Yt(t.suelo):null}}function ko(t){return JSON.stringify(Object.
|
|
1670
|
+
keys(t).sort().map(e=>[e,t[e]]))}function xo(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[
|
|
1671
|
+
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 Jg=new Set(["periodStart","periodEnd","date","model","basis","currency","requests","providerCalls","avoidedCalls","baselineCost","actualCost","measuredSavings","referenceSavings","estimatedSavings",
|
|
1591
1672
|
"eliminatedInputFloorCost","baselineInputTokens","actualInputTokens","eliminatedInputTokens","compressedInputTokens","providerCachedInputTokens","baselineOutputTokens","actualOutputTokens","eliminated\
|
|
1592
|
-
OutputTokens","dimensions"]),
|
|
1593
|
-
keys(a))if(
|
|
1673
|
+
OutputTokens","dimensions"]),Ln="toSavingsSeries";function Kg(t,e){let n=go(e?.granularity,Ln),r=bo(e?.currency,Ln),o=e?.dimensions;return vo(t,n,Ln,s=>{let a=o?xo(o(s),"dimensions",Ln):{};for(let c of Object.
|
|
1674
|
+
keys(a))if(Jg.has(c))throw new TypeError(`[bvsala] ${Ln}: dimension "${c}" repeats a column of the series`);return {clave:ko(a),extra:a}}).map(s=>{let a=yo(s),c=dt(s.inicio);return {periodStart:c,periodEnd:dt(
|
|
1594
1675
|
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,
|
|
1595
1676
|
referenceSavings:a.reference,estimatedSavings:a.estimated,eliminatedInputFloorCost:a.suelo,baselineInputTokens:s.tokens.baselineInput,actualInputTokens:s.tokens.actualInput,eliminatedInputTokens:s.tokens.
|
|
1596
1677
|
eliminatedInput,compressedInputTokens:s.tokens.compressedInput,providerCachedInputTokens:s.tokens.providerCachedInput??null,baselineOutputTokens:s.tokens.baselineOutput,actualOutputTokens:s.tokens.actualOutput,
|
|
1597
|
-
eliminatedOutputTokens:s.tokens.eliminatedOutput,dimensions:Object.freeze({...s.extra})}})}var
|
|
1598
|
-
`[bvsala] ${
|
|
1678
|
+
eliminatedOutputTokens:s.tokens.eliminatedOutput,dimensions:Object.freeze({...s.extra})}})}var ke="toFocusRows",Gg="BV-SALA savings ledger",ad="bivelio/";function Ct(t){return typeof t=="string"&&t.trim()!==""}function Ws(t,e,n,r){let o=typeof t=="function"?t(n):t??e;if(Ct(o))return o;throw new TypeError(
|
|
1679
|
+
`[bvsala] ${ke}: cannot determine the FOCUS ${r} for model "${n}". FOCUS allows no placeholder there: pass it in the options.`)}function Zg(t,e,n){if(!n){let s=new Date(t);return {start:Date.UTC(s.getUTCFullYear(),
|
|
1599
1680
|
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;
|
|
1600
|
-
if(!Number.isFinite(o)||!Number.isFinite(i)||o>=i)throw new TypeError(`[bvsala] ${
|
|
1601
|
-
llingPeriod must contain the charge period it is given`);return {start:o,end:i}}function
|
|
1602
|
-
red`);let n=
|
|
1603
|
-
Id must be a non-empty string or a function`);let c=e.serviceName??
|
|
1604
|
-
tion"?o(l):o;if(!
|
|
1605
|
-
(!
|
|
1606
|
-
startsWith(
|
|
1607
|
-
[g.id,g.nombre,g.subId,g.subNombre,
|
|
1608
|
-
p,d,"HostProviderName"),g=
|
|
1609
|
-
EffectiveCost:0,ListCost:0,ContractedCost:0,BillingCurrency:r,BillingAccountId:v.id,BillingAccountName:v.nombre,BillingPeriodStart:
|
|
1610
|
-
ChargePeriodEnd:
|
|
1681
|
+
if(!Number.isFinite(o)||!Number.isFinite(i)||o>=i)throw new TypeError(`[bvsala] ${ke}: billingPeriod must return valid Dates with start before end`);if(t<o||e>i)throw new TypeError(`[bvsala] ${ke}: bi\
|
|
1682
|
+
llingPeriod must contain the charge period it is given`);return {start:o,end:i}}function Yg(t,e){if(!e||typeof e!="object")throw new TypeError(`[bvsala] ${ke}: options with a billingAccountId are requi\
|
|
1683
|
+
red`);let n=go(e.granularity,ke),r=bo(e.currency,ke),{billingAccountId:o,billingAccountName:i,subAccount:s,tags:a}=e;if(typeof o!="function"&&!Ct(o))throw new TypeError(`[bvsala] ${ke}: billingAccount\
|
|
1684
|
+
Id must be a non-empty string or a function`);let c=e.serviceName??Gg;if(!Ct(c))throw new TypeError(`[bvsala] ${ke}: serviceName must be a non-empty string`);return vo(t,n,ke,l=>{let d=typeof o=="func\
|
|
1685
|
+
tion"?o(l):o;if(!Ct(d))throw new TypeError(`[bvsala] ${ke}: 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&&
|
|
1686
|
+
(!Ct(h?.id)||!Ct(h?.name)))throw new TypeError(`[bvsala] ${ke}: subAccount must return { id, name } as non-empty strings, or undefined`);let m=xo(a?a(l):void 0,"tags",ke);for(let f of Object.keys(m))if(f.
|
|
1687
|
+
startsWith(ad))throw new TypeError(`[bvsala] ${ke}: tag "${f}" uses the reserved "${ad}" prefix`);let g={id:d,nombre:Ct(p)?p:null,subId:h?h.id:null,subNombre:h?h.name:null,tags:m};return {clave:JSON.stringify(
|
|
1688
|
+
[g.id,g.nombre,g.subId,g.subNombre,ko(m)]),extra:g}}).map(l=>{let d=l.modelo,p=Ws(e.serviceProviderName,ed(d),d,"ServiceProviderName"),h=Ws(e.invoiceIssuerName,p,d,"InvoiceIssuerName"),m=Ws(e.hostProviderName,
|
|
1689
|
+
p,d,"HostProviderName"),g=Zg(l.inicio,l.fin,e.billingPeriod),f=yo(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,
|
|
1690
|
+
EffectiveCost:0,ListCost:0,ContractedCost:0,BillingCurrency:r,BillingAccountId:v.id,BillingAccountName:v.nombre,BillingPeriodStart:dt(g.start),BillingPeriodEnd:dt(g.end),ChargePeriodStart:dt(l.inicio),
|
|
1691
|
+
ChargePeriodEnd:dt(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:"\
|
|
1611
1692
|
Usage-Based",InvoiceIssuerName:h,ServiceProviderName:p,HostProviderName:m,ServiceName:c,ServiceCategory:"AI and Machine Learning",ServiceSubcategory:"Generative AI",PricingQuantity:null,PricingUnit:null,
|
|
1612
1693
|
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.
|
|
1613
1694
|
evitadas,x_BiVelioBaselineCost:f.baseline,x_BiVelioActualCost:f.actual,x_BiVelioMeasuredSavings:f.measured,x_BiVelioReferenceSavings:f.reference,x_BiVelioEstimatedSavings:f.estimated,x_BiVelioEliminatedInputFloorCost:f.
|
|
@@ -1621,4 +1702,4 @@ tokens.eliminatedOutput}})}/*! Bundled license information:
|
|
|
1621
1702
|
@noble/curves/abstract/edwards.js:
|
|
1622
1703
|
@noble/curves/ed25519.js:
|
|
1623
1704
|
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
1624
|
-
*/export{
|
|
1705
|
+
*/export{Dc as AnthropicProvider,Be as BV_SALA_VERSION,Jr as BatchSubmitError,nn as CATALOGO,ii as COMPACTION_TRANSFORMS,Ip as COMPACT_ROWS_INSTRUCTION,Pe as CalibrationStateError,$u as DEFAULT_COST_MODEL,Ig as DEFAULT_MAX_STALENESS_SECONDS,Fp as DEFAULT_MIN_SAVED_CHARS,Ru as EMBEDDED_PUBLIC_KEY,Ao as ExactTokenizer,tr as ExecutionRouter,ar as FormatSelector,Do as HeuristicEstimator,Sa as InMemoryCacheBreakpointStore,Kn as InMemoryExactCache,wa as InMemorySemanticCache,Yo as InMemoryToolSetFreezer,nt as LicenseError,g0 as MODELOS_POR_CODIFICACION,Hn as MODELS_BY_ENCODING,ai as MockProvider,xc as OpenAICompatibleProvider,Eo as PRECIOS_AL_DIA,r0 as QUALITY_STATUSES,oa as REFERENCE_MAX_AGE_MS,sa as REFERENCE_MESSAGE_ALLOWANCE,ia as REFERENCE_OUTPUT_SHARE,Ko as ResolverRegistry,Hr as RevocationPoller,zt as RevocationSnapshot,At as SavingsLedger,cr as SchemaRegistry,Gn as Singleflight,Se as StreamAbortedError,_o as TokenizerRegistry,rr as ToolSelector,vn as TraceCollector,ka as UMBRAL_LOCAL,Cn as UsageEmitter,kp as adaptiveK,cp as arithmeticResolver,No as buildExactKey,la as buildInflightKey,F0 as calibrateSemanticFloor,jo as canonicalize,Ba as compactRowsSerializer,Ka as compactToolOutput,Ua as compresionFiel,pm as computeNextDelay,ep as cosine,Ap as createCompactRowsSerializer,Ta as createDefaultResolvers,i0 as createHandoff,iv as createMockProvider,C1 as createSavingsLayer,qa as csvSerializer,La as decodeCompactRows,yp as dedupe,Io as defaultTokenizerRegistry,ns as deriveSeatId,es as deriveStatus,ts as detectCi,ya as embebedorLocal,bb as emptyState,Rp as encodeCompactRows,dp as evalArithmetic,Jn as evaluatePolicy,Oa as executeRetrievalPlan,Mu as gateFromKey,It as heuristicEstimator,qg as instrumentSavingsLayer,am as isKeyset,et as isStrictCompatible,Ma as jsonCompactSerializer,op as keyTokensMatch,Qi as licenseKeyShape,Ur as liveGateFromKey,vb as mergeDelta,$o as modelFamilyOf,Jo as multisetEqual,dn as negationCount,Zb as noopCompressor,Ft as normalizeLicenseKey,Wn as normalizeText,un as numericTokens,Vn as precioDeLista,yb as projectContext,zb as providerNativeBackend,gi as quitarPrefijoDeProveedor,rn as randomId,jg as recordSavingsOnSpan,Oo as registerExactTokenizer,b0 as registrarTokenizadorExacto,wp as renderState,Va as resolveConstraintBackend,ju as resolveDependencies,Ny as resolveLicense,Uo as sameAnswer,ho as savingsSpanAttributes,ne as sha256,oi as shouldCompress,ve as stableStringify,Og as toCsv,Yg as toFocusRows,Vg as toLangfuseGeneration,Kg as toSavingsSeries,sr as uniformColumns,he as validateAgainstSchema,Xd as vectorLocal,Xi as verifyCompactSignature,qt as verifyLicenseToken,Ou as verifyRevocationList,Gb as withProtectedSpans,ln as words};
|