@bivelio/savings-layer 0.4.33 → 0.4.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/gateway/bin.js +649 -649
- package/dist/index.d.ts +240 -87
- package/dist/index.js +1353 -1347
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var _n="2026-09-29";var Rt={"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,cachedInputPer1k:25e-6},
|
|
2
2
|
"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},"gpt-4":{inputPer1k:.03,
|
|
3
3
|
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,cachedInputPer1k:125e-6},
|
|
4
4
|
"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,outputPer1k:.01,cachedInputPer1k:125e-6},
|
|
@@ -20,24 +20,24 @@ cachedInputPer1k:.0015},"gemini-3.8-flash":{inputPer1k:75e-5,outputPer1k:.00375,
|
|
|
20
20
|
h":{inputPer1k:75e-5,outputPer1k:.00375,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,
|
|
21
21
|
cachedInputPer1k:5e-5},"gemini-3.5-flash":{inputPer1k:.0015,outputPer1k:.009,cachedInputPer1k:15e-5},"gemini-3.5-flash-lite":{inputPer1k:3e-4,outputPer1k:.0025,cachedInputPer1k:3e-5},"gemini-3.1-pro-p\
|
|
22
22
|
review":{inputPer1k:.002,outputPer1k:.012,cachedInputPer1k:2e-4},"gemini-2.5-pro":{inputPer1k:.00125,outputPer1k:.01,cachedInputPer1k:125e-6},"gemini-2.5-flash":{inputPer1k:3e-4,outputPer1k:.0025,cachedInputPer1k:3e-5}},
|
|
23
|
-
|
|
23
|
+
Yp={"gemini-3.8-flash":{vigenteHasta:"2027-01-01"},"gemini-3.7-flash":{vigenteHasta:"2027-01-01"},"gemini-3.6-flash":{vigenteHasta:"2027-01-01"}},Zp={"gemini-3.8-flash":[{vigenteDesde:"2027-01-01",precio:{
|
|
24
24
|
inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}],"gemini-3.7-flash":[{vigenteDesde:"2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}],"gemini-3.6-flash":[{vigenteDesde:"\
|
|
25
|
-
2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}]},
|
|
26
|
-
for(let n of
|
|
27
|
-
""&&c!=="-"&&c!=="."&&c!=="_")continue;let l=i.slice(a.length+1);if(!(/^\d/.test(l)&&!/^\d{4}/.test(l)))return t[a]}}function
|
|
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"],
|
|
29
|
-
fromEntries(
|
|
30
|
-
return
|
|
31
|
-
1))))return
|
|
25
|
+
2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}]},Xp=Object.fromEntries(Object.keys(Rt).map(t=>[t,[{...Yp[t],precio:Rt[t]},...Zp[t]??[]]]));var Qp=864e13;function Qa(t){let e=t instanceof Date?t.getTime():t,n=typeof e=="number"&&Number.isFinite(e)&&Math.abs(e)<=Qp?e:Date.now();return new Date(n).toISOString().slice(0,10)}function ec(t,e){
|
|
26
|
+
for(let n of Xp[t]??[])if(!(n.vigenteDesde!==void 0&&e<n.vigenteDesde)&&!(n.vigenteHasta!==void 0&&e>=n.vigenteHasta))return n.precio}function ai(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 l=i.slice(a.length+1);if(!(/^\d/.test(l)&&!/^\d{4}/.test(l)))return t[a]}}function ci(t){return Object.keys(t).sort((e,n)=>n.length-e.length)}var ef=["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"],si={...Rt,...Object.
|
|
29
|
+
fromEntries(ef.map(t=>[t,null]))},tf=ci(si);function Xt(t,e){let n=Qt(t);return n===void 0?void 0:ec(n,Qa(e))}var nf=Object.fromEntries(Object.keys(si).map(t=>[t,si[t]===null?null:t]));function Qt(t){
|
|
30
|
+
return ai(nf,tf,t)??void 0}var rf=/^\d{4}-?\d{2}-?\d{2}$/;function st(t,e){let n=Qt(t);if(n===void 0)return;let r=t.lastIndexOf("/"),o=r>=0?t.slice(r+1):t;if(!(n!==t&&n!==o&&!rf.test(o.slice(n.length+
|
|
31
|
+
1))))return ec(n,Qa(e))}var Ve="0.4.34",wr="x-bvsala-version";var of=0;function Pt(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else {let r=++of,o=Date.now?Date.now():0;for(let i=0;i<
|
|
32
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]}\
|
|
33
|
-
-${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 Yy=["exact","task_equivalent","not_verified","bounded_degradation","rejected"];function Xy(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 li=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.
|
|
34
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,
|
|
35
|
-
Math.ceil(e.length/4))}},
|
|
35
|
+
Math.ceil(e.length/4))}},en=new li;var ui=class{estimators=new Map;modelToTokenizer=new Map;fallbackId;constructor(e=en){this.fallbackId=e.id,this.estimators.set(e.id,e);}register(e){return this.estimators.set(e.id,e),this}mapModel(e,n){
|
|
36
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.
|
|
37
|
-
get(r);if(o)return o}}return this.estimators.get(this.fallbackId)}count(e,n){return this.resolve(n).count(e)}},
|
|
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
|
|
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
|
|
40
|
-
[])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)}},di=new ui;var pi=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}},Sr={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 fi(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 pi(o,i)),r=true;for(let s of Sr[o]??
|
|
40
|
+
[])t.mapModel(s,o),t.mapModel(`openai/${s}`,o);}}return r}var lk=Sr,uk=fi;var 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;nativeCacheWriteInput=0;nativeCacheWrite1hInput=0;nativeCacheMarkedByLayer=null;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){
|
|
41
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.
|
|
42
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.
|
|
43
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);}nativeCacheWrite(e,n){
|
|
@@ -51,139 +51,139 @@ removedInputLocal===0?"measured":"estimated";}else this.actualInput>0?(this.base
|
|
|
51
51
|
repairOutput-this.discoveryOutput):this.baselineOutput,i=e.cachedInputPer1k??e.inputPer1k,s=Math.max(0,this.actualInput-this.unbilledInput),a=Math.max(0,this.actualOutput-this.unbilledOutput),c=Math.min(
|
|
52
52
|
Math.max(0,this.providerCachedInput-this.unbilledCachedInput),s),l=y=>Math.max(0,y-c)/1e3*e.inputPer1k+c/1e3*i,u=n?null:this.reference,d=n?this.providerCacheWritePremiumUsd:0,p=this.servedUnbilledRefusal?
|
|
53
53
|
0:u?u.tierFactor*(this.baselineInput/1e3*u.cachedInputPer1k+this.baselineOutput/1e3*u.outputPer1k):l(this.baselineInput)+o/1e3*e.outputPer1k+d;u&&(r=p>0?"reference":"estimated"),this.servedUnbilledRefusal&&
|
|
54
|
-
(u?r="estimated":n&&r==="estimated"&&(r="measured"));let
|
|
55
|
-
netSavings:b,netSavingsRatio:b,netSavingsUsd:
|
|
54
|
+
(u?r="estimated":n&&r==="estimated"&&(r="measured"));let h=l(s)+a/1e3*e.outputPer1k+this.extraCostUsd+this.cacheWritePremiumUsd+d,f=p===0?0:1-h/p,m=mi(p),g=mi(h),b=sf(f);return {baselineEstimate:m,actual:g,
|
|
55
|
+
netSavings:b,netSavingsRatio:b,netSavingsUsd:mi(m-g),basis:r}}};function mi(t){return Math.round(t*1e10)/1e10}function sf(t){return Math.round(t*1e6)/1e6}var af=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,
|
|
56
56
|
4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,
|
|
57
57
|
1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,
|
|
58
|
-
1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),
|
|
58
|
+
1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),cf=new TextEncoder;function $e(t,e){return t>>>e|t<<32-e}function tc(t){let e=cf.encode(t),n=e.length*
|
|
59
59
|
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(
|
|
60
60
|
[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),a=new Uint32Array(64);for(let l=0;l<o.length;l+=64){for(let y=0;y<16;y++)a[y]=i.getUint32(l+y*4);for(let y=16;y<
|
|
61
|
-
64;y++){let v=a[y-15],x=a[y-2],
|
|
62
|
-
|
|
63
|
-
s[4]=s[4]+
|
|
64
|
-
|
|
65
|
-
normalize("NFC"),e=e.replace(
|
|
66
|
-
ke(s)||ke(s)&&!ke(i)&&!
|
|
67
|
-
return
|
|
68
|
-
return t}function
|
|
61
|
+
64;y++){let v=a[y-15],x=a[y-2],E=$e(v,7)^$e(v,18)^v>>>3,S=$e(x,17)^$e(x,19)^x>>>10;a[y]=a[y-16]+E+a[y-7]+S|0;}let u=s[0],d=s[1],p=s[2],h=s[3],f=s[4],m=s[5],g=s[6],b=s[7];for(let y=0;y<64;y++){let v=$e(
|
|
62
|
+
f,6)^$e(f,11)^$e(f,25),x=f&m^~f&g,E=b+v+x+af[y]+a[y]|0,S=$e(u,2)^$e(u,13)^$e(u,22),C=u&d^u&p^d&p,A=S+C|0;b=g,g=m,m=f,f=h+E|0,h=p,p=d,d=u,u=E+A|0;}s[0]=s[0]+u|0,s[1]=s[1]+d|0,s[2]=s[2]+p|0,s[3]=s[3]+h|0,
|
|
63
|
+
s[4]=s[4]+f|0,s[5]=s[5]+m|0,s[6]=s[6]+g|0,s[7]=s[7]+b|0;}let c="";for(let l=0;l<8;l++)c+=(s[l]>>>0).toString(16).padStart(8,"0");return c}var lf=/\s+/g,uf=[[/′′/g,'"'],[/[‘’‚‛′´`]/g,"'"],[/[“”„‟″«»]/g,'"'],[/[‐-―−]/g,"-"],[/⁄/g,"/"],[/…/g,""]],df=/[¿?¡!;.,:'"·•]/g,pf=/([a-z])\p{M}+/gu,ff=/(^|\s)\p{M}+/gu,
|
|
64
|
+
hi=/\p{L}/u;function ke(t){return t>="0"&&t<="9"}function tn(t){let e=t.normalize("NFKC").toLowerCase();for(let[n,r]of uf)e=e.replace(n,r);return e=e.normalize("NFD").replace(pf,"$1").replace(ff,"$1").
|
|
65
|
+
normalize("NFC"),e=e.replace(df,(n,r,o)=>{let i=o[r-1]??"",s=o[r+1]??"";switch(n){case "\xBF":case "?":case "\xA1":case ";":return ke(i)&&ke(s)?n:"";case "!":return ke(i)?n:"";case ".":case ",":return ke(i)&&
|
|
66
|
+
ke(s)||ke(s)&&!ke(i)&&!hi.test(i)?n:"";case ":":return ke(i)&&ke(s)?n:"";case "'":case '"':return hi.test(i)&&hi.test(s)||ke(i)||ke(s)?n:"";default:return ke(i)||ke(s)?n:""}}),e.replace(lf," ").trim()}function X(t){
|
|
67
|
+
return tc(t)}function de(t){return JSON.stringify(gi(t))}function gi(t){if(Array.isArray(t))return t.map(gi);if(t&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=gi(t[n]);return e}
|
|
68
|
+
return t}function Dn(t){return t.replace(/[-_]?\d{4,}.*$/,"").replace(/[-_](mini|nano|small|large|latest)$/i,"")}function mf(t){let e=new Map,n=o=>{if(typeof o!="string"||o==="")return {sin:o??null};let i=e.
|
|
69
69
|
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,
|
|
70
70
|
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.
|
|
71
|
-
keys(s).length>0?s:null});if(!r.every(o=>o===null))return
|
|
72
|
-
`),o=t.messages.filter(s=>s.role!=="system").map(s=>`${s.role}:${
|
|
73
|
-
`),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:
|
|
74
|
-
systemPromptHash:
|
|
71
|
+
keys(s).length>0?s:null});if(!r.every(o=>o===null))return X(de(r))}function nn(t){let e=t.context??{},n=mf(t.messages),r=t.messages.filter(s=>s.role==="system").map(s=>s.content).join(`
|
|
72
|
+
`),o=t.messages.filter(s=>s.role!=="system").map(s=>`${s.role}:${tn(s.content)}`).join(`
|
|
73
|
+
`),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:Dn(t.model),messages:t.messages,normalizedText:o,
|
|
74
|
+
systemPromptHash:X(r),toolsetHash:X(de(i)),...n!==void 0?{toolTurnsHash:n}:{},structuredDataHash:t.structuredData!==void 0?X(de(t.structuredData)):"none",schemaVersion:t.response?.version??t.response?.
|
|
75
75
|
contractId??"none",contractId:t.response?.contractId??null,temperature:t.temperature??null,seed:t.seed??null,...t.reasoningEffort!=null?{reasoningEffort:t.reasoningEffort}:{},tenantId:e.tenantId??"ano\
|
|
76
76
|
nymous",authorizationScope:e.authorizationScope??"default",principal:e.sessionId??null,locale:e.locale??"und",knowledgeEpoch:e.knowledgeEpoch??"none",freshnessBucket:e.freshnessBucket??"any",safetyPolicyVersion:e.
|
|
77
|
-
safetyPolicyVersion??"none",tokenizer:t.tokenizer,original:t}}var
|
|
78
|
-
t.model,r=
|
|
79
|
-
schema:t.schemaVersion,tools:t.toolsetHash,...
|
|
80
|
-
safety:t.safetyPolicyVersion});return `bvsala:exact:${
|
|
81
|
-
t.model,system:t.systemPromptHash,contract:t.contractId,schema:t.schemaVersion,tools:t.toolsetHash,...
|
|
82
|
-
true,toolDiscovery:e.toolDiscovery===true,maxOut:e.maxOutputTokens??null});return `bvsala:inflight:${
|
|
77
|
+
safetyPolicyVersion??"none",tokenizer:t.tokenizer,original:t}}var nc="n2";function rc(t){return t.toolTurnsHash!==void 0?{toolTurns:t.toolTurnsHash}:{}}function oc(t){return t.reasoningEffort!==void 0?{effort:t.reasoningEffort}:{}}function rn(t,e={}){let n=e.servedModel??
|
|
78
|
+
t.model,r=de({tenant:t.tenantId,scope:t.authorizationScope,principal:t.principal,text:t.normalizedText,modelFamily:n===t.model?t.modelFamily:Dn(n),model:n,system:t.systemPromptHash,contract:t.contractId,
|
|
79
|
+
schema:t.schemaVersion,tools:t.toolsetHash,...rc(t),data:t.structuredDataHash,locale:t.locale,temperature:t.temperature,seed:t.seed,...oc(t),knowledgeEpoch:t.knowledgeEpoch,freshness:t.freshnessBucket,
|
|
80
|
+
safety:t.safetyPolicyVersion});return `bvsala:exact:${nc}:${X(r)}`}function An(t,e={}){let n=de({tenant:t.tenantId,scope:t.authorizationScope,principal:t.principal,text:t.normalizedText,model:e.servedModel??
|
|
81
|
+
t.model,system:t.systemPromptHash,contract:t.contractId,schema:t.schemaVersion,tools:t.toolsetHash,...rc(t),data:t.structuredDataHash,temperature:t.temperature,seed:t.seed,...oc(t),deferrable:e.deferrable===
|
|
82
|
+
true,toolDiscovery:e.toolDiscovery===true,maxOut:e.maxOutputTokens??null});return `bvsala:inflight:${nc}:${X(n)}`}var K="\\p{L}*",hf=[`suicid${K}`,`self[- ]?harm${K}`,`self[- ]?injur${K}`,`self[- ]?mutilat${K}`,"(?:kill|killing|hang|hanging|drown|drowning|cut|cutting|hurt|hurting|harm|harming|shoot|poison|stab|st\
|
|
83
83
|
arve|suffocate|strangle|electrocute|overdose) myself","end (?:my|my own) life","(?:want to|going to|gonna|just|i'll|i will) end it all","take my (?:own )?life","i (?:really |just )?(?:want|wanna) to d\
|
|
84
84
|
ie","i(?:'m| am) (?:going|planning|trying|ready) to die","wish i (?:was|were) dead","better off dead","(?:don't|do not) want to (?:live|be alive|wake up) any ?more","(?:don't|do not) want to be alive",
|
|
85
85
|
"no reason to (?:live|keep living)","take to die","(?:cut|sever|slit|pierce|open) (?:my|my own) (?:\\p{L}+ )?(?:artery|arteries|wrists?|veins?|throat)","(?:carve|cut) (?:\\p{L}+ ){0,3}into my (?:arm|ar\
|
|
86
|
-
ms|skin|leg|legs|wrist|wrists)",`overdos${
|
|
87
|
-
"acabar con mi vida","quiero morir(?:me)?","no quiero (?:seguir viviendo|vivir m\xE1s)","sobredosis",`su\xEFcid${
|
|
86
|
+
ms|skin|leg|legs|wrist|wrists)",`overdos${K}`,"autolesi\\p{L}*","(?:matarme|ahorcarme|ahogarme|envenenarme|lastimarme|hacerme da\xF1o|quitarme la vida)","cortarme (?:las venas|los brazos|las mu\xF1ecas)",
|
|
87
|
+
"acabar con mi vida","quiero morir(?:me)?","no quiero (?:seguir viviendo|vivir m\xE1s)","sobredosis",`su\xEFcid${K}`,"(?:matar-me|penjar-me|ofegar-me|fer-me mal|treure'm la vida)","acabar amb la meva \
|
|
88
88
|
vida","vull morir","no vull (?:seguir vivint|viure m\xE9s)","sobredosi","automutil\\p{L}*","(?:me tuer|me pendre|me noyer|me faire du mal|me mutiler|m'ouvrir les veines|me couper les veines)","mettre \
|
|
89
|
-
fin \xE0 (?:mes jours|ma vie)","en finir avec la vie","(?:je veux|j'ai envie de) mourir","surdose",`suizid${
|
|
90
|
-
en|ritzen|verletzen)","mir das leben nehmen","mein leben beenden","(?:ich will|ich m\xF6chte) (?:nicht mehr leben|sterben)","\xFCberdosis",`autolesion${
|
|
91
|
-
i|tagliarmi le vene|farmi del male|togliermi la vita)","(?:voglio|vorrei) morire","non voglio pi\xF9 vivere",`suic\xEDd${
|
|
92
|
-
rcar|enforcar-me|me afogar|me machucar)","tirar a (?:minha )?(?:pr\xF3pria )?vida","acabar com a minha vida","quero morrer","n\xE3o quero mais viver",`zelfmoord${
|
|
93
|
-
en|ophangen|verdrinken|snijden|iets aandoen|van kant maken)","ik wil dood","overdosis",`samob\xF3j${
|
|
94
|
-
\u017Cycie)","chc\u0119 umrze\u0107","nie chc\u0119 ju\u017C \u017Cy\u0107",`przedawkowa${
|
|
95
|
-
"a\u015F\u0131r\u0131 doz","bunuh diri",`menyakiti diri${
|
|
96
|
-
|
|
97
|
-
|empty inside)","i(?:'m| am) (?:so |really |very )?(?:depressed|hopeless|worthless)","eating disorder",`anorexi${
|
|
89
|
+
fin \xE0 (?:mes jours|ma vie)","en finir avec la vie","(?:je veux|j'ai envie de) mourir","surdose",`suizid${K}`,`selbstmord${K}`,"freitod",`selbstverletz${K}`,"mich (?:umbringen|t\xF6ten|erh\xE4ngen|ertr\xE4nk\
|
|
90
|
+
en|ritzen|verletzen)","mir das leben nehmen","mein leben beenden","(?:ich will|ich m\xF6chte) (?:nicht mehr leben|sterben)","\xFCberdosis",`autolesion${K}`,"(?:uccidermi|ammazzarmi|impiccarmi|annegarm\
|
|
91
|
+
i|tagliarmi le vene|farmi del male|togliermi la vita)","(?:voglio|vorrei) morire","non voglio pi\xF9 vivere",`suic\xEDd${K}`,`automutila${K}`,"autoles\xE3o|autoles\xF5es","(?:me matar|matar-me|me enfo\
|
|
92
|
+
rcar|enforcar-me|me afogar|me machucar)","tirar a (?:minha )?(?:pr\xF3pria )?vida","acabar com a minha vida","quero morrer","n\xE3o quero mais viver",`zelfmoord${K}`,`zelfbeschadig${K}`,"mezelf (?:dod\
|
|
93
|
+
en|ophangen|verdrinken|snijden|iets aandoen|van kant maken)","ik wil dood","overdosis",`samob\xF3j${K}`,`samookalecz${K}`,"(?:zabi\u0107 si\u0119|powiesi\u0107 si\u0119|utopi\u0107 si\u0119|poci\u0105\u0107 si\u0119|skrzywdzi\u0107 si\u0119|odebra\u0107 sobie \
|
|
94
|
+
\u017Cycie)","chc\u0119 umrze\u0107","nie chc\u0119 ju\u017C \u017Cy\u0107",`przedawkowa${K}`,`intihar${K}`,"kendime zarar",`kendimi \xF6ld\xFCr${K}`,"\xF6lmek istiyorum","art\u0131k ya\u015Famak istemiyorum",
|
|
95
|
+
"a\u015F\u0131r\u0131 doz","bunuh diri",`menyakiti diri${K}`,"(?:ingin|mau) mati","tidak ingin hidup lagi","t\u1EF1 t\u1EED|t\u1EF1 s\xE1t|t\u1EF1 l\xE0m h\u1EA1i|t\u1EF1 h\u1EA1i|mu\u1ED1n ch\u1EBFt|kh\xF4ng mu\u1ED1n s\u1ED1ng n\u1EEFa|qu\xE1 li\u1EC1u"],
|
|
96
|
+
gf=["panic attacks?","(?:mental|nervous) breakdown","psychotic (?:episode|break)","hearing voices","mental health crisis","feel(?:ing)? (?:so |really |very |completely )?(?:hopeless|worthless|suicidal\
|
|
97
|
+
|empty inside)","i(?:'m| am) (?:so |really |very )?(?:depressed|hopeless|worthless)","eating disorder",`anorexi${K}`,`bulimi${K}`,"ataques? de (?:p\xE1nico|panico|ansiedad)","crisis de (?:p\xE1nico|panic\
|
|
98
98
|
o|ansiedad)","(?:me siento|estoy) (?:muy )?(?:deprimid[oa]|desesperad[oa]|sin esperanza)","atacs? de (?:p\xE0nic|p\xE1nico|ansietat)","(?:em sento|estic) (?:molt )?(?:deprimit|deprimida|desesperat|des\
|
|
99
|
-
esperada)","crises? (?:de panique|d'angoisse)","attaques? de panique","je suis (?:tr\xE8s )?d\xE9prim\xE9e?",`panikattacke${
|
|
100
|
-
ico","(?:sono|mi sento) (?:molto )?(?:depress[oa]|disperat[oa])","(?:ataques?|crises?) de (?:p\xE2nico|ansiedade)","(?:estou|me sinto) (?:muito )?(?:deprimid[oa]|desesperad[oa])",`paniekaanval${
|
|
101
|
-
tak(?:i)? paniki",`panik atak${
|
|
102
|
-
`anaphyla${
|
|
99
|
+
esperada)","crises? (?:de panique|d'angoisse)","attaques? de panique","je suis (?:tr\xE8s )?d\xE9prim\xE9e?",`panikattacke${K}`,"ich bin (?:so |sehr )?(?:depressiv|verzweifelt)","attacc(?:o|hi) di pan\
|
|
100
|
+
ico","(?:sono|mi sento) (?:molto )?(?:depress[oa]|disperat[oa])","(?:ataques?|crises?) de (?:p\xE2nico|ansiedade)","(?:estou|me sinto) (?:muito )?(?:deprimid[oa]|desesperad[oa])",`paniekaanval${K}`,"a\
|
|
101
|
+
tak(?:i)? paniki",`panik atak${K}`,"serangan panik","c\u01A1n ho\u1EA3ng lo\u1EA1n"],bf=["heart attack","having a stroke","(?:can't|cannot|can not) breathe","(?:not|stopped) breathing","chest pains?",
|
|
102
|
+
`anaphyla${K}`,"(?:is |was |went |gone )unconscious","(?:having|had|is having) a seizure","(?:severe|heavy) bleeding|bleeding (?:heavily|profusely|a lot|won't stop)","swallowed (?:bleach|poison|a batt\
|
|
103
103
|
ery|batteries|pills)","call (?:911|999|112|an ambulance)","medical emergency","infarto","no (?:puedo|puede) respirar","(?:dolor|dolores) (?:en el|de) pecho","(?:est\xE1|esta) inconsciente","emergencia\
|
|
104
104
|
m\xE9dica","infart","no (?:puc|pot) respirar","emerg\xE8ncia m\xE8dica","crise cardiaque","(?:je n'arrive pas \xE0|je ne peux pas|il ne peut pas|elle ne peut pas) respirer","urgence m\xE9dicale","her\
|
|
105
105
|
zinfarkt","(?:kann|bekomme) (?:nicht|keine) (?:atmen|luft)","medizinischer notfall","non riesc[oe] a respirare","emergenza medica","ataque card\xEDaco","n\xE3o consig[oa] respirar","emerg\xEAncia m\xE9dica",
|
|
106
106
|
"hartaanval","zawa\u0142 serca","nie mog\u0119 oddycha\u0107","kalp krizi","nefes alam\u0131yorum","serangan jantung","tidak bisa bernapas","nh\u1ED3i m\xE1u c\u01A1 tim|\u0111\u1ED9t qu\u1EF5|kh\xF4ng th\u1EDF \u0111\u01B0\u1EE3c"],
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
let e=
|
|
107
|
+
vf=/(?<![\p{L}\p{N}])(?:suicide (?:squad|doors?|burn|king|linux|slide|bid)|shoot myself in the foot)(?![\p{L}\p{N}])/gu,bi=t=>new RegExp(`(?<![\\p{L}\\p{N}])(?:${t.join("|")})(?![\\p{L}\\p{N}])`,"u"),
|
|
108
|
+
yf=bi(hf),kf=bi(gf),xf=bi(bf);function wf(t){return t.normalize("NFC").replace(/[‘’ʼ`´]/g,"'").toLowerCase().replace(/\s+/g," ").replace(vf," ")}function Sf(t){if(typeof t!="string"||t==="")return null;
|
|
109
|
+
let e=wf(t);return yf.test(e)?"self-harm":kf.test(e)?"mental-health-crisis":xf.test(e)?"medical-emergency":null}function ic(t){for(let e of t){let n=Sf(e);if(n!==null)return n}return null}var Ef=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\
|
|
110
110
|
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|\
|
|
111
111
|
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\
|
|
112
112
|
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\
|
|
113
113
|
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\
|
|
114
|
-
nhat|m\u1EDBi nh\u1EA5t|gia|gi\xE1|thoi tiet|th\u1EDDi ti\u1EBFt"].join("|")+")\\b","i"),
|
|
114
|
+
nhat|m\u1EDBi nh\u1EA5t|gia|gi\xE1|thoi tiet|th\u1EDDi ti\u1EBFt"].join("|")+")\\b","i"),Cf=new RegExp("\\b("+["my|mine|our|ours|account|balance|subscription|invoice|order|profile","mi|mis|mio|m\xEDo|nu\
|
|
115
115
|
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\
|
|
116
116
|
|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\
|
|
117
117
|
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\
|
|
118
118
|
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\
|
|
119
|
-
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
|
|
120
|
-
r=(t.original.tools??[]).some(v=>v.risk==="write"||v.risk==="destructive"),o=t.freshnessBucket==="live"||t.freshnessBucket==="hour"||
|
|
119
|
+
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 It(t){let e=[],n=t.normalizedText,
|
|
120
|
+
r=(t.original.tools??[]).some(v=>v.risk==="write"||v.risk==="destructive"),o=t.freshnessBucket==="live"||t.freshnessBucket==="hour"||Ef.test(n),i=Cf.test(n),s=(t.temperature??0)>.3&&t.seed==null,a=ic(
|
|
121
121
|
t.messages.filter(v=>v.role==="user").map(v=>typeof v.content=="string"?v.content:"")),c=t.messages.filter(v=>v.role==="user").length,l=(t.original?.tools?.length??0)>0,u=t.messages.some(v=>v.role==="\
|
|
122
122
|
tool"||v.role==="assistant"&&(v.toolCalls?.length??0)>0),d=l||u||c>1,p=t.original?.savings?.semanticCache==="include-agentic";r&&e.push("write/destructive tools present"),o&&e.push("freshness-sensitiv\
|
|
123
123
|
e request"),i&&e.push("personalized/account-scoped request"),s&&e.push("stochastic sampling (temp>0.3, no seed)"),a!==null&&e.push(`sensitive topic (${a}) \u2192 exact and semantic cache off, no reference \
|
|
124
|
-
record (measured and served, never replayed or credited)`);let
|
|
125
|
-
r&&e.push("write/destructive tools \u2192 exact cache off (side effects must execute)"),
|
|
126
|
-
without a freshness bucket \u2192 exact cache off"),
|
|
124
|
+
record (measured and served, never replayed or credited)`);let h=o&&(t.freshnessBucket==null||t.freshnessBucket==="any"),f=t.freshnessBucket==="live",m=i&&t.principal==null,g=!s&&!h&&!f&&!m&&!r&&a===null;
|
|
125
|
+
r&&e.push("write/destructive tools \u2192 exact cache off (side effects must execute)"),f&&e.push("freshnessBucket=live \u2192 exact cache off (answer must be current)"),h&&e.push("freshness-sensitive\
|
|
126
|
+
without a freshness bucket \u2192 exact cache off"),m&&e.push("personalized request with no principal (context.sessionId) \u2192 exact cache off");let b=!r&&!o&&!i&&!s&&t.freshnessBucket!=="day"&&a===
|
|
127
127
|
null&&(!d||p);d&&!p?e.push('agentic request (tools, tool calls/results or more than one user turn) \u2192 semantic cache off by default (opt in with savings.semanticCache: "include-agentic")'):d&&p&&e.
|
|
128
128
|
push('agentic request admitted to the semantic cache by savings.semanticCache: "include-agentic" (write, freshness, personalization and sampling vetoes still apply)');let y=!r&&!o&&!i&&!s&&t.freshnessBucket!==
|
|
129
|
-
"day";return {allowExactCache:g,allowSemanticCache:b,allowElision:y,allowSingleflight:!r&&!
|
|
130
|
-
"hour"?36e5:t.freshnessBucket==="day"?864e5:null,sensitiveTopic:a,reasons:e}}var
|
|
131
|
-
now()>n.expiresAtMs?(this.store.delete(e),null):(this.store.delete(e),this.store.set(e,n),
|
|
132
|
-
next().value;o!==void 0&&this.store.delete(o);}this.store.set(e,{value:
|
|
133
|
-
try{return structuredClone(t)}catch{return t}}var
|
|
129
|
+
"day";return {allowExactCache:g,allowSemanticCache:b,allowElision:y,allowSingleflight:!r&&!m,allowCompression:true,requiresFreshData:o,hasSideEffects:r,isPersonalized:i,isAgentic:d,maxCacheAgeMs:t.freshnessBucket===
|
|
130
|
+
"hour"?36e5:t.freshnessBucket==="day"?864e5:null,sensitiveTopic:a,reasons:e}}var Er=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.
|
|
131
|
+
now()>n.expiresAtMs?(this.store.delete(e),null):(this.store.delete(e),this.store.set(e,n),sc(n.value)):null}async set(e,n,r){if(this.store.size>=this.maxEntries&&!this.store.has(e)){let o=this.store.keys().
|
|
132
|
+
next().value;o!==void 0&&this.store.delete(o);}this.store.set(e,{value:sc(n),expiresAtMs:r!=null?this.now()+r:null});}async delete(e){this.store.delete(e);}get size(){return this.store.size}};function sc(t){
|
|
133
|
+
try{return structuredClone(t)}catch{return t}}var Cr=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.
|
|
134
134
|
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.
|
|
135
|
-
waiters.get(e)??1)+1),n}get activeKeys(){return this.inflight.size}};function
|
|
136
|
-
o=Math.log1p(-n),i=t*o,s=[i],a=i;for(let l=0;l<e;l++)i+=Math.log(t-l)-Math.log(l+1)+r-o,s.push(i),i>a&&(a=i);let c=0;for(let l of s)c+=Math.exp(l-a);return Math.min(1,Math.exp(a+Math.log(c)))}function
|
|
137
|
-
return t<=0||e>=t*n?false:
|
|
135
|
+
waiters.get(e)??1)+1),n}get activeKeys(){return this.inflight.size}};function Mn(t){return !Number.isFinite(t)||t<0?-1:t>=1?1e3:Math.floor(t*1e3+1e-9)}var $n=t=>t/1e3;function Tf(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),
|
|
136
|
+
o=Math.log1p(-n),i=t*o,s=[i],a=i;for(let l=0;l<e;l++)i+=Math.log(t-l)-Math.log(l+1)+r-o,s.push(i),i>a&&(a=i);let c=0;for(let l of s)c+=Math.exp(l-a);return Math.min(1,Math.exp(a+Math.log(c)))}function ki(t,e,n,r){
|
|
137
|
+
return t<=0||e>=t*n?false:Tf(t,e,n)<=r}function Pr(t,e){return Math.ceil(Math.log(e)/Math.log1p(-t))}function Tr(t,e){return 6*t/(Math.PI*Math.PI*(e+1)*(e+1))}var ct=class{total=new Uint32Array(1001);erroneas=new Uint32Array(
|
|
138
138
|
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(
|
|
139
|
-
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
|
|
140
|
-
s);if(i==null)return null;for(;i<1e3&&t.total[i]===0;)i++;return i}function
|
|
141
|
-
n:o,e:i}=t.acumulados(),s=[...new Set(e)].sort((c,l)=>l-c),a=null;for(let c of s){if(!
|
|
142
|
-
e;this.alfa=n;this.primeraMirada=2*
|
|
139
|
+
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 Rf(t,e,n){let{n:r,e:o}=t.acumulados(),i=null;for(let s=1e3;s>=0;s--)ki(r[s],o[s],e,n)&&(i=
|
|
140
|
+
s);if(i==null)return null;for(;i<1e3&&t.total[i]===0;)i++;return i}function xi(t,e,n){let r=[];for(let o of [1,1/4,1/16,1/64,1/256]){let i=Rf(t,e,n*o);i!=null&&r.push(i);}return r}function wi(t,e,n,r){let{
|
|
141
|
+
n:o,e:i}=t.acumulados(),s=[...new Set(e)].sort((c,l)=>l-c),a=null;for(let c of s){if(!ki(o[c],i[c],n,r))break;a={indice:c,retenidas:o[c],erroneas:i[c]};}return a}var Ln=class t{constructor(e,n){this.delta=
|
|
142
|
+
e;this.alfa=n;this.primeraMirada=2*Pr(e,Tr(n,0));}delta;alfa;seleccion=new ct;retenida=new ct;etiquetas=0;miradas=0;candidatoPrevio=null;certificado=null;primeraMirada;etiquetasDeLaMirada(e){return vi(
|
|
143
143
|
this.primeraMirada,e)}exportar(){return {labeled:this.etiquetas,looks:this.miradas,previousCandidate:this.candidatoPrevio,certified:this.certificado?{floorIndex:this.certificado.indice,heldOut:this.certificado.
|
|
144
|
-
retenidas,wrong:this.certificado.erroneas}:null,selection:
|
|
145
|
-
(r===null||typeof r!="object"||Array.isArray(r))&&s("not an object");let a=r,c=a.labeled;
|
|
146
|
-
`${o}.heldOut`);(u.n!==Math.ceil(l/2)||d.n!==Math.floor(l/2))&&s(`the two halves hold ${u.n} and ${d.n} labels, but ${l} labels split by arrival order give ${Math.ceil(l/2)} and ${Math.floor(l/2)}`);let p=
|
|
147
|
-
i.primeraMirada,l);a.looks!==p&&s(`\`looks\` is ${String(a.looks)}, but ${l} labels have already spent ${p} tests of the confidence budget; a state cannot start that spending over`);let
|
|
148
|
-
|
|
149
|
-
ct");let g=
|
|
150
|
-
floorIndex,retenidas:g.heldOut,erroneas:g.wrong},p===0&&s("a floor is certified but no test has run yet"),
|
|
151
|
-
b),v=Math.floor(y/2);(
|
|
152
|
-
te does not pass the test it claims to have passed");let{n:x,e:
|
|
153
|
-
extend the ones the certificate counted");}else p===0&&
|
|
154
|
-
i.candidatoPrevio=
|
|
155
|
-
this.mirar());}mirar(){let e=
|
|
144
|
+
retenidas,wrong:this.certificado.erroneas}:null,selection:ac(this.seleccion),heldOut:ac(this.retenida)}}static restaurar(e,n,r,o){let i=new t(e,n),s=g=>{throw new _e(`importCalibration: ${o}: ${g}`)};
|
|
145
|
+
(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 l=c,u=cc(a.selection,`${o}.selection`),d=cc(a.heldOut,
|
|
146
|
+
`${o}.heldOut`);(u.n!==Math.ceil(l/2)||d.n!==Math.floor(l/2))&&s(`the two halves hold ${u.n} and ${d.n} labels, but ${l} labels split by arrival order give ${Math.ceil(l/2)} and ${Math.floor(l/2)}`);let p=Pf(
|
|
147
|
+
i.primeraMirada,l);a.looks!==p&&s(`\`looks\` is ${String(a.looks)}, but ${l} labels have already spent ${p} tests of the confidence budget; a state cannot start that spending over`);let h=a.previousCandidate;
|
|
148
|
+
h!==null&&!yi(h)&&s("`previousCandidate` must be null or a grid index");let f=a.certified,m=null;if(f!==null){(f===void 0||typeof f!="object"||Array.isArray(f))&&s("`certified` must be null or an obje\
|
|
149
|
+
ct");let g=f;yi(g.floorIndex)||s("`certified.floorIndex` must be a grid index"),(!On(g.heldOut)||!On(g.wrong))&&s("`certified.heldOut` and `certified.wrong` must be non-negative integers"),m={indice:g.
|
|
150
|
+
floorIndex,retenidas:g.heldOut,erroneas:g.wrong},p===0&&s("a floor is certified but no test has run yet"),h!==m.indice&&s("`previousCandidate` must be the certified floor");let b=p-1,y=vi(i.primeraMirada,
|
|
151
|
+
b),v=Math.floor(y/2);(m.retenidas>v||m.erroneas>m.retenidas)&&s("the certificate counts more held-out labels than there were when it was issued"),ki(m.retenidas,m.erroneas,e,Tr(n,b))||s("the certifica\
|
|
152
|
+
te does not pass the test it claims to have passed");let{n:x,e:E}=d.acumulados(),S=x[m.indice]-m.retenidas,C=E[m.indice]-m.erroneas;(S<0||C<0||C>S||S>d.n-v)&&s("the held-out labels at the floor do not\
|
|
153
|
+
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(u),i.retenida.copiarDe(d),i.etiquetas=l,i.miradas=p,
|
|
154
|
+
i.candidatoPrevio=h,i.certificado=m,i}anotar(e,n){let r=Mn(e);r<0||((this.etiquetas%2===0?this.seleccion:this.retenida).anotar(r,n),this.etiquetas++,this.etiquetas>=this.etiquetasDeLaMirada(this.miradas)&&
|
|
155
|
+
this.mirar());}mirar(){let e=Tr(this.alfa,this.miradas);this.miradas++;let n=xi(this.seleccion,this.delta,e),r=this.candidatoPrevio==null?n:[...n,this.candidatoPrevio],o=wi(this.retenida,r,this.delta,e);
|
|
156
156
|
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.
|
|
157
|
-
retenida.n,retenidasEnSuelo:this.certificado?.retenidas??0,erroneasEnSuelo:this.certificado?.erroneas??0,miradas:this.miradas,minimasParaLaSiguiente:
|
|
158
|
-
etiquetasDeLaMirada(this.miradas)}}},
|
|
159
|
-
function
|
|
160
|
-
confidence,similarityThreshold:t.similarityThreshold,grid:1e3},segments:n}}function
|
|
161
|
-
state must be an object");let r=t;r.format!==
|
|
162
|
-
wer SDK (version ${o}); this one reads version ${
|
|
157
|
+
retenida.n,retenidasEnSuelo:this.certificado?.retenidas??0,erroneasEnSuelo:this.certificado?.erroneas??0,miradas:this.miradas,minimasParaLaSiguiente:Pr(this.delta,Tr(this.alfa,this.miradas)),etiquetasParaLaSiguiente:this.
|
|
158
|
+
etiquetasDeLaMirada(this.miradas)}}},_e=class extends Error{constructor(e){super(`[bvsala] ${e}`),this.name="CalibrationStateError";}},lc="bvsala.semantic-calibration",Rr=1,uc=["single_shot","agentic"];
|
|
159
|
+
function dc(t,e){let n={};for(let r of uc){let o=e.get(r);o&&(n[r]=o.exportar());}return {format:lc,version:Rr,embedder:t.embedder,verifier:t.verifier,judge:t.judge,config:{maxErrorRate:t.maxErrorRate,confidence:t.
|
|
160
|
+
confidence,similarityThreshold:t.similarityThreshold,grid:1e3},segments:n}}function pc(t,e){let n=u=>{throw new _e(`importCalibration: ${u}`)};(t===null||typeof t!="object"||Array.isArray(t))&&n("the \
|
|
161
|
+
state must be an object");let r=t;r.format!==lc&&n(`not a semantic calibration state (format ${JSON.stringify(r.format)})`);let o=r.version;typeof o=="number"&&o>Rr&&n(`this state was exported by a ne\
|
|
162
|
+
wer SDK (version ${o}); this one reads version ${Rr}`),o!==Rr&&n(`unknown state version ${JSON.stringify(o)}`);let i=r.config??{},s=[],a=(u,d,p)=>{d!==p&&s.push(`${u}: ${JSON.stringify(d)} in the stat\
|
|
163
163
|
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,
|
|
164
164
|
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\
|
|
165
165
|
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 l=new Map;for(let[
|
|
166
|
-
u,d]of Object.entries(c))
|
|
167
|
-
e)}function
|
|
168
|
-
t)&&t>=0&&t<=1e3}function
|
|
169
|
-
isArray(t)||n("must be an array of [gridIndex, labels, wrong]");let r=new
|
|
170
|
-
s)||s<=o)&&n("grid indices must be increasing integers in [0, 1000]"),(!
|
|
171
|
-
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
|
|
166
|
+
u,d]of Object.entries(c))uc.includes(u)||n(`unknown segment ${JSON.stringify(u)}`),l.set(u,Ln.restaurar(e.maxErrorRate,1-e.confidence,d,`segments.${u}`));return l}function vi(t,e){return Math.ceil(t*1.5**
|
|
167
|
+
e)}function Pf(t,e){let n=0;for(;vi(t,n)<=e;)n++;return n}function On(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=4294967295}function yi(t){return typeof t=="number"&&Number.isInteger(
|
|
168
|
+
t)&&t>=0&&t<=1e3}function ac(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 cc(t,e){let n=i=>{throw new _e(`importCalibration: ${e}: ${i}`)};Array.
|
|
169
|
+
isArray(t)||n("must be an array of [gridIndex, labels, wrong]");let r=new ct,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;(!yi(
|
|
170
|
+
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\
|
|
171
|
+
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 Ir(t){let{maxErrorRate:e}=t,n=t.confidence??.95,r=t.auditRate??.05;if(!(e>0&&e<=.5))throw new RangeError(
|
|
172
172
|
`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\
|
|
173
|
-
.auditRate must be in [0, 1); got ${r}`);return {maxErrorRate:e,confidence:n,auditRate:r}}function
|
|
174
|
-
7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}function
|
|
175
|
-
isArray(t))return `[${t.map(
|
|
176
|
-
stringify(t)??"null"}function
|
|
177
|
-
let l=
|
|
178
|
-
o)}}var
|
|
179
|
-
"fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"];
|
|
180
|
-
decena",v:20+10*e}));N("hundred hundreds",{k:"cien"});N("thousand thousands",{k:"escala",v:1e3});N("million millions",{k:"escala",v:1e6});N("billion billions",{k:"escala",v:1e9});var
|
|
181
|
-
econd","third","fourth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelfth","thirteenth","fourteenth","fifteenth","sixteenth","seventeenth","eighteenth","nineteenth"];
|
|
173
|
+
.auditRate must be in [0, 1); got ${r}`);return {maxErrorRate:e,confidence:n,auditRate:r}}function fc(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>>>
|
|
174
|
+
7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}function Nn(t,e){let n=o=>o!==null&&typeof o=="object";if(n(t.data)&&n(e.data))return _r(t.data)===_r(e.data);let r=o=>o.trim().replace(/\s+/g," ");return r(t.text)===r(e.text)}function _r(t){if(Array.
|
|
175
|
+
isArray(t))return `[${t.map(_r).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)}:${_r(e[n])}`).join(",")}}`}return JSON.
|
|
176
|
+
stringify(t)??"null"}function Mk(t,e){let{maxErrorRate:n,confidence:r}=Ir(e),o=1-r,i=new ct,s=new ct,a=fc(1592642065),c=0;for(let u of t){let d=Mn(u.score),p=a()<.5;d<0||((p?i:s).anotar(d,u.correct),c++);}
|
|
177
|
+
let l=wi(s,xi(i,n,o),n,o);return {maxErrorRate:n,confidence:r,floor:l?$n(l.indice):null,labeled:c,heldOut:s.n,heldOutAtFloor:l?.retenidas??0,wrongHeldOutAtFloor:l?.erroneas??0,minHeldOutToCertify:Pr(n,
|
|
178
|
+
o)}}var Si=new Map;function N(t,e){for(let n of t.split(/\s+/).filter(Boolean))Si.set(n,e);}var If=["zero","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen",
|
|
179
|
+
"fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"];If.forEach((t,e)=>N(t,{k:"unidad",v:e}));["twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"].forEach((t,e)=>N(t,{k:"\
|
|
180
|
+
decena",v:20+10*e}));N("hundred hundreds",{k:"cien"});N("thousand thousands",{k:"escala",v:1e3});N("million millions",{k:"escala",v:1e6});N("billion billions",{k:"escala",v:1e9});var _f=["","first","s\
|
|
181
|
+
econd","third","fourth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelfth","thirteenth","fourteenth","fifteenth","sixteenth","seventeenth","eighteenth","nineteenth"];_f.forEach((t,e)=>{
|
|
182
182
|
t&&(N(t,{k:"ordinal",v:e}),e>=3&&N(`${t}s`,{k:"ordinal",v:e}));});["twentieth","thirtieth","fortieth","fiftieth","sixtieth","seventieth","eightieth","ninetieth"].forEach((t,e)=>{N(t,{k:"ordinal",v:20+10*
|
|
183
183
|
e}),N(`${t}s`,{k:"ordinal",v:20+10*e});});N("hundredth hundredths",{k:"ordinal",v:100});N("thousandth thousandths",{k:"ordinal",v:1e3});N("millionth millionths",{k:"ordinal",v:1e6});N("half halves",{k:"\
|
|
184
184
|
token",t:"f:1/2"});N("quarter quarters",{k:"token",t:"f:1/4"});N("once single",{k:"token",t:"m:1"});N("twice double doubled doubles doubling",{k:"token",t:"m:2"});N("thrice triple tripled triples trip\
|
|
185
185
|
ling",{k:"token",t:"m:3"});N("quadruple quadrupled quadruples quadrupling",{k:"token",t:"m:4"});N("dozen dozens",{k:"token",t:"c:12"});N("pair pairs",{k:"token",t:"c:2"});N("times time",{k:"veces"});N(
|
|
186
|
-
"and",{k:"conector"});var
|
|
186
|
+
"and",{k:"conector"});var Df=["cero","uno","dos","tres","cuatro","cinco","seis","siete","ocho","nueve","diez","","doce","trece","catorce","quince","dieciseis","diecisiete","dieciocho","diecinueve"];Df.
|
|
187
187
|
forEach((t,e)=>t&&N(t,{k:"unidad",v:e}));N("veinte",{k:"decena",v:20});["veintiuno","veintidos","veintitres","veinticuatro","veinticinco","veintiseis","veintisiete","veintiocho","veintinueve"].forEach(
|
|
188
188
|
(t,e)=>N(t,{k:"unidad",v:21+e}));["treinta","cuarenta","cincuenta","sesenta","setenta","ochenta","noventa"].forEach((t,e)=>N(t,{k:"decena",v:30+10*e}));N("cien ciento",{k:"centena",v:100});[["doscient\
|
|
189
189
|
os doscientas",200],["trescientos trescientas",300],["cuatrocientos cuatrocientas",400],["quinientos quinientas",500],["seiscientos seiscientas",600],["setecientos setecientas",700],["ochocientos ocho\
|
|
@@ -196,209 +196,209 @@ forEach(([t,e])=>N(t,{k:"ordinal",v:e}));N("mitad mitades medio media medios med
|
|
|
196
196
|
uanta","seixanta","setanta","vuitanta","noranta"].forEach((t,e)=>N(t,{k:"decena",v:20+10*e}));N("cent",{k:"centena",v:100});N("cents centes",{k:"cien"});N("milio milions",{k:"escala",v:1e6});[["segon \
|
|
197
197
|
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(
|
|
198
198
|
([t,e])=>N(t,{k:"ordinal",v:e}));N("meitat meitats mig mitja",{k:"token",t:"f:1/2"});N("dotzena dotzenes",{k:"token",t:"c:12"});N("parell parells",{k:"token",t:"c:2"});N("vegades vegada",{k:"veces"});
|
|
199
|
-
N("i",{k:"conector"});var
|
|
200
|
-
c=(u="n")=>{r&&e.push(`${u}:${o+i}`),r=false,o=0,i=0,s=null,a=1/0;},l=(u,d)=>{c(),r=true,i=u,s=d;};for(let u=0;u<n.length;u++){let d=
|
|
199
|
+
N("i",{k:"conector"});var Af=/\p{M}+/gu;function Of(t){return t.toLowerCase().normalize("NFD").replace(Af,"").split(/[^\p{L}]+/u).filter(Boolean)}function Ei(t){let e=[],n=Of(t),r=false,o=0,i=0,s=null,a=1/0,
|
|
200
|
+
c=(u="n")=>{r&&e.push(`${u}:${o+i}`),r=false,o=0,i=0,s=null,a=1/0;},l=(u,d)=>{c(),r=true,i=u,s=d;};for(let u=0;u<n.length;u++){let d=Si.get(n[u]);if(!d){c();continue}switch(d.k){case "unidad":{r&&(s==="decena"&&
|
|
201
201
|
d.v<10&&i%10===0||(s==="cien"||s==="centena")&&i%100===0||s==="escala")?(i+=d.v,s="unidad"):l(d.v,"unidad");break}case "decena":{r&&((s==="cien"||s==="centena")&&i%100===0||s==="escala")?(i+=d.v,s="dec\
|
|
202
202
|
ena"):l(d.v,"decena");break}case "centena":{r&&s==="escala"?(i+=d.v,s="centena"):l(d.v,"centena");break}case "cien":{r&&(s==="unidad"||s==="decena")&&i>0&&i<100?(i*=100,s="cien"):l(100,"cien");break}case "\
|
|
203
203
|
escala":{r&&s!=="escala"&&d.v<a?(o+=(i||1)*d.v,i=0,s="escala",a=d.v):(l(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
|
|
204
|
-
c(),e.push(`o:${d.v}`);break}case "veces":{r&&c("m");break}case "conector":{let p=
|
|
205
|
-
c();break}case "token":{c(),e.push(d.t);break}}}return c(),e}function
|
|
206
|
-
Boolean)}function
|
|
207
|
-
1]}`;r.set(a,(r.get(a)??0)+1);}}for(let[i,s]of r){let a=
|
|
208
|
-
e[i]/=o;return e}function
|
|
204
|
+
c(),e.push(`o:${d.v}`);break}case "veces":{r&&c("m");break}case "conector":{let p=Si.get(n[u+1]??"");r&&(s==="decena"||s==="cien"||s==="centena"||s==="escala")&&p!=null&&(p.k==="unidad"||p.k==="decena")||
|
|
205
|
+
c();break}case "token":{c(),e.push(d.t);break}}}return c(),e}function Lf(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 Mf(t){return t.toLowerCase().normalize("NFKC").split(/[^\p{L}\p{N}]+/u).filter(
|
|
206
|
+
Boolean)}function mc(t){let e=new Array(256).fill(0),n=Mf(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+
|
|
207
|
+
1]}`;r.set(a,(r.get(a)??0)+1);}}for(let[i,s]of r){let a=Lf(i),c=a%256,l=a>>>31===1?-1:1;e[c]+=l*(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++)
|
|
208
|
+
e[i]/=o;return e}function jk(t){return mc(t)}function hc(t){return mc(t)}var $f=.72,gc=$f;function Ci(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 Nf=new Set(
|
|
209
209
|
["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\
|
|
210
|
-
\xFAn","ninguna","ninguno","nada","nadie","sense","mai","tampoc","cap","gens","ningu","ning\xFA","res"]),
|
|
210
|
+
\xFAn","ninguna","ninguno","nada","nadie","sense","mai","tampoc","cap","gens","ningu","ning\xFA","res"]),jf=new Set(["the","a","an","of","to","in","on","for","and","or","is","are","was","were","what",
|
|
211
211
|
"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",
|
|
212
212
|
"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\
|
|
213
213
|
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",
|
|
214
214
|
"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",
|
|
215
|
-
"aquests","aquestes","aquell","aquella","que","quin","quina","qui","com","quan","on","dona","vull","necessito","pots","podries","sisplau","gracies","meu","meva","seu","seva","hi"]);function
|
|
216
|
-
match(/\d[\d.,:/-]*/g)??[]).map(e=>e.replace(/[.,:/-]+$/,""))}function
|
|
217
|
-
return false;n.set(r,o-1);}return true}function
|
|
218
|
-
function
|
|
219
|
-
`).map(e=>{let n=
|
|
220
|
-
r[o].rol||!
|
|
221
|
-
1&&!
|
|
222
|
-
lexical-256-v1",
|
|
223
|
-
let n=e.embed==null;if(this.embebedorPropio=n,this.embed=e.embed??
|
|
215
|
+
"aquests","aquestes","aquell","aquella","que","quin","quina","qui","com","quan","on","dona","vull","necessito","pots","podries","sisplau","gracies","meu","meva","seu","seva","hi"]);function _t(t){return (t.
|
|
216
|
+
match(/\d[\d.,:/-]*/g)??[]).map(e=>e.replace(/[.,:/-]+$/,""))}function jn(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)
|
|
217
|
+
return false;n.set(r,o-1);}return true}function Dt(t){return t.split(/\s+/).filter(Boolean)}function At(t){return t.filter(e=>Nf.has(e.replace(/'/g,""))||e.endsWith("n't")).length}var Bf=/^(system|user|assistant|tool):/;
|
|
218
|
+
function bc(t){return t.split(`
|
|
219
|
+
`).map(e=>{let n=Bf.exec(e);return n?{rol:n[1],texto:e.slice(n[0].length)}:{rol:"",texto:e}})}function Ti(t,e){let n=bc(t),r=bc(e);if(n.length!==r.length)return false;for(let o=0;o<n.length;o++)if(n[o].rol!==
|
|
220
|
+
r[o].rol||!zf(n[o].texto,r[o].texto))return false;return true}function zf(t,e){let n=[..._t(t),...Ei(t)],r=[..._t(e),...Ei(e)];if(!jn(n,r))return false;let o=Dt(t),i=Dt(e);if(At(o)!==At(i))return false;let s=d=>d.length>
|
|
221
|
+
1&&!jf.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 l=0;for(let d of a)c.has(d)&&l++;let u=a.size+c.size-l;return u===0?true:l/u>=.75}var Ff="\
|
|
222
|
+
lexical-256-v1",qf="same-answer-v1",vc=class{records=[];embed;verify;similarityThreshold;acceptThreshold;ttlMs;maxRecords;now;embebedorPropio;calibracion;estados=new Map;nombres;pendientes=new Set;aceptacionExplicita;constructor(e={}){
|
|
223
|
+
let n=e.embed==null;if(this.embebedorPropio=n,this.embed=e.embed??hc,this.verify=e.verify,this.similarityThreshold=e.similarityThreshold??(n?gc:.9),this.acceptThreshold=e.acceptThreshold??.85,this.aceptacionExplicita=
|
|
224
224
|
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}:{}},
|
|
225
|
-
this.ttlMs=e.ttlMs,this.maxRecords=e.maxRecords??5e3,this.now=e.now??(()=>Date.now()),e.calibration){let r=
|
|
225
|
+
this.ttlMs=e.ttlMs,this.maxRecords=e.maxRecords??5e3,this.now=e.now??(()=>Date.now()),e.calibration){let r=Ir(e.calibration);this.calibracion={...r,judge:e.calibration.judge??Nn,perRecordFloors:e.calibration.
|
|
226
226
|
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){
|
|
227
227
|
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!==
|
|
228
228
|
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||
|
|
229
229
|
i.schemaVersion!==e.schemaVersion||i.safetyPolicyVersion!==e.safetyPolicyVersion||i.toolsetHash!==e.toolsetHash||i.toolTurnsHash!==e.toolTurnsHash||i.temperature!==e.temperature||i.seed!==e.seed||i.reasoningEffort!==
|
|
230
|
-
e.reasoningEffort||this.ttlMs!=null&&this.now()-i.storedAtMs>this.ttlMs)continue;let s=
|
|
230
|
+
e.reasoningEffort||this.ttlMs!=null&&this.now()-i.storedAtMs>this.ttlMs)continue;let s=Ci(r,i.embedding);if(s<this.similarityThreshold||!Ti(e.normalizedText,i.query))continue;let a=this.verify?await this.
|
|
231
231
|
verify(e.normalizedText,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.
|
|
232
232
|
similarityThreshold,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 {
|
|
233
233
|
hit:await this.mejorCandidata(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,
|
|
234
|
-
l=p=>({hit:null,probe:{reason:p,score:c,segment:o,record:i.record}});if(a==null)return l("calibrating");if(
|
|
235
|
-
i.record.failedAtScore!=null&&c<=i.record.failedAtScore)return l("record_floor");if(r.auditRate>0&&r.random()<r.auditRate)return l("audit");let u
|
|
234
|
+
l=p=>({hit:null,probe:{reason:p,score:c,segment:o,record:i.record}});if(a==null)return l("calibrating");if(Mn(c)<a||this.aceptacionExplicita&&c<this.acceptThreshold)return l("below_floor");if(r.perRecordFloors&&
|
|
235
|
+
i.record.failedAtScore!=null&&c<=i.record.failedAtScore)return l("record_floor");if(r.auditRate>0&&r.random()<r.auditRate)return l("audit");let u=$n(a),d=s.resumen();return {hit:{...i,acceptFloor:this.
|
|
236
236
|
aceptacionExplicita?Math.max(u,this.acceptThreshold):u,calibration:{maxErrorRate:r.maxErrorRate,confidence:r.confidence,floor:u,heldOutAtFloor:d.retenidasEnSuelo,wrongHeldOutAtFloor:d.erroneasEnSuelo,
|
|
237
237
|
labeled:d.etiquetas,segment:o}},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;
|
|
238
238
|
if(!r)return null;let o;try{o=await r.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.
|
|
239
239
|
failedAtScore??-1/0,e.score)),o}async settled(){for(;this.pendientes.size>0;)await Promise.allSettled([...this.pendientes]);}calibrationStatus(e="single_shot"){let n=this.calibracion;if(!n)return null;
|
|
240
|
-
let r=this.estadoDe(e).resumen();return {maxErrorRate:n.maxErrorRate,confidence:n.confidence,floor:r.suelo==null?null
|
|
241
|
-
wrongHeldOutAtFloor:r.erroneasEnSuelo,minHeldOutToCertify:r.minimasParaLaSiguiente,nextTestAt:r.etiquetasParaLaSiguiente}}exportCalibration(){return
|
|
242
|
-
let n=this.identidad("importCalibration"),r=e;if(typeof e=="string")try{r=JSON.parse(e);}catch{throw new
|
|
243
|
-
estados.get(i);if(s&&s.resumen().etiquetas>0)throw new
|
|
244
|
-
for(let[i,s]of o)this.estados.set(i,s);}identidad(e){let n=this.calibracion;if(!n)throw new
|
|
245
|
-
r ${c}, so that a saved calibration is only ever restored under the same one`)},o=this.embebedorPropio?`built_in:${
|
|
246
|
-
null?null:`custom:${this.nombres.verifier??r("verifierId","verifier")}`,s=n.judge===
|
|
247
|
-
maxErrorRate:n.maxErrorRate,confidence:n.confidence,similarityThreshold:this.similarityThreshold}}estadoDe(e){let n=this.estados.get(e);if(!n){let r=this.calibracion;n=new
|
|
240
|
+
let r=this.estadoDe(e).resumen();return {maxErrorRate:n.maxErrorRate,confidence:n.confidence,floor:r.suelo==null?null:$n(r.suelo),labeled:r.etiquetas,heldOut:r.retenidas,heldOutAtFloor:r.retenidasEnSuelo,
|
|
241
|
+
wrongHeldOutAtFloor:r.erroneasEnSuelo,minHeldOutToCertify:r.minimasParaLaSiguiente,nextTestAt:r.etiquetasParaLaSiguiente}}exportCalibration(){return dc(this.identidad("exportCalibration"),this.estados)}importCalibration(e){
|
|
242
|
+
let n=this.identidad("importCalibration"),r=e;if(typeof e=="string")try{r=JSON.parse(e);}catch{throw new _e("importCalibration: the state is a string but not JSON")}let o=pc(r,n);for(let[i]of o){let s=this.
|
|
243
|
+
estados.get(i);if(s&&s.resumen().etiquetas>0)throw new _e(`importCalibration: this cache has already recorded ${s.resumen().etiquetas} labels in the ${i} segment; import right after constructing it`)}
|
|
244
|
+
for(let[i,s]of o)this.estados.set(i,s);}identidad(e){let n=this.calibracion;if(!n)throw new _e(`${e}: this cache runs without \`calibration\``);let r=(a,c)=>{throw new _e(`${e}: pass \`${a}\` naming you\
|
|
245
|
+
r ${c}, so that a saved calibration is only ever restored under the same one`)},o=this.embebedorPropio?`built_in:${Ff}`:`custom:${this.nombres.embedder??r("embedderId","embed function")}`,i=this.verify==
|
|
246
|
+
null?null:`custom:${this.nombres.verifier??r("verifierId","verifier")}`,s=n.judge===Nn?`built_in:${qf}`:`custom:${this.nombres.judge??r("calibration.judgeId","judge")}`;return {embedder:o,verifier:i,judge:s,
|
|
247
|
+
maxErrorRate:n.maxErrorRate,confidence:n.confidence,similarityThreshold:this.similarityThreshold}}estadoDe(e){let n=this.estados.get(e);if(!n){let r=this.calibracion;n=new Ln(r.maxErrorRate,1-r.confidence),
|
|
248
248
|
this.estados.set(e,n);}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,
|
|
249
249
|
answer:n,tenantId:e.tenantId,authorizationScope:e.authorizationScope,principal:e.principal,knowledgeEpoch:e.knowledgeEpoch,contractId:e.contractId,model:e.model,systemPromptHash:e.systemPromptHash,structuredDataHash:e.
|
|
250
250
|
structuredDataHash,locale:e.locale,schemaVersion:e.schemaVersion,safetyPolicyVersion:e.safetyPolicyVersion,toolsetHash:e.toolsetHash,...e.toolTurnsHash!==void 0?{toolTurnsHash:e.toolTurnsHash}:{},temperature:e.
|
|
251
251
|
temperature,seed:e.seed,...e.reasoningEffort!==void 0?{reasoningEffort:e.reasoningEffort}:{},storedAtMs:this.now()});}invalidateEpoch(e){let n=0;for(let r=this.records.length-1;r>=0;r--)this.records[r].
|
|
252
|
-
knowledgeEpoch===e&&(this.records.splice(r,1),n++);return n}get size(){return this.records.length}};var
|
|
252
|
+
knowledgeEpoch===e&&(this.records.splice(r,1),n++);return n}get size(){return this.records.length}};var yc=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()>
|
|
253
253
|
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(
|
|
254
|
-
o);}this.entradas.set(e,{valor:n,vence:this.now()+r});}get size(){return this.entradas.size}};var
|
|
255
|
-
|
|
256
|
-
let r
|
|
257
|
-
return Number.isInteger(t)?String(t):String(Math.round(t*1e9)/1e9)}function
|
|
254
|
+
o);}this.entradas.set(e,{valor:n,vence:this.now()+r});}get size(){return this.entradas.size}};var Ri=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}},
|
|
255
|
+
Uf={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]??Vf(t.normalizedText))?.trim();if(!n)return null;
|
|
256
|
+
let r=Pi(n);return r===null||!Number.isFinite(r)?null:{text:Hf(r),data:{value:r},resolver:"arithmetic"}}};function Vf(t){return /^[0-9+\-*/%.()\s]+$/.test(t.trim())&&/[+\-*/%]/.test(t)?t.trim():null}function Hf(t){
|
|
257
|
+
return Number.isInteger(t)?String(t):String(Math.round(t*1e9)/1e9)}function Pi(t){let e=t.match(/\d+\.?\d*|[+\-*/%()]/g);if(!e||e.join("")!==t.replace(/\s+/g,""))return null;let n=[],r=[],o={"+":1,"-":1,
|
|
258
258
|
"*":2,"/":2,"%":2},i=a=>{let c=n.pop(),l=n.pop();if(l===void 0||c===void 0)return false;switch(a){case "+":return n.push(l+c),true;case "-":return n.push(l-c),true;case "*":return n.push(l*c),true;case "/":return c===
|
|
259
259
|
0?false:(n.push(l/c),true);case "%":return c===0?false:(n.push(l%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&&
|
|
260
260
|
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),
|
|
261
|
-
s=true;}for(;r.length;){let a=r.pop();if(a==="("||!i(a))return null}return n.length===1?n[0]:null}function
|
|
262
|
-
|
|
261
|
+
s=true;}for(;r.length;){let a=r.pop();if(a==="("||!i(a))return null}return n.length===1?n[0]:null}function kc(){return new Ri().register(Uf)}var Wf=/\b(compare|versus|\bvs\b|difference between|both|and then|after that|which is (?:better|cheaper|faster)|compar[ae]|diferencia entre)\b/i,xc=/\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,
|
|
262
|
+
Gf=/\b(summarize|rewrite|translate|classify|extract|reformat|fix|convert|the following|below|above|this text|resume|reescribe|traduce|clasifica)\b/i,Dr=class{classifier;maxRounds;constructor(e={}){this.
|
|
263
263
|
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.
|
|
264
|
-
test(r))return
|
|
265
|
-
.8,"self-contained transformation",0);let i=this.classifier?.classify(r);return i&&i.confidence>=.75?
|
|
266
|
-
e"?
|
|
267
|
-
d question",Math.min(this.maxRounds,2)):
|
|
268
|
-
"SINGLE_RETRIEVAL"?1:t==="MULTI_HOP_RETRIEVAL"?Math.min(e,2):0}function
|
|
269
|
-
nnet-4-6","claude-opus-4-5-20251101","claude-sonnet-4-5-20250929","claude-haiku-4-5-20251001"],
|
|
270
|
-
_tool_bm25_20251119",name:"tool_search_tool_bm25"},regex:{type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"}},
|
|
271
|
-
0?t.slice(e+1):t).toLowerCase()}function
|
|
264
|
+
test(r))return He("TOOL_ACTION",.9,"imperative + write tool available",0);if(n==="off")return He("NO_RETRIEVAL",1,"retrieval disabled by caller",0);if(Gf.test(r)&&!xc.test(r))return He("NO_RETRIEVAL",
|
|
265
|
+
.8,"self-contained transformation",0);let i=this.classifier?.classify(r);return i&&i.confidence>=.75?He(i.executionClass,i.confidence,"local classifier",Kf(i.executionClass,this.maxRounds)):n==="singl\
|
|
266
|
+
e"?He("SINGLE_RETRIEVAL",.7,"caller hint: single",1):n==="multi"?He("MULTI_HOP_RETRIEVAL",.7,"caller hint: multi",Math.min(this.maxRounds,2)):Wf.test(r)?He("MULTI_HOP_RETRIEVAL",.7,"comparison/compoun\
|
|
267
|
+
d question",Math.min(this.maxRounds,2)):xc.test(r)?He("SINGLE_RETRIEVAL",.65,"single factual lookup",1):He("NO_RETRIEVAL",.5,"no retrieval signal (conservative default)",0)}};function Kf(t,e){return t===
|
|
268
|
+
"SINGLE_RETRIEVAL"?1:t==="MULTI_HOP_RETRIEVAL"?Math.min(e,2):0}function He(t,e,n,r){return {executionClass:t,confidence:e,reason:n,rounds:r}}var Jf=["claude-fable-5-1","claude-mythos-5-1","claude-fable-5","claude-mythos-5","claude-opus-5-5","claude-opus-5","claude-sonnet-5-5","claude-opus-4-8","claude-opus-4-7","claude-opus-4-6","claude-so\
|
|
269
|
+
nnet-4-6","claude-opus-4-5-20251101","claude-sonnet-4-5-20250929","claude-haiku-4-5-20251001"],Ar={herramientas:10,tokensDeEsquemas:1e4},wc=5,Yf={regex:200,bm25:500},Sc=1e4,Or={bm25:{type:"tool_search\
|
|
270
|
+
_tool_bm25_20251119",name:"tool_search_tool_bm25"},regex:{type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"}},Zf="bvsala_contract";function Ec(t){let e=t.lastIndexOf("/");return (e>=
|
|
271
|
+
0?t.slice(e+1):t).toLowerCase()}function Ii(t){let e=r=>r.replace(/-\d{8}$/,""),n=e(Ec(t));return Jf.some(r=>e(r)===n)}function _i(t){let e={modo:"off",siempreCargadas:[],variante:"bm25"};if(t===void 0)
|
|
272
272
|
return e;let n=r=>r==="off"||r==="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)?
|
|
273
|
-
[...new Set(t.alwaysLoaded.filter(r=>typeof r=="string"))]:[],variante:t.variant==="regex"?"regex":"bm25"}}function
|
|
274
|
-
risk=="string")}function
|
|
273
|
+
[...new Set(t.alwaysLoaded.filter(r=>typeof r=="string"))]:[],variante:t.variant==="regex"?"regex":"bm25"}}function Di(t){return !t.some(e=>Array.isArray(e.intents)&&e.intents.length>0)&&!t.some(e=>typeof e.
|
|
274
|
+
risk=="string")}function Ai(t){let{opciones:e}=t,n=e.variante,r=(v,x={})=>({aplicar:false,razon:v,variante:n,siempreCargadas:[],diferidas:0,tokensDiferidos:0,...x});if(e.modo==="off")return r("toolSearch\
|
|
275
275
|
is off");if(t.herramientas.length===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; \
|
|
276
|
-
OpenAI documents tool search for its Responses and Agents APIs, not for Chat Completions, which is what the OpenAI-compatible adapter speaks");if(!
|
|
276
|
+
OpenAI documents tool search for its Responses and Agents APIs, not for Chat Completions, which is what the OpenAI-compatible adapter speaks");if(!Ii(t.modelo))return r(`${Ec(t.modelo)} is not in the \
|
|
277
277
|
provider's tool search model compatibility 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\
|
|
278
|
-
is not documented, so the selector keeps 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=
|
|
279
|
-
if(t.herramientas.some(v=>v.id===o.name))return r(`one of your tools is already named \`${o.name}\``);let i=new Set(t.herramientas.map(v=>v.id)),s=e.siempreCargadas.filter(v=>i.has(v)&&v!==
|
|
278
|
+
is not documented, so the selector keeps 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=Or[n];
|
|
279
|
+
if(t.herramientas.some(v=>v.id===o.name))return r(`one of your tools is already named \`${o.name}\``);let i=new Set(t.herramientas.map(v=>v.id)),s=e.siempreCargadas.filter(v=>i.has(v)&&v!==Zf),a=new Set(
|
|
280
280
|
s),c=t.herramientas.filter(v=>!a.has(v.id)),l=c.reduce((v,x)=>v+x.tokens,0),u={siempreCargadas:s,diferidas:c.length,tokensDiferidos:l};if(c.length===0)return r("every tool is in `alwaysLoaded`: nothin\
|
|
281
|
-
g to defer",u);if(c.length>
|
|
281
|
+
g to defer",u);if(c.length>Sc)return r(`${c.length} tools to defer, over the provider's limit of ${Sc}`,u);if(e.modo==="always")return {aplicar:true,variante:n,...u,razon:`toolSearch "always": ${c.length}\
|
|
282
282
|
tool(s) deferred behind the provider'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\
|
|
283
|
-
own API host; a proxy may not forward the search blocks. Use toolSearch "always" if yours does`,u);let d=t.herramientas.reduce((v,x)=>v+x.tokens,0);if(t.herramientas.length<
|
|
283
|
+
own API host; a proxy may not forward the search blocks. Use toolSearch "always" if yours does`,u);let d=t.herramientas.reduce((v,x)=>v+x.tokens,0);if(t.herramientas.length<Ar.herramientas&&d<=Ar.tokensDeEsquemas)
|
|
284
284
|
return r(`${t.herramientas.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 b\
|
|
285
|
-
etter`,u);let p=t.precio.inputPer1k/1e3,
|
|
285
|
+
etter`,u);let p=t.precio.inputPer1k/1e3,h=t.precio.outputPer1k/1e3,f=Math.min(1,Math.max(0,t.lecturaDeCache)),m=c.map(v=>v.tokens).sort((v,x)=>x-v).slice(0,wc).reduce((v,x)=>v+x,0),g=f*p*l,b=p*m+h*Yf[n],
|
|
286
286
|
y={ahorroDelPrefijo:g,costeDeUnaBusqueda:b};return g<b?r(`deferring ${l} tokens of definitions saves ${g.toFixed(6)} per request even with a warm prompt cache, less than one worst-case search costs (${b.
|
|
287
|
-
toFixed(6)}: the ${
|
|
287
|
+
toFixed(6)}: the ${wc} largest definitions uncached plus the longest query); the selector keeps this request`,{...u,...y}):{aplicar:true,variante:n,...u,...y,razon:`${c.length} tool(s) deferred behind t\
|
|
288
288
|
he provider's ${n} search (${l} tokens of definitions out of the cached prefix): it pays even if every request searches once with a warm cache (${g.toFixed(6)} saved vs ${b.toFixed(6)} worst-case sear\
|
|
289
|
-
ch). The provider's counter measures it; the layer credits nothing for it`}}function
|
|
290
|
-
this.maxTools=e.maxTools,this.scoreIntentMatch=e.scoreIntentMatch??
|
|
289
|
+
ch). The provider's counter measures it; the layer credits nothing for it`}}function Cc(t,e,n){return n||Di(t)?[...t]:t.filter(r=>e||r.risk==="read")}var Oi=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});}},Lr=class{maxTools;scoreIntentMatch;learningTurns;freezer;constructor(e={}){
|
|
290
|
+
this.maxTools=e.maxTools,this.scoreIntentMatch=e.scoreIntentMatch??Xf,this.learningTurns=e.learningTurns??16,this.freezer=e.freezer??new Oi;}passthrough(e){return !e||e.length===0?{tools:[],droppedIds:[],
|
|
291
291
|
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 \
|
|
292
|
-
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(
|
|
292
|
+
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(Di(n)){let b=this.passthrough(n);return {...b,reason:`ca\
|
|
293
293
|
talogue declares no \`intents\` and no \`risk\`: nothing to select on, passed through whole (${b.tools.length}/${n.length}). Declare ToolDescriptor.intents/risk to enable pruning`}}let i=r==="TOOL_ACT\
|
|
294
294
|
ION",s=n.filter(b=>i||b.risk==="read"),a=b=>i&&b.risk!=="read",c=s.filter(b=>!a(b)),l=s.filter(b=>a(b));if(this.maxTools===void 0){let b=new Set(s.map(v=>v.id)),y=n.filter(v=>!b.has(v.id)).map(v=>v.id);
|
|
295
295
|
return {tools:s,droppedIds:y,reason:`no maxTools: every tool this request may use passed (${s.length}/${n.length}; writes ${i?"allowed":"blocked"}); set ToolSelectorOptions.maxTools to prune by relevan\
|
|
296
296
|
ce`,setIsStable:y.length===0}}let u=this.maxTools,d=l.map(b=>({tool:b,score:this.scoreIntentMatch(e,b)})).sort((b,y)=>y.score-b.score).map(b=>b.tool),p=c.map(b=>({tool:b,score:this.scoreIntentMatch(e,
|
|
297
|
-
b)})).filter(b=>b.score>0).sort((b,y)=>y.score-b.score).map(b=>b.tool),
|
|
298
|
-
if(o!==void 0){let b=this.freezer.read(o),y=(b?.turns??0)+1;if(b&&y>this.learningTurns){let x=new Set(b.ids),
|
|
299
|
-
tools:
|
|
300
|
-
x cache survives`,setIsStable:true}}let v=[...new Set([...b?.ids??[],...
|
|
301
|
-
id);return {tools:
|
|
302
|
-
isArray(e.intents)?e.intents:[]){let i=
|
|
297
|
+
b)})).filter(b=>b.score>0).sort((b,y)=>y.score-b.score).map(b=>b.tool),f=[...d.slice(0,u),...p.slice(0,Math.max(0,u-l.length))].map(b=>({tool:b})).map(b=>b.tool).sort((b,y)=>b.id<y.id?-1:b.id>y.id?1:0);
|
|
298
|
+
if(o!==void 0){let b=this.freezer.read(o),y=(b?.turns??0)+1;if(b&&y>this.learningTurns){let x=new Set(b.ids),E=n.filter(C=>x.has(C.id));this.freezer.record(o,b.ids,y);let S=new Set(E.map(C=>C.id));return {
|
|
299
|
+
tools:E,droppedIds:n.filter(C=>!S.has(C.id)).map(C=>C.id),reason:`frozen tool set after ${this.learningTurns} turns (${E.length}/${n.length}): it no longer depends on this request's text, so the prefi\
|
|
300
|
+
x cache survives`,setIsStable:true}}let v=[...new Set([...b?.ids??[],...f.map(x=>x.id)])].sort().slice(0,u);this.freezer.record(o,v,y);}let m=new Set(f.map(b=>b.id)),g=n.filter(b=>!m.has(b.id)).map(b=>b.
|
|
301
|
+
id);return {tools:f,droppedIds:g,reason:`selected ${f.length}/${n.length} by intent match (writes ${i?"allowed":"blocked"})`,setIsStable:g.length===0}}};function Xf(t,e){let n=tn(t),r=0;for(let o of Array.
|
|
302
|
+
isArray(e.intents)?e.intents:[]){let i=tn(o);i&&(n.includes(i)?r+=2:i.split(/\s+/).some(s=>s.length>3&&n.includes(s))&&(r+=1));}return r}function Li(t){let e=new Set,n=[];for(let r of t){let o=r.hash??Qf(r.text);e.has(o)||(e.add(o),n.push(r));}return n}function Mi(t,e={maxDocuments:5}){let n=e.minDocuments??1,r=[...t].sort((s,a)=>(a.score??
|
|
303
303
|
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(
|
|
304
|
-
s);else break}return i}async function
|
|
305
|
-
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=
|
|
306
|
-
(r=await e.reranker.rerank(t.query,r));let i=
|
|
307
|
-
...t.userPreferences},decisions:[...t.decisions],openItems:[...t.openItems],evidenceRefs:[...t.evidenceRefs]};for(let[r,o]of Object.entries(e.set??{}))r==="userPreferences"&&
|
|
308
|
-
o):n.confirmedFacts[r]=o;for(let[r,o]of Object.entries(e.append??{})){let i=
|
|
309
|
-
|
|
310
|
-
${r}`});let o=t.history.slice(-e);return n.push(...o,t.current),n}function
|
|
304
|
+
s);else break}return i}async function Mr(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};
|
|
305
|
+
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=Li(r),e.reranker&&
|
|
306
|
+
(r=await e.reranker.rerank(t.query,r));let i=Mi(r,{maxDocuments:t.maxDocuments});return {docs:i,rounds:n,retrievedCount:o,keptCount:i.length}}function Qf(t){return t.trim().replace(/\s+/g," ").toLowerCase()}function fx(){return {goals:[],confirmedFacts:{},userPreferences:{},decisions:[],openItems:[],evidenceRefs:[]}}function mx(t,e){let n={goals:[...t.goals],confirmedFacts:{...t.confirmedFacts},userPreferences:{
|
|
307
|
+
...t.userPreferences},decisions:[...t.decisions],openItems:[...t.openItems],evidenceRefs:[...t.evidenceRefs]};for(let[r,o]of Object.entries(e.set??{}))r==="userPreferences"&&rm(o)?Object.assign(n.userPreferences,
|
|
308
|
+
o):n.confirmedFacts[r]=o;for(let[r,o]of Object.entries(e.append??{})){let i=tm(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],
|
|
309
|
+
nm(n,r);return n}function Tc(t){let e=t.rawTurns??3,n=[],r=em(t.state);r&&n.push({role:"system",content:`Conversation state:
|
|
310
|
+
${r}`});let o=t.history.slice(-e);return n.push(...o,t.current),n}function em(t){let e=[];return t.goals.length&&e.push(`goals: ${t.goals.join("; ")}`),Object.keys(t.confirmedFacts).length&&e.push(`fa\
|
|
311
311
|
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(
|
|
312
312
|
"; ")}`),t.openItems.length&&e.push(`open: ${t.openItems.join("; ")}`),e.join(`
|
|
313
|
-
`)}function
|
|
314
|
-
for(let n of ["goals","decisions","openItems","evidenceRefs"]){let r=t[n].indexOf(e);r>=0&&t[n].splice(r,1);}}function
|
|
315
|
-
`).filter(c=>c.trim().length>0).map(c=>({indent:
|
|
316
|
-
c[2],n),d=Number(c[1]),p=[];for(let
|
|
317
|
-
match(/^\[(\d+)\]:\s*(.*)$/);if(l){let u=l[2];return Number(l[1])===0||u.trim()===""?[]:
|
|
318
|
-
function
|
|
313
|
+
`)}function tm(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 nm(t,e){
|
|
314
|
+
for(let n of ["goals","decisions","openItems","evidenceRefs"]){let r=t[n].indexOf(e);r>=0&&t[n].splice(r,1);}}function rm(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Rc={format:"json-compact",supports(){return true},encode(t){return JSON.stringify(t)},instruction(){return ""}};function Pc(t,e={}){let n=e.delimiter??",",r=e.indent??" ",i=t.split(`
|
|
315
|
+
`).filter(c=>c.trim().length>0).map(c=>({indent:om(c,r),content:c.slice(Ic(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 u=on(
|
|
316
|
+
c[2],n),d=Number(c[1]),p=[];for(let h=0,f=1;h<d&&f<i.length;h++,f++){let m=i[f];if(m.indent!==1)break;let g=on(m.content,n),b={};u.forEach((y,v)=>{b[y]=Bn(g[v]??"null");}),p.push(b);}return p}let l=s.content.
|
|
317
|
+
match(/^\[(\d+)\]:\s*(.*)$/);if(l){let u=l[2];return Number(l[1])===0||u.trim()===""?[]:on(u,n).map(Bn)}}let[a]=_c(i,0,0,n);return a}function Ic(t,e){let n=0;for(;t.startsWith(e,n);)n+=e.length;return n}
|
|
318
|
+
function om(t,e){return Ic(t,e)/e.length}function _c(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=im(s.content,r);if(!a){i++;continue}let{key:c,
|
|
319
319
|
kind:l}=a;if(l.type==="scalar")o[c]=l.value,i++;else if(l.type==="inlineArray")o[c]=l.values,i++;else if(l.type==="emptyArray")o[c]=[],i++;else if(l.type==="table"){let u=[];i++;for(let d=0;d<l.count&&
|
|
320
|
-
i<t.length;d++,i++){let p=t[i];if(p.indent!==n+1)break;let
|
|
321
|
-
i]}function
|
|
322
|
-
let i=Number(r[2]),s=r[3];return i===0||s.trim()===""?{key
|
|
323
|
-
o[1]),s=o[2];return s===""?{key:i,kind:{type:"object"}}:{key:i,kind:{type:"scalar",value:
|
|
324
|
-
'"'?(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
|
|
325
|
-
'"'):t==="null"?null:t==="true"?true:t==="false"?false:/^-?\d+$/.test(t)||/^-?\d*\.\d+$/.test(t)?Number(t):t}function
|
|
326
|
-
'"'):e}function
|
|
327
|
-
`)}function
|
|
328
|
-
e))
|
|
329
|
-
join(o);r.push(`${s}${a}[${e.length}]: ${d}`);return}let c=
|
|
330
|
-
return}r.push(`${s}${a}[${e.length}]:`);let l=n+1,u=i.repeat(l);for(let d of e)if(
|
|
331
|
-
r.push(`${u}${i}${
|
|
332
|
-
o))return null;let i=Object.keys(o);if(i.slice().sort().join("\0")!==r)return null;for(let s of i)if(
|
|
320
|
+
i<t.length;d++,i++){let p=t[i];if(p.indent!==n+1)break;let h=on(p.content,r),f={};l.columns.forEach((m,g)=>{f[m]=Bn(h[g]??"null");}),u.push(f);}o[c]=u;}else {let[u,d]=_c(t,i+1,n+1,r);o[c]=u,i=d;}}return [o,
|
|
321
|
+
i]}function im(t,e){let n=t.match(/^([^[:]+)\[(\d+)\]\{(.*)\}:\s*$/);if(n)return {key:$r(n[1]),kind:{type:"table",count:Number(n[2]),columns:on(n[3],e)}};let r=t.match(/^([^[:]+)\[(\d+)\]:\s*(.*)$/);if(r){
|
|
322
|
+
let i=Number(r[2]),s=r[3];return i===0||s.trim()===""?{key:$r(r[1]),kind:{type:"emptyArray"}}:{key:$r(r[1]),kind:{type:"inlineArray",values:on(s,e).map(Bn)}}}let o=t.match(/^([^:]+):\s*(.*)$/);if(o){let i=$r(
|
|
323
|
+
o[1]),s=o[2];return s===""?{key:i,kind:{type:"object"}}:{key:i,kind:{type:"scalar",value:Bn(s)}}}return null}function on(t,e){let n=[],r="",o=false;for(let i=0;i<t.length;i++){let s=t[i];o?s==='"'?t[i+1]===
|
|
324
|
+
'"'?(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 Bn(t){return t.startsWith('"')&&t.endsWith('"')&&t.length>=2?t.slice(1,-1).replace(/""/g,
|
|
325
|
+
'"'):t==="null"?null:t==="true"?true:t==="false"?false:/^-?\d+$/.test(t)||/^-?\d*\.\d+$/.test(t)?Number(t):t}function $r(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/""/g,
|
|
326
|
+
'"'):e}function sm(t,e={}){let n=e.delimiter??",",r=e.indent??" ",o=[];return ji(null,t,0,o,n,r),o.join(`
|
|
327
|
+
`)}function ji(t,e,n,r,o,i){let s=i.repeat(n),a=t===null?"":`${cm(t)}`;if(Array.isArray(e)){am(a,e,n,r,o,i);return}if(Ni(e)){t!==null&&r.push(`${s}${a}:`);let c=t===null?n:n+1;for(let[l,u]of Object.entries(
|
|
328
|
+
e))ji(l,u,c,r,o,i);return}r.push(`${s}${a}: ${Nr(e,o)}`);}function am(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($i)){let d=e.map(p=>Nr(p,o)).
|
|
329
|
+
join(o);r.push(`${s}${a}[${e.length}]: ${d}`);return}let c=sn(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(f=>Nr(p[f],o)).join(o);r.push(`${d}${h}`);}
|
|
330
|
+
return}r.push(`${s}${a}[${e.length}]:`);let l=n+1,u=i.repeat(l);for(let d of e)if($i(d))r.push(`${u}- ${Nr(d,o)}`);else {let p=[];ji(null,d,0,p,o,i);let[h,...f]=p;r.push(`${u}- ${h??""}`);for(let m of f)
|
|
331
|
+
r.push(`${u}${i}${m}`);}}function sn(t){if(t.length===0)return null;let e=t[0];if(!Ni(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(!Ni(
|
|
332
|
+
o))return null;let i=Object.keys(o);if(i.slice().sort().join("\0")!==r)return null;for(let s of i)if(!$i(o[s]))return null}return n}function cm(t){return /^[A-Za-z_][A-Za-z0-9_]*$/.test(t)?t:Dc(t)}function Nr(t,e){
|
|
333
333
|
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(`
|
|
334
|
-
`)||n.includes('"')||n!==n.trim()||/^(true|false|null)$/.test(n)||/^-?\d/.test(n)?
|
|
335
|
-
"number"||typeof t=="boolean"}function
|
|
336
|
-
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
|
|
337
|
-
encode(e){return
|
|
338
|
-
`)},instruction(){return "Data is CSV: first line is the header row; each subsequent line is one record."}};function
|
|
339
|
-
'""')}"`:e}var
|
|
334
|
+
`)||n.includes('"')||n!==n.trim()||/^(true|false|null)$/.test(n)||/^-?\d/.test(n)?Dc(n):n}function Dc(t){return `"${t.replace(/"/g,'""')}"`}function $i(t){return t===null||typeof t=="string"||typeof t==
|
|
335
|
+
"number"||typeof t=="boolean"}function Ni(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var lm="Data is the compact encoder: `key[N]{c1,c2}:` declares an N-row table with columns c1,c2; ea\
|
|
336
|
+
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 um(t={}){return {format:"compact-rows",supports(){return true},
|
|
337
|
+
encode(e){return sm(e,t)},instruction(){return lm},decode(e){return Pc(e,t)}}}var Ac=um();var Lc={format:"csv",supports(t){return Array.isArray(t)&&sn(t)!==null},encode(t){let e=t,n=sn(e),r=n.map(Oc).join(","),o=e.map(i=>n.map(s=>Oc(i[s])).join(","));return [r,...o].join(`
|
|
338
|
+
`)},instruction(){return "Data is CSV: first line is the header row; each subsequent line is one record."}};function Oc(t){if(t==null)return "";let e=String(t);return /[",\n]/.test(e)?`"${e.replace(/"/g,
|
|
339
|
+
'""')}"`:e}var jr=class{tokenizer;serializers;minSavingsTokens;minSavingsRatio;qualityPenalty;constructor(e){this.tokenizer=e.tokenizer,this.serializers=e.serializers??[Rc,Ac,Lc],this.minSavingsTokens=e.minimumSavingsTokens??
|
|
340
340
|
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 l of this.serializers){if(!l.supports(
|
|
341
|
-
e))continue;let u=l.encode(e);if(l.format!=="json-compact"&&!
|
|
342
|
-
o.push({format:l.format,encoded:u,instruction:d,payloadTokens:p,instructionTokens:
|
|
343
|
-
return l?
|
|
341
|
+
e))continue;let u=l.encode(e);if(l.format!=="json-compact"&&!dm(l,u,e))continue;let d=l.instruction(e),p=this.tokenizer.count(u,r),h=d?this.tokenizer.count(d,r):0,f=this.qualityPenalty(n.model??"",l.format);
|
|
342
|
+
o.push({format:l.format,encoded:u,instruction:d,payloadTokens:p,instructionTokens:h,penalty:f,total:p+h+f});}let i=o.find(l=>l.format==="json-compact"),s={};for(let l of o)s[l.format]=l.total;if(!i){let l=o[0];
|
|
343
|
+
return l?Mc(l,s,"json baseline unavailable"):{chosen:"json-compact",encoded:JSON.stringify(e),instruction:"",candidateTokens:s,instructionOverheadTokens:0,reason:"no serializer supported payload; defa\
|
|
344
344
|
ulted to JSON"}}let a=i,c="json baseline (no challenger cleared thresholds)";for(let l of o){if(l.format==="json-compact")continue;let u=i.total-l.total,d=i.total===0?0:u/i.total;u>=this.minSavingsTokens&&
|
|
345
|
-
d>=this.minSavingsRatio&&l.total<a.total&&(a=l,c=`${l.format} saved ${u} tokens (${(d*100).toFixed(1)}%) vs json`);}return
|
|
346
|
-
n)}catch{return false}}function
|
|
347
|
-
length)return false;for(let s=0;s<t.length;s++)if(!
|
|
348
|
-
call(e,s)||!
|
|
349
|
-
string":return "string";case "number":return "number";case "boolean":return "boolean";default:return}}function
|
|
350
|
-
e.type??
|
|
351
|
-
message:"expected boolean"});break;case "null":t!==null&&r.push({path:n,message:"expected null"});break;}}function
|
|
345
|
+
d>=this.minSavingsRatio&&l.total<a.total&&(a=l,c=`${l.format} saved ${u} tokens (${(d*100).toFixed(1)}%) vs json`);}return Mc(a,s,c)}};function dm(t,e,n){if(!t.decode)return false;try{return Bi(t.decode(e),
|
|
346
|
+
n)}catch{return false}}function Bi(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.
|
|
347
|
+
length)return false;for(let s=0;s<t.length;s++)if(!Bi(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.
|
|
348
|
+
call(e,s)||!Bi(t[s],e[s]))return false;return true}function Mc(t,e,n){return {chosen:t.format,encoded:t.encoded,instruction:t.instruction,candidateTokens:e,instructionOverheadTokens:t.instructionTokens,reason:n}}function be(t,e,n="$"){let r=[];return zi(t,e,n,r),{valid:r.length===0,errors:r}}function pm(t){if(Array.isArray(t))return "array";if(t===null)return "null";switch(typeof t){case "object":return "object";case "\
|
|
349
|
+
string":return "string";case "number":return "number";case "boolean":return "boolean";default:return}}function zi(t,e,n,r){switch(e.enum&&!e.enum.some(i=>bm(i,t))&&r.push({path:n,message:"value not in enum"}),
|
|
350
|
+
e.type??pm(t)){case "object":fm(t,e,n,r);break;case "array":mm(t,e,n,r);break;case "string":hm(t,e,n,r);break;case "number":case "integer":gm(t,e,n,r);break;case "boolean":typeof t!="boolean"&&r.push({path:n,
|
|
351
|
+
message:"expected boolean"});break;case "null":t!==null&&r.push({path:n,message:"expected null"});break;}}function fm(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t)){r.push({path:n,
|
|
352
352
|
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(
|
|
353
353
|
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&&
|
|
354
|
-
|
|
355
|
-
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)=>
|
|
354
|
+
zi(o[i],s,`${n}.${i}`,r);}function mm(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\
|
|
355
|
+
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)=>zi(o,e.items,`${n}[${i}]`,r));}function hm(t,e,n,r){if(typeof t!=
|
|
356
356
|
"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.
|
|
357
357
|
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\
|
|
358
|
-
sion: ${e.pattern}`});}o&&!o.test(t)&&r.push({path:n,message:"string does not match pattern"});}}function
|
|
358
|
+
sion: ${e.pattern}`});}o&&!o.test(t)&&r.push({path:n,message:"string does not match pattern"});}}function gm(t,e,n,r){if(typeof t!="number"||Number.isNaN(t)){r.push({path:n,message:"expected number"});return}
|
|
359
359
|
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.
|
|
360
|
-
minimum&&r.push({path:n,message:`number below minimum ${e.minimum}`});}function
|
|
361
|
-
e,n,r),r}};function
|
|
362
|
-
.${r}`,n);}t.type==="array"&&(t.maxItems==null&&n.push(`${e}: array should set maxItems to bound output`),t.items&&
|
|
363
|
-
tring should set maxLength or use an enum`);}function
|
|
364
|
-
ate + repair"}}function
|
|
365
|
-
return r<n?{compress:false,reason:`net saving ${r} < ${n} min`}:{compress:true,reason:`net saving ${r} tokens`}}function
|
|
360
|
+
minimum&&r.push({path:n,message:`number below minimum ${e.minimum}`});}function bm(t,e){return t===e?true:typeof t!=typeof e?false:t&&e&&typeof t=="object"?JSON.stringify(t)===JSON.stringify(e):false}var Br=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 Fi(
|
|
361
|
+
e,n,r),r}};function Fi(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??{}))Fi(o,`${e}\
|
|
362
|
+
.${r}`,n);}t.type==="array"&&(t.maxItems==null&&n.push(`${e}: array should set maxItems to bound output`),t.items&&Fi(t.items,`${e}[]`,n)),t.type==="string"&&t.maxLength==null&&!t.enum&&n.push(`${e}: s\
|
|
363
|
+
tring should set maxLength or use an enum`);}function zr(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\
|
|
364
|
+
ate + repair"}}function Nx(t=()=>true){return {id:"provider-native",supports:t}}function zn(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;
|
|
365
|
+
return r<n?{compress:false,reason:`net saving ${r} < ${n} min`}:{compress:true,reason:`net saving ${r} tokens`}}function $c(t){return {async compress(e){let n=e.protectedSpans??[],r=e.text,o=[];n.forEach((c,l)=>{
|
|
366
366
|
let u=`\0PROTECT_${l}\0`;o.push({token:u,span:c}),r=r.split(c.text).join(u);});let i=await t.compress({text:r,...e.targetRatio!=null?{targetRatio:e.targetRatio}:{}}),s=i.compressed,a=true;for(let{token:c,
|
|
367
367
|
span:l}of o){if(!s.includes(c)){a=false;break}s=s.split(c).join(l.text);}return a?{...i,compressed:s,protectedSpans:n.length,fidelityPassed:true}:{compressed:e.text,originalTokens:i.originalTokens,compressedTokens:i.
|
|
368
|
-
originalTokens,protectedSpans:n.length,fidelityPassed:false,skipped:true,reason:"protected span lost during compression; fell back to original"}}}}var
|
|
369
|
-
compressedTokens:0,protectedSpans:(t.protectedSpans??[]).length,fidelityPassed:true,skipped:true,reason:"no compressor configured (noop)"}}};function
|
|
368
|
+
originalTokens,protectedSpans:n.length,fidelityPassed:false,skipped:true,reason:"protected span lost during compression; fell back to original"}}}}var Vx={async compress(t){return {compressed:t.text,originalTokens:0,
|
|
369
|
+
compressedTokens:0,protectedSpans:(t.protectedSpans??[]).length,fidelityPassed:true,skipped:true,reason:"no compressor configured (noop)"}}};function Nc(t,e){let n=s=>s.toLowerCase().replace(/[.,;:!¡?¿()[\]{}"«»…]/g,
|
|
370
370
|
" ").replace(/\s+/g," ").trim(),o=n((s=>{let a=new Set,c=[];for(let l of s.split(`
|
|
371
371
|
`)){let u=l.trim();u&&a.has(u)||(u&&a.add(u),c.push(l));}return c.join(`
|
|
372
|
-
`)})(t)),i=n(e);return !(!
|
|
373
|
-
let e=t.replace(
|
|
372
|
+
`)})(t)),i=n(e);return !(!jn(_t(o),_t(i))||At(Dt(o))!==At(Dt(i)))}var qi=["ansi","carriage-return","json","repeated-lines"],vm=256,ym=/\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)|[ -/]+[0-~]|[@-_])/g;function km(t){if(!t.includes("\x1B"))return null;
|
|
373
|
+
let e=t.replace(ym,"");return e.length<t.length?e:null}function xm(t){let e="";for(let n of t.split("\r"))e=n+e.slice(n.length);return e}function wm(t){if(!t.includes("\r")||t.includes(`\r
|
|
374
374
|
`))return null;let e=t.split(`
|
|
375
|
-
`).map(n=>n.includes("\r")?
|
|
376
|
-
`);return e.length<t.length?e:null}var
|
|
377
|
-
i=0,s=false;for(let c=0;c<e.length;c++){let l=e.charCodeAt(c);if(s){l===92?c+=1:l===34&&(s=false);continue}if(l===34){s=true;continue}
|
|
378
|
-
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
|
|
379
|
-
[previous line repeated ${t} more times]`,
|
|
380
|
-
`)){let r=
|
|
381
|
-
`)}function
|
|
382
|
-
`);if(e.length<
|
|
375
|
+
`).map(n=>n.includes("\r")?xm(n):n).join(`
|
|
376
|
+
`);return e.length<t.length?e:null}var Sm=t=>t===32||t===9||t===10||t===13;function Em(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=[],
|
|
377
|
+
i=0,s=false;for(let c=0;c<e.length;c++){let l=e.charCodeAt(c);if(s){l===92?c+=1:l===34&&(s=false);continue}if(l===34){s=true;continue}Sm(l)&&(c>i&&o.push(e.slice(i,c)),i=c+1);}i<e.length&&o.push(e.slice(i));let a=o.
|
|
378
|
+
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 zc=/^\[previous line repeated (\d+) more times\]$/,Cm=t=>`\
|
|
379
|
+
[previous line repeated ${t} more times]`,jc=3;function Tm(t){let e=[];for(let n of t.split(`
|
|
380
|
+
`)){let r=zc.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(`
|
|
381
|
+
`)}function Rm(t){let e=t.split(`
|
|
382
|
+
`);if(e.length<jc||e.some(i=>zc.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,l=Cm(c);if(c+1>=jc&&c*(s.length+1)>l.length+1)n.push(
|
|
383
383
|
s,l),r+=c;else for(let u=i;u<a;u++)n.push(e[u]);i=a;}if(r===0)return null;let o=n.join(`
|
|
384
|
-
`);return
|
|
385
|
-
o=t,i=[];for(let a of
|
|
386
|
-
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
|
|
387
|
-
applied:[],originalChars:t.length,compactChars:t.length,reason:e}}var
|
|
388
|
-
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=>
|
|
384
|
+
`);return Tm(o)!==t?null:o.length<t.length?o:null}var Pm={ansi:km,"carriage-return":wm,json:Em,"repeated-lines":Rm};function Fc(t,e={}){let n=new Set(e.transforms??qi),r=Math.max(1,e.minSavedChars??256),
|
|
385
|
+
o=t,i=[];for(let a of qi){if(!n.has(a))continue;let c=Pm[a](o);c!=null&&c.length<o.length&&(o=c,i.push(a));}let s=t.length-o.length;return i.length===0?Bc(t,"nothing to compact"):s<r?Bc(t,`compaction w\
|
|
386
|
+
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 Bc(t,e){return {text:t,changed:false,
|
|
387
|
+
applied:[],originalChars:t.length,compactChars:t.length,reason:e}}var Im=new Set(["path","paths","file","files","filepath","filename","absolutepath","relativepath","targetfile","notebookpath"]);function _m(t){
|
|
388
|
+
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=>Im.has(n.toLowerCase().replace(/[_-]/g,"")))}function qc(t,e={}){let n=new Map,
|
|
389
389
|
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,
|
|
390
|
-
exceptuados:0};return t.forEach((s,a)=>{if(s.role!=="tool")return;let c=s.toolCallId?n.get(s.toolCallId):void 0,l=c?.nombre??s.name;if(l&&o.has(l)){i.exceptuados+=1;return}if(!e.compactFileViews&&
|
|
391
|
-
argumentos)){i.vistasDeFichero+=1;return}let u=
|
|
392
|
-
`),o=
|
|
393
|
-
options.data??
|
|
390
|
+
exceptuados:0};return t.forEach((s,a)=>{if(s.role!=="tool")return;let c=s.toolCallId?n.get(s.toolCallId):void 0,l=c?.nombre??s.name;if(l&&o.has(l)){i.exceptuados+=1;return}if(!e.compactFileViews&&_m(c?.
|
|
391
|
+
argumentos)){i.vistasDeFichero+=1;return}let u=Fc(s.content,e);u.changed&&i.compactados.push({indice:a,texto:u.text,aplicadas:u.applied,enLaCola:a>r});}),i}var Uc=new WeakSet;function Vc(t){Uc.add(t);}function Ui(t){return typeof t=="object"&&t!==null&&Uc.has(t)}var Vi=class{id="mock";options;constructor(e={}){this.options=e,Vc(this);}async generate(e,n){let r=e.messages.map(c=>c.content).join(`
|
|
392
|
+
`),o=en.count(r);if(e.tools&&e.tools.length>0){let c=JSON.stringify(e.tools.map(l=>({name:l.id,description:l.description,parameters:l.parameters??{}})));o+=en.count(c);}let i,s=false;if(e.schema){let c=this.
|
|
393
|
+
options.data??Fr(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,en.count(i));return {text:i,usage:{
|
|
394
394
|
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.
|
|
395
|
-
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
|
|
396
|
-
enum[0];switch(t.type){case "object":{let e={};for(let n of t.required??[]){let r=t.properties?.[n];e[n]=r?
|
|
397
|
-
array":return t.items?[
|
|
398
|
-
t)}function
|
|
399
|
-
Number(e[2]);return n>5||n===5&&r>=6}function Ne(t){let e=
|
|
400
|
-
return
|
|
401
|
-
|
|
395
|
+
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 Fr(t){if(t.enum&&t.enum.length>0)return t.
|
|
396
|
+
enum[0];switch(t.type){case "object":{let e={};for(let n of t.required??[]){let r=t.properties?.[n];e[n]=r?Fr(r):null;}for(let[n,r]of Object.entries(t.properties??{}))n in e||(e[n]=Fr(r));return e}case "\
|
|
397
|
+
array":return t.items?[Fr(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 Qx(t){return new Vi(
|
|
398
|
+
t)}function Hi(t){let e=t.toLowerCase(),n=e.lastIndexOf("/");return n>=0?e.slice(n+1):e}function Hc(t){let e=/^gpt-(\d+)(?:\.(\d+))?(?![\d.])/.exec(t);if(!e)return false;let n=Number(e[1]),r=e[2]===void 0?0:
|
|
399
|
+
Number(e[2]);return n>5||n===5&&r>=6}function Ne(t){let e=Hi(t);return e.startsWith("gpt-")||e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4")?Hc(e)?1.25:1:e.startsWith("gemini")?1:1.25}function Fn(t){
|
|
400
|
+
return Hc(Hi(t))?1.25:1}function qn(t){let e=t.toLowerCase();return e.startsWith("claude")||e.startsWith("anthropic/")||Hi(e).startsWith("claude")?2:Ne(t)}var Dm="https://developers.openai.com/api/docs/pricing",Am="https://ai.google.dev/gemini-api/docs/pricing",Wi="2026-09-27",z=t=>({...t,fuente:Dm,consultado:Wi}),je=t=>({...t,fuente:Am,consultado:Wi}),
|
|
401
|
+
Om="https://platform.claude.com/docs/en/about-claude/pricing",oe=t=>({...t,fuente:Om,consultado:Wi}),Lm={openai:{flex:{"gpt-5":z({inputPer1k:625e-6,cachedInputPer1k:625e-7,outputPer1k:.005}),"gpt-5-mi\
|
|
402
402
|
ni":z({inputPer1k:125e-6,cachedInputPer1k:125e-7,outputPer1k:.001}),"gpt-5-nano":z({inputPer1k:25e-6,cachedInputPer1k:25e-7,outputPer1k:2e-4}),"gpt-5.2":z({inputPer1k:875e-6,cachedInputPer1k:875e-7,outputPer1k:.007}),
|
|
403
403
|
"gpt-5.4":z({inputPer1k:.00125,cachedInputPer1k:13e-5,outputPer1k:.0075,largo:{estandar:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225},tier:{inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.01125}}}),
|
|
404
404
|
"gpt-5.4-mini":z({inputPer1k:375e-6,cachedInputPer1k:375e-7,outputPer1k:.00225}),"gpt-5.4-nano":z({inputPer1k:1e-4,cachedInputPer1k:1e-5,outputPer1k:625e-6}),"gpt-5.5":z({inputPer1k:.0025,cachedInputPer1k:25e-5,
|
|
@@ -441,105 +441,105 @@ outputPer1k:.006,cachedInputPer1k:2e-4,largo:{estandar:{inputPer1k:.004,outputPe
|
|
|
441
441
|
outputPer1k:.005,cachedInputPer1k:125e-6,largo:{estandar:{inputPer1k:.0025,outputPer1k:.015,cachedInputPer1k:25e-5},tier:{inputPer1k:.00125,outputPer1k:.0075,cachedInputPer1k:25e-5}}}),"gemini-2.5-fla\
|
|
442
442
|
sh":je({inputPer1k:15e-5,outputPer1k:.00125,cachedInputPer1k:3e-5}),"gemini-3.8-flash":je({inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.6-flash":je(
|
|
443
443
|
{inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.1-flash-lite":je({inputPer1k:125e-6,outputPer1k:75e-5,cachedInputPer1k:125e-7}),"gemini-3-flash-pre\
|
|
444
|
-
view":je({inputPer1k:25e-5,outputPer1k:.0015,cachedInputPer1k:5e-5})}}};function
|
|
445
|
-
slice(0,n):"",o=
|
|
446
|
-
i")?"google":o.startsWith("claude-")?"anthropic":null}function
|
|
447
|
-
s=i?i[o]:void 0;if(s&&!(s.vigenteHasta&&r>
|
|
448
|
-
null?{servido:t,factor:null,conDescuento:false}:{servido:t,factor:e,conDescuento:e<1}}var
|
|
449
|
-
"number"&&Number.isFinite(t);function
|
|
450
|
-
standard-rate-tier"};let n=t.uso;if(n.complete===false||!
|
|
451
|
-
return {ok:false,motivo:"incomplete-usage"};let r=
|
|
452
|
-
motivo:"no-tier-price"};let s=Math.max(0,n.inputTokens),a=Ne(
|
|
453
|
-
l?Math.min(Math.max(0,n.cacheWriteInputTokens??0),s-u):0,p=s-u-d,
|
|
454
|
-
outputPer1k},
|
|
455
|
-
{tokens:u,posibles:["cached input"]},{tokens:d,posibles:["cache write"]},{tokens:
|
|
456
|
-
y.inputPer1k,"cache write":y.inputPer1k*a,output:y.outputPer1k}:void 0,x=(
|
|
457
|
-
|
|
458
|
-
void 0&&q.posibles.length===1&&
|
|
459
|
-
std-
|
|
444
|
+
view":je({inputPer1k:25e-5,outputPer1k:.0015,cachedInputPer1k:5e-5})}}};function lt(t){let e=t.lastIndexOf("/");return e>=0?t.slice(e+1):t}function Ot(t){let e=t.toLowerCase(),n=e.indexOf("/"),r=n>0?e.
|
|
445
|
+
slice(0,n):"",o=lt(e);return r==="openai"||r==="azure-openai"?"openai":r==="google"||r==="google-vertex"?"google":r==="anthropic"?"anthropic":/^(gpt-|o[1-9](-|$))/.test(o)?"openai":o.startsWith("gemin\
|
|
446
|
+
i")?"google":o.startsWith("claude-")?"anthropic":null}function Mm(t){return Date.parse(`${t}T23:59:59.999Z`)}function Un(t,e,n,r=Date.now()){if(st(n)===void 0)return;let o=Qt(n);if(o===void 0)return;let i=Lm[t]?.[e],
|
|
447
|
+
s=i?i[o]:void 0;if(s&&!(s.vigenteHasta&&r>Mm(s.vigenteHasta)))return s}function qr(t){let e=st(t);if(e)return {...e,cacheWritePer1k:e.inputPer1k*Ne(lt(t))}}var Wc={flex:.5,default:1,auto:1,priority:1,fast:1,scale:1,standard:1,batch:.5},Gc=Math.min(...Object.values(Wc).filter(t=>t<1)),We="flex";function Gi(t){if(t==null||t==="")return null;let e=Wc[t];return e==
|
|
448
|
+
null?{servido:t,factor:null,conDescuento:false}:{servido:t,factor:e,conDescuento:e<1}}var Ur=1e10;function Ki(t){let e=Math.floor(t*Ur)/Ur;return e>t&&(e=(Math.floor(t*Ur)-1)/Ur),e<=0?0:e}var Vr=t=>typeof t==
|
|
449
|
+
"number"&&Number.isFinite(t);function Hr(t){let e=Gi(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:"\
|
|
450
|
+
standard-rate-tier"};let n=t.uso;if(n.complete===false||!Vr(n.inputTokens)||!Vr(n.outputTokens)||n.cachedInputTokens!=null&&!Vr(n.cachedInputTokens)||n.cacheWriteInputTokens!=null&&!Vr(n.cacheWriteInputTokens))
|
|
451
|
+
return {ok:false,motivo:"incomplete-usage"};let r=qr(t.modelo);if(!r)return {ok:false,motivo:"no-standard-price"};let o=t.origen??Ot(t.modelo),i=o?Un(o,e.servido,t.modelo,t.ahoraMs):void 0;if(!i)return {ok:false,
|
|
452
|
+
motivo:"no-tier-price"};let s=Math.max(0,n.inputTokens),a=Ne(lt(t.modelo)),c=n.cachedInputTokens!=null,l=a<=1||n.cacheWriteInputTokens!=null,u=c?Math.min(Math.max(0,n.cachedInputTokens??0),s):0,d=a>1&&
|
|
453
|
+
l?Math.min(Math.max(0,n.cacheWriteInputTokens??0),s-u):0,p=s-u-d,h=Math.max(0,n.outputTokens),f={input:r.inputPer1k,"cached input":r.cachedInputPer1k??r.inputPer1k,"cache write":r.cacheWritePer1k,output:r.
|
|
454
|
+
outputPer1k},m={input:i.inputPer1k,"cached input":i.cachedInputPer1k,"cache write":i.cacheWritePer1k,output:i.outputPer1k},g=[{tokens:p,posibles:["input",...c?[]:["cached input"],...l?[]:["cache write"]]},
|
|
455
|
+
{tokens:u,posibles:["cached input"]},{tokens:d,posibles:["cache write"]},{tokens:h,posibles:["output"]}],b=p>0&&g[0].posibles.length>1,y=t.precioDelCliente,v=y?{input:y.inputPer1k,"cached input":y.cachedInputPer1k??
|
|
456
|
+
y.inputPer1k,"cache write":y.inputPer1k*a,output:y.outputPer1k}:void 0,x=(D,F)=>{let j=F?v[D]:f[D],q=m[D];return q===void 0?{std:j,aplicado:j}:F?{std:j,aplicado:f[D]>0?j*(q/f[D]):j}:{std:j,aplicado:q}},
|
|
457
|
+
E=new Set,S=D=>{let F=0,j=0;for(let q of g){if(q.tokens<=0)continue;let J=q.posibles[0],Y=x(J,D);for(let B of q.posibles.slice(1)){let Re=x(B,D);Re.std-Re.aplicado<Y.std-Y.aplicado&&(J=B,Y=Re);}m[J]===
|
|
458
|
+
void 0&&q.posibles.length===1&&E.add(J),F+=q.tokens/1e3*Y.std,j+=q.tokens/1e3*Y.aplicado;}return {std:F,aplicado:j}},C=S(false),A=C.std-C.aplicado,T=C.std,R=C.aplicado,M=A,w=false;if(y){let D=S(true);T=D.std;let F=D.
|
|
459
|
+
std-D.aplicado;w=F>A,M=Math.min(F,A),R=w?D.std-M:D.aplicado;}if(!(M>0))return {ok:false,motivo:"no-difference"};let P=Ki(M);if(P<=0)return {ok:false,motivo:"no-difference"};let $=[];if(t.origen===null?$.push("\
|
|
460
460
|
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 \
|
|
461
461
|
tier was read from a response header whose values the provider does not document"),y&&$.push("priced from your costModels: your standard rate times the published tier-to-standard ratio"+(w?", capped a\
|
|
462
|
-
t the difference between the two published rate cards":"")),b){let
|
|
463
|
-
its prompt cache, so those tokens are priced at the smallest per-token difference they could have had`);}
|
|
464
|
-
e tokens add nothing`);let O=$.length===0;return {ok:true,importe:P,basis:O?"measured":"estimated",costeEstandar:
|
|
462
|
+
t the difference between the two published rate cards":"")),b){let D=[...c?[]:["read from"],...l?[]:["written to"]].join(" or ");$.push(`the provider's usage did not say how many input tokens were ${D}\
|
|
463
|
+
its prompt cache, so those tokens are priced at the smallest per-token difference they could have had`);}E.size>0&&$.push(`the provider publishes no ${[...E].join(" or ")} price for this tier, so thos\
|
|
464
|
+
e tokens add nothing`);let O=$.length===0;return {ok:true,importe:P,basis:O?"measured":"estimated",costeEstandar:T,costeAplicado:R,factorEfectivo:R/T,motivoBasis:O?`the provider's own usage for this call\
|
|
465
465
|
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\
|
|
466
|
-
led at the batch rate card)":""):`estimated: ${$.join("; ")}`,consultado:i.consultado}}function
|
|
466
|
+
led at the batch rate card)":""):`estimated: ${$.join("; ")}`,consultado:i.consultado}}function Kc(t,e,n){let r=e??Ot(t);return r!==null&&Un(r,"batch",t,n)!==void 0}var $m="slower and variable: OpenAI\
|
|
467
467
|
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\
|
|
468
|
-
short the request returns 429 and is not charged. Do not put a deferrable request on a user-facing path.",
|
|
468
|
+
short the request returns 429 and is not charged. Do not put a deferrable request on a user-facing path.",Nm='slower and variable: Google targets minutes for the Flex tier ("Minutes (1\u201315 min target)\
|
|
469
469
|
", 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\
|
|
470
|
-
he server side. Do not put a deferrable request on a user-facing path.',
|
|
470
|
+
he server side. Do not put a deferrable request on a user-facing path.',jm="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\
|
|
471
471
|
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\
|
|
472
|
-
n a user-facing path.",
|
|
472
|
+
n a user-facing path.",Bm="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.",Jc="this provider\
|
|
473
473
|
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 \
|
|
474
|
-
request/response call (with the built-in Anthropic and OpenAI providers, layer.batches.submit() sends such requests there)";function
|
|
475
|
-
google"?
|
|
476
|
-
st on a user-facing path.`}var
|
|
477
|
-
return {minimumCacheTokens:
|
|
478
|
-
0),n),o=Math.min(Math.max(0,t.uso.cacheWriteInputTokens??0),n-r),i=n-r-o;if(n<
|
|
479
|
-
cacheWritePer1k,a=i/1e3*t.fila.inputPer1k;return {importe:
|
|
480
|
-
"https:"||e.port!==""?null:
|
|
481
|
-
function
|
|
482
|
-
null?
|
|
483
|
-
n")return;let r=n.call(t);return r==="oficial"||r==="no-oficial"?r:void 0}catch{return}}function
|
|
484
|
-
return typeof t=="object"&&t!==null?
|
|
485
|
-
hash="",e.toString().replace(/\/+$/,"")}catch{return t.replace(/\/+$/,"")}}function
|
|
486
|
-
l: a batch request path must be relative to the provider base (got "${t}")`);return t}var
|
|
487
|
-
return typeof n=="string"&&n!==""?{parada:"content_filter",detalle:n}:{parada:"content_filter"}}function
|
|
488
|
-
e-n)}var
|
|
474
|
+
request/response call (with the built-in Anthropic and OpenAI providers, layer.batches.submit() sends such requests there)";function Yc(t,e=null){return t==null||t===""?Bm:t===We?e==="openai"?$m:e==="\
|
|
475
|
+
google"?Nm:jm:`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\
|
|
476
|
+
st on a user-facing path.`}var Zc=1024;function Lt(t,e){return e==="openai"&&Ot(lt(t))==="openai"&&Ne(lt(t))>1}function Ji(t){let e=st(t);if(!e||!(e.inputPer1k>0))return null;let n=(e.cachedInputPer1k??e.inputPer1k)/e.inputPer1k;
|
|
477
|
+
return {minimumCacheTokens:Zc,cacheReadMultiplier:n,cacheWriteMultiplier:Ne(lt(t))}}function Xc(t){let e=t.consultado??_n,n=Math.max(0,t.uso.inputTokens),r=Math.min(Math.max(0,t.uso.cachedInputTokens??
|
|
478
|
+
0),n),o=Math.min(Math.max(0,t.uso.cacheWriteInputTokens??0),n-r),i=n-r-o;if(n<Zc||i<=0)return {importe:0,costeEstandar:0,costeAplicado:0,tokensOrdinarios:Math.max(0,i),consultado:e};let s=i/1e3*t.fila.
|
|
479
|
+
cacheWritePer1k,a=i/1e3*t.fila.inputPer1k;return {importe:Ki(s-a),costeEstandar:s,costeAplicado:a,tokensOrdinarios:i,consultado:e}}var Yi=new Set;function Ee(t,e){Yi.has(t)||(Yi.add(t),console.warn(e));}function Qc(t){return Yi.has(t)}var zm="BVSALA_SILENCE_DEPRECATIONS";function el(){let t=typeof process<"u"?process.env?.[zm]?.trim():void 0;return t!==void 0&&t!==""&&t!=="0"}var Fm={"api.anthropic.com":"anthropic","api.openai.com":"openai","generativelanguage.googleapis.com":"google"};function ut(t){if(typeof t!="string")return null;try{let e=new URL(t);return e.protocol!==
|
|
480
|
+
"https:"||e.port!==""?null:Fm[e.hostname.toLowerCase()]??null}catch{return null}}function an(t){return ut(t)!==null?"oficial":"no-oficial"}var tl=Symbol.for("@bivelio/savings-layer:provider-origin");function Mt(t){return {esquemaEnFormatoNativo:false,esquemaEstricto:false,esquemaPorPrompt:false,piezasDelAdaptador:t}}var qm=2;function cn(t){return qm*(t??[]).filter(e=>e.parameters==null).length}var Wr=new WeakMap;
|
|
481
|
+
function dt(t,e){return Wr.set(t,e),t}function Gr(t){return typeof t=="object"&&t!==null?Wr.get(t):void 0}var nl=new WeakMap;function Kr(t,e){nl.set(t,e);}function $t(t){return typeof t=="object"&&t!==
|
|
482
|
+
null?nl.get(t):void 0}var rl=new WeakMap;function ln(t,e){rl.set(t,e);}function ol(t){if(typeof t!="object"||t===null)return;let e=rl.get(t);if(e!==void 0)return e;try{let n=t[tl];if(typeof n!="functio\
|
|
483
|
+
n")return;let r=n.call(t);return r==="oficial"||r==="no-oficial"?r:void 0}catch{return}}function il(t,e){let n=Wr.get(t);return n&&Wr.set(e,n),e}var sl=new WeakMap;function al(t,e){sl.set(t,e);}function Jr(t){
|
|
484
|
+
return typeof t=="object"&&t!==null?sl.get(t):void 0}var cl=new WeakSet;function ll(t){typeof t=="object"&&t!==null&&cl.add(t);}function Um(t){return cl.has(t)}function Ce(t,e,n){Um(t)||Ee(e,n);}var ul=new WeakMap;function Yr(t,e){ul.set(t,e);}function dl(t){return typeof t=="object"&&t!==null?ul.get(t):void 0}function Zr(t){try{let e=new URL(t);return e.username="",e.password="",e.search="",e.
|
|
485
|
+
hash="",e.toString().replace(/\/+$/,"")}catch{return t.replace(/\/+$/,"")}}function Xr(t){if(!t.startsWith("/")||t.startsWith("//")||/^\/*[a-z][a-z0-9+.-]*:/i.test(t))throw new Error(`[bvsala] interna\
|
|
486
|
+
l: a batch request path must be relative to the provider base (got "${t}")`);return t}var pl=/^content_filter(?:\s*:\s*(.*?))?\s*$/;function fl(t){return typeof t=="string"&&pl.test(t)}function Zi(t){if(typeof t!="string")return {};let e=pl.exec(t);if(e===null)return {parada:t};let n=e[1];
|
|
487
|
+
return typeof n=="string"&&n!==""?{parada:"content_filter",detalle:n}:{parada:"content_filter"}}function Xi(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0}function ml(t){if(!t)return 0;let{prompt_tokens:e,completion_tokens:n,total_tokens:r}=t;return !Xi(e)||!Xi(n)||!Xi(r)?0:Math.max(0,r-
|
|
488
|
+
e-n)}var Qi=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(
|
|
489
489
|
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,
|
|
490
490
|
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(
|
|
491
491
|
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.
|
|
492
492
|
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),
|
|
493
493
|
i=e.slice(r+1),i.charCodeAt(0)===32&&(i=i.slice(1))),o){case "data":this.datos+=i+`
|
|
494
494
|
`;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":
|
|
495
|
-
this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};async function*
|
|
496
|
-
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
|
|
497
|
-
test(t)&&/unsupported|not supported|unrecognized|unknown (parameter|field|argument)|extra (inputs|fields) (are )?not permitted|not permitted/i.test(t)}var
|
|
498
|
-
"reasoning_effort"];function
|
|
499
|
-
test(t))return null;for(let n of
|
|
500
|
-
ject"){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;for(let s of Object.values(n))if(!
|
|
501
|
-
return false}if(e.items!==void 0&&!
|
|
502
|
-
"object"&&Object.values(r).some(o=>!
|
|
503
|
-
test(t)}function
|
|
504
|
-
`+JSON.stringify(t)}var
|
|
505
|
-
null}var
|
|
506
|
-
true||!
|
|
507
|
-
ser"||o.role==="tool")&&typeof o.content=="string"&&o.content!==""?{puntos:1,indice:r-1}:{puntos:0,indice:-1}}function
|
|
508
|
-
return false}}var
|
|
509
|
-
atible:${e.baseUrl}`,this.fetchImpl=e.fetchImpl??fetch,this.origen=
|
|
510
|
-
opts.stripProviderPrefix,this.opts.baseUrl)
|
|
511
|
-
i.model);return this.leerJson(o,void 0,i,n(i,s),s,false)},solicitar:(o,i)=>this.fetchImpl(`${this.opts.baseUrl.replace(/\/$/,"")}${
|
|
495
|
+
this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};async function*un(t){let e=new Qi;if(typeof t=="string"){yield*e.push(t),yield*e.
|
|
496
|
+
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 Vm(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.
|
|
497
|
+
test(t)&&/unsupported|not supported|unrecognized|unknown (parameter|field|argument)|extra (inputs|fields) (are )?not permitted|not permitted/i.test(t)}var to=["prompt_cache_key","service_tier","seed",
|
|
498
|
+
"reasoning_effort"];function Hm(t,e){if(!/unknown name|cannot find field|unknown (parameter|field|argument)|unrecognized|extra (inputs|fields) (are )?not permitted|not permitted|not supported|unsupported/i.
|
|
499
|
+
test(t))return null;for(let n of to)if(e.has(n)&&new RegExp(`\\b${n}\\b`).test(t))return n;return null}function Be(t){if(t==null||typeof t!="object")return true;let e=t,n=e.properties;if(n&&typeof n=="ob\
|
|
500
|
+
ject"){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;for(let s of Object.values(n))if(!Be(s))
|
|
501
|
+
return false}if(e.items!==void 0&&!Be(e.items))return false;for(let o of ["anyOf","oneOf","allOf"]){let i=e[o];if(Array.isArray(i)&&i.some(s=>!Be(s)))return false}let r=e.$defs??e.definitions;return !(r&&typeof r==
|
|
502
|
+
"object"&&Object.values(r).some(o=>!Be(o)))}function Wm(t){return !/response_format/i.test(t)||/invalid schema/i.test(t)?false:/invalid parameter|not supported|unsupported|unrecognized request argument|unknown parameter/i.
|
|
503
|
+
test(t)}function Gm(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:
|
|
504
|
+
`+JSON.stringify(t)}var Km=/(^|\.)api\.openai\.com$|\.openai\.azure\.com$/i;function es(t,e,n){return e??Ym(n)?t.replace(/^[^/]+\//,""):t}function Jm(t){let e=ut(t);return e==="openai"||e==="google"?e:
|
|
505
|
+
null}var hl="x-gemini-service-tier";function gl(t,e){try{let n=t.headers?.get?.(e);return typeof n=="string"&&n.trim()!==""?n.trim():void 0}catch{return}}function ts(t,e,n){if(e.explicitCacheWrites!==
|
|
506
|
+
true||!Lt(t,n))return null;let r=e.stablePrefixMessages;if(r==null||!Number.isInteger(r)||r<=0||r>e.messages.length)return {puntos:0,indice:-1};let o=e.messages[r-1];return (o.role==="system"||o.role==="u\
|
|
507
|
+
ser"||o.role==="tool")&&typeof o.content=="string"&&o.content!==""?{puntos:1,indice:r-1}:{puntos:0,indice:-1}}function Ym(t){if(ut(t)==="google")return true;try{return Km.test(new URL(t).hostname)}catch{
|
|
508
|
+
return false}}var bl=class{id;opts;fetchImpl;sinResponseFormat=new Set;streamOptionsRejected=false;campoDeTopeAprendido=new Map;camposRechazados=new Map;origen;constructor(e){this.opts=e,this.id=`openai-comp\
|
|
509
|
+
atible:${e.baseUrl}`,this.fetchImpl=e.fetchImpl??fetch,this.origen=Jm(e.baseUrl),Kr(this,this.origen),ln(this,an(e.baseUrl));let n=(o,i)=>o.schema!=null&&!this.sinResponseFormat.has(i),r=o=>es(o,this.
|
|
510
|
+
opts.stripProviderPrefix,this.opts.baseUrl);Yr(this,{protocolo:"openai",origen:this.origen,endpoint:Zr(e.baseUrl),cuerpo:o=>{let i=r(o.model);return this.construirCuerpo(i,o,n(o,i))},leer:(o,i)=>{let s=r(
|
|
511
|
+
i.model);return this.leerJson(o,void 0,i,n(i,s),s,false)},solicitar:(o,i)=>this.fetchImpl(`${this.opts.baseUrl.replace(/\/$/,"")}${Xr(o)}`,{method:i.method,headers:{...i.json!==void 0?{"content-type":"ap\
|
|
512
512
|
plication/json"}:{},...this.opts.apiKey?{authorization:`Bearer ${this.opts.apiKey}`}:{},...this.opts.headers},...i.json!==void 0?{body:JSON.stringify(i.json)}:i.form?{body:i.form}:{},...i.signal?{signal:i.
|
|
513
|
-
signal}:{}})});}async generate(e,n){let r=
|
|
514
|
-
2+
|
|
513
|
+
signal}:{}})});}async generate(e,n){let r=es(e.model,this.opts.stripProviderPrefix,this.opts.baseUrl),o=n?.signal,i=e.schema!=null&&!this.sinResponseFormat.has(r),s=await this.enviar(r,e,i,void 0,o);for(let a=0;a<
|
|
514
|
+
2+to.length&&!s.ok&&!(s.status!==400&&s.status!==422);a++){let c=await eo(s);if(!this.corregirCampoOpcional(r,e,s.status,c,i)){if(s.status===400&&i&&Wm(c))this.sinResponseFormat.add(r),Ce(this,`sin-re\
|
|
515
515
|
sponse-format:${r}`,`[bvsala] 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\
|
|
516
516
|
the following requests 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.backe\
|
|
517
517
|
nd: "none"\`. To recover 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}`)}
|
|
518
|
-
s=await this.enviar(r,e,i,void 0,o);}if(!s.ok){let a=await
|
|
519
|
-
let w=await this.generate(e);w.text!==""&&(yield {type:"text",delta:w.text}),yield {type:"done",response:w};return}let r=
|
|
520
|
-
s=i,a=w=>this.enviar(r,e,false,{includeUsage:w,...o?{signal:o}:{}}),c=await a(s);for(let w=0;w<2+
|
|
518
|
+
s=await this.enviar(r,e,i,void 0,o);}if(!s.ok){let a=await eo(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){
|
|
519
|
+
let w=await this.generate(e);w.text!==""&&(yield {type:"text",delta:w.text}),yield {type:"done",response:w};return}let r=es(e.model,this.opts.stripProviderPrefix,this.opts.baseUrl),o=n.signal,i=!this.streamOptionsRejected,
|
|
520
|
+
s=i,a=w=>this.enviar(r,e,false,{includeUsage:w,...o?{signal:o}:{}}),c=await a(s);for(let w=0;w<2+to.length&&!c.ok&&!(c.status!==400&&c.status!==422);w++){let P=await eo(c);if(this.corregirCampoOpcional(r,
|
|
521
521
|
e,c.status,P,false,s)||this.corregirCampoDeTope(r,e,c.status,P)){c=await a(s);continue}if(!s||c.status!==422&&!/stream_options|include_usage/i.test(P))throw new Error(`provider ${c.status}: ${P}`);if(this.
|
|
522
522
|
opts.requireUsage)throw new Error(`provider ${c.status}: this endpoint rejects stream_options, so a streamed answer would carry no usage and requireUsage is set. ${P}`);s=false,c=await a(false);}if(i&&!s&&c.
|
|
523
|
-
ok&&(this.streamOptionsRejected=true,
|
|
524
|
-
`unmeasured` and never billed. Use `generate()` for a measured figure, or an endpoint that reports usage when streaming.")),!c.ok)throw new Error(`provider ${c.status}: ${await
|
|
523
|
+
ok&&(this.streamOptionsRejected=true,Ce(this,`sin-stream-options:${this.opts.baseUrl}`,"[bvsala] This endpoint rejects `stream_options`, so streamed answers from it carry no usage: they are reported as \
|
|
524
|
+
`unmeasured` and never billed. Use `generate()` for a measured figure, or an endpoint that reports usage when streaming.")),!c.ok)throw new Error(`provider ${c.status}: ${await eo(c)}`);if((c.headers.
|
|
525
525
|
get("content-type")??"").includes("application/json")){let w=await this.leer(c,e,false,r);w.text!==""&&(yield {type:"text",delta:w.text}),yield {type:"done",response:w};return}let l=c.body,u=l&&typeof l.getReader==
|
|
526
|
-
"function"?l:await c.text(),d="",p=new Map,f,m,
|
|
527
|
-
error!=null){let
|
|
528
|
-
reasoning))&&(g=true),typeof O?.content=="string"&&O.content!==""&&(d+=O.content,yield {type:"text",delta:O.content}),typeof O?.refusal=="string"&&(b+=O.refusal);for(let
|
|
529
|
-
index=="number"?
|
|
530
|
-
"string"&&(j.args+=
|
|
531
|
-
ct"&&(
|
|
532
|
-
prompt_tokens!="number",x=typeof
|
|
533
|
-
|
|
534
|
-
{},...S!==void 0?{reasoningTokens:S}:{},...v||x?{complete:false}:{}},
|
|
535
|
-
extra}:{}})).filter(w=>w.name!==""),R=
|
|
536
|
-
{},finishReason:y.parada??
|
|
537
|
-
origen:this.origen,...R?{tierLeidoDe:R}:{},...
|
|
538
|
-
completion_tokens":"max_tokens")}corregirCampoDeTope(e,n,r,o){if(this.opts.maxTokensParam!==void 0||n.maxOutputTokens==null||this.campoDeTopeAprendido.has(e))return false;let i=this.campoDeTope(e);if(
|
|
539
|
-
o,i))return false;let s=i==="max_tokens"?"max_completion_tokens":"max_tokens";return this.campoDeTopeAprendido.set(e,s),
|
|
526
|
+
"function"?l:await c.text(),d="",p=new Map,h,f,m,g=false,b="";for await(let w of un(u)){if(w.data==="[DONE]")break;let P;try{P=JSON.parse(w.data);}catch{continue}if(P===null||typeof P!="object")continue;if(P.
|
|
527
|
+
error!=null){let D=P.error,F=typeof D.message=="string"?D.message:JSON.stringify(P.error);throw new Error(`provider stream error: ${F}`)}let $=P.choices?.[0],O=$?.delta;(Qr(O?.reasoning_content)||Qr(O?.
|
|
528
|
+
reasoning))&&(g=true),typeof O?.content=="string"&&O.content!==""&&(d+=O.content,yield {type:"text",delta:O.content}),typeof O?.refusal=="string"&&(b+=O.refusal);for(let D of O?.tool_calls??[]){let F=typeof D.
|
|
529
|
+
index=="number"?D.index:0,j=p.get(F)??{args:""};!j.id&&typeof D.id=="string"&&D.id!==""&&(j.id=D.id);let q=D.function?.name;!j.name&&typeof q=="string"&&q!==""&&(j.name=q),typeof D.function?.arguments==
|
|
530
|
+
"string"&&(j.args+=D.function.arguments);let J=kl(D.extra_content);j.extra===void 0&&J!==void 0&&(j.extra=J),p.set(F,j);}$?.finish_reason!=null&&(h=$.finish_reason),P.usage!=null&&typeof P.usage=="obje\
|
|
531
|
+
ct"&&(f=P.usage),typeof P.service_tier=="string"&&P.service_tier!==""&&(m=P.service_tier);}if(h===void 0)throw new Error("provider stream ended before completion (no finish_reason)");let y=Zi(h),v=typeof f?.
|
|
532
|
+
prompt_tokens!="number",x=typeof f?.completion_tokens!="number";if(this.opts.requireUsage&&(v||x))throw new Error(xl(f?.prompt_tokens,f?.completion_tokens));let E=vl(f,this.origen,g),S=E.razonamiento,
|
|
533
|
+
C=yl(f),A={inputTokens:f?.prompt_tokens??0,outputTokens:E.salida,...f?.prompt_tokens_details?.cached_tokens!=null?{cachedInputTokens:f.prompt_tokens_details.cached_tokens}:{},...C!==void 0?{cacheWriteInputTokens:C}:
|
|
534
|
+
{},...S!==void 0?{reasoningTokens:S}:{},...v||x?{complete:false}:{}},T=[...p.entries()].sort((w,P)=>w[0]-P[0]).map(([,w])=>({...w.id?{id:w.id}:{},name:w.name??"",arguments:w.args,...w.extra!==void 0?{extraContent:w.
|
|
535
|
+
extra}:{}})).filter(w=>w.name!==""),R=m?"cuerpo":void 0;!m&&this.origen==="google"&&(m=gl(c,hl),m&&(R="cabecera"));let M=ts(r,e,this.origen);yield {type:"done",response:dt({text:d,...T.length>0?{toolCalls:T}:
|
|
536
|
+
{},finishReason:y.parada??h,...y.detalle!==void 0?{finishReasonDetail:y.detalle}:{},...b!==""?{refusal:b}:{},...m?{servedServiceTier:m}:{},usage:A,structuredNatively:false,raw:f??null},{...Mt(cn(e.tools)),
|
|
537
|
+
origen:this.origen,...R?{tierLeidoDe:R}:{},...M?{cacheExplicita:{puntos:M.puntos}}:{}})};}campoDeTope(e){return this.opts.maxTokensParam??this.campoDeTopeAprendido.get(e)??(this.origen==="openai"?"max_\
|
|
538
|
+
completion_tokens":"max_tokens")}corregirCampoDeTope(e,n,r,o){if(this.opts.maxTokensParam!==void 0||n.maxOutputTokens==null||this.campoDeTopeAprendido.has(e))return false;let i=this.campoDeTope(e);if(!Vm(
|
|
539
|
+
o,i))return false;let s=i==="max_tokens"?"max_completion_tokens":"max_tokens";return this.campoDeTopeAprendido.set(e,s),Ce(this,`campo-de-tope:${this.opts.baseUrl}:${e}`,`[bvsala] This endpoint rejects \`${i}\
|
|
540
540
|
\` for model "${e}" with a ${r}, so the output cap is sent as \`${s}\` instead (the rejected request was not billed; the model is noted and the following requests go straight there). To choose the fiel\
|
|
541
|
-
d yourself, set \`maxTokensParam\` on OpenAICompatibleProvider.`),true}corregirCampoOpcional(e,n,r,o,i,s){let a=this.construirCuerpo(e,n,i,s===void 0?void 0:{includeUsage:s}),c=new Set(
|
|
542
|
-
a)),l=
|
|
541
|
+
d yourself, set \`maxTokensParam\` on OpenAICompatibleProvider.`),true}corregirCampoOpcional(e,n,r,o,i,s){let a=this.construirCuerpo(e,n,i,s===void 0?void 0:{includeUsage:s}),c=new Set(to.filter(d=>d in
|
|
542
|
+
a)),l=Hm(o,c);if(l===null||l==="reasoning_effort"&&this.origen==="openai")return false;let u=this.camposRechazados.get(e)??new Set;return u.add(l),this.camposRechazados.set(e,u),Ce(this,`campo-opcional:${this.
|
|
543
543
|
opts.baseUrl}:${e}:${l}`,`[bvsala] This endpoint rejects \`${l}\` for model "${e}" with a ${r}, so it is no longer sent (the rejected request was not billed; the model is noted and the following reque\
|
|
544
544
|
sts go without it).`+(l==="service_tier"?" The request is served on the endpoint's default tier, and no tier discount is credited.":l==="prompt_cache_key"?" The prefix cache keeps working without the \
|
|
545
545
|
routing hint; only its hit rate may drop.":l==="reasoning_effort"?" The model reasons at the endpoint's default effort.":"")),true}campoAdmitido(e,n){return this.camposRechazados.get(e)?.has(n)!==true}async enviar(e,n,r,o,i){
|
|
@@ -547,48 +547,48 @@ let s=this.construirCuerpo(e,n,r,o);return await this.fetchImpl(`${this.opts.bas
|
|
|
547
547
|
{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===
|
|
548
548
|
"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.
|
|
549
549
|
content||null,tool_calls:c.toolCalls.map((l,u)=>({id:l.id??`call_${u}`,type:"function",function:{name:l.name,arguments:l.arguments},...l.extraContent!==void 0&&this.origen!=="openai"?{extra_content:l.
|
|
550
|
-
extraContent}:{}}))}:{role:c.role,content:c.content}),s=
|
|
551
|
-
!r&&i.push({role:"system",content:
|
|
550
|
+
extraContent}:{}}))}:{role:c.role,content:c.content}),s=ts(e,n,this.origen);if(s?.puntos===1){let c=i[s.indice];c.content=[{type:"text",text:c.content,prompt_cache_breakpoint:{mode:"explicit"}}];}n.schema&&
|
|
551
|
+
!r&&i.push({role:"system",content:Gm(n.schema)});let a={model:e,messages:i};if(n.maxOutputTokens!=null&&(a[this.campoDeTope(e)]=n.maxOutputTokens),n.temperature!=null&&(a.temperature=n.temperature),n.
|
|
552
552
|
seed!=null&&this.campoAdmitido(e,"seed")&&(a.seed=n.seed),n.reasoningEffort!=null&&this.campoAdmitido(e,"reasoning_effort")&&(a.reasoning_effort=n.reasoningEffort),n.promptCacheKey!=null&&(this.opts.sendPromptCacheKey??
|
|
553
|
-
this.origen==="openai")&&this.campoAdmitido(e,"prompt_cache_key")&&(a.prompt_cache_key=n.promptCacheKey),n.deferrable===true&&this.campoAdmitido(e,"service_tier")&&(a.service_tier=
|
|
554
|
-
{mode:"explicit"}),n.schema&&r){let c=
|
|
553
|
+
this.origen==="openai")&&this.campoAdmitido(e,"prompt_cache_key")&&(a.prompt_cache_key=n.promptCacheKey),n.deferrable===true&&this.campoAdmitido(e,"service_tier")&&(a.service_tier=We),s&&(a.prompt_cache_options=
|
|
554
|
+
{mode:"explicit"}),n.schema&&r){let c=Be(n.schema);c||Ce(this,"strict-incompatible","[bvsala] The response contract does not meet OpenAI's `strict` mode (in strict, `required` must list ALL the keys i\
|
|
555
555
|
n `properties`, and every object needs `additionalProperties: false`). The schema is sent with `strict: false`: the model is still guided and the layer still validates, but the guarantee comes from th\
|
|
556
556
|
e layer, not the provider. To recover it, make every key in the contract required."),a.response_format={type:"json_schema",json_schema:{name:"bvsala_contract",schema:n.schema,strict:c}};}return n.tools&&
|
|
557
557
|
n.tools.length>0&&(a.tools=n.tools.map(c=>({type:"function",function:{name:c.id,...c.description?{description:c.description}:{},parameters:c.parameters??{type:"object",properties:{}}}}))),o&&(a.stream=
|
|
558
558
|
true,o.includeUsage&&(a.stream_options={include_usage:true})),a}async leer(e,n,r,o){let i=await e.json();return this.leerJson(i,e,n,r,o,this.opts.requireUsage===true)}leerJson(e,n,r,o,i,s){let a=e.choices?.[0]?.
|
|
559
|
-
message,c=a?.content??"",l=typeof a?.refusal=="string"&&a.refusal!==""?a.refusal:void 0,u=(a?.tool_calls??[]).map(A=>{let
|
|
560
|
-
function?.arguments??"",...
|
|
561
|
-
prompt_tokens!="number",g=typeof d.completion_tokens!="number";if(s&&(
|
|
562
|
-
service_tier=="string"&&e.service_tier!==""?e.service_tier:void 0,x=v?"cuerpo":void 0;!v&&this.origen==="google"&&n&&(v=
|
|
559
|
+
message,c=a?.content??"",l=typeof a?.refusal=="string"&&a.refusal!==""?a.refusal:void 0,u=(a?.tool_calls??[]).map(A=>{let T=kl(A.extra_content);return {...A.id?{id:A.id}:{},name:A.function?.name??"",arguments:A.
|
|
560
|
+
function?.arguments??"",...T!==void 0?{extraContent:T}:{}}}).filter(A=>A.name!==""),d=e.usage??{},p=d.prompt_tokens??0,h=vl(d,this.origen,Qr(a?.reasoning_content)||Qr(a?.reasoning)),f=h.salida,m=typeof d.
|
|
561
|
+
prompt_tokens!="number",g=typeof d.completion_tokens!="number";if(s&&(m||g))throw new Error(xl(d.prompt_tokens,d.completion_tokens));let{parada:b,detalle:y}=Zi(e.choices?.[0]?.finish_reason),v=typeof e.
|
|
562
|
+
service_tier=="string"&&e.service_tier!==""?e.service_tier:void 0,x=v?"cuerpo":void 0;!v&&this.origen==="google"&&n&&(v=gl(n,hl),v&&(x="cabecera"));let E=yl(d),S=ts(i,r,this.origen),C=h.razonamiento;return dt(
|
|
563
563
|
{text:c,...u.length>0?{toolCalls:u}:{},...b?{finishReason:b}:{},...y!==void 0?{finishReasonDetail:y}:{},...l!==void 0?{refusal:l}:{},...v?{servedServiceTier:v}:{},...r.deferrable===true&&this.campoAdmitido(
|
|
564
|
-
i,"service_tier")?{requestedServiceTier:
|
|
565
|
-
{cacheWriteInputTokens:
|
|
566
|
-
null&&o&&
|
|
567
|
-
completion_tokens_details?.reasoning_tokens;if(!(typeof n!="number"||!Number.isInteger(n)||n<0)&&!(n===0&&e))return n}function
|
|
568
|
-
return i===0?{salida:r,razonamiento:o}:{salida:r+i,razonamiento:Math.max(i,o??0)}}function
|
|
569
|
-
e:void 0}function
|
|
570
|
-
mpt=${t??"absent"}, completion=${e??"absent"}); cannot measure cost. For gateways/streaming, ensure usage reporting is enabled.`}async function
|
|
571
|
-
<no body>"}}function
|
|
572
|
-
`+JSON.stringify(t)}var
|
|
573
|
-
return
|
|
574
|
-
test(t)}function
|
|
564
|
+
i,"service_tier")?{requestedServiceTier:We}:{},usage:{inputTokens:p,outputTokens:f,...d.prompt_tokens_details?.cached_tokens!=null?{cachedInputTokens:d.prompt_tokens_details.cached_tokens}:{},...E!==void 0?
|
|
565
|
+
{cacheWriteInputTokens:E}:{},...C!==void 0?{reasoningTokens:C}:{},...m||g?{complete:false}:{}},structuredNatively:r.schema!=null&&o,raw:e},{esquemaEnFormatoNativo:r.schema!=null&&o,esquemaEstricto:r.schema!=
|
|
566
|
+
null&&o&&Be(r.schema),esquemaPorPrompt:r.schema!=null&&!o,piezasDelAdaptador:cn(r.tools),origen:this.origen,...x?{tierLeidoDe:x}:{},...S?{cacheExplicita:{puntos:S.puntos}}:{}})}};function Zm(t,e){let n=t?.
|
|
567
|
+
completion_tokens_details?.reasoning_tokens;if(!(typeof n!="number"||!Number.isInteger(n)||n<0)&&!(n===0&&e))return n}function vl(t,e,n){let r=t?.completion_tokens??0,o=Zm(t,n),i=e==="openai"?0:ml(t);
|
|
568
|
+
return i===0?{salida:r,razonamiento:o}:{salida:r+i,razonamiento:Math.max(i,o??0)}}function yl(t){let e=t?.prompt_tokens_details?.cache_write_tokens;return typeof e=="number"&&Number.isInteger(e)&&e>=0?
|
|
569
|
+
e:void 0}function kl(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function Qr(t){return typeof t=="string"&&t!==""}function xl(t,e){return `provider returned incomplete usage (pro\
|
|
570
|
+
mpt=${t??"absent"}, completion=${e??"absent"}); cannot measure cost. For gateways/streaming, ensure usage reporting is enabled.`}async function eo(t){try{return (await t.text()).slice(0,500)}catch{return "\
|
|
571
|
+
<no body>"}}function wl(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:
|
|
572
|
+
`+JSON.stringify(t)}var Xm=["claude-opus-5-5","claude-sonnet-5-5","claude-fable-5-1","claude-mythos-5-1"],Qm=["claude-opus-4-7","claude-opus-4-8","claude-opus-5","claude-sonnet-5","claude-fable-5","claude-mythos-5"];function eh(t){return /claude-[a-z]+-\d[a-z0-9-]*/.exec(t.toLowerCase())?.[0]}function Sl(t,e){let n=eh(t);return n===void 0?false:e.some(r=>n===r||n.startsWith(`${r}-`))}function El(t){return Sl(t,Xm)}function Cl(t){
|
|
573
|
+
return Sl(t,Qm)}function Tl(t){return /tool_choice/i.test(t)&&/not supported|unsupported|not available/i.test(t)}function Rl(t){return /\b(temperature|top_p|top_k)\b/i.test(t)&&/deprecated|not supported|unsupported|non-default|not allowed/i.
|
|
574
|
+
test(t)}function Pl(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(l=>l.
|
|
575
575
|
type==="tool_search_tool_result"&&l.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=[],
|
|
576
|
-
c=true;for(let l of s.tool_references){if(typeof l?.tool_name!="string"){c=false;break}a.includes(l.tool_name)||a.push(l.tool_name);}c&&e.push({busqueda:o,id:r,uso:n,resultado:i,herramientas:a});}return e}var
|
|
577
|
-
bytes:4*1024*1024,porEntrada:64*1024,claves:4096},
|
|
576
|
+
c=true;for(let l of s.tool_references){if(typeof l?.tool_name!="string"){c=false;break}a.includes(l.tool_name)||a.push(l.tool_name);}c&&e.push({busqueda:o,id:r,uso:n,resultado:i,herramientas:a});}return e}var th={
|
|
577
|
+
bytes:4*1024*1024,porEntrada:64*1024,claves:4096},no=class{constructor(e=th){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(
|
|
578
578
|
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>
|
|
579
579
|
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.
|
|
580
|
-
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
|
|
581
|
-
if(n===null||typeof n!="object")continue;let r=n;if(r.type!=="compaction")continue;e.iteraciones++,e.input+=
|
|
582
|
-
let o=r.cache_creation,i=
|
|
583
|
-
Math.min(s,a);}return e.iteraciones>0?e:null}function
|
|
580
|
+
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 dn=t=>typeof t=="number"&&Number.isFinite(t)&&t>0?t:0;function Il(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){
|
|
581
|
+
if(n===null||typeof n!="object")continue;let r=n;if(r.type!=="compaction")continue;e.iteraciones++,e.input+=dn(r.input_tokens),e.output+=dn(r.output_tokens),e.cacheRead+=dn(r.cache_read_input_tokens);
|
|
582
|
+
let o=r.cache_creation,i=dn(o?.ephemeral_5m_input_tokens),s=dn(o?.ephemeral_1h_input_tokens),a=typeof r.cache_creation_input_tokens=="number"?dn(r.cache_creation_input_tokens):i+s;e.cacheWrite+=a,e.cacheWrite1h+=
|
|
583
|
+
Math.min(s,a);}return e.iteraciones>0?e:null}function ns(t,e,n){let r=t??{},o=Il(r.iterations),i=_l(r.cache_read_input_tokens,o?.cacheRead),s=_l(r.cache_creation_input_tokens,o?.cacheWrite),a=r.cache_creation?.ephemeral_1h_input_tokens,c=typeof a==
|
|
584
584
|
"number"||(o?.cacheWrite1h??0)>0?Math.min(Math.max(0,(typeof a=="number"?a:0)+(o?.cacheWrite1h??0)),s??0):void 0,l=(r.input_tokens??0)+(o?.input??0)+(s??0)+(i??0),u=(e??0)+(o?.output??0),d=typeof r.input_tokens!=
|
|
585
585
|
"number",p=typeof e!="number";return {usage:{inputTokens:l,outputTokens:u,...i!=null?{cachedInputTokens:i}:{},...s!=null?{cacheWriteInputTokens:s}:{},...c!==void 0?{cacheWrite1hInputTokens:c}:{},...n||
|
|
586
|
-
p||o?{}:{reasoningTokens:0},...d||p?{complete:false}:{}},entradaAusente:d,salidaAusente:p}}function
|
|
587
|
-
function
|
|
588
|
-
{},...n,...r?{cache_creation:r}:{}}}function
|
|
589
|
-
tool_calls";case "refusal":return "content_filter";default:return t}}var
|
|
590
|
-
"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"||!
|
|
591
|
-
isArray(t.iterations)&&t.iterations.length>1)}function
|
|
586
|
+
p||o?{}:{reasoningTokens:0},...d||p?{complete:false}:{}},entradaAusente:d,salidaAusente:p}}function _l(t,e){return e?(t??0)+e:t}function rs(t){let e=t?.service_tier;return typeof e=="string"&&e!==""?e:void 0}
|
|
587
|
+
function os(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??
|
|
588
|
+
{},...n,...r?{cache_creation:r}:{}}}function is(t){return t==="thinking"||t==="redacted_thinking"}function ss(t){switch(t){case "end_turn":return "stop";case "max_tokens":return "length";case "tool_use":return "\
|
|
589
|
+
tool_calls";case "refusal":return "content_filter";default:return t}}var nh=new Set([null,"cyber","general_harms"]);function as(t){if(t.stopReason!=="refusal")return false;let e=t.stopDetails;if(e===null||typeof e!=
|
|
590
|
+
"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"||!nh.has(r)||t.bloques!==0||t.outputTokens!==0||Array.
|
|
591
|
+
isArray(t.iterations)&&t.iterations.length>1)}function Vn(t,e){if(t!=="refusal"||e===null||typeof e!="object"||Array.isArray(e))return;let n=e.category;return typeof n=="string"&&n!==""?n:void 0}var ro=4,Ge="bvsala_contract",oh={"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\
|
|
592
592
|
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\
|
|
593
593
|
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\
|
|
594
594
|
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\
|
|
@@ -596,54 +596,54 @@ ct. This exchange has a call without its result, a result for a call that turn d
|
|
|
596
596
|
. 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\
|
|
597
597
|
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\
|
|
598
598
|
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\
|
|
599
|
-
urn of the conversation to keep the native tool loop."},
|
|
600
|
-
baseUrl??"https://api.anthropic.com/v1"}`,this.fetchImpl=e.fetchImpl??fetch,
|
|
601
|
-
"https://api.anthropic.com/v1"
|
|
602
|
-
replace(/\/$/,"")}${
|
|
599
|
+
urn of the conversation to keep the native tool loop."},Dl=class{id;opts;fetchImpl;busquedas=new no;sinToolChoiceForzado=new Set;sinMuestreo=new Set;constructor(e={}){this.opts=e,this.id=`anthropic:${e.
|
|
600
|
+
baseUrl??"https://api.anthropic.com/v1"}`,this.fetchImpl=e.fetchImpl??fetch,al(this,oo(e.baseUrl)?"oficial":"compatible"),ln(this,an(e.baseUrl??"https://api.anthropic.com/v1"));let n=this.opts.baseUrl??
|
|
601
|
+
"https://api.anthropic.com/v1";Yr(this,{protocolo:"anthropic",origen:dh(n),endpoint:Zr(n),cuerpo:r=>this.construirCuerpo(r).body,leer:(r,o)=>this.leerMensaje(r,o,false,false,false,false),solicitar:(r,o)=>{let i=`${n.
|
|
602
|
+
replace(/\/$/,"")}${Xr(r)}`;return this.fetchImpl(i,{method:o.method,headers:{...o.json!==void 0?{"content-type":"application/json"}:{},"anthropic-version":this.opts.apiVersion??"2023-06-01",...this.opts.
|
|
603
603
|
apiKey?{"x-api-key":this.opts.apiKey}:{},...this.opts.headers},...o.json!==void 0?{body:JSON.stringify(o.json)}:{},...o.signal?{signal:o.signal}:{}})}});}modeloEnElCable(e){return this.opts.stripProviderPrefix??
|
|
604
|
-
|
|
605
|
-
r.reenviadas)}async*generateStream(e,n={}){if(e.schema!=null||e.deferrable===true){let
|
|
606
|
-
response:o}=await this.enviarConCorrecciones(e,true,n.signal);if((o.headers.get("content-type")??"").includes("application/json")){let
|
|
607
|
-
r.reenviadas);
|
|
608
|
-
g=false,b,y;for await(let
|
|
609
|
-
usage??l,typeof R.message?.id=="string"&&R.message.id!==""&&(b=R.message.id),y=R.message?.diagnostics;else if(
|
|
604
|
+
oo(this.opts.baseUrl)?e.replace(/^[^/]+\//,""):e}async generate(e,n){let{cuerpo:r,response:o}=await this.enviarConCorrecciones(e,false,n?.signal);return this.leer(o,e,r.contratoNativo,r.turnoAnadido,r.esquemaPorPrompt,
|
|
605
|
+
r.reenviadas)}async*generateStream(e,n={}){if(e.schema!=null||e.deferrable===true){let T=await this.generate(e);T.text!==""&&(yield {type:"text",delta:T.text}),yield {type:"done",response:T};return}let{cuerpo:r,
|
|
606
|
+
response:o}=await this.enviarConCorrecciones(e,true,n.signal);if((o.headers.get("content-type")??"").includes("application/json")){let T=await this.leer(o,e,r.contratoNativo,r.turnoAnadido,r.esquemaPorPrompt,
|
|
607
|
+
r.reenviadas);T.text!==""&&(yield {type:"text",delta:T.text}),yield {type:"done",response:T};return}let i=o.body,s=i&&typeof i.getReader=="function"?i:await o.text(),a="",c=new Map,l,u,d=false,p=false,h,f,m=0,
|
|
608
|
+
g=false,b,y;for await(let T of un(s)){let R;try{R=JSON.parse(T.data);}catch{continue}if(R===null||typeof R!="object")continue;let M=T.event!=="message"?T.event:R.type??T.event;if(M==="message_start")l=R.message?.
|
|
609
|
+
usage??l,typeof R.message?.id=="string"&&R.message.id!==""&&(b=R.message.id),y=R.message?.diagnostics;else if(M==="content_block_start"){m+=1;let w=R.content_block;is(w?.type)&&(g=true),typeof R.index==
|
|
610
610
|
"number"&&w&&c.set(R.index,{tipo:w.type??"",...typeof w.id=="string"?{id:w.id}:{},...typeof w.name=="string"?{name:w.name}:{},json:"",...w.content!==void 0?{content:w.content}:{},...e.toolSearch&&(w.type===
|
|
611
|
-
"server_tool_use"||w.type==="tool_search_tool_result")?{crudo:w}:{}});}else if(
|
|
612
|
-
text",delta:w.text};else if(w?.type==="input_json_delta"&&typeof w.partial_json=="string"){let P=typeof R.index=="number"?c.get(R.index):void 0;P&&(P.json+=w.partial_json);}}else if(
|
|
613
|
-
d=true,
|
|
614
|
-
er stream error: ${R.error?.type}: ${R.error?.message}`)}if(!p&&!d)throw new Error("provider stream ended before completion (no message_delta)");let v=
|
|
615
|
-
{inputTokens:0,outputTokens:0,complete:false};if(this.opts.requireUsage&&
|
|
616
|
-
map(([,
|
|
617
|
-
(
|
|
618
|
-
|
|
619
|
-
json);
|
|
620
|
-
f
|
|
621
|
-
{},...this.diagnosticoDe(e,y),usage:
|
|
622
|
-
construirCuerpo(e);n&&(i.body.stream=true);let s=await this.enviar(i.body,r);for(let a=0;a<2&&!s.ok&&s.status===400;a++){let c=await
|
|
623
|
-
sinToolChoiceForzado.has(o)&&
|
|
624
|
-
: ${c}`);i=this.construirCuerpo(e),n&&(i.body.stream=true),s=await this.enviar(i.body,r);}if(!s.ok)throw new Error(`provider ${s.status}: ${await
|
|
611
|
+
"server_tool_use"||w.type==="tool_search_tool_result")?{crudo:w}:{}});}else if(M==="content_block_delta"){let w=R.delta;if(w?.type==="text_delta"&&typeof w.text=="string"&&w.text!=="")a+=w.text,yield {type:"\
|
|
612
|
+
text",delta:w.text};else if(w?.type==="input_json_delta"&&typeof w.partial_json=="string"){let P=typeof R.index=="number"?c.get(R.index):void 0;P&&(P.json+=w.partial_json);}}else if(M==="message_delta")
|
|
613
|
+
d=true,h=R.delta?.stop_reason??h,R.delta&&"stop_details"in R.delta&&(f=R.delta.stop_details),R.usage&&(u=os(u,R.usage));else if(M==="message_stop"){p=true;break}else if(M==="error")throw new Error(`provid\
|
|
614
|
+
er stream error: ${R.error?.type}: ${R.error?.message}`)}if(!p&&!d)throw new Error("provider stream ended before completion (no message_delta)");let v=os(l,u),E=(d?ns(v,u?.output_tokens,g):void 0)?.usage??
|
|
615
|
+
{inputTokens:0,outputTokens:0,complete:false};if(this.opts.requireUsage&&E.complete===false)throw new Error(Ll(d?v.input_tokens:void 0,d?u?.output_tokens:void 0));let S=[...c.entries()].sort((T,R)=>T[0]-R[0]).
|
|
616
|
+
map(([,T])=>T).filter(T=>T.tipo==="tool_use"&&T.name!==Ge).map(T=>({...T.id?{id:T.id}:{},name:T.name??"",arguments:uh(T.json)})).filter(T=>T.name!==""),C=rs(v),A=e.toolSearch?Ol([...c.entries()].sort(
|
|
617
|
+
(T,R)=>T[0]-R[0]).map(([,T])=>({type:T.tipo,name:T.name,content:T.content})),r.reenviadas):void 0;if(e.toolSearch){let T=[];for(let[,R]of [...c.entries()].sort((M,w)=>M[0]-w[0]))if(R.tipo==="tool_use")
|
|
618
|
+
T.push({type:"tool_use",id:R.id,name:R.name});else if(R.tipo==="tool_search_tool_result"&&R.crudo)T.push(R.crudo);else if(R.tipo==="server_tool_use"&&R.crudo){let M=R.json===""?R.crudo.input??{}:lh(R.
|
|
619
|
+
json);M!==void 0&&T.push({...R.crudo,input:M});}this.recordarBusquedas(T);}yield {type:"done",response:dt({text:a,...S.length>0?{toolCalls:S}:{},...h?{finishReason:ss(h)}:{},...Vn(h,f)!==void 0?{finishReasonDetail:Vn(
|
|
620
|
+
h,f)}:{},...d&&as({stopReason:h,stopDetails:f,bloques:m,outputTokens:u?.output_tokens,iterations:v.iterations})?{unbilledRefusal:true}:{},...C?{servedServiceTier:C}:{},...A?{toolSearch:A}:{},...b?{providerMessageId:b}:
|
|
621
|
+
{},...this.diagnosticoDe(e,y),usage:E,structuredNatively:false,raw:{usage:v,stop_reason:h}},Mt((r.turnoAnadido?1:0)+cn(e.tools)))};}async enviarConCorrecciones(e,n,r){let o=this.modeloEnElCable(e.model),i=this.
|
|
622
|
+
construirCuerpo(e);n&&(i.body.stream=true);let s=await this.enviar(i.body,r);for(let a=0;a<2&&!s.ok&&s.status===400;a++){let c=await Ml(s),l=i.body.tool_choice;if((l?.type==="any"||l?.type==="tool")&&!this.
|
|
623
|
+
sinToolChoiceForzado.has(o)&&Tl(c))this.sinToolChoiceForzado.add(o);else if(i.body.temperature!==void 0&&!this.sinMuestreo.has(o)&&Rl(c))this.sinMuestreo.add(o);else throw new Error(`provider ${s.status}\
|
|
624
|
+
: ${c}`);i=this.construirCuerpo(e),n&&(i.body.stream=true),s=await this.enviar(i.body,r);}if(!s.ok)throw new Error(`provider ${s.status}: ${await Ml(s)}`);return {cuerpo:i,response:s}}async enviar(e,n){let r=(this.
|
|
625
625
|
opts.baseUrl??"https://api.anthropic.com/v1").replace(/\/$/,"");return await this.fetchImpl(`${r}/messages`,{method:"POST",headers:{"content-type":"application/json","anthropic-version":this.opts.apiVersion??
|
|
626
626
|
"2023-06-01",...this.opts.apiKey?{"x-api-key":this.opts.apiKey}:{},...this.opts.headers},body:JSON.stringify(e),...n?{signal:n}:{}})}construirCuerpo(e){let n=this.reenvioDeBusquedas(e),{system:r,messages:o,
|
|
627
|
-
finDelPrefijo:i,prefijoEnSystem:s,turnoAnadido:a}=
|
|
627
|
+
finDelPrefijo:i,prefijoEnSystem:s,turnoAnadido:a}=ih(e,n?.anteponer,v=>this.avisar(`anthropic-herramientas-${v}`,oh[v]));if(o.length===0)throw new Error("anthropic: the request has no user/assistant m\
|
|
628
628
|
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(v=>({name:v.id,...v.description?{description:v.description}:
|
|
629
|
-
{},input_schema:v.parameters??{type:"object",properties:{}}})),l=e.toolSearch?-1:c.length-1,u=this.modeloEnElCable(e.model),d=
|
|
630
|
-
toolSearch&&c.length>0){let v=new Set(e.toolSearch.alwaysLoaded);for(let x of c)v.has(x.name)||(x.defer_loading=true);c.unshift({...
|
|
631
|
-
0,x=c.some(S=>S.name===
|
|
629
|
+
{},input_schema:v.parameters??{type:"object",properties:{}}})),l=e.toolSearch?-1:c.length-1,u=this.modeloEnElCable(e.model),d=El(u)||this.sinToolChoiceForzado.has(u),p=Cl(u)||this.sinMuestreo.has(u);if(e.
|
|
630
|
+
toolSearch&&c.length>0){let v=new Set(e.toolSearch.alwaysLoaded);for(let x of c)v.has(x.name)||(x.defer_loading=true);c.unshift({...Or[e.toolSearch.variant]});}let h=false,f=false,m=false,g;if(e.schema){let v=c.length>
|
|
631
|
+
0,x=c.some(S=>S.name===Ge),E=Be(e.schema);x?(r.push({type:"text",text:wl(e.schema)}),f=true,this.avisar("anthropic-contrato-nombre-ocupado",`[bvsala] One of your tools is already named \`${Ge}\`, so the \
|
|
632
632
|
output contract cannot travel as a tool without colliding with it (duplicate tool names are a provider error). The schema is sent as prompt text instead, which is measurably more expensive on this API\
|
|
633
|
-
. Rename that tool to get the cheaper path.`)):d&&
|
|
633
|
+
. Rename that tool to get the cheaper path.`)):d&&E?(g={type:"json_schema",schema:e.schema},h=!v,this.avisar(`anthropic-sin-tool-choice-forzado:${u}`,`[bvsala] Model "${u}" does not accept a forced \`t\
|
|
634
634
|
ool_choice\` (\`any\` or \`tool\` is a 400 on this model, with or without thinking). The output contract travels as structured output (\`output_config.format\`) instead, which the provider still enforces`+
|
|
635
635
|
(v?"; your tools stay callable with `tool_choice: auto`, and the final text answer comes back in the contract's shape. The guarantee on this request is still the layer's (`constraints.backend: \"none\"`\
|
|
636
636
|
), because the model may call one of your tools first.":'. The guarantee stays native (`constraints.backend: "provider-native"`).')+" See https://platform.claude.com/docs/en/agents-and-tools/tool-use/\
|
|
637
|
-
define-tools#forcing-tool-use")):(!
|
|
637
|
+
define-tools#forcing-tool-use")):(!E&&!v&&this.avisar("anthropic-strict-incompatible","[bvsala] The response contract does not meet `strict` mode (in strict, `required` must list ALL the keys in `prop\
|
|
638
638
|
erties`, and every object needs `additionalProperties: false`). The schema is sent without `strict`: the model is still guided and the layer still validates, but the guarantee comes from the layer, no\
|
|
639
|
-
t the provider."),
|
|
640
|
-
ext.":"Return the final answer in the required shape.",input_schema:e.schema,...
|
|
639
|
+
t the provider."),h=E&&!v&&!d,c.push({name:Ge,description:v?"Return the final answer in the required shape. Use the other tools first if you need data; call this one instead of writing the answer as t\
|
|
640
|
+
ext.":"Return the final answer in the required shape.",input_schema:e.schema,...h?{strict:true}:{}}),v&&d?(r.push({type:"text",text:`When you have the final answer, deliver it by calling the \`${Ge}\` to\
|
|
641
641
|
ol instead of writing it as text. Call the other tools first if you need data.`}),this.avisar(`anthropic-sin-tool-choice-forzado:${u}`,`[bvsala] Model "${u}" does not accept a forced \`tool_choice\` (\`a\
|
|
642
642
|
ny\` or \`tool\` is a 400 on this model, with or without thinking), and this contract does not meet \`strict\` mode, so it cannot travel as structured output either. The contract travels as one extra tool \
|
|
643
643
|
with \`tool_choice: auto\` and one sentence in \`system\` telling the model to answer through it. If the model answers in prose anyway, the layer repairs it with a second call. Make the schema strict-comp\
|
|
644
644
|
atible (every key in \`required\`, \`additionalProperties: false\`) to get the provider-enforced path. See https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools#forcing-tool-use`)):
|
|
645
|
-
v&&(
|
|
646
|
-
fic shape is only GUARANTEED by forcing that exact tool, and forcing ours would leave the model unable to call yours. The contract travels as one extra tool"+(
|
|
645
|
+
v&&(m=this.opts.forceAnswerThroughTool!==false,this.avisar("anthropic-contrato-con-herramientas","[bvsala] This request carries BOTH your tools and an output contract. On Anthropic's Messages API a speci\
|
|
646
|
+
fic shape is only GUARANTEED by forcing that exact tool, and forcing ours would leave the model unable to call yours. The contract travels as one extra tool"+(m?' and the request is sent with `tool_ch\
|
|
647
647
|
oice: {type: "any"}`, so the model must answer through SOME tool \u2014 yours or the contract \u2014 and can no longer reply in prose. Your tool turn is untouched. The guarantee is still the layer\'s, not the pr\
|
|
648
648
|
ovider\'s (`constraints.backend: "none"`), because the model may pick one of your tools and defer the final answer to the next turn.':", not forced (`forceAnswerThroughTool: false`). The guarantee is \
|
|
649
649
|
the layer's, not the provider's (`constraints.backend: \"none\"`), and if the model answers in prose the layer pays a second full call to repair it \u2014 on this API that second call re-pays the whole tool-\
|
|
@@ -651,116 +651,116 @@ use overhead.")+" Dropping either the tools or the contract from this request is
|
|
|
651
651
|
4096,messages:o};r.length>0&&(b.system=r),e.temperature!=null&&(p&&e.temperature!==1?this.avisar(`anthropic-sin-temperature:${u}`,`[bvsala] Model "${u}" rejects a non-default \`temperature\` with a 400 \
|
|
652
652
|
(its sampling is fixed; the same holds for \`top_p\` and \`top_k\`). The request is sent WITHOUT \`temperature\` rather than failing, so its output is sampled, not deterministic: temperature ${e.temperature}\
|
|
653
653
|
was not applied. Drop \`temperature\` for this model to silence this warning (or create the layer with \`silenceWarnings\`). See https://platform.claude.com/docs/en/models/sonnet-5-5/overview`):b.temperature=
|
|
654
|
-
e.temperature),c.length>0&&(b.tools=c),g&&(b.output_config={format:g}),
|
|
654
|
+
e.temperature),c.length>0&&(b.tools=c),g&&(b.output_config={format:g}),h&&!g?b.tool_choice={type:"tool",name:Ge}:m&&(b.tool_choice={type:"any"}),e.deferrable===true&&this.avisar("anthropic-sin-tier-dife\
|
|
655
655
|
rible","[bvsala] This request was declared deferrable, but the Anthropic Messages API has NO cheaper synchronous tier: its `service_tier` chooses between priority capacity (more expensive) and standar\
|
|
656
656
|
d, not a flex. The request goes out unchanged and the report credits no discount. The 50% for deferring exists in the Message Batches API, which is asynchronous and does not fit a request/response cal\
|
|
657
|
-
l: send such requests with layer.batches.submit() instead.");let y=this.marcarCache(e,r,o,i,s,l>=0?c[l]:void 0);return e.cacheDiagnostics&&
|
|
658
|
-
cacheDiagnostics.previousMessageId}),this.opts.automaticCache===true&&e.cachePlacement==null&&e.stablePrefixMessages!=null&&y<Math.min(this.opts.maxCacheBreakpoints??
|
|
659
|
-
meral"}),{body:b,contratoNativo:
|
|
657
|
+
l: send such requests with layer.batches.submit() instead.");let y=this.marcarCache(e,r,o,i,s,l>=0?c[l]:void 0);return e.cacheDiagnostics&&oo(this.opts.baseUrl)&&(b.diagnostics={previous_message_id:e.
|
|
658
|
+
cacheDiagnostics.previousMessageId}),this.opts.automaticCache===true&&e.cachePlacement==null&&e.stablePrefixMessages!=null&&y<Math.min(this.opts.maxCacheBreakpoints??ro,ro)&&(b.cache_control={type:"ephe\
|
|
659
|
+
meral"}),{body:b,contratoNativo:h,turnoAnadido:a,esquemaPorPrompt:f,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=Or[e.
|
|
660
660
|
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 l=i.
|
|
661
661
|
para(c);if(!l)return;let u=[];for(let d of l)if(!(d.busqueda!==r||o.has(d.id))&&d.herramientas.every(p=>n.has(p))){o.add(d.id),u.push(d.uso,d.resultado),s.resultados+=1;for(let p of d.herramientas)s.herramientas.
|
|
662
|
-
includes(p)||s.herramientas.push(p);}return u.length>0?u:void 0}};return s}recordarBusquedas(e){let n=e.filter(r=>r.type==="tool_use"&&r.name!==
|
|
663
|
-
length!==0&&this.busquedas.recordar(n,
|
|
664
|
-
|
|
665
|
-
null&&!u&&s&&s.defer_loading!==true&&a>0&&(s.cache_control=l(),a-=1);let d=r[r.length-1],p=d?.content[d.content.length-1];if(e.cachePlacement?.tail===true&&a>0&&p&&(p.cache_control=l(),a-=1),a>0&&o){let
|
|
666
|
-
mensaje]?.content[o.bloque];
|
|
667
|
-
if(e.cacheDiagnostics?.previousMessageId==null||!
|
|
662
|
+
includes(p)||s.herramientas.push(p);}return u.length>0?u:void 0}};return s}recordarBusquedas(e){let n=e.filter(r=>r.type==="tool_use"&&r.name!==Ge).map(r=>r.id).filter(r=>typeof r=="string"&&r!=="");n.
|
|
663
|
+
length!==0&&this.busquedas.recordar(n,Pl(e));}avisar(e,n){Ce(this,e,n);}marcarCache(e,n,r,o,i,s){if(e.promptCacheKey!=null,e.stablePrefixMessages==null)return 0;let a=Math.min(this.opts.maxCacheBreakpoints??
|
|
664
|
+
ro,ro);if(a<=0)return 0;let c=a,l=()=>e.cachePlacement?.ttl==="1h"?{type:"ephemeral",ttl:"1h"}:{type:"ephemeral"},u=i>0?n[i-1]:void 0;u&&(u.cache_control=l(),a-=1),e.stablePrefixMessages===0&&e.cachePlacement==
|
|
665
|
+
null&&!u&&s&&s.defer_loading!==true&&a>0&&(s.cache_control=l(),a-=1);let d=r[r.length-1],p=d?.content[d.content.length-1];if(e.cachePlacement?.tail===true&&a>0&&p&&(p.cache_control=l(),a-=1),a>0&&o){let h=r[o.
|
|
666
|
+
mensaje]?.content[o.bloque];h&&h.cache_control==null&&(h.cache_control=l(),a-=1);}return c-a}async leer(e,n,r,o,i,s){let a=await e.json();return this.leerMensaje(a,n,r,o,i,this.opts.requireUsage===true,s)}diagnosticoDe(e,n){
|
|
667
|
+
if(e.cacheDiagnostics?.previousMessageId==null||!oo(this.opts.baseUrl))return {};if(n===void 0)return {};if(n===null)return {cacheDiagnostics:{missReason:"none"}};if(typeof n!="object")return {};let r=n.cache_miss_reason;
|
|
668
668
|
if(r===null)return {cacheDiagnostics:{missReason:"pending"}};if(r===void 0||typeof r!="object")return {};let o=r.type,i=r.cache_missed_input_tokens;return typeof o!="string"||o===""?{}:{cacheDiagnostics:{
|
|
669
|
-
missReason:o,...typeof i=="number"&&Number.isFinite(i)&&i>=0?{missedInputTokens:i}:{}}}}leerMensaje(e,n,r,o,i,s,a){let c=e.content??[],l=c.some(x=>
|
|
670
|
-
"").join(""),d=c.filter(x=>x.type==="tool_use"&&x.name!==
|
|
671
|
-
e"&&x.name===
|
|
672
|
-
|
|
673
|
-
void 0?{finishReasonDetail:
|
|
674
|
-
iterations:
|
|
675
|
-
id}:{},...this.diagnosticoDe(n,e.diagnostics),raw:e},{...
|
|
676
|
-
p=
|
|
677
|
-
p(g));};for(let
|
|
678
|
-
n-pareja":"sin-ids"),
|
|
679
|
-
x+=1;let S=
|
|
680
|
-
push(A),p(
|
|
681
|
-
"assistant"&&(o.unshift({role:"user",content:[{type:"text",text:"(continue)"}]}),s&&(s={mensaje:s.mensaje+1,bloque:s.bloque}),
|
|
682
|
-
function
|
|
683
|
-
let s=e.map(c=>
|
|
669
|
+
missReason:o,...typeof i=="number"&&Number.isFinite(i)&&i>=0?{missedInputTokens:i}:{}}}}leerMensaje(e,n,r,o,i,s,a){let c=e.content??[],l=c.some(x=>is(x.type)),u=c.filter(x=>x.type==="text").map(x=>x.text??
|
|
670
|
+
"").join(""),d=c.filter(x=>x.type==="tool_use"&&x.name!==Ge).map(x=>({...x.id?{id:x.id}:{},name:x.name??"",arguments:JSON.stringify(x.input??{})})).filter(x=>x.name!==""),p=c.find(x=>x.type==="tool_us\
|
|
671
|
+
e"&&x.name===Ge),h=p?JSON.stringify(p.input??{}):u,f=e.usage,{usage:m,entradaAusente:g,salidaAusente:b}=ns(f,f?.output_tokens,l);if(s&&(g||b))throw new Error(Ll(f?.input_tokens,f?.output_tokens));let y=rs(
|
|
672
|
+
f),v=n.toolSearch?Ol(c,a):void 0;return n.toolSearch&&this.recordarBusquedas(c),dt({text:h,...d.length>0?{toolCalls:d}:{},...e.stop_reason?{finishReason:ss(e.stop_reason)}:{},...Vn(e.stop_reason,e.stop_details)!==
|
|
673
|
+
void 0?{finishReasonDetail:Vn(e.stop_reason,e.stop_details)}:{},...as({stopReason:e.stop_reason,stopDetails:e.stop_details,bloques:Array.isArray(e.content)?e.content.length:0,outputTokens:f?.output_tokens,
|
|
674
|
+
iterations:f?.iterations})?{unbilledRefusal:true}:{},...y?{servedServiceTier:y}:{},usage:m,structuredNatively:n.schema!=null&&r,...v?{toolSearch:v}:{},...typeof e.id=="string"&&e.id!==""?{providerMessageId:e.
|
|
675
|
+
id}:{},...this.diagnosticoDe(n,e.diagnostics),raw:e},{...Mt((o?1:0)+cn(n.tools)),esquemaPorPrompt:i})}};function ih(t,e,n){let r=[],o=[],i=t.stablePrefixMessages??0,s,a=0,c=true,l=ch(t),u=new Set,d=t.messages,
|
|
676
|
+
p=m=>{if(m>=i)return;let g=o.length-1;s={mensaje:g,bloque:o[g].content.length-1};},h=(m,g)=>{m.content!==""&&(o.push({role:m.role==="assistant"?"assistant":"user",content:[{type:"text",text:m.content}]}),
|
|
677
|
+
p(g));};for(let m=0;m<d.length;m++){let g=d[m];if(g.role==="system"&&c){r.push({type:"text",text:g.content}),m<i&&(a=r.length);continue}if(c=false,g.role!=="assistant"){g.role==="tool"&&n(g.toolCallId?"si\
|
|
678
|
+
n-pareja":"sin-ids"),h(g,m);continue}let b=e?e(g):void 0;b&&l.cargar(b);let y=g.content!==""?[{type:"text",text:g.content}]:[],v=g.toolCalls??[],x=m+1;if(v.length>0){for(;x<d.length&&d[x].role==="tool";)
|
|
679
|
+
x+=1;let S=sh(v,d.slice(m+1,x),l,u);if("llamadas"in S){o.push({role:"assistant",content:[...b??[],...y,...S.llamadas]}),p(m);let C={role:"user",content:[]};o.push(C),S.resultados.forEach((A,T)=>{C.content.
|
|
680
|
+
push(A),p(m+1+T);}),m=x-1;continue}n(S.motivo);}let E=b?[...b,...y]:y;E.length>0&&(o.push({role:"assistant",content:E}),p(m));for(let S=m+1;S<x;S++)h(d[S],S);m=x-1;}let f=false;return o.length>0&&o[0].role===
|
|
681
|
+
"assistant"&&(o.unshift({role:"user",content:[{type:"text",text:"(continue)"}]}),s&&(s={mensaje:s.mensaje+1,bloque:s.bloque}),f=true),{system:r,messages:o,finDelPrefijo:s,prefijoEnSystem:a,turnoAnadido:f}}
|
|
682
|
+
function sh(t,e,n,r){if(t.some(c=>!c.id)||e.some(c=>!c.toolCallId))return {motivo:"sin-ids"};let o=t.map(c=>Al(c.id)),i=new Set(o);if(i.size!==o.length||o.some(c=>r.has(c)))return {motivo:"sin-pareja"};
|
|
683
|
+
let s=e.map(c=>Al(c.toolCallId));if(s.length!==o.length||new Set(s).size!==s.length||s.some(c=>!i.has(c)))return {motivo:"sin-pareja"};let a=t.map(c=>ah(c.arguments));if(a.some(c=>c===void 0))return {motivo:"\
|
|
684
684
|
sin-pareja"};if(t.some(c=>!n.tiene(c.name)))return {motivo:"no-disponibles"};for(let c of o)r.add(c);return {llamadas:t.map((c,l)=>({type:"tool_use",id:o[l],name:c.name,input:a[l]})),resultados:e.map((c,l)=>({
|
|
685
|
-
type:"tool_result",tool_use_id:s[l],...c.content!==""?{content:c.content}:{},...c.isError===true?{is_error:true}:{}}))}}function
|
|
686
|
-
"object"&&n!==null&&!Array.isArray(n);if(e(t))return t;if(typeof t=="string"){if(t.trim()==="")return {};try{let n=JSON.parse(t);return e(n)?n:void 0}catch{return}}}function
|
|
685
|
+
type:"tool_result",tool_use_id:s[l],...c.content!==""?{content:c.content}:{},...c.isError===true?{is_error:true}:{}}))}}function Al(t){return t.replace(/[^a-zA-Z0-9_-]/g,"_")}function ah(t){let e=n=>typeof n==
|
|
686
|
+
"object"&&n!==null&&!Array.isArray(n);if(e(t))return t;if(typeof t=="string"){if(t.trim()==="")return {};try{let n=JSON.parse(t);return e(n)?n:void 0}catch{return}}}function ch(t){let e=new Set((t.tools??
|
|
687
687
|
[]).map(r=>r.id));if(!t.toolSearch)return {tiene:r=>e.has(r),cargar:()=>{}};let n=new Set(t.toolSearch.alwaysLoaded.filter(r=>e.has(r)));return {tiene:r=>n.has(r),cargar(r){for(let o of r){if(o.type!=="\
|
|
688
|
-
tool_search_tool_result")continue;let i=o.content?.tool_references;if(Array.isArray(i))for(let s of i)typeof s?.tool_name=="string"&&e.has(s.tool_name)&&n.add(s.tool_name);}}}}function
|
|
689
|
-
test(new URL(t??"https://api.anthropic.com/v1").hostname)}catch{return false}}function
|
|
688
|
+
tool_search_tool_result")continue;let i=o.content?.tool_references;if(Array.isArray(i))for(let s of i)typeof s?.tool_name=="string"&&e.has(s.tool_name)&&n.add(s.tool_name);}}}}function oo(t){try{return /(^|\.)api\.anthropic\.com$/i.
|
|
689
|
+
test(new URL(t??"https://api.anthropic.com/v1").hostname)}catch{return false}}function Ol(t,e){let n=0,r=0,o=[];for(let i of t)if(i.type==="server_tool_use"&&typeof i.name=="string"&&i.name.startsWith("to\
|
|
690
690
|
ol_search_tool"))n+=1;else if(i.type==="tool_search_tool_result"){let s=i.content;if(s&&s.type==="tool_search_tool_result_error")r+=1;else if(s&&Array.isArray(s.tool_references))for(let a of s.tool_references)
|
|
691
|
-
typeof a?.tool_name=="string"&&!o.includes(a.tool_name)&&o.push(a.tool_name);}return {searches:n,loaded:o,errors:r,...e&&e.resultados>0?{resent:{results:e.resultados,tools:[...e.herramientas]}}:{}}}function
|
|
692
|
-
try{return JSON.parse(t)}catch{return}}function
|
|
693
|
-
t"}, output=${e??"absent"}); cannot measure cost.`}async function
|
|
694
|
-
PROHIBITED_CONTENT","IMAGE_RECITATION","IMAGE_OTHER","ESCALATION"]),
|
|
695
|
-
"NO_IMAGE"]);function
|
|
696
|
-
t==="STOP"?{parada:n?"tool_calls":"stop",reproducible:true}:t==="MAX_TOKENS"?{parada:"length",reproducible:true}:
|
|
697
|
-
t)}}function
|
|
698
|
-
if(n==="none")return
|
|
691
|
+
typeof a?.tool_name=="string"&&!o.includes(a.tool_name)&&o.push(a.tool_name);}return {searches:n,loaded:o,errors:r,...e&&e.resultados>0?{resent:{results:e.resultados,tools:[...e.herramientas]}}:{}}}function lh(t){
|
|
692
|
+
try{return JSON.parse(t)}catch{return}}function uh(t){try{return JSON.stringify(JSON.parse(t===""?"{}":t))}catch{return t}}function Ll(t,e){return `provider returned incomplete usage (input=${t??"absen\
|
|
693
|
+
t"}, output=${e??"absent"}); cannot measure cost.`}async function Ml(t){try{return (await t.text()).slice(0,500)}catch{return "<no body>"}}function dh(t){return ut(t)==="anthropic"?"anthropic":null}var Nl="https://generativelanguage.googleapis.com/v1beta",jl="x-gemini-service-tier",ph=new Set(["SAFETY","RECITATION","LANGUAGE","OTHER","BLOCKLIST","PROHIBITED_CONTENT","SPII","IMAGE_SAFETY","IMAGE_\
|
|
694
|
+
PROHIBITED_CONTENT","IMAGE_RECITATION","IMAGE_OTHER","ESCALATION"]),fh=new Set(["MALFORMED_FUNCTION_CALL","UNEXPECTED_TOOL_CALL","TOO_MANY_TOOL_CALLS","MISSING_THOUGHT_SIGNATURE","MALFORMED_RESPONSE",
|
|
695
|
+
"NO_IMAGE"]);function Bl(t,e,n){return e!==void 0&&e!==""&&e!=="BLOCK_REASON_UNSPECIFIED"?{parada:"content_filter",detalle:e,reproducible:true}:t===void 0||t===""||t==="FINISH_REASON_UNSPECIFIED"?{reproducible:true}:
|
|
696
|
+
t==="STOP"?{parada:n?"tool_calls":"stop",reproducible:true}:t==="MAX_TOKENS"?{parada:"length",reproducible:true}:ph.has(t)?{parada:"content_filter",detalle:t,reproducible:true}:{parada:t,reproducible:!fh.has(
|
|
697
|
+
t)}}function mh(t){return /(^|\/)gemini-2\.5/.test(t)}function $l(t){return /-pro\b/.test(t)}function zl(t,e){let n=e.toLowerCase();if(mh(t)){let o={minimal:1024,low:1024,medium:8192,high:24576,xhigh:24576};
|
|
698
|
+
if(n==="none")return $l(t)?null:{config:{thinkingBudget:0},noSeApaga:false};let i=o[n];return i===void 0?null:{config:{thinkingBudget:i},noSeApaga:false}}let r=$l(t)?"LOW":"MINIMAL";switch(n){case "none":return {
|
|
699
699
|
config:{thinkingLevel:r},noSeApaga:true};case "minimal":return {config:{thinkingLevel:r},noSeApaga:false};case "low":return {config:{thinkingLevel:"LOW"},noSeApaga:false};case "medium":return {config:{thinkingLevel:"\
|
|
700
|
-
MEDIUM"},noSeApaga:false};case "high":case "xhigh":return {config:{thinkingLevel:"HIGH"},noSeApaga:false};default:return {config:{thinkingLevel:e.toUpperCase()},noSeApaga:false}}}function
|
|
701
|
-
exec(t);return e?e[1].toUpperCase():null}function
|
|
702
|
-
thought_signature;return typeof n=="string"&&n!==""?n:void 0}function
|
|
703
|
-
if(t.isError===true)return {error:t.content};try{let e=JSON.parse(t.content);if(e!==null&&typeof e=="object"&&!Array.isArray(e))return e}catch{}return {result:t.content}}function
|
|
700
|
+
MEDIUM"},noSeApaga:false};case "high":case "xhigh":return {config:{thinkingLevel:"HIGH"},noSeApaga:false};default:return {config:{thinkingLevel:e.toUpperCase()},noSeApaga:false}}}function Fl(t){let e=/thinking level (\w+) is not supported/i.
|
|
701
|
+
exec(t);return e?e[1].toUpperCase():null}function hh(t){return typeof t=="string"&&t!==""?{google:{thought_signature:t}}:void 0}function gh(t){let e=t?.google;if(e===null||typeof e!="object")return;let n=e.
|
|
702
|
+
thought_signature;return typeof n=="string"&&n!==""?n:void 0}function bh(t){try{let e=JSON.parse(t===""?"{}":t);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return {}}}function vh(t){
|
|
703
|
+
if(t.isError===true)return {error:t.content};try{let e=JSON.parse(t.content);if(e!==null&&typeof e=="object"&&!Array.isArray(e))return e}catch{}return {result:t.content}}function ql(t){let e=[],n=[],r=true,
|
|
704
704
|
o=[],i=0,s=(a,c)=>{if(c.length===0)return;let l=n[n.length-1];l&&l.role===a?l.parts.push(...c):n.push({role:a,parts:c});};for(let a of t){if(a.role==="system"&&r){a.content!==""&&e.push({text:a.content});
|
|
705
705
|
continue}if(r=false,a.role==="tool"){let c=a.toolCallId?o.find(d=>d.id===a.toolCallId):void 0,l=c??o[i],u=a.name??l?.name;if(i+=1,!u){s("user",a.content!==""?[{text:a.content}]:[]);continue}s("user",[{functionResponse:{
|
|
706
|
-
...c?.id?{id:c.id}:{},name:u,response:
|
|
707
|
-
...u.id?{id:u.id}:{},name:u.name,args:
|
|
708
|
-
parts:e}}:{},contents:n}}function ve(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0}function
|
|
709
|
-
s=t?.totalTokenCount,a=(ve(n)?n:0)+(ve(i)?i:0),c=ve(r)?r:0,l=ve(o)?o:0,u=ve(s)&&ve(n)?Math.max(0,s-n-c-l-(ve(i)?i:0)):0,d;(ve(o)||ve(s))&&(d=l+u),d===0&&e&&(d=void 0);let p=ve(r)||ve(s)&&ve(n),
|
|
710
|
-
p;return {inputTokens:a,outputTokens:c+l+u,...ve(t?.cachedContentTokenCount)?{cachedInputTokens:t.cachedContentTokenCount}:{},...d!==void 0?{reasoningTokens:d}:{},...
|
|
706
|
+
...c?.id?{id:c.id}:{},name:u,response:vh(a)}}]);continue}if(a.role==="assistant"){let c=a.content!==""?[{text:a.content}]:[],l=a.toolCalls??[];for(let u of l){let d=gh(u.extraContent);c.push({functionCall:{
|
|
707
|
+
...u.id?{id:u.id}:{},name:u.name,args:bh(u.arguments)},...d!==void 0?{thoughtSignature:d}:{}});}o=l,i=0,s("model",c);continue}s("user",a.content!==""?[{text:a.content}]:[]);}return {...e.length>0?{systemInstruction:{
|
|
708
|
+
parts:e}}:{},contents:n}}function ve(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0}function Ul(t,e){let n=t?.promptTokenCount,r=t?.candidatesTokenCount,o=t?.thoughtsTokenCount,i=t?.toolUsePromptTokenCount,
|
|
709
|
+
s=t?.totalTokenCount,a=(ve(n)?n:0)+(ve(i)?i:0),c=ve(r)?r:0,l=ve(o)?o:0,u=ve(s)&&ve(n)?Math.max(0,s-n-c-l-(ve(i)?i:0)):0,d;(ve(o)||ve(s))&&(d=l+u),d===0&&e&&(d=void 0);let p=ve(r)||ve(s)&&ve(n),h=ve(n)&&
|
|
710
|
+
p;return {inputTokens:a,outputTokens:c+l+u,...ve(t?.cachedContentTokenCount)?{cachedInputTokens:t.cachedContentTokenCount}:{},...d!==void 0?{reasoningTokens:d}:{},...h?{}:{complete:false}}}var Hn=class{texto="";llamadas=[];paradaNativa;bloqueo;uso;huboPensamiento=false;idDeRespuesta;ultimo;sumar(e){
|
|
711
711
|
if(this.ultimo=e,e.error!=null){let i=e.error,s=typeof i.message=="string"?i.message:JSON.stringify(e.error);throw new Error(`provider stream error: ${s}`)}e.usageMetadata!=null&&typeof e.usageMetadata==
|
|
712
712
|
"object"&&(this.uso=e.usageMetadata),typeof e.responseId=="string"&&e.responseId!==""&&(this.idDeRespuesta??=e.responseId);let n=e.promptFeedback?.blockReason;typeof n=="string"&&n!==""&&(this.bloqueo=
|
|
713
713
|
n);let r="",o=e.candidates?.[0];for(let i of o?.content?.parts??[]){if(i.thought===true){this.huboPensamiento=true;continue}if(i.functionCall&&typeof i.functionCall.name=="string"&&i.functionCall.name!==""){
|
|
714
|
-
let s=
|
|
714
|
+
let s=hh(i.thoughtSignature);this.llamadas.push({...typeof i.functionCall.id=="string"&&i.functionCall.id!==""?{id:i.functionCall.id}:{},name:i.functionCall.name,arguments:JSON.stringify(i.functionCall.
|
|
715
715
|
args??{}),...s!==void 0?{extraContent:s}:{}});continue}typeof i.text=="string"&&i.text!==""&&(r+=i.text);}return this.texto+=r,typeof o?.finishReason=="string"&&o.finishReason!==""&&(this.paradaNativa=
|
|
716
|
-
o.finishReason),r}terminado(){return this.paradaNativa!==void 0||this.bloqueo!==void 0}};function
|
|
717
|
-
""):e}function
|
|
718
|
-
o body>"}}var
|
|
719
|
-
this.oficial=
|
|
720
|
-
s=new
|
|
721
|
-
done",response:c};return}let r=
|
|
716
|
+
o.finishReason),r}terminado(){return this.paradaNativa!==void 0||this.bloqueo!==void 0}};function cs(t){let e=t.replace(/^models\//,"");return e.includes("/")?e.replace(/^[^/]+\//,"").replace(/^models\//,
|
|
717
|
+
""):e}function Vl(t,e){try{let n=t.headers?.get?.(e);return typeof n=="string"&&n.trim()!==""?n.trim():void 0}catch{return}}async function ls(t){try{return (await t.text()).slice(0,500)}catch{return "<n\
|
|
718
|
+
o body>"}}var Hl=class{id;opts;fetchImpl;base;oficial;nivelAprendido=new Map;constructor(e={}){this.opts=e,this.base=(e.baseUrl??Nl).replace(/\/$/,""),this.id=`google:${this.base}`,this.fetchImpl=e.fetchImpl??fetch,
|
|
719
|
+
this.oficial=ut(this.base)==="google",Kr(this,this.oficial?"google":null),ln(this,an(this.base));}async generate(e,n){let r=cs(e.model),o=await this.enviarConCorrecciones(r,e,false,n?.signal),i=await o.json(),
|
|
720
|
+
s=new Hn;return s.sumar(i),this.cerrar(s,e,o,i)}async*generateStream(e,n={}){if(e.schema!=null||e.deferrable===true){let c=await this.generate(e,n);c.text!==""&&(yield {type:"text",delta:c.text}),yield {type:"\
|
|
721
|
+
done",response:c};return}let r=cs(e.model),o=await this.enviarConCorrecciones(r,e,true,n.signal),i=new Hn;if((o.headers.get("content-type")??"").includes("application/json")){let c=await o.json();for(let l of Array.
|
|
722
722
|
isArray(c)?c:[c])i.sumar(l);if(!i.terminado())throw new Error("provider stream ended before completion (no finishReason)");i.texto!==""&&(yield {type:"text",delta:i.texto}),yield {type:"done",response:this.
|
|
723
|
-
cerrar(i,e,o,c)};return}let s=o.body,a=s&&typeof s.getReader=="function"?s:await o.text();for await(let c of
|
|
723
|
+
cerrar(i,e,o,c)};return}let s=o.body,a=s&&typeof s.getReader=="function"?s:await o.text();for await(let c of un(a)){let l;try{l=JSON.parse(c.data);}catch{continue}if(l===null||typeof l!="object")continue;
|
|
724
724
|
let u=i.sumar(l);u!==""&&(yield {type:"text",delta:u});}if(!i.terminado())throw new Error("provider stream ended before completion (no finishReason)");yield {type:"done",response:this.cerrar(i,e,o,i.uso??
|
|
725
|
-
null)};}async enviarConCorrecciones(e,n,r,o){let i=await this.enviar(e,n,r,o);for(let s=0;s<3&&!i.ok&&i.status===400;s++){let a=await
|
|
725
|
+
null)};}async enviarConCorrecciones(e,n,r,o){let i=await this.enviar(e,n,r,o);for(let s=0;s<3&&!i.ok&&i.status===400;s++){let a=await ls(i),c=Fl(a),l=this.cuerpo(e,n).generationConfig?.thinkingConfig?.
|
|
726
726
|
thinkingLevel;if(c===null||l===void 0||c!==String(l).toUpperCase())throw new Error(`provider ${i.status}: ${a}`);let u=c==="MINIMAL"?"LOW":null,d=this.nivelAprendido.get(e)??new Map;d.set(c,u),this.nivelAprendido.
|
|
727
|
-
set(e,d),
|
|
728
|
-
(the rejected request was not billed; the model is noted and the following requests go straight there)."),i=await this.enviar(e,n,r,o);}if(!i.ok)throw new Error(`provider ${i.status}: ${await
|
|
727
|
+
set(e,d),Ce(this,`google-nivel:${this.base}:${e}:${c}`,`[bvsala] Model "${e}" rejects thinkingLevel ${c} with a 400, so `+(u?`${u} is sent instead`:"no thinking level is sent (the model's default)")+"\
|
|
728
|
+
(the rejected request was not billed; the model is noted and the following requests go straight there)."),i=await this.enviar(e,n,r,o);}if(!i.ok)throw new Error(`provider ${i.status}: ${await ls(i)}`);
|
|
729
729
|
return i}async enviar(e,n,r,o){let i=r?"streamGenerateContent?alt=sse":"generateContent";return await this.fetchImpl(`${this.base}/models/${encodeURIComponent(e)}:${i}`,{method:"POST",headers:{"conten\
|
|
730
730
|
t-type":"application/json",...this.opts.apiKey?{"x-goog-api-key":this.opts.apiKey}:{},...this.opts.headers},body:JSON.stringify(this.cuerpo(e,n)),...o?{signal:o}:{}})}cuerpo(e,n){let{systemInstruction:r,
|
|
731
|
-
contents:o}=
|
|
731
|
+
contents:o}=ql(n.messages),i={};n.maxOutputTokens!=null&&(i.maxOutputTokens=n.maxOutputTokens),n.temperature!=null&&(i.temperature=n.temperature),n.seed!=null&&(i.seed=n.seed),n.schema!=null&&(i.responseMimeType=
|
|
732
732
|
"application/json",i.responseJsonSchema=n.schema);let s=this.pensamiento(e,n);s!==void 0&&(i.thinkingConfig=s);let a=n.tools&&n.tools.length>0?[{functionDeclarations:n.tools.map(c=>({name:c.id,description:c.
|
|
733
733
|
description??"",...c.parameters!=null?{parametersJsonSchema:c.parameters}:{}}))}]:void 0;return {contents:o,...r?{systemInstruction:r}:{},...a?{tools:a}:{},...this.opts.safetySettings?{safetySettings:this.
|
|
734
|
-
opts.safetySettings}:{},...Object.keys(i).length>0?{generationConfig:i}:{},...n.deferrable===true?{serviceTier:
|
|
735
|
-
if(n.reasoningEffort!=null){let i=
|
|
736
|
-
thinking cannot be turned off on Gemini 2.5 Pro), so no thinking config is sent for it.`);else {i.noSeApaga&&
|
|
734
|
+
opts.safetySettings}:{},...Object.keys(i).length>0?{generationConfig:i}:{},...n.deferrable===true?{serviceTier:We}:{}}}pensamiento(e,n){let r=this.opts.thinkingConfig?{...this.opts.thinkingConfig}:void 0;
|
|
735
|
+
if(n.reasoningEffort!=null){let i=zl(e,n.reasoningEffort);if(i===null)Ce(this,`google-esfuerzo:${e}:${n.reasoningEffort}`,`[bvsala] reasoningEffort "${n.reasoningEffort}" has no equivalent on "${e}" (\
|
|
736
|
+
thinking cannot be turned off on Gemini 2.5 Pro), so no thinking config is sent for it.`);else {i.noSeApaga&&Ce(this,`google-no-se-apaga:${e}`,`[bvsala] Thinking cannot be turned off on "${e}" (Google:\
|
|
737
737
|
\xABReasoning cannot be turned off for Gemini 2.5 Pro or 3 models\xBB), so reasoningEffort "none" is sent as the lowest level, ${String(i.config.thinkingLevel)}. Its thinking tokens are billed as out\
|
|
738
738
|
put.`);let{thinkingLevel:s,thinkingBudget:a,...c}=r??{};r={...c,...i.config};}}let o=r?.thinkingLevel;if(r&&typeof o=="string"){let i=this.nivelAprendido.get(e),s=o.toUpperCase();if(i?.has(s)){let a=i.
|
|
739
|
-
get(s),{thinkingLevel:c,...l}=r;r=a?{...l,thinkingLevel:a}:l;}}return r&&Object.keys(r).length>0?r:void 0}cerrar(e,n,r,o){let i=
|
|
740
|
-
false)throw new Error(`provider returned incomplete usage (promptTokenCount=${e.uso?.promptTokenCount??"absent"}, candidatesTokenCount=${e.uso?.candidatesTokenCount??"absent"}); cannot measure cost.`);let s=
|
|
741
|
-
e.paradaNativa,e.bloqueo,e.llamadas.length>0),a=typeof e.uso?.serviceTier=="string"&&e.uso.serviceTier!==""?e.uso.serviceTier:void 0,c=a?"cuerpo":void 0;return !a&&this.oficial&&(a=
|
|
742
|
-
cera")),
|
|
743
|
-
{},...n.deferrable===true?{requestedServiceTier:
|
|
744
|
-
0),esquemaEnFormatoNativo:n.schema!=null,origen:this.oficial?"google":null,...c?{tierLeidoDe:c}:{}})}};var
|
|
745
|
-
now()-this.start}all(){return this.events}};var
|
|
746
|
-
`"${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
|
|
747
|
-
let r=
|
|
748
|
-
new TypeError(l)}return t}function
|
|
749
|
-
o() output");let n=e.outputLen;if(t.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function
|
|
750
|
-
let e="";for(let n=0;n<t.length;n++)e+=
|
|
751
|
-
t<=Je.f)return t-(Je.a-10)}function
|
|
752
|
-
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=
|
|
753
|
-
i)),a=
|
|
754
|
-
|
|
755
|
-
`"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}var
|
|
756
|
-
new Uint8Array(e),this.view=
|
|
757
|
-
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){
|
|
758
|
-
|
|
759
|
-
o-8,BigInt(this.length*8),i),this.process(r,0);let a=
|
|
739
|
+
get(s),{thinkingLevel:c,...l}=r;r=a?{...l,thinkingLevel:a}:l;}}return r&&Object.keys(r).length>0?r:void 0}cerrar(e,n,r,o){let i=Ul(e.uso,e.huboPensamiento);if(this.opts.requireUsage===true&&i.complete===
|
|
740
|
+
false)throw new Error(`provider returned incomplete usage (promptTokenCount=${e.uso?.promptTokenCount??"absent"}, candidatesTokenCount=${e.uso?.candidatesTokenCount??"absent"}); cannot measure cost.`);let s=Bl(
|
|
741
|
+
e.paradaNativa,e.bloqueo,e.llamadas.length>0),a=typeof e.uso?.serviceTier=="string"&&e.uso.serviceTier!==""?e.uso.serviceTier:void 0,c=a?"cuerpo":void 0;return !a&&this.oficial&&(a=Vl(r,jl),a&&(c="cabe\
|
|
742
|
+
cera")),dt({text:e.texto,...e.llamadas.length>0?{toolCalls:e.llamadas}:{},...s.parada!==void 0?{finishReason:s.parada}:{},...s.detalle!==void 0?{finishReasonDetail:s.detalle}:{},...a?{servedServiceTier:a}:
|
|
743
|
+
{},...n.deferrable===true?{requestedServiceTier:We}:{},...s.reproducible?{}:{replayable:false},...e.idDeRespuesta?{providerMessageId:e.idDeRespuesta}:{},usage:i,structuredNatively:n.schema!=null,raw:o},{...Mt(
|
|
744
|
+
0),esquemaEnFormatoNativo:n.schema!=null,origen:this.oficial?"google":null,...c?{tierLeidoDe:c}:{}})}};var pt=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.
|
|
745
|
+
now()-this.start}all(){return this.events}};var Ke=class extends Error{status;constructor(e,n){super(e),this.name="LicenseError",n&&(this.status=n);}};function us(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function io(t,e=""){if(typeof t!="number"){let n=e&&
|
|
746
|
+
`"${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 De(t,e,n=""){
|
|
747
|
+
let r=us(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}`,l=s+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):
|
|
748
|
+
new TypeError(l)}return t}function ds(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 Gl(t,e){De(t,void 0,"digestInt\
|
|
749
|
+
o() output");let n=e.outputLen;if(t.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function Wn(...t){for(let e=0;e<t.length;e++)t[e].fill(0);}function so(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var Kl=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",yh=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function ao(t){if(De(t),Kl)return t.toHex();
|
|
750
|
+
let e="";for(let n=0;n<t.length;n++)e+=yh[t[n]];return e}var Je={_0:48,_9:57,A:65,F:70,a:97,f:102};function Wl(t){if(t>=Je._0&&t<=Je._9)return t-Je._0;if(t>=Je.A&&t<=Je.F)return t-(Je.A-10);if(t>=Je.a&&
|
|
751
|
+
t<=Je.f)return t-(Je.a-10)}function Gn(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(Kl)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?
|
|
752
|
+
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=Wl(t.charCodeAt(
|
|
753
|
+
i)),a=Wl(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 ps(...t){let e=0;for(let r=0;r<t.length;r++){let o=t[r];De(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 Jl(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 Yl(t=32){
|
|
754
|
+
io(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(
|
|
755
|
+
`"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}var Zl=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});var co=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=
|
|
756
|
+
new Uint8Array(e),this.view=so(this.buffer);}update(e){ds(this),De(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=so(e);for(;o<=i-s;s+=
|
|
757
|
+
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){ds(this),
|
|
758
|
+
Gl(e,this),this.finished=true;let{buffer:n,view:r,blockLen:o,isLE:i}=this,{pos:s}=this;n[s++]=128,Wn(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(
|
|
759
|
+
o-8,BigInt(this.length*8),i),this.process(r,0);let a=so(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_s\
|
|
760
760
|
ha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[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.
|
|
761
|
-
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 ae=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var
|
|
762
|
-
o=new Uint32Array(n);for(let i=0;i<n;i++){let{h:s,l:a}=
|
|
763
|
-
n+r+o+(t/2**32|0)|0,
|
|
761
|
+
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 ae=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var lo=BigInt(4294967295),Xl=BigInt(32);function kh(t,e=false){return e?{h:Number(t&lo),l:Number(t>>Xl&lo)}:{h:Number(t>>Xl&lo)|0,l:Number(t&lo)|0}}function Ql(t,e=false){let n=t.length,r=new Uint32Array(n),
|
|
762
|
+
o=new Uint32Array(n);for(let i=0;i<n;i++){let{h:s,l:a}=kh(t[i],e);[r[i],o[i]]=[s,a];}return [r,o]}var fs=(t,e,n)=>t>>>n,ms=(t,e,n)=>t<<32-n|e>>>n,Nt=(t,e,n)=>t>>>n|e<<32-n,jt=(t,e,n)=>t<<32-n|e>>>n,Kn=(t,e,n)=>t<<64-n|e>>>n-32,Jn=(t,e,n)=>t>>>n-32|e<<64-n;function ze(t,e,n,r){let o=(e>>>0)+(r>>>0);return {h:t+n+(o/2**32|0)|0,l:o|0}}var eu=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),tu=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,nu=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),ru=(t,e,n,r,o)=>e+
|
|
763
|
+
n+r+o+(t/2**32|0)|0,ou=(t,e,n,r,o)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(o>>>0),iu=(t,e,n,r,o,i)=>e+n+r+o+i+(t/2**32|0)|0;var su=Ql(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242",
|
|
764
764
|
"0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc6\
|
|
765
765
|
8b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","\
|
|
766
766
|
0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3\
|
|
@@ -768,159 +768,159 @@ c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a6
|
|
|
768
768
|
x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5d\
|
|
769
769
|
efb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0x\
|
|
770
770
|
eada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c1\
|
|
771
|
-
00d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),
|
|
772
|
-
super(128,e,16,false);}get(){let{Ah:e,Al:n,Bh:r,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:l,El:u,Fh:d,Fl:p,Gh:
|
|
773
|
-
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=l|0,this.El=u|0,this.Fh=d|0,this.Fl=p|0,this.Gh=
|
|
774
|
-
16;v++,n+=4)
|
|
775
|
-
A,
|
|
776
|
-
Gh:
|
|
777
|
-
|
|
778
|
-
let O=
|
|
779
|
-
u|0),{h:d,l:p}=
|
|
780
|
-
f,m,
|
|
781
|
-
0;Dh=ae[6]|0;Dl=ae[7]|0;Eh=ae[8]|0;El=ae[9]|0;Fh=ae[10]|0;Fl=ae[11]|0;Gh=ae[12]|0;Gl=ae[13]|0;Hh=ae[14]|0;Hl=ae[15]|0;constructor(){super(64);}};var
|
|
782
|
-
expected boolean, got type="+typeof t)}return t}function
|
|
783
|
-
"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
|
|
784
|
-
function
|
|
785
|
-
return
|
|
786
|
-
"expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function
|
|
771
|
+
00d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),wh=su[0],Sh=su[1],ft=new Uint32Array(80),mt=new Uint32Array(80),hs=class extends co{constructor(e){
|
|
772
|
+
super(128,e,16,false);}get(){let{Ah:e,Al:n,Bh:r,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:l,El:u,Fh:d,Fl:p,Gh:h,Gl:f,Hh:m,Hl:g}=this;return [e,n,r,o,i,s,a,c,l,u,d,p,h,f,m,g]}set(e,n,r,o,i,s,a,c,l,u,d,p,h,f,m,g){this.Ah=
|
|
773
|
+
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=l|0,this.El=u|0,this.Fh=d|0,this.Fl=p|0,this.Gh=h|0,this.Gl=f|0,this.Hh=m|0,this.Hl=g|0;}process(e,n){for(let v=0;v<
|
|
774
|
+
16;v++,n+=4)ft[v]=e.getUint32(n),mt[v]=e.getUint32(n+=4);for(let v=16;v<80;v++){let x=ft[v-15]|0,E=mt[v-15]|0,S=Nt(x,E,1)^Nt(x,E,8)^fs(x,E,7),C=jt(x,E,1)^jt(x,E,8)^ms(x,E,7),A=ft[v-2]|0,T=mt[v-2]|0,R=Nt(
|
|
775
|
+
A,T,19)^Kn(A,T,61)^fs(A,T,6),M=jt(A,T,19)^Jn(A,T,61)^ms(A,T,6),w=nu(C,M,mt[v-7],mt[v-16]),P=ru(w,S,R,ft[v-7],ft[v-16]);ft[v]=P|0,mt[v]=w|0;}let{Ah:r,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:u,Eh:d,El:p,Fh:h,Fl:f,
|
|
776
|
+
Gh:m,Gl:g,Hh:b,Hl:y}=this;for(let v=0;v<80;v++){let x=Nt(d,p,14)^Nt(d,p,18)^Kn(d,p,41),E=jt(d,p,14)^jt(d,p,18)^Jn(d,p,41),S=d&h^~d&m,C=p&f^~p&g,A=ou(y,E,C,Sh[v],mt[v]),T=iu(A,b,x,S,wh[v],ft[v]),R=A|0,
|
|
777
|
+
M=Nt(r,o,28)^Kn(r,o,34)^Kn(r,o,39),w=jt(r,o,28)^Jn(r,o,34)^Jn(r,o,39),P=r&i^r&a^i&a,$=o&s^o&c^s&c;b=m|0,y=g|0,m=h|0,g=f|0,h=d|0,f=p|0,{h:d,l:p}=ze(l|0,u|0,T|0,R|0),l=a|0,u=c|0,a=i|0,c=s|0,i=r|0,s=o|0;
|
|
778
|
+
let O=eu(R,w,$);r=tu(O,T,M,P),o=O|0;}(({h:r,l:o}=ze(this.Ah|0,this.Al|0,r|0,o|0))),{h:i,l:s}=ze(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=ze(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=ze(this.Dh|0,this.Dl|0,l|0,
|
|
779
|
+
u|0),{h:d,l:p}=ze(this.Eh|0,this.El|0,d|0,p|0),{h,l:f}=ze(this.Fh|0,this.Fl|0,h|0,f|0),{h:m,l:g}=ze(this.Gh|0,this.Gl|0,m|0,g|0),{h:b,l:y}=ze(this.Hh|0,this.Hl|0,b|0,y|0),this.set(r,o,i,s,a,c,l,u,d,p,
|
|
780
|
+
h,f,m,g,b,y);}roundClean(){Wn(ft,mt);}destroy(){this.destroyed=true,Wn(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}},gs=class extends hs{Ah=ae[0]|0;Al=ae[1]|0;Bh=ae[2]|0;Bl=ae[3]|0;Ch=ae[4]|0;Cl=ae[5]|
|
|
781
|
+
0;Dh=ae[6]|0;Dl=ae[7]|0;Eh=ae[8]|0;El=ae[9]|0;Fh=ae[10]|0;Fl=ae[11]|0;Gh=ae[12]|0;Gl=ae[13]|0;Hh=ae[14]|0;Hl=ae[15]|0;constructor(){super(64);}};var uo=Jl(()=>new gs,Zl(3));var ne=(t,e,n)=>De(t,e,n),vs=io,ys=ao,Fe=(...t)=>ps(...t),au=t=>Gn(t),mo=us,cu=t=>Yl(t),fo=BigInt(0),bs=BigInt(1);function pn(t,e=""){if(typeof t!="boolean"){let n=e&&`"${e}" `;throw new TypeError(n+"\
|
|
782
|
+
expected boolean, got type="+typeof t)}return t}function Eh(t){if(typeof t=="bigint"){if(!po(t))throw new RangeError("positive bigint expected, got "+t)}else vs(t);return t}function Ye(t,e=""){if(typeof t!=
|
|
783
|
+
"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 lu(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?fo:BigInt("0x"+t)}function ks(t){return lu(ao(t))}function Ze(t){return lu(ao(Yn(De(t)).reverse()))}
|
|
784
|
+
function xs(t,e){if(io(e),e===0)throw new RangeError("zero length");t=Eh(t);let n=t.toString(16);if(n.length>e*2)throw new RangeError("number too large");return Gn(n.padStart(e*2,"0"))}function uu(t,e){
|
|
785
|
+
return xs(t,e).reverse()}function du(t,e){if(t=ne(t),e=ne(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 Yn(t){return Uint8Array.from(ne(t))}var po=t=>typeof t=="bigint"&&fo<=t;function Ch(t,e,n){return po(t)&&po(e)&&po(n)&&e<=t&&t<n}function ws(t,e,n,r){if(!Ch(e,n,r))throw new RangeError(
|
|
786
|
+
"expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function Ss(t){if(t<fo)throw new Error("expected non-negative bigint, got "+t);let e;for(e=0;t>fo;t>>=bs,e+=1);return e}var pu=t=>(bs<<BigInt(t))-bs;function Bt(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(
|
|
787
787
|
`param "${i}" is invalid: expected own property`);let c=t[i];if(a&&c===void 0)return;let l=typeof c;if(l!==s||c===null)throw new TypeError(`param "${i}" is invalid: expected ${s}, got ${l}`)}let o=(i,s)=>Object.
|
|
788
|
-
entries(i).forEach(([a,c])=>r(a,c,s));o(e,false),o(n,true);}var
|
|
789
|
-
modulus, got "+e);let n=t%e;return n>=ce?n:e+n}function Ae(t,e,n){if(e<ce)throw new Error("pow2: expected non-negative exponent, got "+e);let r=t;for(;e-- >ce;)r*=r,r%=n;return r}function
|
|
788
|
+
entries(i).forEach(([a,c])=>r(a,c,s));o(e,false),o(n,true);}var Es=()=>{throw new Error("not implemented")};var ce=BigInt(0),ie=BigInt(1),zt=BigInt(2),gu=BigInt(3),bu=BigInt(4),vu=BigInt(5),Th=BigInt(7),yu=BigInt(8),Rh=BigInt(9),ku=BigInt(16);function Q(t,e){if(e<=ce)throw new Error("mod: expected positive \
|
|
789
|
+
modulus, got "+e);let n=t%e;return n>=ce?n:e+n}function Ae(t,e,n){if(e<ce)throw new Error("pow2: expected non-negative exponent, got "+e);let r=t;for(;e-- >ce;)r*=r,r%=n;return r}function fu(t,e){if(t===ce)throw new Error("invert: expected non-zer\
|
|
790
790
|
o number");if(e<=ce)throw new Error("invert: expected positive modulus, got "+e);let n=Q(t,e),r=e,o=ce,s=ie;for(;n!==ce;){let l=r/n,u=r-n*l,d=o-s*l;r=n,n=u,o=s,s=d;}if(r!==ie)
|
|
791
|
-
throw new Error("invert: does not exist");return Q(o,e)}function
|
|
792
|
-
r);return
|
|
793
|
-
n=
|
|
794
|
-
cmov(
|
|
795
|
-
o=
|
|
796
|
-
if(
|
|
797
|
-
g=u.sqr(g),
|
|
798
|
-
|
|
799
|
-
BYTES:"number",BITS:"number"},n=
|
|
800
|
-
ORDER<=ie)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function
|
|
801
|
-
if(n===ie)return e;let o=r.ONE,i=e;for(;n>ce;)n&ie&&(o=r.mul(o,i)),i=r.sqr(i),n>>=ie;return o}function
|
|
802
|
-
a,r.mul(a,c)),r.ONE),s=r.inv(i);return e.reduceRight((a,c,l)=>r.is0(c)?a:(o[l]=r.mul(a,o[l]),r.mul(a,c)),s),o}function
|
|
803
|
-
let n=
|
|
804
|
-
|
|
791
|
+
throw new Error("invert: does not exist");return Q(o,e)}function Cs(t,e,n){let r=t;if(!r.eql(r.sqr(e),n))throw new Error("Cannot find square root")}function xu(t,e){let n=t,r=(n.ORDER+ie)/bu,o=n.pow(e,
|
|
792
|
+
r);return Cs(n,o,e),o}function Ph(t,e){let n=t,r=(n.ORDER-vu)/yu,o=n.mul(e,zt),i=n.pow(o,r),s=n.mul(e,i),a=n.mul(n.mul(s,zt),i),c=n.mul(s,n.sub(a,n.ONE));return Cs(n,c,e),c}function Ih(t){let e=vo(t),
|
|
793
|
+
n=wu(t),r=n(e,e.neg(e.ONE)),o=n(e,r),i=n(e,e.neg(r)),s=(t+Th)/ku;return((a,c)=>{let l=a,u=l.pow(c,s),d=l.mul(u,r),p=l.mul(u,o),h=l.mul(u,i),f=l.eql(l.sqr(d),c),m=l.eql(l.sqr(p),c);u=l.cmov(u,d,f),d=l.
|
|
794
|
+
cmov(h,p,m);let g=l.eql(l.sqr(d),c),b=l.cmov(u,d,g);return Cs(l,b,c),b})}function wu(t){if(t<gu)throw new Error("sqrt is not defined for small field");let e=t-ie,n=0;for(;e%zt===ce;)e/=zt,n++;let r=zt,
|
|
795
|
+
o=vo(t);for(;mu(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return xu;let i=o.pow(r,e),s=(e+ie)/zt;return function(c,l){let u=c;if(u.is0(l))return l;
|
|
796
|
+
if(mu(u,l)!==1)throw new Error("Cannot find square root");let d=n,p=u.mul(u.ONE,i),h=u.pow(l,e),f=u.pow(l,s);for(;!u.eql(h,u.ONE);){if(u.is0(h))return u.ZERO;let m=1,g=u.sqr(h);for(;!u.eql(g,u.ONE);)if(m++,
|
|
797
|
+
g=u.sqr(g),m===d)throw new Error("Cannot find square root");let b=ie<<BigInt(d-m-1),y=u.pow(p,b);d=m,p=u.sqr(y),h=u.mul(h,p),f=u.mul(f,y);}return f}}function _h(t){return t%bu===gu?xu:t%yu===vu?Ph:t%ku===
|
|
798
|
+
Rh?Ih(t):wu(t)}var Xe=(t,e)=>(Q(t,e)&ie)===ie,Dh=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Su(t){let e={ORDER:"bigint",
|
|
799
|
+
BYTES:"number",BITS:"number"},n=Dh.reduce((r,o)=>(r[o]="function",r),e);if(Bt(t,n),Ye(t.BYTES,"BYTES"),Ye(t.BITS,"BITS"),t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.
|
|
800
|
+
ORDER<=ie)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function Ah(t,e,n){let r=t;if(n<ce)throw new Error("invalid exponent, negatives unsupported");if(n===ce)return r.ONE;
|
|
801
|
+
if(n===ie)return e;let o=r.ONE,i=e;for(;n>ce;)n&ie&&(o=r.mul(o,i)),i=r.sqr(i),n>>=ie;return o}function bo(t,e,n=false){let r=t,o=new Array(e.length).fill(n?r.ZERO:void 0),i=e.reduce((a,c,l)=>r.is0(c)?a:(o[l]=
|
|
802
|
+
a,r.mul(a,c)),r.ONE),s=r.inv(i);return e.reduceRight((a,c,l)=>r.is0(c)?a:(o[l]=r.mul(a,o[l]),r.mul(a,c)),s),o}function mu(t,e){let n=t,r=(n.ORDER-ie)/zt,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 Oh(t,e){if(e!==void 0&&vs(e),t<=ce)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);
|
|
803
|
+
let n=Ss(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 hu=new WeakMap,
|
|
804
|
+
go=class{ORDER;BITS;BYTES;isLE;ZERO=ce;ONE=ie;_lengths;_mod;constructor(e,n={}){if(e<=ie)throw new Error("invalid field: expected ORDER > 1, got "+e);let r;this.isLE=false,n!=null&&typeof n=="object"&&(typeof n.
|
|
805
805
|
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.
|
|
806
|
-
freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:i}=
|
|
806
|
+
freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:i}=Oh(e,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2\
|
|
807
807
|
048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=i,Object.freeze(this);}create(e){return Q(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got\
|
|
808
808
|
"+typeof e);return ce<=e&&e<this.ORDER}is0(e){return e===ce}isValidNot0(e){return !this.is0(e)&&this.isValid(e)}isOdd(e){return (e&ie)===ie}neg(e){return Q(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return Q(
|
|
809
|
-
e*e,this.ORDER)}add(e,n){return Q(e+n,this.ORDER)}sub(e,n){return Q(e-n,this.ORDER)}mul(e,n){return Q(e*n,this.ORDER)}pow(e,n){return
|
|
810
|
-
return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return
|
|
811
|
-
isLE?
|
|
812
|
-
s: expected "+r+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,i?0:l.length-e.length),e=l;}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=i?
|
|
813
|
-
|
|
814
|
-
freeze(
|
|
815
|
-
throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function
|
|
816
|
-
shiftBy:s}}function
|
|
817
|
-
isNeg:p,isNegF:
|
|
818
|
-
e.ZERO,this.Fn=e.Fn,this.bits=n;}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>
|
|
809
|
+
e*e,this.ORDER)}add(e,n){return Q(e+n,this.ORDER)}sub(e,n){return Q(e-n,this.ORDER)}mul(e,n){return Q(e*n,this.ORDER)}pow(e,n){return Ah(this,e,n)}div(e,n){return Q(e*fu(n,this.ORDER),this.ORDER)}sqrN(e){
|
|
810
|
+
return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return fu(e,this.ORDER)}sqrt(e){let n=hu.get(this);return n||hu.set(this,n=_h(this.ORDER)),n(this,e)}toBytes(e){return this.
|
|
811
|
+
isLE?uu(e,this.BYTES):xs(e,this.BYTES)}fromBytes(e,n=false){ne(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.fromByte\
|
|
812
|
+
s: expected "+r+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,i?0:l.length-e.length),e=l;}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=i?Ze(e):
|
|
813
|
+
ks(e);if(a&&(c=Q(c,s)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return bo(this,e)}cmov(e,n,r){return pn(r,"condition"),r?n:e}};Object.
|
|
814
|
+
freeze(go.prototype);function vo(t,e={}){return new go(t,e)}var yo=BigInt(0),Is=BigInt(1);function Eu(t,e){let n=e.negate();return t?n:e}function xo(t,e){let n=bo(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function Pu(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)
|
|
815
|
+
throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Ts(t,e){Pu(t,e);let n=Math.ceil(e/t)+1,r=2**(t-1),o=2**t,i=pu(t),s=BigInt(t);return {windows:n,windowSize:r,mask:i,maxNumber:o,
|
|
816
|
+
shiftBy:s}}function Cu(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+=Is);let l=e*r,u=l+Math.abs(a)-1,d=a===0,p=a<0,h=e%2!==0;return {nextN:c,offset:u,isZero:d,
|
|
817
|
+
isNeg:p,isNegF:h,offsetF:l}}var Rs=new WeakMap,Iu=new WeakMap;function Ps(t){return Iu.get(t)||1}function Tu(t){if(t!==yo)throw new Error("invalid wNAF")}var ko=class{BASE;ZERO;Fn;bits;constructor(e,n){this.BASE=e.BASE,this.ZERO=
|
|
818
|
+
e.ZERO,this.Fn=e.Fn,this.bits=n;}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>yo;)n&Is&&(r=r.add(o)),o=o.double(),n>>=Is;return r}precomputeWindow(e,n){let{windows:r,windowSize:o}=Ts(n,this.bits),i=[],
|
|
819
819
|
s=e,a=s;for(let c=0;c<r;c++){a=s,i.push(a);for(let l=1;l<o;l++)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,
|
|
820
|
-
s=
|
|
821
|
-
ZERO){let i=
|
|
822
|
-
get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),
|
|
823
|
-
e);return i===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),n,o)}createCache(e,n){
|
|
824
|
-
ds"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let c of ["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>
|
|
825
|
-
let o=
|
|
826
|
-
freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:i}}function
|
|
827
|
-
let n=e,r=
|
|
828
|
-
sqrt(o.div(
|
|
829
|
-
g,y,c),g}function p(
|
|
830
|
-
this.X=d("x",g),this.Y=d("y",b),this.Z=d("z",y,true),this.T=d("t",v),Object.freeze(this);}static CURVE(){return s}static fromAffine(g){if(g instanceof
|
|
831
|
-
x:b,y}=g||{};return d("x",b),d("y",y),new
|
|
832
|
-
o.ORDER;
|
|
833
|
-
"bad point: x=0 and x_0=1");return O!==$&&(P=l(-P)),
|
|
834
|
-
return
|
|
835
|
-
|
|
836
|
-
p(g);let{X:b,Y:y,Z:v}=this,{X:x,Y:
|
|
837
|
-
let{a:g}=s,{X:b,Y:y,Z:v}=this,x=l(b*b),
|
|
838
|
-
Y:x,Z:
|
|
839
|
-
this.add(g.negate())}multiply(g){if(!i.isValidNot0(g))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:b,f:y}=
|
|
840
|
-
if(!i.isValid(g))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return g===
|
|
841
|
-
is0()}isTorsionFree(){return
|
|
842
|
-
throw new Error("invZ was invalid");return {x:
|
|
843
|
-
return
|
|
844
|
-
this.ep=e;}static fromBytes(e){
|
|
845
|
-
return this.ep.toAffine(e)}toHex(){return
|
|
820
|
+
s=Ts(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:d,isNegF:p,offsetF:h}=Cu(r,a,s);r=c,u?i=i.add(Eu(p,n[h])):o=o.add(Eu(d,n[l]));}return Tu(r),{p:o,f:i}}wNAFUnsafe(e,n,r,o=this.
|
|
821
|
+
ZERO){let i=Ts(e,this.bits);for(let s=0;s<i.windows&&r!==yo;s++){let{nextN:a,offset:c,isZero:l,isNeg:u}=Cu(r,s,i);if(r=a,!l){let d=n[c];o=o.add(u?d.negate():d);}}return Tu(r),o}getPrecomputes(e,n,r){let o=Rs.
|
|
822
|
+
get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),Rs.set(n,o))),o}cached(e,n,r){let o=Ps(e);return this.wNAF(o,this.getPrecomputes(o,e,r),n)}unsafe(e,n,r,o){let i=Ps(
|
|
823
|
+
e);return i===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),n,o)}createCache(e,n){Pu(n,this.bits),Iu.set(e,n),Rs.delete(e);}hasCache(e){return Ps(e)!==1}};function Ru(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Su(e),e}else return vo(t,{isLE:n})}function _u(t,e,n={},r){if(r===void 0&&(r=t==="edwar\
|
|
824
|
+
ds"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let c of ["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>yo))throw new Error(`CURVE.${c} must be positive bigint`)}
|
|
825
|
+
let o=Ru(e.p,n.Fp,r),i=Ru(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.
|
|
826
|
+
freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:i}}function Du(t,e){return function(r){let o=t(r);return {secretKey:o,publicKey:e(o)}}}var ht=BigInt(0),se=BigInt(1),_s=BigInt(2),Lh=BigInt(8);function Mh(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 Au(t,e={}){
|
|
827
|
+
let n=e,r=_u("edwards",t,n,n.FpFnLE),{Fp:o,Fn:i}=r,s=r.CURVE,{h:a}=s;Bt(n,{},{uvRatio:"function"});let c=_s<<BigInt(i.BYTES*8)-se,l=m=>o.create(m),u=n.uvRatio===void 0?(m,g)=>{try{return {isValid:!0,value:o.
|
|
828
|
+
sqrt(o.div(m,g))}}catch{return {isValid:false,value:ht}}}:n.uvRatio;if(!Mh(o,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function d(m,g,b=false){let y=b?se:ht;return ws("coordinate "+m,
|
|
829
|
+
g,y,c),g}function p(m){if(!(m instanceof h))throw new Error("EdwardsPoint expected")}class h{static BASE=new h(s.Gx,s.Gy,se,l(s.Gx*s.Gy));static ZERO=new h(ht,se,se,ht);static Fp=o;static Fn=i;X;Y;Z;T;constructor(g,b,y,v){
|
|
830
|
+
this.X=d("x",g),this.Y=d("y",b),this.Z=d("z",y,true),this.T=d("t",v),Object.freeze(this);}static CURVE(){return s}static fromAffine(g){if(g instanceof h)throw new Error("extended point not allowed");let{
|
|
831
|
+
x:b,y}=g||{};return d("x",b),d("y",y),new h(b,y,se,l(b*y))}static fromBytes(g,b=false){let y=o.BYTES,{a:v,d:x}=s;g=Yn(ne(g,y,"point")),pn(b,"zip215");let E=Yn(g),S=g[y-1];E[y-1]=S&-129;let C=Ze(E),A=b?c:
|
|
832
|
+
o.ORDER;ws("point.y",C,ht,A);let T=l(C*C),R=l(T-se),M=l(x*T-v),{isValid:w,value:P}=u(R,M);if(!w)throw new Error("bad point: invalid y coordinate");let $=(P&se)===se,O=(S&128)!==0;if(!b&&P===ht&&O)throw new Error(
|
|
833
|
+
"bad point: x=0 and x_0=1");return O!==$&&(P=l(-P)),h.fromAffine({x:P,y:C})}static fromHex(g,b=false){return h.fromBytes(au(g),b)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,b=true){
|
|
834
|
+
return f.createCache(this,g),b||this.multiply(_s),this}assertValidity(){let g=this,{a:b,d:y}=s;if(g.is0())throw new Error("bad point: ZERO");let{X:v,Y:x,Z:E,T:S}=g,C=l(v*v),A=l(x*x),T=l(E*E),R=l(T*T),
|
|
835
|
+
M=l(C*b),w=l(T*l(M+A)),P=l(R+l(y*l(C*A)));if(w!==P)throw new Error("bad point: equation left != right (1)");let $=l(v*x),O=l(E*S);if($!==O)throw new Error("bad point: equation left != right (2)")}equals(g){
|
|
836
|
+
p(g);let{X:b,Y:y,Z:v}=this,{X:x,Y:E,Z:S}=g,C=l(b*S),A=l(x*v),T=l(y*S),R=l(E*v);return C===A&&T===R}is0(){return this.equals(h.ZERO)}negate(){return new h(l(-this.X),this.Y,this.Z,l(-this.T))}double(){
|
|
837
|
+
let{a:g}=s,{X:b,Y:y,Z:v}=this,x=l(b*b),E=l(y*y),S=l(_s*l(v*v)),C=l(g*x),A=b+y,T=l(l(A*A)-x-E),R=C+E,M=R-S,w=C-E,P=l(T*M),$=l(R*w),O=l(T*w),D=l(M*R);return new h(P,$,D,O)}add(g){p(g);let{a:b,d:y}=s,{X:v,
|
|
838
|
+
Y:x,Z:E,T:S}=this,{X:C,Y:A,Z:T,T:R}=g,M=l(v*C),w=l(x*A),P=l(S*y*R),$=l(E*T),O=l((v+x)*(C+A)-M-w),D=$-P,F=$+P,j=l(w-b*M),q=l(O*D),J=l(F*j),Y=l(O*j),B=l(D*F);return new h(q,J,B,Y)}subtract(g){return p(g),
|
|
839
|
+
this.add(g.negate())}multiply(g){if(!i.isValidNot0(g))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:b,f:y}=f.cached(this,g,v=>xo(h,v));return xo(h,[b,y])[0]}multiplyUnsafe(g){
|
|
840
|
+
if(!i.isValid(g))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return g===ht?h.ZERO:this.is0()||g===se?this:f.unsafe(this,g,b=>xo(h,b))}isSmallOrder(){return this.clearCofactor().
|
|
841
|
+
is0()}isTorsionFree(){return f.unsafe(this,s.n).is0()}toAffine(g){let b=this,y=g,{X:v,Y:x,Z:E}=b,S=b.is0();y==null&&(y=S?Lh:o.inv(E));let C=l(v*y),A=l(x*y),T=o.mul(E,y);if(S)return {x:ht,y:se};if(T!==se)
|
|
842
|
+
throw new Error("invZ was invalid");return {x:C,y:A}}clearCofactor(){return a===se?this:this.multiplyUnsafe(a)}toBytes(){let{x:g,y:b}=this.toAffine(),y=o.toBytes(b);return y[y.length-1]|=g&se?128:0,y}toHex(){
|
|
843
|
+
return ys(this.toBytes())}toString(){return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let f=new ko(h,i.BITS);return i.BITS>=8&&h.BASE.precompute(8),Object.freeze(h.prototype),Object.freeze(h),h}var wo=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){
|
|
844
|
+
this.ep=e;}static fromBytes(e){Es();}static fromHex(e){Es();}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity();}toAffine(e){
|
|
845
|
+
return this.ep.toAffine(e)}toHex(){return ys(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){
|
|
846
846
|
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.
|
|
847
|
-
ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,n){return this.ep.precompute(e,n),this}};function
|
|
848
|
-
equired');let r=e,o=n;
|
|
849
|
-
outputLen,u=2*a.BYTES;if(l!==void 0&&(
|
|
850
|
-
w=>w:o.adjustScalarBytes,
|
|
851
|
-
let P=
|
|
852
|
-
w),
|
|
853
|
-
"context"),!!i)))}function v(w,P,$={}){w=ne(w,void 0,"message"),i&&(w=i(w));let{prefix:O,scalar:
|
|
854
|
-
if(!c.isValid(Y))throw new Error("sign failed: invalid s");let B=
|
|
855
|
-
!!x.zip215:O.zip215,j=
|
|
856
|
-
B,Re,
|
|
857
|
-
is0()}let S=a.BYTES,
|
|
858
|
-
try{return !!t.fromBytes(w,P===void 0?x.zip215:P)}catch{return false}}let
|
|
859
|
-
O=$===32;if(!O&&$!==57)throw new Error("only defined for 25519 and 448");let
|
|
860
|
-
0,P));return p($).subarray(0,P)}};return Object.freeze(
|
|
847
|
+
ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,n){return this.ep.precompute(e,n),this}};function Ou(t,e,n={}){if(typeof e!="function")throw new Error('"hash" function param is r\
|
|
848
|
+
equired');let r=e,o=n;Bt(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:i}=o,{BASE:s,Fp:a,Fn:c}=t,l=r.
|
|
849
|
+
outputLen,u=2*a.BYTES;if(l!==void 0&&(Ye(l,"hash.outputLen"),l!==u))throw new Error(`hash.outputLen must be ${u}, got ${l}`);let d=o.randomBytes===void 0?cu:o.randomBytes,p=o.adjustScalarBytes===void 0?
|
|
850
|
+
w=>w:o.adjustScalarBytes,h=o.domain===void 0?(w,P,$)=>{if(pn($,"phflag"),P.length||$)throw new Error("Contexts/pre-hash are not supported");return w}:o.domain;function f(w){return c.create(Ze(w))}function m(w){
|
|
851
|
+
let P=C.secretKey;ne(w,C.secretKey,"secretKey");let $=ne(r(w),2*P,"hashedSecretKey"),O=p($.slice(0,P)),D=$.slice(P,2*P),F=f(O);return {head:O,prefix:D,scalar:F}}function g(w){let{head:P,prefix:$,scalar:O}=m(
|
|
852
|
+
w),D=s.multiply(O),F=D.toBytes();return {head:P,prefix:$,scalar:O,point:D,pointBytes:F}}function b(w){return g(w).pointBytes}function y(w=Uint8Array.of(),...P){let $=Fe(...P);return f(r(h($,ne(w,void 0,
|
|
853
|
+
"context"),!!i)))}function v(w,P,$={}){w=ne(w,void 0,"message"),i&&(w=i(w));let{prefix:O,scalar:D,pointBytes:F}=g(P),j=y($.context,O,w),q=s.multiply(j).toBytes(),J=y($.context,q,F,w),Y=c.create(j+J*D);
|
|
854
|
+
if(!c.isValid(Y))throw new Error("sign failed: invalid s");let B=Fe(q,c.toBytes(Y));return ne(B,C.signature,"result")}let x={zip215:o.zip215};function E(w,P,$,O=x){let{context:D}=O,F=O.zip215===void 0?
|
|
855
|
+
!!x.zip215:O.zip215,j=C.signature;w=ne(w,j,"signature"),P=ne(P,void 0,"message"),$=ne($,C.publicKey,"publicKey"),F!==void 0&&pn(F,"zip215"),i&&(P=i(P));let q=j/2,J=w.subarray(0,q),Y=Ze(w.subarray(q,j)),
|
|
856
|
+
B,Re,ee;try{B=t.fromBytes($,F),Re=t.fromBytes(J,F),ee=s.multiplyUnsafe(Y);}catch{return false}if(!F&&B.isSmallOrder())return false;let Kt=y(D,J,$,P);return Re.add(B.multiplyUnsafe(Kt)).subtract(ee).clearCofactor().
|
|
857
|
+
is0()}let S=a.BYTES,C={secretKey:S,publicKey:S,signature:2*S,seed:S};function A(w){return w=w===void 0?d(C.seed):w,ne(w,C.seed,"seed")}function T(w){return mo(w)&&w.length===C.secretKey}function R(w,P){
|
|
858
|
+
try{return !!t.fromBytes(w,P===void 0?x.zip215:P)}catch{return false}}let M={getExtendedPublicKey:g,randomSecretKey:A,isValidSecretKey:T,isValidPublicKey:R,toMontgomery(w){let{y:P}=t.fromBytes(w),$=C.publicKey,
|
|
859
|
+
O=$===32;if(!O&&$!==57)throw new Error("only defined for 25519 and 448");let D=O?a.div(se+P,se-P):a.div(P-se,P+se);return a.toBytes(D)},toMontgomerySecret(w){let P=C.secretKey;ne(w,P);let $=r(w.subarray(
|
|
860
|
+
0,P));return p($).subarray(0,P)}};return Object.freeze(C),Object.freeze(M),Object.freeze({keygen:Du(A,b),getPublicKey:b,sign:v,verify:E,utils:M,Point:t,lengths:C})}var jh=BigInt(0),Qe=BigInt(1),Mu=BigInt(2);var Bh=BigInt(5),zh=BigInt(8),fn=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Ms={p:fn,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:zh,
|
|
861
861
|
a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6d\
|
|
862
|
-
c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function
|
|
863
|
-
i*t%i,c=Ae(a,
|
|
864
|
-
return t[0]&=248,t[31]&=127,t[31]|=64,t}var
|
|
865
|
-
s=Q(t*r*i,n),a=Q(e*s*s,n),c=s,l=Q(s*
|
|
866
|
-
"1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var
|
|
867
|
-
fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),
|
|
868
|
-
|
|
869
|
-
oint expected")}init(e){return new t(e)}static fromBytes(e){
|
|
870
|
-
let a=i(s*s),c=i(Qe+n*a),l=i(Qe-n*a),u=i(c*c),d=i(l*l),p=i(n*r*u-d),{isValid:
|
|
871
|
-
"invalid ristretto255 encoding 2");return new t(new
|
|
872
|
-
l=s(c*c),{value:u}
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
t.measure_grace_days:0;return {...t,expires_at:t.measure_expires_at,grace_days:Math.max(0,e)}}var
|
|
862
|
+
c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Fh(t){let e=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),i=fn,a=t*t%
|
|
863
|
+
i*t%i,c=Ae(a,Mu,i)*a%i,l=Ae(c,Qe,i)*t%i,u=Ae(l,Bh,i)*l%i,d=Ae(u,e,i)*u%i,p=Ae(d,n,i)*d%i,h=Ae(p,r,i)*p%i,f=Ae(h,o,i)*h%i,m=Ae(f,o,i)*h%i,g=Ae(m,e,i)*u%i;return {pow_p_5_8:Ae(g,Mu,i)*t%i,b2:a}}function qh(t){
|
|
864
|
+
return t[0]&=248,t[31]&=127,t[31]|=64,t}var As=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function $s(t,e){let n=fn,r=Q(e*e*e,n),o=Q(r*r*e,n),i=Fh(t*o).pow_p_5_8,
|
|
865
|
+
s=Q(t*r*i,n),a=Q(e*s*s,n),c=s,l=Q(s*As,n),u=a===t,d=a===Q(-t,n),p=a===Q(-t*As,n);return u&&(s=c),(d||p)&&(s=l),Xe(s,n)&&(s=Q(-s,n)),{isValid:u||d,value:s}}var bt=Au(Ms,{uvRatio:$s}),gt=bt.Fp,ju=bt.Fn;function Uh(t){return Ou(bt,uo,Object.assign({adjustScalarBytes:qh,zip215:true},t))}var Bu=Uh({});var Os=As;BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");var Hh=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt(
|
|
866
|
+
"1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var $u=t=>$s(Qe,t),Kh=BigInt("0x7\
|
|
867
|
+
fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Ls=t=>gt.create(Ze(t)&Kh);var vt=class t extends wo{static BASE=new t(
|
|
868
|
+
bt.BASE);static ZERO=new t(bt.ZERO);static Fp=gt;static Fn=ju;constructor(e){super(e);}static fromAffine(e){return new t(bt.fromAffine(e))}assertSame(e){if(!(e instanceof t))throw new Error("RistrettoP\
|
|
869
|
+
oint expected")}init(e){return new t(e)}static fromBytes(e){De(e,32);let{a:n,d:r}=Ms,o=fn,i=x=>gt.create(x),s=Ls(e);if(!du(gt.toBytes(s),e)||Xe(s,o))throw new Error("invalid ristretto255 encoding 1");
|
|
870
|
+
let a=i(s*s),c=i(Qe+n*a),l=i(Qe-n*a),u=i(c*c),d=i(l*l),p=i(n*r*u-d),{isValid:h,value:f}=$u(i(p*d)),m=i(f*l),g=i(f*m*p),b=i((s+s)*m);Xe(b,o)&&(b=i(-b));let y=i(c*g),v=i(b*y);if(!h||Xe(v,o)||y===jh)throw new Error(
|
|
871
|
+
"invalid ristretto255 encoding 2");return new t(new bt(b,y,Qe,v))}static fromHex(e){return t.fromBytes(Gn(e))}toBytes(){let{X:e,Y:n,Z:r,T:o}=this.ep,i=fn,s=g=>gt.create(g),a=s(s(r+n)*s(r-n)),c=s(e*n),
|
|
872
|
+
l=s(c*c),{value:u}=$u(s(a*l)),d=s(u*a),p=s(u*c),h=s(d*p*o),f;if(Xe(o*h,i)){let g=s(n*Os),b=s(e*Os);e=g,n=b,f=s(d*Hh);}else f=p;Xe(e*h,i)&&(n=s(-n));let m=s((r-n)*f);return Xe(m,i)&&(m=s(-m)),gt.toBytes(
|
|
873
|
+
m)}equals(e){this.assertSame(e);let{X:n,Y:r}=this.ep,{X:o,Y:i}=e.ep,s=l=>gt.create(l),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(vt.BASE);Object.freeze(
|
|
874
|
+
vt.ZERO);Object.freeze(vt.prototype);Object.freeze(vt);function zu(t){if(t.plan!=="measure"||typeof t.measure_expires_at!="number"||!Number.isFinite(t.measure_expires_at))return t;let e=typeof t.measure_grace_days=="number"&&Number.isFinite(t.measure_grace_days)?
|
|
875
|
+
t.measure_grace_days:0;return {...t,expires_at:t.measure_expires_at,grace_days:Math.max(0,e)}}var So=`-----BEGIN PUBLIC KEY-----
|
|
876
876
|
MCowBQYDK2VwAyEAWBiklf0kmDIVmM7nMiCxwiEAkwQIiqWGuRiRDJonsFY=
|
|
877
|
-
-----END PUBLIC KEY-----`;function
|
|
878
|
-
length%4?"=".repeat(4-e.length%4):"";return
|
|
879
|
-
function
|
|
880
|
-
function
|
|
881
|
-
oken"};let n=t.split("."),r=n[0],o=n[1],i=n[2],s;try{s=JSON.parse(
|
|
882
|
-
d=e.keys[u];if(!d)return {ok:false,reason:`unknown key id "${u}"`};a=d;}else {if(!e)return {ok:false,reason:"no verification key"};a=e;}let c;try{if(c=
|
|
883
|
-
return {ok:false,reason:"invalid public key"}}let l=false;try{l=
|
|
884
|
-
{ok:false,reason:"bad signature"}}function
|
|
885
|
-
signatureValid:!0,payload:
|
|
886
|
-
t.expires_at?"active":e<=r?"grace":"expired"}function
|
|
887
|
-
alid",...i.reason?{reason:i.reason}:{}};let s=i.payload,a=n.nowSeconds??Math.floor(Date.now()/1e3),c=
|
|
888
|
-
if(o.header?.typ!==
|
|
877
|
+
-----END PUBLIC KEY-----`;function Fu(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 Ns(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.
|
|
878
|
+
length%4?"=".repeat(4-e.length%4):"";return Fu(e+n)}function Yh(t){let e=t.replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=Fu(e);return n.subarray(n.length-32)}var Zh=new TextEncoder,qu=new TextDecoder;
|
|
879
|
+
function js(t){return typeof t=="object"&&t!==null&&"keys"in t}function yt(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 Xh=/^[A-Za-z0-9_-]+$/;
|
|
880
|
+
function Uu(t){let e=t.split(".");return e.length===3&&e.every(n=>Xh.test(n))}function Xn(t){return t===""?"empty":Uu(t)?"token":"malformed"}function Qn(t,e){if(!Uu(t))return {ok:false,reason:"malformed t\
|
|
881
|
+
oken"};let n=t.split("."),r=n[0],o=n[1],i=n[2],s;try{s=JSON.parse(qu.decode(Ns(r)));}catch{return {ok:false,reason:"header is not valid JSON"}}let a;if(js(e)){let u=typeof s.kid=="string"?s.kid:e.defaultKid,
|
|
882
|
+
d=e.keys[u];if(!d)return {ok:false,reason:`unknown key id "${u}"`};a=d;}else {if(!e)return {ok:false,reason:"no verification key"};a=e;}let c;try{if(c=Yh(a),c.length!==32)return {ok:!1,reason:"invalid public key"}}catch{
|
|
883
|
+
return {ok:false,reason:"invalid public key"}}let l=false;try{l=Bu.verify(Ns(i),Zh.encode(`${r}.${o}`),c);}catch{return {ok:false,reason:"signature verification error"}}return l?{ok:true,header:s,payloadBytes:Ns(o)}:
|
|
884
|
+
{ok:false,reason:"bad signature"}}function kt(t,e){let n=Qn(t,e);if(!n.ok||!n.payloadBytes)return {signatureValid:false,...n.reason?{reason:n.reason}:{}};try{let r=JSON.parse(qu.decode(n.payloadBytes));return {
|
|
885
|
+
signatureValid:!0,payload:zu(r)}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function er(t,e,n){if(n?.has(t.jti))return "revoked";let r=t.expires_at+t.grace_days*86400;return e<=
|
|
886
|
+
t.expires_at?"active":e<=r?"grace":"expired"}function Vu(t,e,n={}){let r=yt(t);if(Xn(r)==="empty")return {status:"none",reason:"empty"};let i=kt(r,e);if(!i.signatureValid||!i.payload)return {status:"inv\
|
|
887
|
+
alid",...i.reason?{reason:i.reason}:{}};let s=i.payload,a=n.nowSeconds??Math.floor(Date.now()/1e3),c=er(s,a,n.revoked);return c==="revoked"?{status:c,payload:s,reason:"license revoked"}:{status:c,payload:s}}var Hu="BVSALA-REVOC",Qh=300,eg=new TextDecoder;function Eo(t,e,n={}){let r=l=>({ok:false,seq:-1,asOf:0,revoked:new Set,reason:l}),o=Qn(t,e);if(!o.ok||!o.payloadBytes)return r(o.reason??"bad signature");
|
|
888
|
+
if(o.header?.typ!==Hu)return r(`unexpected token type "${String(o.header?.typ??"")}" (want ${Hu})`);let i;try{i=JSON.parse(eg.decode(o.payloadBytes));}catch{return r("payload is not valid JSON")}if(typeof i.
|
|
889
889
|
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.
|
|
890
|
-
nowSeconds??Math.floor(Date.now()/1e3),c=n.maxSkewSeconds??
|
|
890
|
+
nowSeconds??Math.floor(Date.now()/1e3),c=n.maxSkewSeconds??Qh;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 xt=class{_seq=-1;_asOf=0;_lastContactAt=0;set=new Set;get seq(){
|
|
891
891
|
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.
|
|
892
892
|
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&&
|
|
893
|
-
(this._asOf=e.asOf),r||o}};function
|
|
894
|
-
c?.plan==="measure"?[]:c?.features??[]),u=()=>{if(s==="empty")return "none";if(!c)return "invalid";let p=
|
|
895
|
-
expires_at+c.grace_days*86400,
|
|
896
|
-
isEntitled:p=>d()&&l.has(p),isActive:()=>d(),status:u,reason:()=>c?void 0:a.reason,plan:()=>c&&d()?c.plan:void 0,refreshAfter:()=>{if(c)return Math.min(c.expires_at,r()+86400)}}}function
|
|
893
|
+
(this._asOf=e.asOf),r||o}};function mn(t,e,n){let r=()=>Math.floor((n.now?n.now():Date.now())/1e3),o=n.startedAt??r(),i=yt(t),s=Xn(i),a=s==="token"?kt(i,e):{signatureValid:false,reason:s},c=a.signatureValid?a.payload:void 0,l=new Set(
|
|
894
|
+
c?.plan==="measure"?[]:c?.features??[]),u=()=>{if(s==="empty")return "none";if(!c)return "invalid";let p=er(c,r(),n.revocation.snapshot());if(n.maxStalenessSeconds!=null&&(p==="active"||p==="grace")){let h=c.
|
|
895
|
+
expires_at+c.grace_days*86400,f=Math.min(o,h),m=Math.max(n.revocation.lastContactAt,f);if(r()-m>n.maxStalenessSeconds)return "stale"}return p},d=()=>{let p=u();return p==="active"||p==="grace"};return {
|
|
896
|
+
isEntitled:p=>d()&&l.has(p),isActive:()=>d(),status:u,reason:()=>c?void 0:a.reason,plan:()=>c&&d()?c.plan:void 0,refreshAfter:()=>{if(c)return Math.min(c.expires_at,r()+86400)}}}function Co(t,e,n){return mn(t,e,{revocation:new xt,...n?{now:n}:{}})}var hn={pollIntervalSeconds:900,floorSeconds:300,maxIntervalSeconds:3600,jitterRatio:.1,maxSkewSeconds:300,requestTimeoutMs:3e4},Wu=3,tg=12;function Bs(t){let e=t.random??Math.random,n;if(t.consecutiveFailures>
|
|
897
897
|
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:
|
|
898
|
-
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
|
|
898
|
+
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 ng=10,gn=class{constructor(e){this.opts=e;}opts;timer=null;controller=null;consecutiveFailures=0;stopped=false;started=false;lastEtag=null;consecutive304=0;now(){
|
|
899
899
|
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();
|
|
900
900
|
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"});
|
|
901
|
-
return}let n=new AbortController;this.controller=n;let r=this.opts.requestTimeoutMs??
|
|
901
|
+
return}let n=new AbortController;this.controller=n;let r=this.opts.requestTimeoutMs??hn.requestTimeoutMs,o=setTimeout(()=>n.abort(),r);o.unref?.();let i={accept:"application/json"};this.lastEtag&&(i["\
|
|
902
902
|
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?.(
|
|
903
|
-
{type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=
|
|
904
|
-
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 l=
|
|
905
|
-
opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??
|
|
903
|
+
{type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=ng&&(this.consecutive304=0,this.lastEtag=null);return}if(this.consecutive304=0,!s.ok)throw new Error(`revocat\
|
|
904
|
+
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 l=Eo(c.list,this.opts.publicKeyPem,{minSeq:this.
|
|
905
|
+
opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??hn.maxSkewSeconds});if(!l.ok){let d=l.reason??"rejected";this.opts.onEvent?.({type:"rejected",reason:d}),this.avisar(`r\
|
|
906
906
|
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}.`);
|
|
907
907
|
return}a&&(this.lastEtag=a),this.opts.snapshot.markContact(this.now());let u=this.opts.snapshot.apply(l);this.opts.onEvent?.(u?{type:"applied",seq:l.seq,size:this.opts.snapshot.snapshot().size}:{type:"\
|
|
908
908
|
unchanged",seq:l.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.
|
|
909
|
-
silenceWarnings??this.opts.silenciarAvisos)}avisar(e,n){this.callado()||
|
|
910
|
-
|
|
909
|
+
silenceWarnings??this.opts.silenciarAvisos)}avisar(e,n){this.callado()||Ee(`poller:${this.opts.url}:${e}`,n);}avisarFalloDeRed(e){if(this.callado())return;let n=this.consecutiveFailures;if(n<Wu||(n-Wu)%
|
|
910
|
+
tg!==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\
|
|
911
911
|
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)
|
|
912
|
-
return;let e=
|
|
913
|
-
opts.pollIntervalSeconds??
|
|
912
|
+
return;let e=Bs({refreshAfter:this.opts.getRefreshAfter?.(),nowSeconds:this.now(),consecutiveFailures:this.consecutiveFailures,floorSeconds:this.opts.floorSeconds??hn.floorSeconds,pollIntervalSeconds:this.
|
|
913
|
+
opts.pollIntervalSeconds??hn.pollIntervalSeconds,maxIntervalSeconds:this.opts.maxIntervalSeconds??hn.maxIntervalSeconds,jitterRatio:this.opts.jitterRatio??hn.jitterRatio,...this.opts.random?{random:this.
|
|
914
914
|
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.
|
|
915
|
-
controller?.abort();}};var
|
|
915
|
+
controller?.abort();}};var Ft=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=
|
|
916
916
|
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){let n=this.now();this.buffer.push({report:e,at:n});
|
|
917
|
-
let r=
|
|
917
|
+
let r=rg(e);r&&this.buffer.push({report:r,at:n}),this.buffer.length>this.maxBuffer&&this.buffer.splice(0,this.buffer.length-this.maxBuffer),this.buffer.length>=this.maxBatch&&this.flush();}start(){this.
|
|
918
918
|
timer||(this.timer=setInterval(()=>{this.flush();},this.flushIntervalMs),this.timer.unref?.());}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0),this.flush();}async stopAndDrain(e){this.timer&&
|
|
919
919
|
(clearInterval(this.timer),this.timer=void 0);let n=e??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.
|
|
920
920
|
length>=i?r+1:0,r>=2)break}}async flush(){if(this.inflight)return this.inflight;if(this.buffer.length!==0){this.inflight=this.hacerFlush();try{await this.inflight;}finally{this.inflight=null;}}}async hacerFlush(){
|
|
921
921
|
let e=this.options.fetchImpl??globalThis.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-typ\
|
|
922
|
-
e":"application/json",authorization:`Bearer ${this.options.serviceAccountKey}`,[
|
|
923
|
-
this.requeue(n),this.avisarDeFallo(`the server responded ${o.status}`)):o.status===401||o.status===403?(
|
|
922
|
+
e":"application/json",authorization:`Bearer ${this.options.serviceAccountKey}`,[wr]:`${this.options.surface??"sdk"}/${Ve}`},body:JSON.stringify(r)});o.ok?this.fallosSeguidos=0:o.status>=500?(this.fallosSeguidos++,
|
|
923
|
+
this.requeue(n),this.avisarDeFallo(`the server responded ${o.status}`)):o.status===401||o.status===403?(Ee(`metering-auth-${o.status}`,`[bv-sala] usage reporting is being rejected with HTTP ${o.status}\
|
|
924
924
|
at ${this.options.url}. Check 'serviceAccountKey' (rotated? revoked? from another organization?). Until it works, no usage is reported: the dashboard will say it sees no traffic and billable seats wi\
|
|
925
925
|
ll show zero.`),this.options.onAuthError?.(o.status)):(this.fallosSeguidos++,this.avisarDeFallo(o.status===404||o.status===405?`HTTP ${o.status}: the reporting URL looks wrong`:`the server rejected th\
|
|
926
926
|
e batch with HTTP ${o.status}`));}catch(r){this.fallosSeguidos++,this.requeue(n),this.avisarDeFallo(r instanceof Error?r.message:"network error");}}avisarDeFallo(e){if(this.options.silenceWarnings)return;
|
|
@@ -930,220 +930,220 @@ buffer],this.buffer.length>this.maxBuffer&&(this.buffer.length=this.maxBuffer);}
|
|
|
930
930
|
{},requestId:n.requestId,model:n.model,at:e.at,avoidedLlm:n.calls.avoidedLlm,actualLlm:n.calls.actualLlm,baselineInputTokens:n.tokens.baselineInput,actualInputTokens:n.tokens.actualInput,eliminatedInputTokens:n.
|
|
931
931
|
tokens.eliminatedInput,compressedInputTokens:n.tokens.compressedInput,baselineOutputTokens:n.tokens.baselineOutput,actualOutputTokens:n.tokens.actualOutput,providerCachedInputTokens:n.tokens.providerCachedInput??
|
|
932
932
|
0,cacheResult:n.cache.result,...n.cost.eliminatedInputFloorCost!==void 0&&Number.isFinite(n.cost.eliminatedInputFloorCost)&&n.cost.eliminatedInputFloorCost>0&&n.tokens.eliminatedInput>0?{eliminatedInputFloorCost:n.
|
|
933
|
-
cost.eliminatedInputFloorCost}:{},...
|
|
933
|
+
cost.eliminatedInputFloorCost}:{},...og(n),baselineCost:n.cost.baselineEstimate,actualCost:n.cost.actual,netSavings:n.cost.netSavings,...n.cost.basis?{basis:n.cost.basis}:{},...n.cost.basis==="referen\
|
|
934
934
|
ce"&&n.cache.reference&&/^[A-Za-z0-9._:/-]{1,128}$/.test(n.cache.reference.requestId)&&Number.isInteger(n.cache.reference.at)?{referenceRequestId:n.cache.reference.requestId,referenceAt:n.cache.reference.
|
|
935
|
-
at}:{},...n.attribution?.sessionId?{sessionId:n.attribution.sessionId}:{},...n.attribution?.agentId?{agentId:n.attribution.agentId}:{}}}};function
|
|
935
|
+
at}:{},...n.attribution?.sessionId?{sessionId:n.attribution.sessionId}:{},...n.attribution?.agentId?{agentId:n.attribution.agentId}:{}}}};function rg(t){let e=t.measure;if(!e)return null;let n=e.wouldHaveSaved.
|
|
936
936
|
usd;if(!(Number.isFinite(n)&&n>0))return null;let r=`${t.requestId}:shadow`;if(!/^[A-Za-z0-9._:/-]{1,128}$/.test(r))return null;let o=Math.max(0,t.cost.actual),i=Math.max(0,o-n),s=o>0?Math.min(1,(o-i)/
|
|
937
|
-
o):0,{measure:a,nativeSavings:c,...l}=t;return {...l,requestId:r,cache:{...t.cache,result:"miss"},cost:{baselineEstimate:o,actual:i,netSavings:s,netSavingsRatio:s,netSavingsUsd:o-i,basis:"shadow"}}}function
|
|
937
|
+
o):0,{measure:a,nativeSavings:c,...l}=t;return {...l,requestId:r,cache:{...t.cache,result:"miss"},cost:{baselineEstimate:o,actual:i,netSavings:s,netSavingsRatio:s,netSavingsUsd:o-i,basis:"shadow"}}}function og(t){
|
|
938
938
|
let e=t.nativeSavings;if(!e||e.basis!=="measured")return {};let n=r=>Number.isFinite(r)&&r>=0;return !n(e.readDiscountUsd)||!n(e.writePremiumUsd)?{}:!(e.readDiscountUsd>0)&&!(e.writePremiumUsd>0)?{}:{...e.
|
|
939
|
-
readDiscountUsd>0?{nativeCacheReadSavings:e.readDiscountUsd}:{},...e.writePremiumUsd>0?{nativeCacheWritePremium:e.writePremiumUsd}:{}}}function
|
|
940
|
-
]";return new RegExp(`-${e}{8,10}-${e}{5}$`).test(t)}function
|
|
941
|
-
t.NETLIFY)}async function
|
|
942
|
-
if(t.KUBERNETES_SERVICE_HOST||
|
|
943
|
-
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
|
|
944
|
-
ONS","GITLAB_CI","CIRCLECI","TRAVIS","JENKINS_URL","BUILDKITE","TF_BUILD","TEAMCITY_VERSION","BITBUCKET_BUILD_NUMBER","CODEBUILD_BUILD_ID","HEROKU_TEST_RUN_ID","DRONE"];function
|
|
945
|
-
return false;for(let e of
|
|
939
|
+
readDiscountUsd>0?{nativeCacheReadSavings:e.readDiscountUsd}:{},...e.writePremiumUsd>0?{nativeCacheWritePremium:e.writePremiumUsd}:{}}}function To(){return globalThis.process}function ig(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\
|
|
940
|
+
]";return new RegExp(`-${e}{8,10}-${e}{5}$`).test(t)}function sg(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??
|
|
941
|
+
t.NETLIFY)}async function ag(){if(To()?.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 cg(t,e=ag){
|
|
942
|
+
if(t.KUBERNETES_SERVICE_HOST||sg(t))return;let n=t.HOSTNAME??t.COMPUTERNAME??await e();if(!(!n||ig(n)))return n}async function lg(){let t=To();if(!t||!t.env)return;let e=t.env,n=await cg(e),r=[t.platform,
|
|
943
|
+
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 ug=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTI\
|
|
944
|
+
ONS","GITLAB_CI","CIRCLECI","TRAVIS","JENKINS_URL","BUILDKITE","TF_BUILD","TEAMCITY_VERSION","BITBUCKET_BUILD_NUMBER","CODEBUILD_BUILD_ID","HEROKU_TEST_RUN_ID","DRONE"];function tr(){let t=To()?.env;if(!t)
|
|
945
|
+
return false;for(let e of ug){let n=t[e];if(n&&n!=="false"&&n!=="0")return true}return false}async function dg(t,e){let n=globalThis.crypto,r=new TextEncoder;if(n?.subtle)try{let s=await n.subtle.importKey("raw",
|
|
946
946
|
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}\
|
|
947
|
-
|${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
|
|
948
|
-
if(!r)return;let o=await
|
|
949
|
-
toolSelector??new
|
|
950
|
-
null?e:Math.min(e,n)}function
|
|
951
|
-
eger (got ${String(e)}).`)}var
|
|
952
|
-
ted before any provider request was sent"),this.name="StreamAbortedError",this.requestSent=e;}},
|
|
953
|
-
job=n,this.notSubmitted=r;}};var
|
|
947
|
+
|${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 nr(t){let n=To()?.env?.BVSALA_SEAT_ID;if(n&&pg.test(n))return n;let r=await lg();
|
|
948
|
+
if(!r)return;let o=await dg(t,r);if(o)return `m-${o.slice(0,32)}`}var pg=/^[A-Za-z0-9._:/-]{1,128}$/;var Gu={inputPer1k:5e-4,outputPer1k:.0015,cachedInputPer1k:5e-5};function Ro(t){return {exactCache:t.exactCache??new Er,semanticCache:t.semanticCacheStore??t.semanticCache,singleflight:t.singleflight??new Cr,resolvers:t.resolvers??kc(),router:t.router??new Dr,toolSelector:t.
|
|
949
|
+
toolSelector??new Lr,formatSelector:t.formatSelector??new jr({tokenizer:t.tokenizer}),schemaRegistry:t.schemaRegistry??new Br,constraintBackends:t.constraintBackends??[]}}function G(t){let e=t.maxOutputTokens,n=t.response?.maxOutputTokens;return e==null?n??void 0:n==null?e:Math.min(e,n)}function zs(t){let e=t.response?.maxOutputTokens??256,n=t.maxOutputTokens;return n==
|
|
950
|
+
null?e:Math.min(e,n)}function Fs(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\
|
|
951
|
+
eger (got ${String(e)}).`)}var Te=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\
|
|
952
|
+
ted before any provider request was sent"),this.name="StreamAbortedError",this.requestSent=e;}},Po=class extends Error{job;notSubmitted;constructor(e,n,r,o){super(e,o),this.name="BatchSubmitError",this.
|
|
953
|
+
job=n,this.notSubmitted=r;}};var fg={"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.\
|
|
954
954
|
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\
|
|
955
955
|
.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,
|
|
956
956
|
"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-sonnet-5-5":true,"claude-fable-5":true,"claude-fa\
|
|
957
957
|
ble-5-1":true,"claude-mythos-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-fla\
|
|
958
958
|
sh":true,"gemini-3.6-flash":true,"gemini-3.1-flash-lite":true,"gemini-3-flash-preview":true,"gemini-3.5-flash":true,"gemini-3.5-flash-lite":true,"gemini-3.1-pro-preview":true,"gemini-2.5-pro":true,"gemini-2.5-flash":true},
|
|
959
|
-
|
|
960
|
-
/^qwq/,/^qwen3/,/^glm-(4\.[5-9]|[5-9])/,/magistral/];function
|
|
961
|
-
return "unclassified-model";let o=
|
|
959
|
+
mg=new Set(["claude-opus-4-7","claude-opus-4-8"]),hg=[/^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($|[-_.])/,
|
|
960
|
+
/^qwq/,/^qwen3/,/^glm-(4\.[5-9]|[5-9])/,/magistral/];function Ku(t){let e=t.lastIndexOf("/"),n=(e>=0?t.slice(e+1):t).toLowerCase();if(hg.some(i=>i.test(n)))return "reasoning-model";let r=Qt(t);if(r===void 0)
|
|
961
|
+
return "unclassified-model";let o=fg[r];if(o===true)return "reasoning-model";if(o!==false)return "unclassified-model";if(mg.has(r))return "temperature-ignored"}var qs={minimumCacheTokens:1024,cacheReadMultiplier:.5,cacheWriteMultiplier:1},Ju={minimumCacheTokens:1024,cacheReadMultiplier:.1,cacheWriteMultiplier:1.25},gg=[["claude-fable-5-1",512],["claude-mytho\
|
|
962
962
|
s-5-1",512],["claude-fable-5",512],["claude-mythos-5",512],["claude-opus-5-5",512],["claude-opus-5",512],["claude-sonnet-5-5",512],["claude-opus-4-7",2048],["claude-opus-4-6",4096],["claude-opus-4-5",
|
|
963
|
-
4096],["claude-haiku-4-5",4096],["claude-3-5-haiku",2048]];function
|
|
964
|
-
cacheReadMultiplier:.1,cacheWriteMultiplier:1};var
|
|
965
|
-
n)),c=a*i*r.cacheReadMultiplier+(1-a)*i*r.cacheWriteMultiplier;return s+c}function
|
|
963
|
+
4096],["claude-haiku-4-5",4096],["claude-3-5-haiku",2048]];function Us(t){for(let[e,n]of gg)if(t===e||t.startsWith(`${e}-`))return {...Ju,minimumCacheTokens:n};return Ju}var Vs={minimumCacheTokens:1024,
|
|
964
|
+
cacheReadMultiplier:.1,cacheWriteMultiplier:1};var Yu={minimumCacheTokens:1024,cacheReadMultiplier:1,cacheWriteMultiplier:1};function Io(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,
|
|
965
|
+
n)),c=a*i*r.cacheReadMultiplier+(1-a)*i*r.cacheWriteMultiplier;return s+c}function Hs(t){let e=Io(t.originalTokens,t.stablePrefixTokens,t.prefixHitRate,t.tier),n=Io(t.compressedTokens,0,0,t.tier)+(t.compressorCostTokens??
|
|
966
966
|
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}\
|
|
967
967
|
< ${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*
|
|
968
968
|
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\
|
|
969
|
-
es not touch the cache tier";return {comprimir:r>0,costeComprimido:n,costeSinComprimir:e,ganancia:r,razon:a}}function
|
|
970
|
-
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
|
|
971
|
-
totalTokens?null:1)}var
|
|
972
|
-
1)*e}estado(e){return this.estados.get(e)}decidir(e,n){let r=
|
|
973
|
-
{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 ${
|
|
969
|
+
es not touch the cache tier";return {comprimir:r>0,costeComprimido:n,costeSinComprimir:e,ganancia:r,razon:a}}function Zu(t){let e=o=>Hs({...t,prefixHitRate:o}).ganancia;if(e(0)<=0||e(1)>0)return null;let n=0,
|
|
970
|
+
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 bg(t){let e=Zu({originalTokens:t.totalTokens,compressedTokens:t.totalTokens,stablePrefixTokens:t.stablePrefixTokens,tier:t.tier});return e??(Io(t.totalTokens,t.stablePrefixTokens,0,t.tier)<=t.
|
|
971
|
+
totalTokens?null:1)}var _o=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-
|
|
972
|
+
1)*e}estado(e){return this.estados.get(e)}decidir(e,n){let r=bg(n),o=this.estados.get(e),i=vg(o);return n.stablePrefixTokens<=0?{marcar:false,razon:"no stable prefix to cache",umbral:r,observada:i}:r==null?
|
|
973
|
+
{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 ${bn(i)} did not reach the ${bn(
|
|
974
974
|
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 \
|
|
975
|
-
is only observable on requests that were marked`,umbral:r,observada:i}:i!=null&&i>r?{marcar:true,razon:`measured hit rate ${
|
|
976
|
-
razon:`prefix-cache marking OFF: measured hit rate ${
|
|
977
|
-
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
|
|
978
|
-
if(!t)return null;let e=t.tokensLeidos+t.tokensEscritos;return e<=0?t.marcadas>0?0:null:t.tokensLeidos/e}function
|
|
979
|
-
i=Math.min(o,Math.max(0,n.escritos1h));if(r===0&&o===0)return;let a=
|
|
980
|
-
Math.max(0,e.inputPer1k-p):0,
|
|
981
|
-
{},cacheReadTokens:r,cacheWriteTokens:o,cacheWrite1hTokens:i,inputPer1k:e.inputPer1k,cachedInputPer1k:p,writeMultiplier:c,write1hMultiplier:l,readDiscountUsd:
|
|
982
|
-
basis:d?"measured":"unmeasured"}}var
|
|
983
|
-
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
|
|
984
|
-
return
|
|
985
|
-
"";return `${t.role}${t.name??""}${t.toolCallId??""}${e}${t.content}${n}`}function
|
|
986
|
-
let e=0;for(;e<t.length&&t[e].role==="system";)e+=1;return e}function
|
|
987
|
-
tardias:0},"1h":{resueltas:0,reutilizadas:0,tardias:0}}}var
|
|
975
|
+
is only observable on requests that were marked`,umbral:r,observada:i}:i!=null&&i>r?{marcar:true,razon:`measured hit rate ${bn(i)} beats the ${bn(r)} break-even`,umbral:r,observada:i}:(o.apagada=true,{marcar:false,
|
|
976
|
+
razon:`prefix-cache marking OFF: measured hit rate ${bn(i)} did not reach the ${bn(r)} break-even, so marking was costing money`,umbral:r,observada:i})}registrar(e,n){let r=this.estados.get(e)??{marcadas:0,
|
|
977
|
+
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 vg(t){
|
|
978
|
+
if(!t)return null;let e=t.tokensLeidos+t.tokensEscritos;return e<=0?t.marcadas>0?0:null:t.tokensLeidos/e}function bn(t){return t==null?"n/a":`${(t*100).toFixed(1)}%`}var yg={anthropic:"explicit",openai:"automatic",google:"implicit",unknown:"unknown"};function Ws(t){return Math.round(t*1e10)/1e10}function Xu(t,e,n){let r=Math.max(0,n.leidos),o=Math.max(0,n.escritos),
|
|
979
|
+
i=Math.min(o,Math.max(0,n.escritos1h));if(r===0&&o===0)return;let a=Ot(t)??"unknown",c=Ne(t),l=qn(t),u=e.cachedInputPer1k,d=n.contadorCompleto&&u!==void 0&&Number.isFinite(u),p=u??e.inputPer1k,h=d?r/1e3*
|
|
980
|
+
Math.max(0,e.inputPer1k-p):0,f=d?(o-i)/1e3*e.inputPer1k*Math.max(0,c-1)+i/1e3*e.inputPer1k*Math.max(0,l-1):0;return {provider:a,mechanism:yg[a],...n.marcadoPorLaCapa!==void 0?{layerMarked:n.marcadoPorLaCapa}:
|
|
981
|
+
{},cacheReadTokens:r,cacheWriteTokens:o,cacheWrite1hTokens:i,inputPer1k:e.inputPer1k,cachedInputPer1k:p,writeMultiplier:c,write1hMultiplier:l,readDiscountUsd:Ws(h),writePremiumUsd:Ws(f),netUsd:Ws(h-f),
|
|
982
|
+
basis:d?"measured":"unmeasured"}}var vn={"5m":3e5,"30m":18e5,"1h":36e5},Oe=["5m","30m","1h"],td=20;function Qu(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.
|
|
983
|
+
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 ed(t){
|
|
984
|
+
return Qu(t,0).toString(36)+"."+Qu(t,2654435769).toString(36)}function kg(t){let e=t.toolCalls?.length?t.toolCalls.map(r=>`${r.id??""}${r.name}${r.arguments}`).join(""):"",n=t.isError===true?"error":
|
|
985
|
+
"";return `${t.role}${t.name??""}${t.toolCallId??""}${e}${t.content}${n}`}function nd(t,e){let n=[ed(`bvsala-prefijo\0${t}`)];for(let r of e)n.push(ed(`${n[n.length-1]}${kg(r)}`));return n}function Ao(t){
|
|
986
|
+
let e=0;for(;e<t.length&&t[e].role==="system";)e+=1;return e}function Gs(){return {"5m":0,"30m":0,"1h":0}}function Ks(){return {"5m":{resueltas:0,reutilizadas:0,tardias:0},"30m":{resueltas:0,reutilizadas:0,
|
|
987
|
+
tardias:0},"1h":{resueltas:0,reutilizadas:0,tardias:0}}}var Do=1,rd=1440*6e4;function Qs(t){return `bvsala:cache-breakpoints:v${Do}:${t}`}var kn=class{clases=new Map;porHuella=new Map;maxPorClase;maxClases;prediccionesMinimas;confirmacionMinima;memoria;constructor(e={}){
|
|
988
988
|
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??
|
|
989
989
|
.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!==
|
|
990
|
-
e||a.indice!==s)continue;let c=Math.max(0,r-a.escrita);c>
|
|
990
|
+
e||a.indice!==s)continue;let c=Math.max(0,r-a.escrita);c>vn["1h"]||(this.resolverReutilizada(o,a,c),i={tipo:a.tipo,indice:s,huecoMs:c,...a.posicionDelProveedor!==void 0?{posicionDelProveedor:a.posicionDelProveedor}:
|
|
991
991
|
{},...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","\
|
|
992
992
|
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,
|
|
993
993
|
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.
|
|
994
994
|
idDelProveedor}:{}},l=this.porHuella.get(s);l&&l.contadas!==7&&this.descartar(l),this.porHuella.set(s,c),n.cola.push(c);for(let u of Oe)n.pendientes[o][u]+=1;}}verificar(e,n,r){if(n.posicionDelProveedor===
|
|
995
|
-
void 0)return;let o=n.ttl??"5m";if(n.huecoMs>
|
|
995
|
+
void 0)return;let o=n.ttl??"5m";if(n.huecoMs>vn[o])return;let i=this.estadoDe(e);i.predichas+=1,r>=n.posicionDelProveedor*.98&&(i.confirmadas+=1),i.predichas>=this.prediccionesMinimas&&i.confirmadas/i.
|
|
996
996
|
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["\
|
|
997
|
-
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
|
|
998
|
-
i["30m"]),en1h
|
|
997
|
+
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:Js(i["5m"]),en30m:Js(
|
|
998
|
+
i["30m"]),en1h:Js(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(){
|
|
999
999
|
return this.porHuella.size}exportarClase(e){let r=this.clases.get(e)??this.estadoVacio(),o=r.cabeza,i=c=>Oe.map(l=>{let u=r.contadores[c][l];return [u.resueltas,u.reutilizadas,u.tardias]}),s=c=>Oe.map(
|
|
1000
|
-
l=>r.pendientes[c][l]),a={v:
|
|
1000
|
+
l=>r.pendientes[c][l]),a={v:Do,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.
|
|
1001
1001
|
huella,c.tipo,c.indice,c.escrita,c.contadas,0,c.posicionDelProveedor??null,c.ttl??null,c.idDelProveedor??null]),cur:Oe.map(c=>Math.max(0,r.cursores[c]-o)),pr:r.predichas,co:r.confirmadas,off:r.apagada};
|
|
1002
1002
|
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>
|
|
1003
|
-
|
|
1004
|
-
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!==
|
|
1003
|
+
Do)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.
|
|
1004
|
+
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!==Do||e.clase!==n)return null;let r=i=>typeof i==
|
|
1005
1005
|
"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<
|
|
1006
|
-
3;c++){let l=s[c];if(!Array.isArray(l)||l.length!==3||!l.every(r))return null;let[u,d,p]=l;if(d>u||p>d||!r(a[c]))return null;let
|
|
1007
|
-
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,l,u,d,p,f
|
|
1008
|
-
"S"&&a!=="H"&&a!=="T"||!r(c)||c===0||typeof l!="number"||!Number.isFinite(l)||!r(u)||u>7||d!==0&&d!==1||p!==null&&!(typeof p=="number"&&Number.isFinite(p)&&p>0)||
|
|
1009
|
-
!(typeof
|
|
1010
|
-
{},...
|
|
1011
|
-
!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:
|
|
1006
|
+
3;c++){let l=s[c];if(!Array.isArray(l)||l.length!==3||!l.every(r))return null;let[u,d,p]=l;if(d>u||p>d||!r(a[c]))return null;let h=Oe[c];o.contadores[i][h]={resueltas:u,reutilizadas:d,tardias:p},o.pendientes[i][h]=
|
|
1007
|
+
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,l,u,d,p,h,f]=i;if(typeof s!="string"||d===0&&s===""||a!==
|
|
1008
|
+
"S"&&a!=="H"&&a!=="T"||!r(c)||c===0||typeof l!="number"||!Number.isFinite(l)||!r(u)||u>7||d!==0&&d!==1||p!==null&&!(typeof p=="number"&&Number.isFinite(p)&&p>0)||h!==null&&h!=="5m"&&h!=="1h"||f!==null&&
|
|
1009
|
+
!(typeof f=="string"&&f!==""&&f.length<=256))return null;o.cola.push({clase:n,tipo:a,huella:s,indice:c,escrita:l,contadas:u,descartada:d===1,...p!==null?{posicionDelProveedor:p}:{},...h!==null?{ttl:h}:
|
|
1010
|
+
{},...f!==null?{idDelProveedor:f}:{}});}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[Oe[i]]=s;}return !r(e.pr)||
|
|
1011
|
+
!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:Ks(),H:Ks(),T:Ks()},pendientes:{S:Gs(),H:Gs(),T:Gs()},cola:[],
|
|
1012
1012
|
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.
|
|
1013
1013
|
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(
|
|
1014
1014
|
s.huella);}this.clases.delete(r);}return n}descartar(e){let n=this.clases.get(e.clase);Oe.forEach((r,o)=>{e.contadas&1<<o||(n&&(n.pendientes[e.tipo][r]=Math.max(0,n.pendientes[e.tipo][r]-1)),e.contadas|=
|
|
1015
1015
|
1<<o);}),e.descartada=true;}resolverReutilizada(e,n,r){Oe.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+=
|
|
1016
|
-
1,r<=
|
|
1017
|
-
e.cabeza);for(;i<e.cola.length&&n-e.cola[i].escrita>
|
|
1016
|
+
1,r<=vn[o]&&(s.reutilizadas+=1),o==="1h"&&r<=vn["1h"]&&r>vn["5m"]&&(s.tardias+=1),n.contadas|=1<<i;}),this.reducirSiHaceFalta(e.contadores[n.tipo]);}vencer(e,n){for(Oe.forEach((r,o)=>{let i=Math.max(e.cursores[r],
|
|
1017
|
+
e.cabeza);for(;i<e.cola.length&&n-e.cola[i].escrita>vn[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+=
|
|
1018
1018
|
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),
|
|
1019
1019
|
e.cabeza+=1;}if(e.cabeza>1024&&e.cabeza*2>e.cola.length){e.cola.splice(0,e.cabeza);for(let r of Oe)e.cursores[r]-=e.cabeza;e.cabeza=0;}}reducirSiHaceFalta(e){for(let n of Oe)e[n].resueltas>=this.memoria&&
|
|
1020
|
-
(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
|
|
1021
|
-
0}function
|
|
1022
|
-
0,i-s),Math.min(1,i+s)]}function
|
|
1023
|
-
o=t.primaDeUnaHora!=null&&t.primaDeUnaHora>r?t.primaDeUnaHora:null,i=
|
|
1020
|
+
(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 Js(t){return t.resueltas>0?t.reutilizadas/t.resueltas:
|
|
1021
|
+
0}function Ys(t,e){let n=t-e;return n>0?Math.max(0,(t-1)/n):1}function Zs(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(
|
|
1022
|
+
0,i-s),Math.min(1,i+s)]}function Xs(t,e,n,r,o){return e+n>=o&&Zs(t,e+n)[0]>r?true:e>=o&&Zs(t,e)[1]<r?false:null}function od(t){let e=t.muestrasMinimas??5,n=t.tramo.cacheReadMultiplier,r=t.tramo.cacheWriteMultiplier,
|
|
1023
|
+
o=t.primaDeUnaHora!=null&&t.primaDeUnaHora>r?t.primaDeUnaHora:null,i=Ys(r,n),s=o!=null?Ys(o,n):null,a={historial:true,cola:false,ttl:"5m",razon:"",equilibrio:i};if(t.estadistica.apagada)return {...a,razon:`\
|
|
1024
1024
|
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\
|
|
1025
|
-
n reuse measurement here`};let c=y=>({en5m:
|
|
1026
|
-
|
|
1027
|
-
l.push(`history re-sent only ${
|
|
1028
|
-
ixed placement kept`));let g=
|
|
1029
|
-
en ${
|
|
1030
|
-
tokens.T:y==="H"?t.tokens.H:t.tokens.S;if(x.en5m!==true&&x.en1h===true)b="1h",l.push(`1h TTL: re-sent ${
|
|
1031
|
-
0){let[S]=
|
|
1032
|
-
tokens then beats the extra premium on the ${
|
|
1033
|
-
t.tramo.cacheReadMultiplier),r=t.estadistica.T,o=t.estadistica.H,i=(a,c,l)=>
|
|
1025
|
+
n reuse measurement here`};let c=y=>({en5m:Xs(y.k5m,y.muestras5m,y.pendientes5m,i,e),en1h:s!=null?Xs(y.k1h,y.muestras1h,y.pendientes1h,s,e):null}),l=[],u=t.estadistica.H,d=t.estadistica.T,p=c(u),h=c(d),
|
|
1026
|
+
f=y=>`${y.k5m}/${y.muestras5m} in 5 min, ${y.k1h}/${y.muestras1h} in 1 h`,m=true;t.hayHistorial&&(p.en5m===true||p.en1h===true?l.push(`history re-sent (${f(u)}): above break-even, marked`):p.en5m===false?(m=false,
|
|
1027
|
+
l.push(`history re-sent only ${f(u)} (break-even ${yn(i)}): breakpoint moved back to the system header, no write premium on a prefix nobody re-reads`)):l.push(`history: not conclusive yet (${f(u)}), f\
|
|
1028
|
+
ixed placement kept`));let g=h.en5m===true||h.en1h===true;l.push(g?`continued ${f(d)}: above break-even, tail marked so the next turn reads this whole prompt`:h.en5m===false?`continued only ${f(d)} (break-ev\
|
|
1029
|
+
en ${yn(i)}): tail not marked`:`tail: not conclusive yet (${f(d)}), not marked`);let b="5m";if(o!=null){let y=g?"T":m&&t.hayHistorial?"H":"S",v=t.estadistica[y],x=y==="T"?h:y==="H"?p:c(v),E=y==="T"?t.
|
|
1030
|
+
tokens.T:y==="H"?t.tokens.H:t.tokens.S;if(x.en5m!==true&&x.en1h===true)b="1h",l.push(`1h TTL: re-sent ${f(v)} (1 h break-even ${yn(s)}), while 5 min does not pay`);else if(x.en5m===true&&v.muestras1h>=e&&E>
|
|
1031
|
+
0){let[S]=Zs(v.kTardias,v.muestras1h+v.pendientes1h),C=Math.max(0,E-t.lecturaPrevista()),A=S*(r-n)*E,T=(o-r)*C;A>T&&(b="1h",l.push(`1h TTL: at least ${yn(S)} of re-sends come after 5 min; re-reading ${E}\
|
|
1032
|
+
tokens then beats the extra premium on the ${C} written now`));}}return {historial:m,cola:g,ttl:b,razon:l.join("; "),equilibrio:i}}function id(t){let e=t.muestrasMinimas??5,n=Ys(t.tramo.cacheWriteMultiplier,
|
|
1033
|
+
t.tramo.cacheReadMultiplier),r=t.estadistica.T,o=t.estadistica.H,i=(a,c,l)=>Xs(a,c,l,n,e)===false;if(t.estadistica.apagada)return {explicita:false,historial:true,razon:`provider default kept: the provider's co\
|
|
1034
1034
|
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:`\
|
|
1035
|
-
provider default kept: continued ${r.k30m}/${r.muestras30m} within 30 min, not clearly below the ${
|
|
1036
|
-
explicita:true,historial:s,razon:`explicit mode: continued only ${r.k30m}/${r.muestras30m} within 30 min (break-even ${
|
|
1037
|
-
istory":"system header"}`,equilibrio:n}}function
|
|
1038
|
-
if(!t||!e)return null;let r=
|
|
1035
|
+
provider default kept: continued ${r.k30m}/${r.muestras30m} within 30 min, not clearly below the ${yn(n)} break-even`,equilibrio:n};let s=!t.hayHistorial||!i(o.k30m,o.muestras30m,o.pendientes30m);return {
|
|
1036
|
+
explicita:true,historial:s,razon:`explicit mode: continued only ${r.k30m}/${r.muestras30m} within 30 min (break-even ${yn(n)}), so the question is not written; breakpoint at the ${s?"end of the stable h\
|
|
1037
|
+
istory":"system header"}`,equilibrio:n}}function yn(t){return `${(t*100).toFixed(1)}%`}var sd=.5;function xg(t,e){return e.inputPer1k<=0||e.outputPer1k<=0?null:Math.max(t.inputPer1k/e.inputPer1k,t.outputPer1k/e.outputPer1k)}function wg(t){return 1-t}function Sg(t,e=sd){return e-t}function ad(t,e,n=sd){
|
|
1038
|
+
if(!t||!e)return null;let r=xg(t,e);if(r==null||!Number.isFinite(r))return null;let o=wg(r),i=Sg(r,n),s=i>0,a=c=>`${(c*100).toFixed(1)}%`;return {r,equilibrio:o,escaladoMaximo:i,viable:s,razon:s?`the c\
|
|
1039
1039
|
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\
|
|
1040
|
-
o escalations it cannot reach the ${a(n)} target, so this pair is not worth the quality risk`}}var
|
|
1041
|
-
ude-opus-4":"claude-haiku-4-5","claude-sonnet-4":"claude-haiku-4-5","claude-3-5-sonnet":"claude-3-5-haiku"};function
|
|
1042
|
-
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]??
|
|
1043
|
-
n.length)==="-"&&/^\d{4}/.test(t.slice(n.length+1)))return e[n]}var
|
|
1044
|
-
e)}decidir(e,n){let r=this.estados.get(e),o=
|
|
1040
|
+
o escalations it cannot reach the ${a(n)} target, so this pair is not worth the quality risk`}}var ea={"gpt-4":"gpt-4o","gpt-4-turbo":"gpt-4o-mini","gpt-4o":"gpt-4o-mini","gpt-4.1":"gpt-4.1-mini","cla\
|
|
1041
|
+
ude-opus-4":"claude-haiku-4-5","claude-sonnet-4":"claude-haiku-4-5","claude-3-5-sonnet":"claude-3-5-haiku"};function Eg(t){return Object.keys(t).sort((e,n)=>n.length-e.length||e.localeCompare(n))}function cd(t,e=ea){
|
|
1042
|
+
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]??Cg(o,e);return !i||i===o?null:r+i}function Cg(t,e){for(let n of Eg(e))if(t.startsWith(n)&&t.charAt(
|
|
1043
|
+
n.length)==="-"&&/^\d{4}/.test(t.slice(n.length+1)))return e[n]}var Oo=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(
|
|
1044
|
+
e)}decidir(e,n){let r=this.estados.get(e),o=Tg(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\
|
|
1045
1045
|
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}\
|
|
1046
1046
|
); 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(
|
|
1047
1047
|
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)}\
|
|
1048
1048
|
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,
|
|
1049
|
-
n&&(r.escaladas+=1),this.estados.set(e,r);}};function
|
|
1050
|
-
for(let r of
|
|
1049
|
+
n&&(r.escaladas+=1),this.estados.set(e,r);}};function Tg(t){return !t||t.enrutadas<=0?null:t.escaladas/t.enrutadas}var Rg=["enum","pattern","maximum","minimum","maxLength","minLength","maxItems","minItems"];function Pg(t){return t?ta(t)?"value-constrained":"structural":"none"}function ta(t,e=0){if(e>12)return false;let n=t;
|
|
1050
|
+
for(let r of Rg)if(n[r]!==void 0)return true;if(t.properties){for(let r of Object.values(t.properties))if(ta(r,e+1))return true}return !!(t.items&&ta(t.items,e+1))}function ld(t){let e=Pg(t.schema),n=(t.tools??
|
|
1051
1051
|
[]).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\
|
|
1052
1052
|
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\
|
|
1053
1053
|
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 \
|
|
1054
|
-
content has somewhere to fall":"output contract checks shape only: a well-formed answer with wrong content passes"}}function
|
|
1054
|
+
content has somewhere to fall":"output contract checks shape only: a well-formed answer with wrong content passes"}}function na(t){let e=[];if(e.push("non-empty"),t.texto.trim()==="")return {acepta:false,
|
|
1055
1055
|
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 \
|
|
1056
1056
|
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\
|
|
1057
1057
|
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,
|
|
1058
1058
|
motivo:"the cheap model's answer is not valid JSON",comprobaciones:e}}let r=be(n,t.schema);return r.valid?{acepta:true,motivo:"the cheap model's answer satisfies the output contract",comprobaciones:e}:{
|
|
1059
|
-
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
|
|
1060
|
-
JSON.parse(t),r=JSON.parse(e);}catch{return {divergen:false,motivo:"not comparable (at least one answer is not JSON)"}}let o=
|
|
1061
|
-
le facts (free prose only)"}:
|
|
1062
|
-
of a false valid \u2014 it is a reason to look, never a verdict"}}var
|
|
1063
|
-
an")n.push(`b:${t}`);else if(typeof t=="string"){let r=t.trim();r.length>0&&r.length<=
|
|
1064
|
-
t")for(let r of Object.keys(t).sort())
|
|
1065
|
-
, because a number nobody can check is not a number at all but a promise, and this product exists to stop making those. ";function
|
|
1066
|
-
0,t)}function
|
|
1067
|
-
"object":t.items?"array":void 0)){case "string":return t.maxLength!=null?{valor:
|
|
1068
|
-
{valor:Math.trunc(t.maximum)}:void 0;case "number":return;case "array":{if(t.maxItems==null||!t.items)return;let n=
|
|
1069
|
-
ject":{if(t.additionalProperties!==false||!t.properties)return;let n={};for(let[r,o]of Object.entries(t.properties)){let i=
|
|
1070
|
-
t);return e?JSON.stringify(e.valor):null}function
|
|
1071
|
-
let o=r.minimumSavingsTokens??
|
|
1059
|
+
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 ud(t,e){let n,r;try{n=
|
|
1060
|
+
JSON.parse(t),r=JSON.parse(e);}catch{return {divergen:false,motivo:"not comparable (at least one answer is not JSON)"}}let o=Lo(n),i=Lo(r);return o.length===0&&i.length===0?{divergen:false,motivo:"no comparab\
|
|
1061
|
+
le facts (free prose only)"}:_g(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 \
|
|
1062
|
+
of a false valid \u2014 it is a reason to look, never a verdict"}}var Ig=40;function Lo(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\
|
|
1063
|
+
an")n.push(`b:${t}`);else if(typeof t=="string"){let r=t.trim();r.length>0&&r.length<=Ig&&n.push(`s:${r.toLowerCase()}`);}else if(Array.isArray(t))for(let r of t)Lo(r,e+1,n);else if(t&&typeof t=="objec\
|
|
1064
|
+
t")for(let r of Object.keys(t).sort())Lo(t[r],e+1,n);return n.sort()}function _g(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 dd="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\
|
|
1065
|
+
, because a number nobody can check is not a number at all but a promise, and this product exists to stop making those. ";function Dg(t){if(t<=0)return "";let e=dd;for(;e.length<t;)e+=dd;return e.slice(
|
|
1066
|
+
0,t)}function Ag(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 ra(t){if(t.enum&&t.enum.length>0)return {valor:Ag(t.enum)};switch(t.type??(t.properties?
|
|
1067
|
+
"object":t.items?"array":void 0)){case "string":return t.maxLength!=null?{valor:Dg(t.maxLength)}:void 0;case "boolean":return {valor:false};case "null":return {valor:null};case "integer":return t.maximum!=null?
|
|
1068
|
+
{valor:Math.trunc(t.maximum)}:void 0;case "number":return;case "array":{if(t.maxItems==null||!t.items)return;let n=ra(t.items);return n?{valor:Array.from({length:t.maxItems},()=>n.valor)}:void 0}case "ob\
|
|
1069
|
+
ject":{if(t.additionalProperties!==false||!t.properties)return;let n={};for(let[r,o]of Object.entries(t.properties)){let i=ra(o);if(!i)return;n[r]=i.valor;}return {valor:n}}default:return}}function Og(t){let e=ra(
|
|
1070
|
+
t);return e?JSON.stringify(e.valor):null}function pd(t,e){let n=Og(t);return n===null?null:e(n)}var Mo=16,fd=64,Lg=8,Mg="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 md(t,e,n,r={}){
|
|
1071
|
+
let o=r.minimumSavingsTokens??Lg,i;try{if(sa(t,0))return {applied:!1,reason:"schema has a pattern; no witness can be synthesised to prove the round trip"};i=ca(t,0);}catch(R){return {applied:false,reason:R instanceof
|
|
1072
1072
|
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;
|
|
1073
|
-
if(!s)return {applied:false,reason:"nothing to compact"};let a=R=>
|
|
1074
|
-
i.compact)),
|
|
1075
|
-
b=
|
|
1076
|
-
evidencia;if(
|
|
1077
|
-
e model, not of the schema: ${
|
|
1078
|
-
chmarks/ab-live.ts) and pass it in`};let S=
|
|
1079
|
-
he input win is capped by the size of the schema while the output loss grows with the answer and is billed ${x} input, so no schema is big enough to buy it back`};let
|
|
1080
|
-
n.inputPer1k:
|
|
1081
|
-
ut tokens ($${b.toFixed(9)}): the compact contract saves ${
|
|
1082
|
-
1)} input tokens equivalent): the compact contract saves ${
|
|
1083
|
-
codedEnumValues:i.coded,schemaTokensOriginal:d,schemaTokensCompact:p,modelledShapeSavingTokens:
|
|
1084
|
-
function
|
|
1085
|
-
ok:false,reason:"compact witness does not validate against the compact schema"};if(!
|
|
1086
|
-
ject"||t.type==null&&t.properties!=null}function
|
|
1087
|
-
ng")?null:e}function
|
|
1073
|
+
if(!s)return {applied:false,reason:"nothing to compact"};let a=R=>xn(R,s,true),c=R=>xn(R,s,false),l=Fg(t),u=$g(t,i.compact,s,l);if(!u.ok)return {applied:false,reason:u.reason};let d=e(JSON.stringify(t)),p=e(JSON.stringify(
|
|
1074
|
+
i.compact)),h=d-p,f=Number.POSITIVE_INFINITY;for(let R of l){let M=e(JSON.stringify(R))-e(JSON.stringify(a(R)));M<f&&(f=M);}Number.isFinite(f)||(f=0);let m=R=>R/1e3*n.inputPer1k,g=R=>R/1e3*n.outputPer1k,
|
|
1075
|
+
b=m(o),y=n.outputPer1k>0?(o-h)*n.inputPer1k/n.outputPer1k:Number.NEGATIVE_INFINITY,v=Number.isFinite(y)?y.toFixed(1):"any",x=n.inputPer1k>0?`${(n.outputPer1k/n.inputPer1k).toFixed(1)}x`:"more than",E=r.
|
|
1076
|
+
evidencia;if(E==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\
|
|
1077
|
+
e model, not of the schema: ${Mg}. Here the compact contract saves ${h} input tokens and output is billed ${x} input, so it only pays while the output delta stays above ${v} tokens. Measure yours (ben\
|
|
1078
|
+
chmarks/ab-live.ts) and pass it in`};let S=E.deltaTokens;if(S<0)return {applied:false,reason:`the measured output delta is ${S} tokens: this model writes MORE from a compact contract (${E.procedencia}). T\
|
|
1079
|
+
he input win is capped by the size of the schema while the output loss grows with the answer and is billed ${x} input, so no schema is big enough to buy it back`};let C=m(h)+g(S),A=n.inputPer1k>0?C*1e3/
|
|
1080
|
+
n.inputPer1k:h,T=`+${S} tokens (${S>0?"the model wrote LESS":"no measured change"}), ${E.procedencia}`;return C<b?{applied:false,reason:`net saving $${C.toFixed(9)}/request is below the floor of ${o} inp\
|
|
1081
|
+
ut tokens ($${b.toFixed(9)}): the compact contract saves ${h} input tokens and the measured output delta is ${T}; break-even at ${v}`}:{applied:true,reason:`net saving $${C.toFixed(9)}/request (${A.toFixed(
|
|
1082
|
+
1)} input tokens equivalent): the compact contract saves ${h} input tokens and the measured output delta is ${T}; break-even at ${v}`,plan:{compactSchema:i.compact,expand:c,compact:a,renamedKeys:i.renamed,
|
|
1083
|
+
codedEnumValues:i.coded,schemaTokensOriginal:d,schemaTokensCompact:p,modelledShapeSavingTokens:f,measuredOutputDeltaTokens:S,outputDeltaProvenance:E.procedencia,breakEvenOutputDeltaTokens:y,netSavingUsd:C}}}
|
|
1084
|
+
function $g(t,e,n,r){for(let o of r){if(!be(o,t).valid)return {ok:false,reason:"synthesised witness does not satisfy the caller's own schema; nothing can be proven"};let i=xn(o,n,true);if(!be(i,e).valid)return {
|
|
1085
|
+
ok:false,reason:"compact witness does not validate against the compact schema"};if(!aa(xn(i,n,false),o))return {ok:false,reason:"round trip is not the identity"}}return {ok:true}}function hd(t){return t.type==="ob\
|
|
1086
|
+
ject"||t.type==null&&t.properties!=null}function gd(t){return t.type==="array"||t.type==null&&t.items!=null}function Ng(t){let e=t.enum;return !e||e.length===0||e.length>fd||!e.every(n=>typeof n=="stri\
|
|
1087
|
+
ng")?null:e}function ca(t,e){if(e>Mo)throw new RangeError("schema too deep");let n=Ng(t);if(n){if(t.minLength!=null)return {compact:t,renamed:0,coded:0};let r=bd(n,true);if(!r)return {compact:t,renamed:0,
|
|
1088
1088
|
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,
|
|
1089
|
-
enumBack:i},renamed:0,coded:o}}return
|
|
1090
|
-
let r=0,o=0,i=new Map,s=new Map;for(let[p,
|
|
1091
|
-
let c={};for(let[p]of n)c[a?.get(p)??p]=s.get(p);let l={...t,properties:c};t.required&&(l.required=t.required.map(p=>a?.get(p)??p));let u={};if(a){let p=new Map;for(let[m
|
|
1092
|
-
m
|
|
1093
|
-
if(!t.items)return {compact:t,renamed:0,coded:0};let n=
|
|
1089
|
+
enumBack:i},renamed:0,coded:o}}return hd(t)?jg(t,e):gd(t)?Bg(t,e):{compact:t,renamed:0,coded:0}}function jg(t,e){let n=Object.entries(t.properties??{});if(n.length===0)return {compact:t,renamed:0,coded:0};
|
|
1090
|
+
let r=0,o=0,i=new Map,s=new Map;for(let[p,h]of n){let f=ca(h,e+1);s.set(p,f.compact),f.node&&i.set(p,f.node),r+=f.renamed,o+=f.coded;}let a=null;t.additionalProperties===false&&(a=bd(n.map(([p])=>p),false));
|
|
1091
|
+
let c={};for(let[p]of n)c[a?.get(p)??p]=s.get(p);let l={...t,properties:c};t.required&&(l.required=t.required.map(p=>a?.get(p)??p));let u={};if(a){let p=new Map;for(let[f,m]of a)p.set(m,f);let h=false;for(let[
|
|
1092
|
+
f,m]of a)f!==m&&(h=true);if(h){u.keysFwd=a,u.keysBack=p;for(let[f,m]of a)f!==m&&(r+=1);}}i.size>0&&(u.props=i);let d=!u.keysFwd&&!u.props;return {compact:l,...d?{}:{node:u},renamed:r,coded:o}}function Bg(t,e){
|
|
1093
|
+
if(!t.items)return {compact:t,renamed:0,coded:0};let n=ca(t.items,e+1);return {compact:{...t,items:n.compact},...n.node?{node:{items:n.node}}:{},renamed:n.renamed,coded:n.coded}}function bd(t,e){let n=[
|
|
1094
1094
|
...t].sort(),r=new Set,o=new Map;n.forEach((s,a)=>{let c=e?s.toUpperCase():s,l=s;for(let u=1;u<s.length;u++){let d=c.slice(0,u);if(!r.has(d)){l=d;break}}if(l===s){let u=a.toString(36);u.length<s.length&&
|
|
1095
|
-
!r.has(u)&&(l=u);}r.add(l),o.set(s,l);});let i=new Set(t);for(let[s,a]of o)if(a!==s&&i.has(a))return null;return o}function
|
|
1096
|
-
t;if(e.items&&Array.isArray(t))return t.map(i=>
|
|
1097
|
-
l);i[c]=u?
|
|
1098
|
-
r,0));return n}function
|
|
1099
|
-
if(n>
|
|
1100
|
-
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?
|
|
1095
|
+
!r.has(u)&&(l=u);}r.add(l),o.set(s,l);});let i=new Set(t);for(let[s,a]of o)if(a!==s&&i.has(a))return null;return o}function xn(t,e,n){let r=n?e.enumFwd:e.enumBack;if(r&&typeof t=="string")return r.get(t)??
|
|
1096
|
+
t;if(e.items&&Array.isArray(t))return t.map(i=>xn(i,e.items,n));let o=n?e.keysFwd:e.keysBack;if((o||e.props)&&zg(t)){let i={};for(let[s,a]of Object.entries(t)){let c=o?.get(s)??s,l=n?s:c,u=e.props?.get(
|
|
1097
|
+
l);i[c]=u?xn(a,u,n):a;}return i}return t}function zg(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Fg(t){let e=Math.min(fd,Math.max(1,oa(t,0))),n=[];for(let r=0;r<e;r++)n.push(ia(t,
|
|
1098
|
+
r,0));return n}function oa(t,e){if(e>Mo)return 0;let n=t.enum?.length??0;for(let r of Object.values(t.properties??{}))n=Math.max(n,oa(r,e+1));return t.items&&(n=Math.max(n,oa(t.items,e+1))),n}function ia(t,e,n){
|
|
1099
|
+
if(n>Mo)return null;if(t.enum&&t.enum.length>0)return t.enum[Math.min(e,t.enum.length-1)];if(hd(t)){let r={};for(let[o,i]of Object.entries(t.properties??{}))r[o]=ia(i,e,n+1);return r}if(gd(t)){if(t.maxItems===
|
|
1100
|
+
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?ia(i,e,n+1):null)}switch(t.type){case "string":{if(t.maxLength===0)return "";
|
|
1101
1101
|
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===
|
|
1102
|
-
"integer"?Math.round(r):r}case "boolean":return true;case "null":return null;default:return null}}function
|
|
1103
|
-
values(t.properties??{}))if(
|
|
1104
|
-
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(!
|
|
1105
|
-
return false;for(let s of o)if(!Object.prototype.hasOwnProperty.call(e,s)||!
|
|
1106
|
-
enums)",pares:8}},
|
|
1102
|
+
"integer"?Math.round(r):r}case "boolean":return true;case "null":return null;default:return null}}function sa(t,e){if(e>Mo)throw new RangeError("schema too deep");if(t.pattern!=null)return true;for(let n of Object.
|
|
1103
|
+
values(t.properties??{}))if(sa(n,e+1))return true;return !!(t.items&&sa(t.items,e+1))}function aa(t,e){if(t===e)return true;if(t===null||e===null||typeof t!="object"||typeof e!="object")return false;let n=Array.
|
|
1104
|
+
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(!aa(t[s],e[s]))return false;return true}let o=Object.keys(t),i=Object.keys(e);if(o.length!==i.length)
|
|
1105
|
+
return false;for(let s of o)if(!Object.prototype.hasOwnProperty.call(e,s)||!aa(t[s],e[s]))return false;return true}var qg="2026-08-14",vd={"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 \
|
|
1106
|
+
enums)",pares:8}},Ug=ci(vd);function Vg(t){return ai(vd,Ug,t)}var $o=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&&
|
|
1107
1107
|
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,
|
|
1108
|
-
origen:"remembered",procedencia:`measured by the caller on an earlier request for this contract on ${e}`};let i=
|
|
1109
|
-
Velio on ${e} (${
|
|
1110
|
-
r=
|
|
1111
|
-
n)}:${
|
|
1112
|
-
o=new Map;for(let l=0;l<t.length;l++){let u=t[l];if(u.role!=="tool")continue;r.push(l);let d=(u.toolCallId?n.get(u.toolCallId):void 0)??u.name,p=u.toolCallId?e.get(u.toolCallId):void 0,
|
|
1113
|
-
o.set(l,
|
|
1114
|
-
get(l);if(u===void 0||s.get(u)===l)continue;let d=
|
|
1115
|
-
(r,o)=>n.has(o)?{...r,content:
|
|
1116
|
-
o==="google"||o==="google-vertex"?
|
|
1108
|
+
origen:"remembered",procedencia:`measured by the caller on an earlier request for this contract on ${e}`};let i=Vg(e);return i?{deltaTokens:i.deltaTokens,origen:"catalogue",procedencia:`measured by Bi\
|
|
1109
|
+
Velio on ${e} (${qg}, ${i.pares} paired reps, ${i.contrato}, ${i.salidaDelBrazoA}-token answers) \u2014 NOT measured on YOUR contract`}:null}};var ua="[BiVelio Savings: an older tool result was trimmed here to lower the cost; the most recent results travel in full.]",Hg=new TextEncoder;function Wg(t){return Hg.encode(t).length}function Gg(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;
|
|
1110
|
+
r=la(o);}catch{r=n;}return `${t} ${r}`}function la(t){return t===null||typeof t!="object"?JSON.stringify(t)??"null":Array.isArray(t)?`[${t.map(la).join(",")}]`:`{${Object.keys(t).sort().map(n=>`${JSON.stringify(
|
|
1111
|
+
n)}:${la(t[n])}`).join(",")}}`}function yd(t){let e=new Map,n=new Map;for(let l of t)if(l.role==="assistant"&&l.toolCalls)for(let u of l.toolCalls)u.id&&(e.set(u.id,u.arguments),n.set(u.id,u.name));let r=[],
|
|
1112
|
+
o=new Map;for(let l=0;l<t.length;l++){let u=t[l];if(u.role!=="tool")continue;r.push(l);let d=(u.toolCallId?n.get(u.toolCallId):void 0)??u.name,p=u.toolCallId?e.get(u.toolCallId):void 0,h=Gg(d,p);h!==null&&
|
|
1113
|
+
o.set(l,h);}let i=r.length?r[r.length-1]:-1,s=new Map;for(let l of r){let u=o.get(l);if(u===void 0)continue;let d=s.get(u);(d===void 0||l>d)&&s.set(u,l);}let a=[],c=0;for(let l of r){if(l===i)continue;let u=o.
|
|
1114
|
+
get(l);if(u===void 0||s.get(u)===l)continue;let d=Wg(t[l].content);d<1024||(a.push(l),c+=d);}return {indices:a,bytesOriginales:c}}function kd(t,e){if(e.length===0)return t;let n=new Set(e);return t.map(
|
|
1115
|
+
(r,o)=>n.has(o)?{...r,content:ua}:r)}function No(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"?qs:o==="anthropic"?Us(i):
|
|
1116
|
+
o==="google"||o==="google-vertex"?Vs:/^(gpt-|o[1-9](-|$)|chatgpt)/.test(i)?qs:i.startsWith("claude")?Us(i):i.startsWith("gemini")?Vs:Yu}function xd(t){let e=t.prefix!=null,n=Hs({originalTokens:t.originalTokens,
|
|
1117
1117
|
compressedTokens:t.compressedTokens,stablePrefixTokens:t.prefix?.stableTokens??0,prefixHitRate:t.prefix?.hitRate??0,tier:t.tier,...t.compressorCostTokens!=null?{compressorCostTokens:t.compressorCostTokens}:
|
|
1118
1118
|
{}});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.
|
|
1119
|
-
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
|
|
1119
|
+
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 Sd(t){let e=u=>u/1e3*t.precio.inputPer1k,n=u=>u/1e3*t.precio.outputPer1k,r=e(t.promptTokens+t.descriptoresLigeros)+n(t.salidaDelSondeo),o=e(t.promptTokens+t.esquemasCompletos)+n(t.salidaFinal),
|
|
1120
1120
|
i=r+e(t.promptTokens+t.esquemasDeLaSegunda)+n(t.salidaFinal),s=o-i,a=r,c=s>0&&s>=a,l;return s<=0?l=`discovery costs more than it saves: the prompt (${t.promptTokens} tokens) is paid twice and the sche\
|
|
1121
1121
|
mas avoided (${t.esquemasCompletos-t.esquemasDeLaSegunda}) do not cover it`:c?l=`${t.esquemasCompletos-t.esquemasDeLaSegunda} schema tokens avoided in the worst case, enough to pay for the repeated pr\
|
|
1122
1122
|
ompt and the probe`:l="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,
|
|
1123
|
-
costeDeDosLlamadas:i,ganancia:s,perdidaSiDegrada:a,razon:l}}function
|
|
1124
|
-
0,
|
|
1125
|
-
get(c);if(!l){i.push(c);continue}o.includes(l.id)||(o.push(l.id),l.risk==="read"&&s.size<Math.max(0,n)&&s.add(l.id));}return {tools:e.filter(c=>c.risk!=="read"||s.has(c.id)),reconocidos:o,ignorados:i}}function
|
|
1126
|
-
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
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1123
|
+
costeDeDosLlamadas:i,ganancia:s,perdidaSiDegrada:a,razon:l}}function Ed(t){let n=(t.description??(Array.isArray(t.intents)?t.intents.join("; "):"")).trim().split(/\r?\n/,1)[0]??"",r=n.length>wd?n.slice(
|
|
1124
|
+
0,wd-1).trimEnd()+"\u2026":n;return {id:t.id,intents:t.intents,risk:t.risk,...r?{description:r}:{}}}var wd=200;function Cd(t,e,n){let r=new Map(e.map(c=>[c.id,c])),o=[],i=[],s=new Set;for(let c of t){let l=r.
|
|
1125
|
+
get(c);if(!l){i.push(c);continue}o.includes(l.id)||(o.push(l.id),l.risk==="read"&&s.size<Math.max(0,n)&&s.add(l.id));}return {tools:e.filter(c=>c.risk!=="read"||s.has(c.id)),reconocidos:o,ignorados:i}}function Td(t,e){
|
|
1126
|
+
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 Jg=2;function ma(t){return X(de({messages:t.messages,structuredData:t.structuredData??null,tools:t.tools??[],schema:t.response?.schema??null}))}function Rd(t){return t.temperature===0}var wt=t=>typeof t==
|
|
1127
|
+
"number"&&Number.isInteger(t)&&t>=0;function Yg(t,e){if(wt(t.reasoningTokens)){if(!e)return t.reasoningTokens;if(wt(e.reasoningTokens))return t.reasoningTokens+e.reasoningTokens}}function Pd(t){if(t.contadorSimulado)
|
|
1128
|
+
return "simulated-provider";if(t.origen==="no-oficial")return "unofficial-origin";let e=t.usoPrimario;if(!e||e.complete===false||!wt(e.inputTokens)||e.inputTokens<=0||!wt(e.outputTokens))return "no-usage";let n=t.
|
|
1129
|
+
usoReparacion;if(n&&(n.complete===false||!wt(n.outputTokens)))return "no-usage";if(t.eliminatedInput!==0||t.compressedInput!==0||t.elididoLocal!==0||Math.abs(t.sentLocalSinSondeo-t.baselineInput)>Jg)return "\
|
|
1130
|
+
layer-changed-request";if(t.codebookAplicado)return "codebook";if(t.tokensDelSondeo!==0||t.sondeoAplicado)return "tool-discovery";if(t.busquedaNativa===true)return "native-tool-search";if(t.hayEsquema&&(!t.
|
|
1131
|
+
esquemaNativo||t.esquemaPorPrompt))return "schema-in-prompt";if(t.hayEsquema&&!t.esquemaEnFormatoNativo)return "schema-not-verbatim";if(t.hayEsquema&&!t.esquemaEstricto)return "schema-not-strict";if(t.modeloServido!==
|
|
1132
|
+
t.modeloPedido)return "cheaper-model-served";if(!t.cacheable)return "not-cacheable";let r=Gi(t.tierServido),o=r?.conDescuento&&r.factor!=null&&r.factor>0&&r.factor<1?r.factor:void 0,i=Yg(e,n);return {v:2,
|
|
1133
|
+
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?{tierFactor:o}:{},layerInsertions:Math.
|
|
1134
|
+
max(0,t.mensajesDeLaCapa)+Math.max(0,t.piezasDelAdaptador)+(t.hayEsquema?1:0),...i!==void 0?{reasoningTokens:i}:{},requestFingerprint:t.huella(),textSha256:X(t.textoServido)}}var jo=t=>typeof t=="stri\
|
|
1135
|
+
ng"&&t.length>0;function Id(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))return "malformed";let n=e,r=n.tierFactor,
|
|
1136
|
+
o=n.reasoningTokens;return n.v===2&&typeof n.inputTokens=="number"&&Number.isInteger(n.inputTokens)&&n.inputTokens>0&&wt(n.outputTokens)&&typeof n.at=="number"&&Number.isFinite(n.at)&&(r===void 0||typeof r==
|
|
1137
|
+
"number"&&r>0&&r<1)&&wt(n.layerInsertions)&&(o===void 0||wt(o))&&jo(n.requestId)&&jo(n.model)&&jo(n.requestFingerprint)&&jo(n.textSha256)?{v:2,requestId:n.requestId,at:n.at,model:n.model,inputTokens:n.
|
|
1138
|
+
inputTokens,outputTokens:n.outputTokens,...r!==void 0?{tierFactor:r}:{},layerInsertions:n.layerInsertions,...o!==void 0?{reasoningTokens:o}:{},requestFingerprint:n.requestFingerprint,textSha256:n.textSha256,
|
|
1139
|
+
...typeof n.cacheKey=="string"?{cacheKey:n.cacheKey}:{}}:"malformed"}function Zg(t,e){if(!e.determinista)return "sampled";if(e.salidaDelModelo!==void 0)return e.salidaDelModelo;if(t.reasoningTokens===void 0)
|
|
1140
|
+
return "reasoning-not-reported";if(t.reasoningTokens!==0)return "reasoning-reported"}function _d(t,e){if(e.textoServidoSha256!==t.textSha256)return {ok:false,reason:"witness"};if(e.claveLeida!==void 0&&t.cacheKey!==
|
|
1141
|
+
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.ahoraMs-t.at;if(!(n>=-3e5&&n<=2592e6))return {ok:false,
|
|
1142
|
+
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,o=r?.cachedInputPer1k;if(!r||typeof o!="numb\
|
|
1143
|
+
er"||!Number.isFinite(o)||!(o>0)||!Number.isFinite(r.inputPer1k)||o>r.inputPer1k||typeof r.outputPer1k!="number"||!Number.isFinite(r.outputPer1k)||r.outputPer1k<0)return {ok:false,reason:"no-cached-price"};
|
|
1144
|
+
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.max(0,e.topeDeSalida):Number.POSITIVE_INFINITY,
|
|
1145
|
+
a=Zg(t,e),c=a===void 0?Math.floor(.95*Math.min(t.outputTokens,s)):0,l=Math.min(1,t.tierFactor??1,e.diferible?Gc:1);return {ok:true,...a!==void 0?{outputNotCredited:a}:{},credit:{requestId:t.requestId,at:t.
|
|
1146
|
+
at,inputTokens:t.inputTokens,outputTokens:t.outputTokens,creditedInputTokens:i,creditedOutputTokens:c,cachedInputPer1k:o,outputPer1k:r.outputPer1k,tierFactor:l}}}var rr={done:true,value:void 0},or=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){
|
|
1147
1147
|
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);},
|
|
1148
1148
|
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.
|
|
1149
1149
|
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.
|
|
@@ -1152,179 +1152,180 @@ terminado)return;let r=e.toolCalls?.length??0,o=this.primerEventoAt??(n.vivo&&r>
|
|
|
1152
1152
|
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(){
|
|
1153
1153
|
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.
|
|
1154
1154
|
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)
|
|
1155
|
-
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(
|
|
1156
|
-
esperas.splice(0);if(n){n.reject(e);for(let o of r)o.resolve(
|
|
1157
|
-
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(
|
|
1155
|
+
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(rr);}fallarCola(e){this.cerrada=true;let[n,...r]=this.
|
|
1156
|
+
esperas.splice(0);if(n){n.reject(e);for(let o of r)o.resolve(rr);}else this.errorPendiente={valor:e};}siguiente(){if(this.consumidorSalio)return Promise.resolve(rr);let e=this.cola.shift();if(e)return Promise.
|
|
1157
|
+
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(rr):new Promise((n,r)=>{this.esperas.
|
|
1158
1158
|
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(),
|
|
1159
|
-
this.consumidorSalio=true,this.cola.length=0,Promise.resolve(
|
|
1160
|
-
"fail_open"?"fail_open":"provider"}}function
|
|
1161
|
-
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
|
|
1162
|
-
hechos,n=
|
|
1159
|
+
this.consumidorSalio=true,this.cola.length=0,Promise.resolve(rr))}}};function Xg(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===
|
|
1160
|
+
"fail_open"?"fail_open":"provider"}}function Qg(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!==
|
|
1161
|
+
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 Dd(t){let e=t.
|
|
1162
|
+
hechos,n=Xg(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,
|
|
1163
1163
|
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\
|
|
1164
1164
|
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.
|
|
1165
|
-
finishReason}:{},capSetByCaller:s!=null,...s!=null?{outputLimit:s}:{}};}if(n==="exact_cache")r.cacheMatch={kind:"exact",...t.
|
|
1166
|
-
let i=e.semantico;r.cacheMatch={kind:"semantic",ageMs:i.ageMs,similarity:i.similarity,similarityFloor:i.similarityFloor,acceptFloor:i.
|
|
1167
|
-
embedder,factGuard:"passed",...i.calibration?{calibration:{...i.calibration}}:{}};}let o=
|
|
1168
|
-
source==="coalesced"?t.sharedFrom??"provider":t.source,...t?.schema?{schema:{...t.schema}}:{},...t?.repair?{repair:{...t.repair}}:
|
|
1169
|
-
{cacheMatch:
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1165
|
+
finishReason}:{},...i?.finishReasonDetail!==void 0?{finishReasonDetail:i.finishReasonDetail}:{},capSetByCaller:s!=null,...s!=null?{outputLimit:s}:{}};}if(n==="exact_cache")r.cacheMatch={kind:"exact",...t.
|
|
1166
|
+
ageMs!==void 0?{ageMs:t.ageMs}:{}};else if(n==="semantic_cache"&&e?.semantico){let i=e.semantico;r.cacheMatch={kind:"semantic",ageMs:i.ageMs,similarity:i.similarity,similarityFloor:i.similarityFloor,acceptFloor:i.
|
|
1167
|
+
acceptFloor,...i.verifierRan?{verifierScore:i.verifierScore}:{},embedder:i.embedder,factGuard:"passed",...i.calibration?{calibration:{...i.calibration}}:{}};}let o=Qg(t.cascada);return o&&(r.cascade=o),
|
|
1168
|
+
r}function Ad(t){return {source:"coalesced",sharedFrom:t==null?"provider":t.source==="coalesced"?t.sharedFrom??"provider":t.source,...t?.schema?{schema:{...t.schema}}:{},...t?.repair?{repair:{...t.repair}}:
|
|
1169
|
+
{},...t?.truncation?{truncation:{...t.truncation}}:{},...t?.cacheMatch?{cacheMatch:e0(t.cacheMatch)}:{},...t?.cascade?{cascade:{...t.cascade}}:{}}}function e0(t){return t.kind==="semantic"&&t.calibration?
|
|
1170
|
+
{...t,calibration:{...t.calibration}}:{...t}}var zo="https://savings.bivelio.com/dashboard/account",Od=["semantic_cache","deterministic_resolvers","format_selection","compression","context_elision","tool_result_elision","model_cascade","output_c\
|
|
1171
|
+
odebook","prompt_cache_placement","deferred_tier"],Ld=`[bvsala] Measure license: the layer is running in SHADOW mode. Every request goes to your provider exactly as you built it and nothing is served \
|
|
1172
|
+
from any cache; \`report.measure.wouldHaveSaved\` shows what the levers would have saved (a lower bound, never billed). To turn the levers on, upgrade to a paid plan at ${zo} - the layer picks up the \
|
|
1173
|
+
new license by itself (with \`serviceAccountKey\` and \`licenseServerUrl\`) or on restart.`,t0=1e4,Bo=class{constructor(e=t0){this.max=e;}max;vistas=new Map;enVuelo=new Map;vista(e,n){let r=this.vistas.
|
|
1173
1174
|
get(e);return r===void 0?false:n>r?(this.vistas.delete(e),false):true}anotar(e,n){for(this.vistas.delete(e),this.vistas.set(e,n);this.vistas.size>this.max;){let r=this.vistas.keys().next().value;if(r===void 0)
|
|
1174
1175
|
break;this.vistas.delete(r);}}hayEnVuelo(e){return (this.enVuelo.get(e)??0)>0}entrar(e){this.enVuelo.set(e,(this.enVuelo.get(e)??0)+1);}salir(e){let n=(this.enVuelo.get(e)??0)-1;n<=0?this.enVuelo.delete(
|
|
1175
|
-
e):this.enVuelo.set(e,n);}tamano(){return this.vistas.size}};function
|
|
1176
|
-
able","do not feel comfortable","'d rather not","would rather not","don't think i can","do not think i can"].join("|")+")",
|
|
1177
|
-
tant|good|great|amazing|nice|relieved|pleased|delighted|impressed|helpful|useful|valuable|lucky|blessed|thrilled|fun|cool|beautiful|wonderful)",
|
|
1176
|
+
e):this.enVuelo.set(e,n);}tamano(){return this.vistas.size}};function Md(t){return Math.round(t*1e10)/1e10}var ba="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\
|
|
1177
|
+
able","do not feel comfortable","'d rather not","would rather not","don't think i can","do not think i can"].join("|")+")",ha="(?:much|many times|happy|glad|grateful|excited|thankful|proud|sorry|impor\
|
|
1178
|
+
tant|good|great|amazing|nice|relieved|pleased|delighted|impressed|helpful|useful|valuable|lucky|blessed|thrilled|fun|cool|beautiful|wonderful)",n0=`(?:help(?! but| feeling| thinking| noticing| wonderi\
|
|
1178
1179
|
ng| laughing| smiling| myself| it(?![\\p{L}]))|assist|provide|comply|fulfil|fulfill|create|write|generate|produce|give|share|support|engage|participate|answer|respond|discuss|offer|continue|draft|facil\
|
|
1179
|
-
itate|contribute|go along|go into|walk you through|explain how|describe how(?! ${
|
|
1180
|
+
itate|contribute|go along|go into|walk you through|explain how|describe how(?! ${ha})|tell you how(?! ${ha})|teach|instruct|encourage|condone|endorse|promote|role-?play|pretend|do that|do this|do so|w\
|
|
1180
1181
|
ith that|with this|with your request|with this request|that request|this request|determine|identify(?! any| anything| a single| no )|know|access|disclose|reveal|divulge|verify|confirm|locate|find(?! a\
|
|
1181
1182
|
ny| anything| a single| no | nothing| it in me)|find out|track|trace|guess|predict|diagnose|recommend(?![^.!?]{0,60}enough)|prescribe|advise|look up|retrieve|obtain|browse|search|speculate|infer|asses\
|
|
1182
|
-
s|evaluate|comment on|speak to|give out|dox|tell (?:you )?(?:whether|if))`,
|
|
1183
|
+
s|evaluate|comment on|speak to|give out|dox|tell (?:you )?(?:whether|if))`,r0="i(?:'ll| will| must| need to|'d| would)?(?: have to)? ?(?:respectfully |politely )?decline",o0="(?:(?:that|this|it)(?:'s|\
|
|
1183
1184
|
is) not something i(?:'m| am)? ?(?:can|will|able to|comfortable)|(?:it|that|this)(?:'s| is| would be| would not be| wouldn't be) (?:not )?(?:appropriate|ethical|responsible) for me to|i(?:'m| am) not\
|
|
1184
|
-
sure (?:that )?it(?:'s| is| would be) appropriate)",
|
|
1185
|
-
|i am afraid|as an ai|as a language model|as an assistant|i understand|i appreciate|thank you for|thanks for|while i understand|while i appreciate)",k="\\p{L}*",
|
|
1186
|
-
oy en condiciones de|me siento c\xF3mod[oa])",
|
|
1185
|
+
sure (?:that )?it(?:'s| is| would be) appropriate)",i0="(?:(?:i'm |i am |i'm really |i am really |i'm so |really |so )?sorry|i apologi[sz]e|my apologies|apologies|unfortunately|regrettably|i'm afraid\
|
|
1186
|
+
|i am afraid|as an ai|as a language model|as an assistant|i understand|i appreciate|thank you for|thanks for|while i understand|while i appreciate)",k="\\p{L}*",Nd="no (?:puedo|voy a|me es posible|est\
|
|
1187
|
+
oy en condiciones de|me siento c\xF3mod[oa])",s0=`(?:ayudar${k}|asistir${k}|proporcionar${k}|facilitar${k}|dar${k}|ofrecer${k}|crear${k}|escribir${k}|generar${k}|compartir${k}|cumplir|responder${k}|co\
|
|
1187
1188
|
laborar|participar|atender${k}|hacer eso|hacerlo|con eso|con esto|con esa|con esta|con tu|determinar${k}|identificar${k}|saber${k}|acceder|revelar${k}|divulgar${k}|verificar${k}|confirmar${k}|localiza\
|
|
1188
|
-
r${k}|rastrear${k}|adivinar${k}|predecir${k}|diagnosticar${k}|recomendar${k}(?![^.!?]{0,60}suficiente)|recetar${k}|aconsejar${k})`,
|
|
1189
|
-
erdona|lamentablemente|desafortunadamente|me temo que|como (?:una )?(?:ia|inteligencia artificial|modelo de lenguaje|asistente)|entiendo)",
|
|
1190
|
-
cions de)",
|
|
1189
|
+
r${k}|rastrear${k}|adivinar${k}|predecir${k}|diagnosticar${k}|recomendar${k}(?![^.!?]{0,60}suficiente)|recetar${k}|aconsejar${k})`,a0="(?:lo siento|lo lamento|siento|lamento|disculpa|disculpe|perd\xF3n|p\
|
|
1190
|
+
erdona|lamentablemente|desafortunadamente|me temo que|como (?:una )?(?:ia|inteligencia artificial|modelo de lenguaje|asistente)|entiendo)",jd="no (?:puc|et puc|us puc|em sento c\xF2mod[ea]|estic en condi\
|
|
1191
|
+
cions de)",c0=`(?:ajudar${k}|assistir${k}|proporcionar${k}|facilitar${k}|donar${k}|oferir${k}|crear${k}|escriure${k}|generar${k}|compartir${k}|complir|respondre${k}|col\xB7laborar|participar|fer aix\xF2|fer\
|
|
1191
1192
|
-ho|amb aix\xF2|amb aquesta|amb la teva|determinar${k}|identificar${k}|saber${k}|accedir|revelar${k}|divulgar${k}|verificar${k}|confirmar${k}|localitzar${k}|rastrejar${k}|endevinar${k}|predir${k}|diag\
|
|
1192
|
-
nosticar${k}|recomanar${k}(?![^.!?]{0,60}prou)|receptar${k}|aconsellar${k})`,
|
|
1193
|
-
ntel\xB7lig\xE8ncia artificial|model de llenguatge|assistent)|entenc)",
|
|
1193
|
+
nosticar${k}|recomanar${k}(?![^.!?]{0,60}prou)|receptar${k}|aconsellar${k})`,l0="(?:ho sento|ho lamento|em sap greu|disculpa|disculpeu|perdona|malauradament|lamentablement|dissortadament|com a (?:ia|i\
|
|
1194
|
+
ntel\xB7lig\xE8ncia artificial|model de llenguatge|assistent)|entenc)",Bd="(?:je ne (?:peux|pourrai|pourrais|vais|souhaite)(?: malheureusement)? pas|je ne suis pas en mesure d[e']|je refuse d[e'])",u0="\
|
|
1194
1195
|
(?: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|d\xE9terminer|identifier|savoir|divulguer|r\
|
|
1195
|
-
\xE9v\xE9ler|v\xE9rifier|confirmer|localiser|retrouver|deviner|pr\xE9dire|diagnostiquer|prescrire|conseiller|recommander(?![^.!?]{0,60}assez))",
|
|
1196
|
-
ment|h\xE9las|je comprends|en tant qu'(?:ia|intelligence artificielle|mod\xE8le de langage|assistant))",
|
|
1197
|
-
keine\\p{L}*)(?: \\p{L}+){0,3}?",
|
|
1198
|
-
llen|identifizieren|wissen|zugreifen|preisgeben|offenlegen|verraten|\xFCberpr\xFCfen|best\xE4tigen|ausfindig machen|orten|verfolgen|erraten|vorhersagen|diagnostizieren|verschreiben|raten|sagen, ob)",
|
|
1199
|
-
(?:es tut mir leid|tut mir leid|entschuldigung|entschuldige|leider|bedauerlicherweise|ich verstehe|als (?:eine )?(?:ki|k\xFCnstliche intelligenz|sprachmodell|assistent))",
|
|
1200
|
-
o di|riesco a|mi sento a mio agio (?:a|nel))",
|
|
1196
|
+
\xE9v\xE9ler|v\xE9rifier|confirmer|localiser|retrouver|deviner|pr\xE9dire|diagnostiquer|prescrire|conseiller|recommander(?![^.!?]{0,60}assez))",d0="(?:d\xE9sol\xE9e?|je suis d\xE9sol\xE9e?|je regrette|malheureuse\
|
|
1197
|
+
ment|h\xE9las|je comprends|en tant qu'(?:ia|intelligence artificielle|mod\xE8le de langage|assistant))",zd="(?:ich (?:kann|werde|darf|m\xF6chte)|(?:kann|werde|darf|m\xF6chte) ich)(?: \\p{L}+){0,4}? (?:nicht|\
|
|
1198
|
+
keine\\p{L}*)(?: \\p{L}+){0,3}?",p0="(?:helfen|unterst\xFCtzen|bereitstellen|geben|erstellen|schreiben|generieren|beantworten|liefern|nachkommen|teilen|anbieten|erkl\xE4ren|behilflich sein|bestimmen|festste\
|
|
1199
|
+
llen|identifizieren|wissen|zugreifen|preisgeben|offenlegen|verraten|\xFCberpr\xFCfen|best\xE4tigen|ausfindig machen|orten|verfolgen|erraten|vorhersagen|diagnostizieren|verschreiben|raten|sagen, ob)",f0="\
|
|
1200
|
+
(?:es tut mir leid|tut mir leid|entschuldigung|entschuldige|leider|bedauerlicherweise|ich verstehe|als (?:eine )?(?:ki|k\xFCnstliche intelligenz|sprachmodell|assistent))",Fd="non (?:posso|sono in grad\
|
|
1201
|
+
o di|riesco a|mi sento a mio agio (?:a|nel))",m0=`(?:aiutar${k}|assister${k}|fornir${k}|crear${k}|scriver${k}|generar${k}|condivider${k}|risponder${k}|dar${k}|offrir${k}|soddisfare|partecipare|farlo|f\
|
|
1201
1202
|
are questo|con questo|con questa|determinar${k}|identificar${k}|saper${k}|accedere|rivelar${k}|divulgar${k}|verificar${k}|confermar${k}|localizzar${k}|rintracciar${k}|indovinar${k}|prevedere|diagnosti\
|
|
1202
|
-
car${k}|prescriver${k}|consigliar${k}(?![^.!?]{0,60}abbastanza))`,
|
|
1203
|
-
istente))",
|
|
1203
|
+
car${k}|prescriver${k}|consigliar${k}(?![^.!?]{0,60}abbastanza))`,h0="(?:mi dispiace|spiacente|purtroppo|sfortunatamente|capisco|come (?:un'?\\s?)?(?:ia|intelligenza artificiale|modello linguistico|ass\
|
|
1204
|
+
istente))",qd="n\xE3o (?:posso|consigo|vou|sou capaz de|estou em condi\xE7\xF5es de|me sinto confort\xE1vel (?:em|a))",g0=`(?:ajudar${k}|auxiliar${k}|assistir${k}|fornecer${k}|criar${k}|escrever${k}|g\
|
|
1204
1205
|
erar${k}|compartilhar${k}|partilhar${k}|dar${k}|oferecer${k}|responder${k}|atender${k}|cumprir|participar|fazer isso|com isso|com esse|com essa|determinar${k}|identificar${k}|saber${k}|acessar|aceder|\
|
|
1205
|
-
revelar${k}|divulgar${k}|verificar${k}|confirmar${k}|localizar${k}|rastrear${k}|adivinhar${k}|prever${k}|diagnosticar${k}|receitar${k}|aconselhar${k}|recomendar${k}(?![^.!?]{0,60}o suficiente))`,
|
|
1206
|
-
?:desculpe|desculpa|sinto muito|lamento|infelizmente|entendo|compreendo|como (?:uma? )?(?:ia|intelig\xEAncia artificial|modelo de linguagem|assistente))",
|
|
1207
|
-
|
|
1208
|
-
`^(?:${
|
|
1209
|
-
y|simply|just|ever|always)",
|
|
1206
|
+
revelar${k}|divulgar${k}|verificar${k}|confirmar${k}|localizar${k}|rastrear${k}|adivinhar${k}|prever${k}|diagnosticar${k}|receitar${k}|aconselhar${k}|recomendar${k}(?![^.!?]{0,60}o suficiente))`,b0="(\
|
|
1207
|
+
?:desculpe|desculpa|sinto muito|lamento|infelizmente|entendo|compreendo|como (?:uma? )?(?:ia|intelig\xEAncia artificial|modelo de linguagem|assistente))",Vt="(?:[\\s,]+[\\p{L}'\u2019-]+){0,4}?[\\s,]+",
|
|
1208
|
+
va=[`${ba}${Vt}${n0}`,r0,o0,`${Nd}${Vt}${s0}`,"lamento no poder",`${jd}${Vt}${c0}`,`${Bd}${Vt}${u0}`,`${zd} ${p0}`,`${Fd}${Vt}${m0}`,`${qd}${Vt}${g0}`].join("|"),v0=[i0,a0,l0,d0,f0,h0,b0].join("|"),y0=new RegExp(
|
|
1209
|
+
`^(?:${va})(?![\\p{L}])`,"u"),k0=new RegExp(`^(?:${v0})(?![\\p{L}])`,"u"),Ud=new RegExp(`(?:^|[^\\p{L}'])(?:${va})(?![\\p{L}])`,"u"),x0="(?:really|even|honestly|quite|possibly|truly|personally|actuall\
|
|
1210
|
+
y|simply|just|ever|always)",ya="i(?:'m| am)? ?(?:can't|cannot|can not|won't|will not|not going to|not able to|unable to)",w0=["wait","believe","imagine (?:how|what|why|anything|anyone|anybody|life|liv\
|
|
1210
1211
|
ing|being|a (?:better|world|life|time|single))","thank","stress","(?:over|under)?emphasi[sz]e","overstate","understate","exaggerate","(?:recommend|praise|rave about|speak highly of|say enough good)[^.\
|
|
1211
|
-
!?]{0,60}enough","say enough","get enough","help (?:but|feeling|thinking|noticing|wondering|laughing|smiling|myself|it)",`(?:tell you|say|express|describe|explain|put into words) (?:how|what a) ${
|
|
1212
|
+
!?]{0,60}enough","say enough","get enough","help (?:but|feeling|thinking|noticing|wondering|laughing|smiling|myself|it)",`(?:tell you|say|express|describe|explain|put into words) (?:how|what a) ${ha}`,
|
|
1212
1213
|
"express (?:my|our) (?:gratitude|thanks|appreciation)","begin to (?:describe|imagine|tell|express|thank|understand|fathom|comprehend|count)","agree (?:more|with you more)","complain","disagree","deny \
|
|
1213
1214
|
(?:that|it|this|the)","fault (?:you|it|that|this|the)","argue with (?:that|this|you|those|these|the (?:logic|results|data|numbers|math|facts))","find (?:any|anything|a single|no|nothing)","identify (?\
|
|
1214
1215
|
:any|anything|a single)","spot (?:any|anything|a single)","see (?:any|anything|a single|why not|a (?:reason|problem|downside|issue|bug))","think of (?:any|anything|a (?:reason|better|single|downside))",
|
|
1215
1216
|
"lie","sugar-?coat(?: it| this| that)?","bore you","belabou?r","rehash","judge you","keep you","get over","resist","top (?:that|this)","go wrong","say (?:that )?i","pretend (?:otherwise|(?:that )?(?:i\
|
|
1216
|
-
'm|i am|it's|it is|this is|everything|there's|there is|we|you))","remember (?:a time|the last time|when i)","stop (?:thinking|smiling|laughing|listening|reading|talking about)"],
|
|
1217
|
+
'm|i am|it's|it is|this is|everything|there's|there is|we|you))","remember (?:a time|the last time|when i)","stop (?:thinking|smiling|laughing|listening|reading|talking about)"],S0="(?:be (?:100% |com\
|
|
1217
1218
|
pletely |entirely |absolutely |totally |fully |one hundred percent )?(?:sure|certain)|say (?:for (?:sure|certain)|with (?:certainty|confidence)|definitively|exactly|precisely|for a fact)|know (?:for (\
|
|
1218
1219
|
?:sure|certain)|exactly|precisely)|guarantee|promise|speak for|vouch for|recall|remember|run|test|execute|see (?:your|the) (?:screen|code|file|image|output|logs?))[^.!?]{0,160}?(?:,|\\s)(?:but|however)\
|
|
1219
|
-
(?![\\p{L}])",
|
|
1220
|
+
(?![\\p{L}])",Fo=`(?:${x0} ){0,2}(?:(?:${w0.join("|")})(?![\\p{L}])|${S0})`,Vd="no (?:(?:te|le|les|os|lo|la|me|se) )?(?:puedo|voy a)",E0=["esperar",`creer${k}`,`imaginar${k}`,"dejar de",`evitar${k}`,`\
|
|
1220
1221
|
agradecer${k}`,`negar${k}`,`mentir${k}`,`quejar${k}`,"estar m\xE1s",`(?:encontrar|ver|detectar|identificar|notar)${k} (?:ning\xFAn|ninguna|ningun|nada|ni un|motivo para no|raz\xF3n para no)`,`recomend\
|
|
1221
1222
|
ar${k}[^.!?]{0,60}(?:suficiente|bastante)`,`(?:enfatizar|recalcar|subrayar|insistir|exagerar|ponderar)${k}`,`(?:decir|expresar)${k} (?:lo|cu\xE1nto|cuanto|c\xF3mo de|como de)`,`resistir${k}`,"m\xE1s que",
|
|
1222
|
-
"sino","pedir m\xE1s"],
|
|
1223
|
-
ejecutar${k}|probar${k}|recordar${k}|ver (?:tu|la|el) (?:pantalla|c\xF3digo|archivo))[^.!?]{0,160}?(?:,|\\s)(?:pero|aunque|sin embargo)(?![\\p{L}])`,
|
|
1224
|
-
no (?:(?:et|us|el|la|ho|em|li|els|les) )?(?:puc|penso|podr\xE9)",
|
|
1223
|
+
"sino","pedir m\xE1s"],C0=`(?:estar (?:100 ?% |completamente |totalmente |del todo )?segur[oa]|asegurar${k}|garantizar${k}|prometer${k}|(?:decir|saber|afirmar)${k} con (?:certeza|seguridad|exactitud)|\
|
|
1224
|
+
ejecutar${k}|probar${k}|recordar${k}|ver (?:tu|la|el) (?:pantalla|c\xF3digo|archivo))[^.!?]{0,160}?(?:,|\\s)(?:pero|aunque|sin embargo)(?![\\p{L}])`,ka=`(?:(?:${E0.join("|")})(?![\\p{L}])|${C0})`,Hd="\
|
|
1225
|
+
no (?:(?:et|us|el|la|ho|em|li|els|les) )?(?:puc|penso|podr\xE9)",T0=[`esperar${k}`,`creure${k}`,`imaginar${k}`,"deixar de",`evitar${k}`,`agrair${k}`,`negar${k}`,`mentir${k}`,`queixar${k}`,"estar m\xE9s",
|
|
1225
1226
|
`(?:trobar|veure|detectar|identificar)${k} (?:cap|res|ni un|ni una)`,`recomanar${k}[^.!?]{0,60}prou`,`(?:emfatitzar|remarcar|subratllar|insistir|exagerar)${k}`,`dir${k} (?:com de|quant|prou)`,`resisti\
|
|
1226
|
-
r${k}`,"m\xE9s que","sin\xF3","fer altra cosa que"],
|
|
1227
|
-
executar${k}|provar${k}|recordar${k})[^.!?]{0,160}?(?:,|\\s)(?:per\xF2|pero|tot i que)(?![\\p{L}])`,
|
|
1228
|
-
sement)? pas",
|
|
1227
|
+
r${k}`,"m\xE9s que","sin\xF3","fer altra cosa que"],R0=`(?:estar (?:100 ?% |completament |del tot )?segura?|assegurar${k}|garantir${k}|prometre${k}|(?:dir|saber|afirmar)${k} amb (?:certesa|seguretat)|\
|
|
1228
|
+
executar${k}|provar${k}|recordar${k})[^.!?]{0,160}?(?:,|\\s)(?:per\xF2|pero|tot i que)(?![\\p{L}])`,xa=`(?:(?:${T0.join("|")})(?![\\p{L}])|${R0})`,Wd="je ne (?:peux|pourrai|pourrais|vais)(?: malheureu\
|
|
1229
|
+
sement)? pas",P0="(?:vous |te |t'|me |m'|le |la |les |l'|lui |leur |y |en |se |s')",I0=["attendre","croire","imaginer","emp\xEAcher","remercier","(?:trop |assez )?(?:insister|souligner|exag\xE9rer)","\
|
|
1229
1230
|
mentir","nier","plaindre","\xEAtre plus","(?:trouver|voir|d\xE9tecter|identifier|rep\xE9rer) (?:aucun|aucune|rien|de (?:probl\xE8me|raison|souci))","dire (?:\xE0 quel point|combien|assez)","recommande\
|
|
1230
|
-
r[^.!?]{0,60}assez","r\xE9sister","faire autrement que"],
|
|
1231
|
-
ter|souvenir|rappeler|voir (?:votre|ton|ta|le|la) (?:\xE9cran|code|fichier))[^.!?]{0,160}?(?:,|\\s)(?:mais|cependant|toutefois)(?![\\p{L}])",
|
|
1232
|
-
n (?:(?:ti|vi|la|lo|le|gli|ne|mi|ci) )?(?:posso|riesco a|sono in grado di|ho intenzione di)",
|
|
1231
|
+
r[^.!?]{0,60}assez","r\xE9sister","faire autrement que"],_0="(?:\xEAtre (?:(?:tout \xE0 fait|absolument|enti\xE8rement|100 ?%) )?(?:s\xFBre?|certaine?)|garantir|promettre|affirmer|dire avec certitude|ex\xE9cuter|tes\
|
|
1232
|
+
ter|souvenir|rappeler|voir (?:votre|ton|ta|le|la) (?:\xE9cran|code|fichier))[^.!?]{0,160}?(?:,|\\s)(?:mais|cependant|toutefois)(?![\\p{L}])",wa=`${P0}*(?:(?:${I0.join("|")})(?![\\p{L}])|${_0})`,Gd="no\
|
|
1233
|
+
n (?:(?:ti|vi|la|lo|le|gli|ne|mi|ci) )?(?:posso|riesco a|sono in grado di|ho intenzione di)",D0=[`aspettar${k}`,`creder${k}`,`immaginar${k}`,"fare a meno",`ringraziar${k}`,"che","non",`negar${k}`,`men\
|
|
1233
1234
|
tir${k}`,`lamentar${k}`,"(?:essere|esser) pi\xF9",`(?:trovare|vedere|notare|individuare|rilevare) (?:nessun${k}|niente|alcun${k}|un solo)`,`consigliar${k}[^.!?]{0,60}abbastanza`,`(?:sottolinear|enfati\
|
|
1234
|
-
zzar|insister|esagerar)${k}`,`dir${k} (?:quanto|abbastanza)`,`resister${k}`],
|
|
1235
|
-
|affermar)${k} con certezza|eseguir${k}|testar${k}|ricordar${k})[^.!?]{0,160}?(?:,|\\s)(?:ma|per\xF2|tuttavia)(?![\\p{L}])`,
|
|
1236
|
-
|o|a|me) )?(?:posso|consigo|vou|sou capaz de)",
|
|
1235
|
+
zzar|insister|esagerar)${k}`,`dir${k} (?:quanto|abbastanza)`,`resister${k}`],A0=`(?:(?:esserne|essere) (?:del tutto |completamente |al 100 ?% )?(?:sicur[oa]|cert[oa])|garantir${k}|prometter${k}|(?:dir\
|
|
1236
|
+
|affermar)${k} con certezza|eseguir${k}|testar${k}|ricordar${k})[^.!?]{0,160}?(?:,|\\s)(?:ma|per\xF2|tuttavia)(?![\\p{L}])`,Sa=`(?:(?:${D0.join("|")})(?![\\p{L}])|${A0})`,Kd="n\xE3o (?:(?:te|lhe|lhes|vos\
|
|
1237
|
+
|o|a|me) )?(?:posso|consigo|vou|sou capaz de)",O0=["esperar","acreditar",`imaginar${k}`,"deixar de",`evitar${k}`,`agradecer${k}`,`negar${k}`,`mentir${k}`,`(?:me )?(?:queixar|reclamar)${k}`,"concordar \
|
|
1237
1238
|
mais","estar mais","sen\xE3o","(?:fazer )?mais (?:do )?que",`(?:encontrar|ver|identificar|detetar|detectar|notar) (?:nenhum${k}|nada|um \xFAnico|uma \xFAnica)`,`recomendar${k}[^.!?]{0,60}(?:o )?sufici\
|
|
1238
|
-
ente`,`(?:enfatizar|sublinhar|ressaltar|insistir|exagerar)${k}`,`dizer${k} (?:o quanto|quanto|como|o suficiente)`,`resistir${k}`],
|
|
1239
|
+
ente`,`(?:enfatizar|sublinhar|ressaltar|insistir|exagerar)${k}`,`dizer${k} (?:o quanto|quanto|como|o suficiente)`,`resistir${k}`],L0=`(?:ter (?:a )?certeza|estar (?:100 ?% |completamente |totalmente )\
|
|
1239
1240
|
?(?:segur[oa]|cert[oa])|garantir${k}|prometer${k}|(?:dizer|afirmar|saber)${k} com (?:certeza|seguran\xE7a)|executar${k}|testar${k}|lembrar${k})[^.!?]{0,160}?(?:,|\\s)(?:mas|por\xE9m|contudo)(?![\\p{L}])`,
|
|
1240
|
-
|
|
1241
|
+
Ea=`(?:(?:${O0.join("|")})(?![\\p{L}])|${L0})`,Jd="(?:ich (?:kann|werde|darf)|kann ich|werde ich)",M0=["(?:kaum|nicht) erwarten","glauben","vorstellen","genug (?:danken|betonen|empfehlen|loben|sagen|h\
|
|
1241
1242
|
ervorheben)","oft genug","\\p{L}*l\xFCgen","leugnen","bestreiten","beschweren","beklagen","(?:mehr|besser) zustimmen","widerstehen","keine?n? (?:fehler|probleme?|grund|haken|m\xE4ngel|bugs?|nachteile?|ei\
|
|
1242
|
-
nw\xE4nde?)","sagen, wie (?:sehr|froh|dankbar|gl\xFCcklich)"]
|
|
1243
|
-
(?![\\p{L}])",
|
|
1244
|
-
s(?!${
|
|
1245
|
-
(?!\\s(?:nur|mehr als|anders|umhin))`].join("|")+")","u"),
|
|
1246
|
-
)`,`${
|
|
1247
|
-
(?:lo siento(?: mucho)?|lo lamento|disculpa|disculpe|perd\xF3n|perdona|lamentablemente|desafortunadamente|me temo que)",
|
|
1248
|
-
amentablement|dissortadament)"
|
|
1249
|
-
der|bedauerlicherweise)",
|
|
1250
|
-
|
|
1251
|
-
(?:\\s(?:te|le|les|os))?\\s(?!${
|
|
1252
|
-
"ma")}${
|
|
1243
|
+
nw\xE4nde?)","sagen, wie (?:sehr|froh|dankbar|gl\xFCcklich)"],$0="(?:(?:mit )?sicherheit|genau|garantieren|versprechen|100 ?%|ausf\xFChren|testen|erinnern)[^.!?]{0,160}?(?:,|\\s)(?:aber|jedoch|allerdings)\
|
|
1244
|
+
(?![\\p{L}])",Yd=`[^.!?]*?(?<![\\p{L}])(?:(?:${M0.join("|")})(?![\\p{L}])|${$0})`,Zd="(?:no[,.!]? |non[,.!]? |n\xE3o[,.!]? |nein[,.!]? )?",N0=new RegExp("^"+Zd+"(?:"+[`${ya}\\s(?!${Fo})\\p{L}`,`${Vd}\\\
|
|
1245
|
+
s(?!${ka})\\p{L}`,`${Hd}\\s(?!${xa})\\p{L}`,`${Wd}\\s?(?!${wa})\\p{L}`,`${Gd}\\s(?!${Sa})\\p{L}`,`${Kd}\\s(?!${Ea})\\p{L}`,`${Jd}(?!${Yd})(?:\\s[\\p{L}\\p{N}'-]+){0,6}?\\s(?:nicht|keine?\\p{L}*)(?![\\p{L}])\
|
|
1246
|
+
(?!\\s(?:nur|mehr als|anders|umhin))`].join("|")+")","u"),j0=new RegExp("^"+Zd+"(?:"+[`${ya}\\s(?=${Fo})`,`${Vd}\\s(?=${ka})`,`${Hd}\\s(?=${xa})`,`${Wd}\\s?(?=${wa})`,`${Gd}\\s(?=${Sa})`,`${Kd}\\s(?=${Ea}\
|
|
1247
|
+
)`,`${Jd}(?=${Yd})`].join("|")+")","u"),B0="(?:(?:i'm |i am )?(?:really |so |very |truly |terribly )?sorry|i apologi[sz]e|my apologies|apologies|unfortunately|regrettably|i'm afraid|i am afraid)",z0="\
|
|
1248
|
+
(?:lo siento(?: mucho)?|lo lamento|disculpa|disculpe|perd\xF3n|perdona|lamentablemente|desafortunadamente|me temo que)",F0="(?:ho sento(?: molt)?|em sap greu|disculpa|disculpeu|perdona|malauradament|l\
|
|
1249
|
+
amentablement|dissortadament)",q0="(?:(?:je suis )?(?:vraiment )?d\xE9sol\xE9e?|je regrette|pardon|malheureusement|h\xE9las)",U0="(?:es tut mir (?:sehr |wirklich )?leid|tut mir leid|entschuldigung|lei\
|
|
1250
|
+
der|bedauerlicherweise)",V0="(?:mi dispiace(?: molto)?|spiacente|scusa|scusami|mi scuso|purtroppo|sfortunatamente)",H0="(?:desculpe|desculpa|sinto muito|lamento|pe\xE7o desculpa|infelizmente)",W0=Fo,G0=ka,
|
|
1251
|
+
K0=xa,J0=wa,Y0=Sa,Z0=Ea,qt=t=>`[,.!:;]?\\s(?:(?:${t})\\s)?`,X0="\\s\\p{L}",Q0=[`${B0}${qt("but|however,?")}(?:as an ai(?: language model| assistant)?,?\\s)?${ba}\\s(?!${W0})\\p{L}`,`${z0}${qt("pero")}${Nd}\
|
|
1252
|
+
(?:\\s(?:te|le|les|os))?\\s(?!${G0})\\p{L}`,`${F0}${qt("per\xF2|pero")}${jd}\\s(?!${K0})\\p{L}`,`${q0}${qt("mais")}${Bd}(?:\\s(?:vous|te))?\\s?(?!${J0})\\p{L}`,`${U0}${qt("aber")}${zd}${X0}`,`${V0}${qt(
|
|
1253
|
+
"ma")}${Fd}\\s(?!${Y0})\\p{L}`,`${H0}${qt("mas")}${qd}\\s(?!${Z0})\\p{L}`].join("|"),eb="(?:(?:i'm |i am )?(?:really |so |very |truly |terribly )?sorry|i apologi[sz]e|my apologies|apologies)",tb="(?:(\
|
|
1253
1254
|
?:is|are|was|would be|could be|may be|might be|it's|that's|this is|it is|that is)(?: considered| generally| strictly| both)? (?:illegal|unlawful|unethical|against|a violation|a serious violation|a bre\
|
|
1254
1255
|
ach|an invasion|prohibited|not (?:something|appropriate|possible|allowed|permitted|legal|ethical|safe|advisable|ok|okay))|violates?|goes against|go against|infringes?|i (?:don't|do not) have (?:access\
|
|
1255
|
-
|the ability|the means|the capability|any way|a way|information about|any information about|personal (?:information|data)))",
|
|
1256
|
+
|the ability|the means|the capability|any way|a way|information about|any information about|personal (?:information|data)))",nb="(?:(?:es|son|ser\xEDa|ser\xEDan|est\xE1|estar\xEDa|resulta)(?: considerado)? (?:ile\
|
|
1256
1257
|
gal|poco \xE9tic[oa]|inapropiad[oa]|contrari[oa] a|una violaci\xF3n|una infracci\xF3n|una invasi\xF3n|prohibid[oa])|no (?:es|ser\xEDa|est\xE1) (?:apropiado|posible|\xE9tico|legal|permitido|algo)|viola|violar\xEDa|infringe|va\
|
|
1257
|
-
en contra|no tengo (?:acceso|la capacidad|forma de|manera de|informaci\xF3n (?:sobre|personal)|datos personales))",
|
|
1258
|
-
rari a|una violaci\xF3|una infracci\xF3|prohibit)|no (?:\xE9s|seria) (?:apropiat|adequat|possible|\xE8tic|legal|perm\xE8s)|viola|infringeix|va en contra)",
|
|
1259
|
-
ill\xE9gale?|contraire \xE0|une violation|une atteinte|interdite?|inappropri\xE9)|(?:ce )?n'est pas (?:appropri\xE9|possible|\xE9thique|l\xE9gal|autoris\xE9)|viole|enfreint|va \xE0 l'encontre)",
|
|
1258
|
+
en contra|no tengo (?:acceso|la capacidad|forma de|manera de|informaci\xF3n (?:sobre|personal)|datos personales))",rb="(?:(?:\xE9s|s\xF3n|seria|serien) (?:il\xB7legal|ilegal|poc \xE8tic|inadequat|inapropiat|cont\
|
|
1259
|
+
rari a|una violaci\xF3|una infracci\xF3|prohibit)|no (?:\xE9s|seria) (?:apropiat|adequat|possible|\xE8tic|legal|perm\xE8s)|viola|infringeix|va en contra)",ob="(?:(?:c'est|est|sont|serait|seraient) (?:\
|
|
1260
|
+
ill\xE9gale?|contraire \xE0|une violation|une atteinte|interdite?|inappropri\xE9)|(?:ce )?n'est pas (?:appropri\xE9|possible|\xE9thique|l\xE9gal|autoris\xE9)|viole|enfreint|va \xE0 l'encontre)",ib="(?\
|
|
1260
1261
|
:(?:ist|sind|w\xE4re|w\xE4ren)(?: \\p{L}+)? (?:illegal|rechtswidrig|unethisch|verboten|unangemessen|unzul\xE4ssig|ein versto\xDF|nicht (?:angemessen|m\xF6glich|erlaubt|zul\xE4ssig|legal|ethisch))|verst\xF6\xDFt|verletzt)",
|
|
1261
|
-
|
|
1262
|
-
)",
|
|
1263
|
-
|
|
1264
|
-
m sap greu|disculpa|perdona),?\\s(?:per\xF2|pero)\\s${
|
|
1265
|
-
uldigung),?\\saber\\s${
|
|
1266
|
-
"|"),
|
|
1262
|
+
sb="(?:(?:\xE8|sono|sarebbe|sarebbero) (?:illegale|illecito|non etico|contrario a|una violazione|vietato|inappropriato)|non (?:\xE8|sarebbe) (?:appropriato|possibile|etico|legale|consentito)|viola|va contro\
|
|
1263
|
+
)",ab="(?:(?:\xE9|s\xE3o|seria|seriam) (?:ilegal|anti\xE9tic[oa]|contr\xE1ri[oa] a|uma viola\xE7\xE3o|proibid[oa]|inapropriad[oa])|n\xE3o (?:\xE9|seria) (?:apropriado|poss\xEDvel|\xE9tico|legal|permitido)|viola|vai contra)",
|
|
1264
|
+
Ut="(?:[\\p{L}\\p{N}'\u2019-]+[\\s,]+){0,14}?",cb=[`${eb},?\\sbut\\s${Ut}${tb}`,`(?:lo siento(?: mucho)?|lo lamento|disculpa|disculpe|perd\xF3n|perdona),?\\spero\\s${Ut}${nb}`,`(?:ho sento(?: molt)?|e\
|
|
1265
|
+
m sap greu|disculpa|perdona),?\\s(?:per\xF2|pero)\\s${Ut}${rb}`,`(?:(?:je suis )?(?:vraiment )?d\xE9sol\xE9e?|pardon),?\\smais\\s${Ut}${ob}`,`(?:es tut mir (?:sehr |wirklich )?leid|tut mir leid|entsch\
|
|
1266
|
+
uldigung),?\\saber\\s${Ut}${ib}`,`(?:mi dispiace(?: molto)?|spiacente|scusa|scusami|mi scuso),?\\sma\\s${Ut}${sb}`,`(?:desculpe|desculpa|sinto muito|lamento|pe\xE7o desculpa),?\\smas\\s${Ut}${ab}`].join(
|
|
1267
|
+
"|"),lb=new RegExp(`^(?:${Q0}|(?:${cb})(?![\\p{L}]))`,"u"),ub="(?:(?:i'm |i am )?(?:really |so |very |truly |deeply |terribly )?sorry (?:to hear|to read|that you|you(?:'re| are)|you feel|for what you|\
|
|
1267
1268
|
about what you)|it sounds like you(?:'re| are)|that sounds (?:really |so |very |incredibly )?(?:hard|difficult|painful|overwhelming|tough|awful)|i(?:'m| am) (?:really |so |very )?(?:concerned|worried)\
|
|
1268
|
-
(?:about|for|by|to hear)|i hear (?:you|how|that you)|you(?:'re| are) not alone|i(?:'m| am) (?:so |really )?glad you reached out)",
|
|
1269
|
+
(?:about|for|by|to hear)|i hear (?:you|how|that you)|you(?:'re| are) not alone|i(?:'m| am) (?:so |really )?glad you reached out)",db="(?:mental health (?:professional|provider|expert|specialist|servi\
|
|
1269
1270
|
ce|services|support|crisis|line)|therapist|counsel(?:l)?or|psychologist|psychiatrist|crisis (?:line|hotline|helpline|center|centre|text line|counsel(?:l)?or|team|service|services)|(?:suicide|crisis) (\
|
|
1270
1271
|
?:prevention|hotline|helpline|lifeline)|hotline|helpline|lifeline|samaritans|emergency services|emergency number|call (?:911|988|999|112|000|emergency)|988|someone you trust|people you trust|(?:a )?tr\
|
|
1271
1272
|
usted (?:person|friend|adult|family member|individual|someone|loved one)|someone who can (?:help|support|provide support)|reach out to (?:someone|a friend|friends|family|a loved one|loved ones)|profes\
|
|
1272
|
-
sional (?:help|support)|seek (?:immediate|urgent|professional) (?:help|support))",
|
|
1273
|
-
ando)|escuchar|o\xEDr|leer|saber)|parece que (?:est\xE1s|estas) (?:pasando|atravesando)|me preocupa)",
|
|
1273
|
+
sional (?:help|support)|seek (?:immediate|urgent|professional) (?:help|support))",pb="(?:(?:lo )?(?:siento|lamento) (?:mucho |much\xEDsimo )?(?:que (?:te sientas|est\xE9s|estes|te encuentres|pases|est\xE9s pas\
|
|
1274
|
+
ando)|escuchar|o\xEDr|leer|saber)|parece que (?:est\xE1s|estas) (?:pasando|atravesando)|me preocupa)",fb="(?:profesional(?:es)? de (?:la )?salud mental|psic\xF3log[oa]|psiquiatra|terapeuta|l\xEDnea (?:de )?\
|
|
1274
1275
|
(?:crisis|ayuda|prevenci\xF3n|atenci\xF3n)|tel\xE9fono de la esperanza|024|servicios de emergencia|(?:llama|llamar|llames) al (?:112|911|024)|alguien de (?:tu )?confianza|(?:una )?persona de (?:tu )?confianza|\
|
|
1275
|
-
ayuda profesional)",
|
|
1276
|
+
ayuda profesional)",mb="(?:em sap (?:molt )?greu (?:que (?:et sentis|estiguis|passis)|sentir|llegir|saber)|ho sento (?:molt|molt\xEDssim)|sembla que (?:est\xE0s|passes) (?:passant|travessant)?)",hb="(\
|
|
1276
1277
|
?:professional(?:s)? de (?:la )?salut mental|psic\xF2leg|psic\xF2loga|psiquiatre|terapeuta|l\xEDnia (?:d'ajuda|d'atenci\xF3|de crisi|de prevenci\xF3)|tel\xE8fon de l'esperan\xE7a|024|serveis d'emerg\xE8ncia|(?:truca|trucar|t\
|
|
1277
|
-
ruquis) al (?:112|024)|alg\xFA de (?:la teva )?confian\xE7a|(?:una )?persona de confian\xE7a|ajuda professional)",
|
|
1278
|
-
apprendre|de lire|d'entendre|que tu|que vous)|il semble que (?:tu traverses|vous traversez)|\xE7a a l'air (?:tr\xE8s |vraiment )?(?:difficile|dur))",
|
|
1278
|
+
ruquis) al (?:112|024)|alg\xFA de (?:la teva )?confian\xE7a|(?:una )?persona de confian\xE7a|ajuda professional)",gb="(?:(?:je suis )?(?:vraiment |sinc\xE8rement |tellement |profond\xE9ment )?d\xE9sol\xE9e? (?:d'\
|
|
1279
|
+
apprendre|de lire|d'entendre|que tu|que vous)|il semble que (?:tu traverses|vous traversez)|\xE7a a l'air (?:tr\xE8s |vraiment )?(?:difficile|dur))",bb="(?:professionnel(?:le)?s? de (?:la )?sant\xE9 ment\
|
|
1279
1280
|
ale|psychologue|psychiatre|th\xE9rapeute|ligne d'\xE9coute|ligne de crise|ligne d'assistance|num\xE9ro d'urgence|services d'urgence|(?:appelle|appelez|composez|compose) le (?:3114|15|112|911)|3114|personne de \
|
|
1280
|
-
confiance|quelqu'un en qui (?:tu as|vous avez) confiance|aide professionnelle|sos amiti\xE9)",
|
|
1281
|
-
klingt (?:sehr |wirklich )?(?:schwer|belastend|schmerzhaft)|ich mache mir sorgen)",
|
|
1282
|
-
ge|krisendienst|krisentelefon|notruf\\p{L}*|notdienst|rettungsdienst|vertrauensperson|jemandem,? dem (?:du|sie) vertrau\\p{L}*|professionelle hilfe|professionelle unterst\xFCtzung)",
|
|
1283
|
-
(?:molto |davvero |tanto )?(?:sentire|leggere|sapere|che tu|che ti|che stia)|sembra che (?:tu stia|stai) (?:passando|attraversando))",
|
|
1281
|
+
confiance|quelqu'un en qui (?:tu as|vous avez) confiance|aide professionnelle|sos amiti\xE9)",vb="(?:es tut mir (?:sehr |wirklich |so )?leid,? (?:dass|zu h\xF6ren|das zu h\xF6ren|zu lesen|das zu lesen)|das \
|
|
1282
|
+
klingt (?:sehr |wirklich )?(?:schwer|belastend|schmerzhaft)|ich mache mir sorgen)",yb="(?:psychotherapeut\\p{L}*|psycholog\\p{L}*|psychiater\\p{L}*|therapeut\\p{L}*|fachkraft f\xFCr psychische|telefonseelsor\
|
|
1283
|
+
ge|krisendienst|krisentelefon|notruf\\p{L}*|notdienst|rettungsdienst|vertrauensperson|jemandem,? dem (?:du|sie) vertrau\\p{L}*|professionelle hilfe|professionelle unterst\xFCtzung)",kb="(?:mi dispiace\
|
|
1284
|
+
(?:molto |davvero |tanto )?(?:sentire|leggere|sapere|che tu|che ti|che stia)|sembra che (?:tu stia|stai) (?:passando|attraversando))",xb="(?:professionista della salute mentale|psicolog[oa]|psichiatr\
|
|
1284
1285
|
a|terapeuta|linea (?:di crisi|di ascolto|di supporto|d'ascolto)|telefono amico|telefono azzurro|numero di emergenza|servizi di emergenza|(?:chiama|chiamare) (?:il )?(?:112|118)|persona di fiducia|qual\
|
|
1285
|
-
cuno di cui ti fidi|aiuto professionale)",
|
|
1286
|
-
a) (?:passando|a passar))",
|
|
1287
|
-
igar) (?:para )?(?:o )?(?:188|192|112|190)|188|pessoa de confian\xE7a|algu\xE9m (?:de confian\xE7a|em quem (?:voc\xEA )?confie)|ajuda profissional|sns 24)",
|
|
1288
|
-
join("|")})(?![\\p{L}])`,"u"),
|
|
1289
|
-
\\p{L}'])(?:${
|
|
1290
|
-
|
|
1291
|
-
matchAll(/[.!?。](?:\s|$)/g)],n=e.length>=2?e[1].index+1:t.length;return t.slice(0,Math.min(n,240))}function
|
|
1292
|
-
if(typeof t!="string"||t==="")return null;let e=
|
|
1293
|
-
o)||
|
|
1294
|
-
/[‘’ʼ`´]/g,"'").toLowerCase().replace(/\s+/g," ").trim().replace(/^[\s*#>_"'«“¿¡(\[-]+/u,"").trim();return e?
|
|
1286
|
+
cuno di cui ti fidi|aiuto professionale)",wb="(?:sinto muito (?:que voc\xEA|por voc\xEA estar|em saber|ouvir|que esteja|que estejas)|lamento (?:muito )?(?:que voc\xEA|saber|ouvir)|parece que voc\xEA (?:est\xE1|estej\
|
|
1287
|
+
a) (?:passando|a passar))",Sb="(?:profissional de sa\xFAde mental|profissionais de sa\xFAde mental|psic\xF3log[oa]|psiquiatra|terapeuta|cvv|linha de (?:apoio|crise|ajuda)|servi\xE7os de emerg\xEAncia|(?:ligue|liga|l\
|
|
1288
|
+
igar) (?:para )?(?:o )?(?:188|192|112|190)|188|pessoa de confian\xE7a|algu\xE9m (?:de confian\xE7a|em quem (?:voc\xEA )?confie)|ajuda profissional|sns 24)",Eb=new RegExp(`^(?:${[ub,pb,mb,gb,vb,kb,wb].
|
|
1289
|
+
join("|")})(?![\\p{L}])`,"u"),Cb=new RegExp(`(?<![\\p{L}\\p{N}])(?:${[db,fb,hb,bb,yb,xb,Sb].join("|")})(?![\\p{L}\\p{N}])`,"u"),Tb=2e4,Rb="(?:explain|detail|describe|elaborate)",Pb=new RegExp(`(?:^|[^\
|
|
1290
|
+
\\p{L}'])(?:${va}|${ba}${Vt}${Rb})(?![\\p{L}])`,"gu"),Ib=new RegExp(`^[^\\p{L}]*${ya}\\s${Fo}`,"u");function $d(t,e){for(let n of t.matchAll(e))if(!Ib.test(t.slice(n.index)))return true;return false}var _b=new RegExp(
|
|
1291
|
+
Ud.source,"gu");function Db(t){return t.slice(0,4*300).replace(/[‘’ʼ`´]/g,"'").toLowerCase().replace(/\s+/g," ").trim().replace(/^[\s*#>_"'«“¿¡(\[-]+/u,"").trim()}function Ab(t){let e=[...t.
|
|
1292
|
+
matchAll(/[.!?。](?:\s|$)/g)],n=e.length>=2?e[1].index+1:t.length;return t.slice(0,Math.min(n,240))}function ga(t){let e=/[.!?。:;](?:\s|$)/.exec(t);return e?t.slice(e.index+1).trim():""}function ir(t){
|
|
1293
|
+
if(typeof t!="string"||t==="")return null;let e=Db(t);if(e==="")return null;let n=Ab(e),r=j0.test(n);if(!r&&(y0.test(n)||N0.test(n)))return "opens-with-refusal";let o=r?ga(n):n;return k0.test(n)&&Ud.test(
|
|
1294
|
+
o)||lb.test(n)?"apology-then-refusal":e.length<=300&&$d(r?ga(e):e,_b)?"short-refusal":Eb.test(n)&&Cb.test(n)?"redirection":$d(Ob(t,r),Pb)?"partial-refusal":null}function Ob(t,e){let n=t.slice(0,Tb).replace(
|
|
1295
|
+
/[‘’ʼ`´]/g,"'").toLowerCase().replace(/\s+/g," ").trim().replace(/^[\s*#>_"'«“¿¡(\[-]+/u,"").trim();return e?ga(n):n}function qo(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,
|
|
1295
1296
|
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==
|
|
1296
|
-
"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
|
|
1297
|
-
n=Math.round(e*100)/100;return n===0?"<0.01%":Number.isInteger(n)?`${n}%`:`${n.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}%`}function
|
|
1297
|
+
"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 Lb(t){let e=t*100,
|
|
1298
|
+
n=Math.round(e*100)/100;return n===0?"<0.01%":Number.isInteger(n)?`${n}%`:`${n.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}%`}function Xd(t){let e=Lb(t);return `[bvsala] Verification sampling is ON \
|
|
1298
1299
|
(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\
|
|
1299
1300
|
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\
|
|
1300
|
-
your statement or any commission.`}function
|
|
1301
|
-
\` must be a number from 0 to 1 and \`verification.maxCheckCostUsd\`, when set, a positive number (got sampleRate ${e}); verification sampling is OFF.`}var
|
|
1301
|
+
your statement or any commission.`}function Qd(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\
|
|
1302
|
+
\` must be a number from 0 to 1 and \`verification.maxCheckCostUsd\`, when set, a positive number (got sampleRate ${e}); verification sampling is OFF.`}var ep="[bvsala] Verification sampling is set, b\
|
|
1302
1303
|
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\
|
|
1303
|
-
g/usage` \u2014 or pass `verification.onCheck` to receive them yourself. No request will be sent twice until then.",
|
|
1304
|
-
request was not affected.";function
|
|
1304
|
+
g/usage` \u2014 or pass `verification.onCheck` to receive them yourself. No request will be sent twice until then.",tp="[bvsala] verification sampling hit an internal error and skipped a request; your\
|
|
1305
|
+
request was not affected.";function np(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?
|
|
1305
1306
|
{tools:[...t.tools]}:{},...t.response?.schema?{schema:t.response.schema}:{},...G(t)!=null?{maxOutputTokens:G(t)}:{},...t.temperature!==void 0?{temperature:t.temperature}:{},...t.seed!==void 0?{seed:t.
|
|
1306
|
-
seed}:{}}}function
|
|
1307
|
+
seed}:{}}}function rp(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==="\
|
|
1307
1308
|
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===
|
|
1308
1309
|
"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>
|
|
1309
1310
|
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?
|
|
1310
|
-
{estrato:"tokens_compressed"}:{estrato:"unchanged"}}function
|
|
1311
|
-
i*1e10)/1e10}var
|
|
1311
|
+
{estrato:"tokens_compressed"}:{estrato:"unchanged"}}function op(t,e){if(!(e>0))return false;if(e>=1)return true;let n=X(`${t}:verification-sample`);return Number.parseInt(n.slice(0,13),16)/2**52<e}function ip(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(
|
|
1312
|
+
i*1e10)/1e10}var Mb=32,$b=6e5;function Nb(t){return new Date(t).toISOString().slice(0,10)}var Uo=class{tasa;tope;onCheck;waitUntil;provider;precio;contrato;now;sumidero;avisar;enVuelo=new Set;cerrado=false;constructor(e){
|
|
1312
1313
|
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,
|
|
1313
|
-
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=
|
|
1314
|
-
via:r,precio:this.precio,...this.tope!==void 0?{tope:this.tope}:{}}),a;if(i&&"estrato"in s){let u=this.precio(e.model);if(!u)throw new Error("price vanished between classification and launch");a={peticion:
|
|
1315
|
-
e),precios:u,estrato:s.estrato};}let c=this.now();this.sumidero.contar?.(
|
|
1316
|
-
excluida};return {...n,report:{...o,verification:l}}}catch{return this.avisar("verificacion-fallo-interno",
|
|
1314
|
+
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=op(o.requestId,this.tasa),s=rp({request:e,result:n,
|
|
1315
|
+
via:r,precio:this.precio,...this.tope!==void 0?{tope:this.tope}:{}}),a;if(i&&"estrato"in s){let u=this.precio(e.model);if(!u)throw new Error("price vanished between classification and launch");a={peticion:np(
|
|
1316
|
+
e),precios:u,estrato:s.estrato};}let c=this.now();this.sumidero.contar?.(Nb(c),"estrato"in s?s.estrato:s.excluida),a&&this.lanzar(e,n,c,a);let l="estrato"in s?{sampled:i,stratum:s.estrato}:{sampled:i,excluded:s.
|
|
1317
|
+
excluida};return {...n,report:{...o,verification:l}}}catch{return this.avisar("verificacion-fallo-interno",tp),n}}cerrar(){this.cerrado=true;let e=[...this.enVuelo];this.enVuelo.clear();for(let n of e)if(!n.
|
|
1317
1318
|
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.
|
|
1318
1319
|
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??
|
|
1319
|
-
0,outputTokens:i.tokens.actualOutput},prices:{inputPer1k:s.inputPer1k,...s.cachedInputPer1k!==void 0?{cachedInputPer1k:s.cachedInputPer1k}:{},outputPer1k:s.outputPer1k}};if(this.enVuelo.size>=
|
|
1320
|
+
0,outputTokens:i.tokens.actualOutput},prices:{inputPer1k:s.inputPer1k,...s.cachedInputPer1k!==void 0?{cachedInputPer1k:s.cachedInputPer1k}:{},outputPer1k:s.outputPer1k}};if(this.enVuelo.size>=Mb){this.
|
|
1320
1321
|
registrar({...a,outcome:"dropped"});return}let c=()=>{},l=new Promise(d=>{c=d;}),u={base:a,abortar:new AbortController,decidido:false,reloj:void 0,terminar:c};if(this.enVuelo.add(u),u.reloj=setTimeout(()=>{
|
|
1321
|
-
try{u.abortar.abort();}catch{}this.resolverVuelo(u,{...a,outcome:"check_failed"});}
|
|
1322
|
-
{signal:u.abortar.signal}));}catch(p){d=Promise.reject(p);}d.then(p=>{let
|
|
1322
|
+
try{u.abortar.abort();}catch{}this.resolverVuelo(u,{...a,outcome:"check_failed"});},$b),u.reloj.unref?.(),setTimeout(()=>{if(u.decidido)return;let d;try{d=Promise.resolve(this.provider.generate(o.peticion,
|
|
1323
|
+
{signal:u.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(u,h);},()=>{this.resolverVuelo(
|
|
1323
1324
|
u,{...a,outcome:"check_failed"});});},0),this.waitUntil)try{this.waitUntil(l.catch(()=>{}));}catch{}}checkDeLaRespuesta(e,n,r,o){let i=r?.usage,s=i?.inputTokens,a=i?.outputTokens,c=i?.cachedInputTokens??
|
|
1324
|
-
0,l=
|
|
1325
|
-
"string"?/^[a-z_]{1,32}$/.test(d)?d:"other":void 0;return {...e,outcome:"paired",naive:{cost:
|
|
1325
|
+
0,l=h=>typeof h=="number"&&Number.isSafeInteger(h)&&h>=0;if(!i||i.complete===false||!l(s)||!l(a)||!l(c)||s===0&&a===0)return {...e,outcome:"check_unmeasured"};let u=Math.min(c,s),d=r.finishReason,p=typeof d==
|
|
1326
|
+
"string"?/^[a-z_]{1,32}$/.test(d)?d:"other":void 0;return {...e,outcome:"paired",naive:{cost:ip({inputTokens:s,outputTokens:a,cachedInputTokens:u},o),inputTokens:s,cachedInputTokens:u,outputTokens:a,...p!==
|
|
1326
1327
|
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.
|
|
1327
|
-
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
|
|
1328
|
+
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 Ca=true,pp=new WeakSet;function jb(t){typeof t=="object"&&t!==null&&pp.add(t);}function cp(t){return typeof t=="object"&&t!==null&&pp.has(t)}function lp(t,e){switch(t){case "none":return Bb();case "inv\
|
|
1328
1329
|
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\
|
|
1329
1330
|
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 \
|
|
1330
1331
|
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\
|
|
@@ -1332,96 +1333,96 @@ status: invalid)":"BiVelio license key is not valid (it does not verify). Check
|
|
|
1332
1333
|
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\
|
|
1333
1334
|
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\
|
|
1334
1335
|
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\
|
|
1335
|
-
license is not active. See https://savings.bivelio.com/dashboard/account${t?` (license status: ${t})`:""}`}}function
|
|
1336
|
+
license is not active. See https://savings.bivelio.com/dashboard/account${t?` (license status: ${t})`:""}`}}function Bb(){return "BiVelio license required: none was configured. Pass { licenseKey } \u2014 t\
|
|
1336
1337
|
he signed token from your subscription, verified offline. This published package has no unlicensed mode. To try it without paying, the free Measure license (no card) runs the layer in shadow mode. Cop\
|
|
1337
|
-
y your key and a ready-to-paste snippet at https://savings.bivelio.com/dashboard/install (license status: none)"}function
|
|
1338
|
+
y your key and a ready-to-paste snippet at https://savings.bivelio.com/dashboard/install (license status: none)"}function zb(){return "licenseGate must implement isActive(): a gate that cannot prove th\
|
|
1338
1339
|
e license is live is refused. In this published package an injected gate is not a licensing path at all \u2014 pass { licenseKey } instead, from https://savings.bivelio.com/dashboard/install (license statu\
|
|
1339
|
-
s: invalid)"}var
|
|
1340
|
-
this.config=e,e.silenceWarnings===true&&
|
|
1341
|
-
verjaDeCascada=new
|
|
1342
|
-
precio:o=>this.precioConocido(o),contrato:(o,i)=>
|
|
1343
|
-
this.comprobador.decidir(e,n,r):n}cerrarVerificacion(){this.comprobador?.cerrar();}async generate(e){this.assertLicensed(),
|
|
1344
|
-
r;try{r=await this.generateOptimized(e,n);}catch(o){if(o instanceof
|
|
1345
|
-
e,o),"fail-open")}return this.conVerificacion(e,r,"optimizado")}generateStream(e,n={},r){let o;try{o=new
|
|
1346
|
-
ejecutarStream(e,o,r),o.handle}async ejecutarStream(e,n,r){try{if(r&&await r,n.abortado)throw new
|
|
1347
|
-
e);n.completar(a,{vivo:!1,motivo:o});return}this.assertLicensed(),
|
|
1348
|
-
if(a instanceof
|
|
1340
|
+
s: invalid)"}var Vo=class{deps;config;now;generateId;contratosQueIncumplen;verjaDeCache=new _o;espejoDeCache=new kn;verjaDeCascada;memoriaDelCodebook=new $o;referenciasDeLider=new WeakMap;memoriaDeSombra=new Bo;noReproducibles=new WeakSet;negativasSinCobro=new WeakSet;comprobador;constructor(e,n={}){
|
|
1341
|
+
this.config=e,e.silenceWarnings===true&&ll(e.provider),this.deps=Ro(e),this.now=e.now??(()=>Date.now()),this.generateId=e.generateId??(()=>Pt()),this.contratosQueIncumplen=e.constraintMemory??new Set,this.
|
|
1342
|
+
verjaDeCascada=new Oo(e.modelCascade?.exploration!=null?{exploracion:e.modelCascade.exploration}:{});let r=qo(e.verification);this.comprobador=r.activo&&n.verificacion?new Uo({ajustes:r,provider:e.provider,
|
|
1343
|
+
precio:o=>this.precioConocido(o),contrato:(o,i)=>Fb(o,i),now:this.now,sumidero:n.verificacion,avisar:(o,i)=>this.avisar(o,i)}):void 0;}conVerificacion(e,n,r){return n.report.measure?n:this.comprobador?
|
|
1344
|
+
this.comprobador.decidir(e,n,r):n}cerrarVerificacion(){this.comprobador?.cerrar();}async generate(e){this.assertLicensed(),Fs(e),e=this.conPalancasPorDefecto(e);let n={llamadas:0,falloDelProveedor:false,sinContador:0},
|
|
1345
|
+
r;try{r=await this.generateOptimized(e,n);}catch(o){if(o instanceof Ke||this.config.failOpen===false||n.falloDelProveedor||n.llamadas>0||cp(o))throw o;return this.conVerificacion(e,await this.failOpenDirect(
|
|
1346
|
+
e,o),"fail-open")}return this.conVerificacion(e,r,"optimizado")}generateStream(e,n={},r){let o;try{o=new or(this.now,n?.signal);}catch(i){let s=new or(this.now);return s.fallar(i),s.handle}return this.
|
|
1347
|
+
ejecutarStream(e,o,r),o.handle}async ejecutarStream(e,n,r){try{if(r&&await r,n.abortado)throw new Te(!1);e=this.conPalancasPorDefecto(e);let o=this.motivoDeEntregaEntera(e);if(o){let a=await this.generate(
|
|
1348
|
+
e);n.completar(a,{vivo:!1,motivo:o});return}this.assertLicensed(),Fs(e),n.entrarEnVivo();let i={llamadas:0,falloDelProveedor:!1,sinContador:0},s;try{s=await this.generateOptimized(e,i,n.sumidero);}catch(a){
|
|
1349
|
+
if(a instanceof Ke||a instanceof Te)throw a;if(n.sumidero.senal.aborted)throw new Te(i.llamadas>0);if(this.config.failOpen===!1||i.falloDelProveedor||i.llamadas>0||cp(a))throw a;let c=this.conVerificacion(
|
|
1349
1350
|
e,await this.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:"\
|
|
1350
1351
|
shortcut"});}catch(o){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.
|
|
1351
1352
|
semanticCacheDefault,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){
|
|
1352
1353
|
return e.response?.schema!=null?"output-contract":e.savings?.deferrable===true?"deferrable":typeof this.config.provider.generateStream!="function"?"provider-without-streaming":null}async llamarProveedor(e,n){
|
|
1353
1354
|
n.llamadas+=1;let r;try{r=await this.config.provider.generate(e);}catch(o){throw n.falloDelProveedor=true,o}return r.usage.complete===false&&(n.sinContador+=1),r}async llamarProveedorEnStream(e,n,r){if(r.senal.
|
|
1354
|
-
aborted)throw new
|
|
1355
|
-
s.delta,r.texto(s.delta));else if(s.type==="done"){i=s.response;break}}}catch(s){throw r.senal.aborted?new
|
|
1355
|
+
aborted)throw new Te(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+=
|
|
1356
|
+
s.delta,r.texto(s.delta));else if(s.type==="done"){i=s.response;break}}}catch(s){throw r.senal.aborted?new Te(true):(n.falloDelProveedor=true,s)}if(!i)throw r.senal.aborted?new Te(true):(n.falloDelProveedor=
|
|
1356
1357
|
true,new Error(`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-text\
|
|
1357
1358
|
o-distinto:${this.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 \
|
|
1358
|
-
is reported and cached. Its generateStream must end with a done whose response.text equals the concatenated deltas.`),i=
|
|
1359
|
-
let l=e.savings?.standalone===true&&
|
|
1360
|
-
colocacion:null},p=
|
|
1359
|
+
is reported and cached. Its generateStream must end with a done whose response.text equals the concatenated deltas.`),i=il(i,{...i,text:o})),r.sirvioEnVivo=true,i}decidirMarcadoDeCache(e,n,r,o,i,s,a,c=null){
|
|
1360
|
+
let l=e.savings?.standalone===true&&Lt(n,$t(this.config.provider))?Ji(n):null,u=l!==null,d={marcar:false,huella:"",claveDeVerja:"",mensajesDePrefijo:0,cacheWriteMultiplier:1,explicita:u,explicitaPorColocador:false,
|
|
1361
|
+
colocacion:null},p=Ra(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 tha\
|
|
1361
1362
|
t does not discount 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 pr\
|
|
1362
1363
|
efix cannot hit. 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 trav\
|
|
1363
1364
|
el is decided by a non-deterministic probe, so the tool block \u2014 which renders first \u2014 varies across requests that would share a prefix fingerprint. Marking would pay the 1.25x write premium for a pref\
|
|
1364
|
-
ix that cannot hit. Turn tool discovery off to reclaim the prefix cache."}),d;let
|
|
1365
|
-
marcado;
|
|
1365
|
+
ix that cannot hit. Turn tool discovery off to reclaim the prefix cache."}),d;let h=null;if(this.config.cacheBreakpoints==="auto"&&!u){let C=this.colocarConEspejo(e,n,r,o,s,p,a,c);if("marcado"in C)return C.
|
|
1366
|
+
marcado;h=C.observacion;}let f=p.cacheWriteMultiplier>1&&!u,m=f?Zb(r):true,g=Ao(r);if(f&&s>g&&!m&&(a.record("prefix-cache-history","deferred",{reason:`first follow-up of this conversation: nothing shows \
|
|
1366
1367
|
the history will be sent again, and writing it costs ${(p.cacheWriteMultiplier-1).toFixed(2)}x of its tokens that only a later turn can recover. The history is marked from the next turn or tool-loop s\
|
|
1367
|
-
tep on.`}),s=g),s<=0){let
|
|
1368
|
-
e),v=this.tokensFor(this.assemblePromptText(r,o.tools),e),x=
|
|
1369
|
-
|
|
1370
|
-
...u?{mode:"explicit"}:{}}),S.marcar?{marcar:true,huella:x,claveDeVerja:
|
|
1368
|
+
tep on.`}),s=g),s<=0){let C=f&&m?this.prefijoDeHerramientas(e,n,r,o.tools,p,a):null;return C?{...C,colocacion:h}:{...d,colocacion:h}}let b=r.slice(0,s),y=this.tokensFor(this.assemblePromptText(b,o.tools),
|
|
1369
|
+
e),v=this.tokensFor(this.assemblePromptText(r,o.tools),e),x=X(de({model:n,tools:(o.tools??[]).map(C=>C.id),prefijo:b.map(C=>`${C.role}:${C.content}`)})),E=u?`${x}|explicit`:x,S=this.verjaDeCache.decidir(
|
|
1370
|
+
E,{totalTokens:v,stablePrefixTokens:y,tier:l??p});return a.record("prefix-cache",S.marcar?"marked":"skipped",{reason:S.razon,stablePrefixTokens:y,breakEvenHitRate:S.umbral,observedHitRate:S.observada,
|
|
1371
|
+
...u?{mode:"explicit"}:{}}),S.marcar?{marcar:true,huella:x,claveDeVerja:E,mensajesDePrefijo:s,cacheWriteMultiplier:p.cacheWriteMultiplier,explicita:u,explicitaPorColocador:false,colocacion:h}:{...d,colocacion:h}}prefijoDeHerramientas(e,n,r,o,i,s){
|
|
1371
1372
|
let a=i.minimumCacheTokens;if(o.length===0||a==null)return null;let c=this.tokensFor(this.assemblePromptText([],o),e);if(c<a)return s.record("prefix-cache","skipped",{reason:`the tool catalogue (${c} \
|
|
1372
|
-
tokens) is below this model's minimum cacheable prefix (${a}): the provider would not cache it`,stablePrefixTokens:c}),null;let l=
|
|
1373
|
-
|
|
1373
|
+
tokens) is below this model's minimum cacheable prefix (${a}): the provider would not cache it`,stablePrefixTokens:c}),null;let l=X(de({model:n,tools:o.map(d=>d.id),prefijo:[]})),u=this.verjaDeCache.decidir(
|
|
1374
|
+
l,{totalTokens:this.tokensFor(this.assemblePromptText(r,o),e),stablePrefixTokens:c,tier:i});return s.record("prefix-cache",u.marcar?"marked":"skipped",{reason:u.razon,boundary:"tools",stablePrefixTokens:c,
|
|
1374
1375
|
breakEvenHitRate:u.umbral,observedHitRate:u.observada}),u.marcar?{marcar:true,huella:l,claveDeVerja:l,mensajesDePrefijo:0,cacheWriteMultiplier:i.cacheWriteMultiplier,explicita:false,explicitaPorColocador:false}:
|
|
1375
|
-
null}colocarConEspejo(e,n,r,o,i,s,a,c=null){let{tramoOpenAI:l,conPrima:u}=this.primasDelColocador(e,n,s);if(!u&&!l)return {observacion:null};let d=
|
|
1376
|
-
huellas??this.huellasDelColocador(e,n,r,o.tools),
|
|
1377
|
-
...p>d?{H:p}:{},T:
|
|
1376
|
+
null}colocarConEspejo(e,n,r,o,i,s,a,c=null){let{tramoOpenAI:l,conPrima:u}=this.primasDelColocador(e,n,s);if(!u&&!l)return {observacion:null};let d=Ao(r),p=Math.max(d,Math.min(i,r.length)),h=r.length,f=c?.
|
|
1377
|
+
huellas??this.huellasDelColocador(e,n,r,o.tools),m=f[d],g=c?.clase===m?c:null,b=g?.espejo??this.espejoDeCache,y=this.now(),v=b.observar(m,f,y),x=b.estadistica(m,y),E=g?{mirrorStore:g.estado}:{},S={S:d,
|
|
1378
|
+
...p>d?{H:p}:{},T:h},C=q=>this.tokensFor(this.assemblePromptText(r.slice(0,q),o.tools),e),A={clase:m,huellas:f,tramos:S,coincidencia:v,enviada:y,...g?{conAlmacen:true}:{}};if(l){let q=id({estadistica:x,
|
|
1378
1379
|
tramo:l,hayHistorial:p>d});a.record("prefix-cache-placement",q.explicita?"explicit":"provider-default",{reason:q.razon,breakEvenReuseRate:q.equilibrio,continuedWithin30m:x.T.en30m,samples:x.T.muestras30m,
|
|
1379
|
-
...
|
|
1380
|
-
huella:"",claveDeVerja:"",mensajesDePrefijo:0,cacheWriteMultiplier:1,explicita:true,explicitaPorColocador:true,colocacion:{...
|
|
1381
|
-
|
|
1382
|
-
observada,mode:"explicit"}),{marcado:{marcar:
|
|
1383
|
-
explicitaPorColocador:true,colocacion:{...
|
|
1384
|
-
R:null,tokens:
|
|
1385
|
-
{reason:
|
|
1386
|
-
T.muestras5m,providerConfirmedReads:`${x.confirmadas}/${x.predichas}`,...
|
|
1387
|
-
claveDeVerja:"",mensajesDePrefijo:0,cacheWriteMultiplier:1,explicita:false,explicitaPorColocador:false,colocacion:O}};let
|
|
1388
|
-
cola?"+T":""}@${
|
|
1389
|
-
cola?
|
|
1380
|
+
...E});let J={...A,cola:!q.explicita,ttl:"5m",ultimo:q.explicita?null:"T",indiceDelUltimo:q.explicita?null:h};if(!q.explicita)return {observacion:J};let Y=q.historial?p:d;if(Y<=0)return {marcado:{marcar:false,
|
|
1381
|
+
huella:"",claveDeVerja:"",mensajesDePrefijo:0,cacheWriteMultiplier:1,explicita:true,explicitaPorColocador:true,colocacion:{...J,ultimo:null,indiceDelUltimo:null}}};let B=Y===d?"S":"H",Re=`${m}|explicit|${B}`,
|
|
1382
|
+
ee=this.verjaDeCache.decidir(Re,{totalTokens:C(h),stablePrefixTokens:C(Y),tier:l});return a.record("prefix-cache",ee.marcar?"marked":"skipped",{reason:ee.razon,breakEvenHitRate:ee.umbral,observedHitRate:ee.
|
|
1383
|
+
observada,mode:"explicit"}),{marcado:{marcar:ee.marcar,huella:ee.marcar?this.huellaDelPrefijo(n,o.tools,r,Y):"",claveDeVerja:ee.marcar?Re:"",mensajesDePrefijo:ee.marcar?Y:0,cacheWriteMultiplier:1,explicita:true,
|
|
1384
|
+
explicitaPorColocador:true,colocacion:{...J,ultimo:ee.marcar?B:null,indiceDelUltimo:ee.marcar?Y:null}}}}let T={S:d>0?C(d):0,H:p>d?C(p):0,T:C(h)},R=qn(n),M=od({estadistica:x,tramo:s,primaDeUnaHora:R>s.cacheWriteMultiplier?
|
|
1385
|
+
R:null,tokens:T,hayHistorial:p>d,lecturaPrevista:()=>v?C(v.indice):0}),w=M.historial&&p>d?p:d,P=M.cola?"T":w>0?w===p&&p>d?"H":"S":null,$=M.cola?h:w>0?w:null;a.record("prefix-cache-placement",P??"none",
|
|
1386
|
+
{reason:M.razon||"fixed placement",boundary:w===0?"none":w===d?"system":"history",tail:M.cola,ttl:M.ttl,breakEvenReuseRate:M.equilibrio,historyReusedWithin5m:x.H.en5m,continuedWithin5m:x.T.en5m,samples:x.
|
|
1387
|
+
T.muestras5m,providerConfirmedReads:`${x.confirmadas}/${x.predichas}`,...E});let O={...A,cola:M.cola,ttl:M.ttl,ultimo:null,indiceDelUltimo:null};if(P==null||$==null)return {marcado:{marcar:false,huella:"",
|
|
1388
|
+
claveDeVerja:"",mensajesDePrefijo:0,cacheWriteMultiplier:1,explicita:false,explicitaPorColocador:false,colocacion:O}};let D=M.ttl==="1h"?{...s,cacheWriteMultiplier:R}:s,F=`${m}|${w===0?"-":w===d?"S":"H"}${M.
|
|
1389
|
+
cola?"+T":""}@${M.ttl}`,j=this.verjaDeCache.decidir(F,{totalTokens:T.T,stablePrefixTokens:M.cola?T.T:w===d?T.S:T.H,tier:D});return a.record("prefix-cache",j.marcar?"marked":"skipped",{reason:j.razon,stablePrefixTokens:M.
|
|
1390
|
+
cola?T.T:w===d?T.S:T.H,breakEvenHitRate:j.umbral,observedHitRate:j.observada}),j.marcar?{marcado:{marcar:true,huella:this.huellaDelPrefijo(n,o.tools,r,w),claveDeVerja:F,mensajesDePrefijo:w,cacheWriteMultiplier:s.
|
|
1390
1391
|
cacheWriteMultiplier,explicita:false,explicitaPorColocador:false,colocacion:{...O,ultimo:P,indiceDelUltimo:$}}}:{marcado:{marcar:false,huella:"",claveDeVerja:"",mensajesDePrefijo:0,cacheWriteMultiplier:1,explicita:false,
|
|
1391
1392
|
explicitaPorColocador:false,colocacion:O}}}apuntarEnElEspejo(e,n,r,o=this.espejoDeCache,i={}){let s=e.colocacion,a=n.complete!==false,c=Math.max(0,n.cachedInputTokens??0),l=Math.max(0,n.cacheWriteInputTokens??
|
|
1392
|
-
0),u=s.ultimo!=null&&s.indiceDelUltimo!=null,d=s.coincidencia?.indice;if(a&&u&&s.coincidencia&&d!==void 0&&s.indiceDelUltimo>=d&&s.indiceDelUltimo-d<
|
|
1393
|
-
s.clase,s.coincidencia,c);let
|
|
1394
|
-
coincidencia.posicionDelProveedor,providerCacheRead:c,confirmed:
|
|
1395
|
-
apagada&&!p.apagada?{reason:`the provider's counter confirmed only ${
|
|
1393
|
+
0),u=s.ultimo!=null&&s.indiceDelUltimo!=null,d=s.coincidencia?.indice;if(a&&u&&s.coincidencia&&d!==void 0&&s.indiceDelUltimo>=d&&s.indiceDelUltimo-d<td){let p=o.estadistica(s.clase,s.enviada);o.verificar(
|
|
1394
|
+
s.clase,s.coincidencia,c);let h=o.estadistica(s.clase,s.enviada);if(h.predichas>p.predichas){let f=h.confirmadas>p.confirmadas,m=i.diagnostico;r.record("prefix-cache-placement","verified",{predictedRead:s.
|
|
1395
|
+
coincidencia.posicionDelProveedor,providerCacheRead:c,confirmed:f,...!f&&m?{cacheMissReason:m.missReason,...m.missedInputTokens!==void 0?{cacheMissedInputTokensEstimate:m.missedInputTokens}:{}}:{},...h.
|
|
1396
|
+
apagada&&!p.apagada?{reason:`the provider's counter confirmed only ${h.confirmadas} of ${h.predichas} predicted cache reads: this traffic goes back to the fixed placement`}:{}});}}o.registrar({clase:s.
|
|
1396
1397
|
clase,huellas:s.huellas,tramos:s.tramos,enviada:s.enviada,ultimoMarcado:u?s.ultimo:null,posicionDelProveedor:a&&u?c+l:null,ttl:s.ttl,idDelProveedor:this.config.cacheMissDiagnostics===true&&u?i.id??null:
|
|
1397
|
-
null});}async apuntarEnElAlmacen(e,n,r,o){let i=this.config.cacheBreakpointStore,s=e.colocacion,a=
|
|
1398
|
-
uld not read the placement store (${
|
|
1398
|
+
null});}async apuntarEnElAlmacen(e,n,r,o){let i=this.config.cacheBreakpointStore,s=e.colocacion,a=Qs(s.clase),c;try{c=await i.get(a);}catch(u){r.record("prefix-cache-placement","store-error",{reason:`co\
|
|
1399
|
+
uld not read the placement store (${dp(u)}), so this request was not recorded`});return}let l=new kn;if(c!=null&&l.importarClase(s.clase,c)==="newer"){r.record("prefix-cache-placement","store-error",{
|
|
1399
1400
|
reason:"the placement store holds a state written by a newer SDK version; left untouched"});return}l.observar(s.clase,s.huellas,s.enviada),this.apuntarEnElEspejo(e,n,r,l,o);try{await i.set(a,l.exportarClase(
|
|
1400
|
-
s.clase),
|
|
1401
|
-
!o.setIsStable||i)return null;let s
|
|
1402
|
-
primasDelColocador(e,n,a);if(!l&&!c)return null;let u=this.huellasDelColocador(e,n,r,o.tools),d=u[
|
|
1403
|
-
d,
|
|
1404
|
-
o);return {tramoOpenAI:i?
|
|
1405
|
-
return
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
modeloServido:e.model,candidato:l,enruta:false,elegible:false,razon:c.razon,fuerza:c.fuerza,bucket:
|
|
1410
|
-
null,tasaDeMuestreo:0},g=v=>(o.record("model-cascade",s==="on"?"not routed":"not eligible",{reason:v}),{...
|
|
1401
|
+
s.clase),rd);}catch(u){r.record("prefix-cache-placement","store-error",{reason:`could not write the placement store (${dp(u)})`});}}async cargarEspejo(e,n,r,o,i){if(this.config.cacheBreakpoints!=="auto"||
|
|
1402
|
+
!o.setIsStable||i)return null;let s=$t(this.config.provider);if(e.savings?.standalone===true&&Lt(n,s))return null;let a=Ra(n,this.config.compressionEconomics);if(!a)return null;let{tramoOpenAI:c,conPrima:l}=this.
|
|
1403
|
+
primasDelColocador(e,n,a);if(!l&&!c)return null;let u=this.huellasDelColocador(e,n,r,o.tools),d=u[Ao(r)],p=new kn,h;try{let f=await this.config.cacheBreakpointStore.get(Qs(d));h=f==null?"empty":p.importarClase(
|
|
1404
|
+
d,f)==="loaded"?"loaded":"unreadable";}catch{h="unavailable";}return {clase:d,huellas:u,espejo:p,estado:h}}primasDelColocador(e,n,r){let o=$t(this.config.provider),i=e.savings?.standalone===void 0&&Lt(n,
|
|
1405
|
+
o);return {tramoOpenAI:i?Ji(n):null,conPrima:r.cacheWriteMultiplier>1&&!i}}huellasDelColocador(e,n,r,o){let i=de({model:n,tools:(o??[]).map(s=>s.id),schema:e.response?.schema??null});return nd(i,r)}huellaDelPrefijo(e,n,r,o){
|
|
1406
|
+
return X(de({model:e,tools:(n??[]).map(i=>i.id),prefijo:r.slice(0,o).map(i=>`${i.role}:${i.content}`)}))}decidirCascada(e,n,r,o,i=this.now()){let s=r.modelCascade??"off",a={modo:"off",modeloPedido:e.model,
|
|
1407
|
+
modeloServido:e.model,candidato:null,enruta:false,elegible:false,razon:"the model cascade is off",fuerza:"none",bucket:"",economia:null,observada:null,muestras:0,precioBarato:null,tasaDeMuestreo:0};if(s==="\
|
|
1408
|
+
off")return a;let c=ld({schema:e.response?.schema,tools:e.tools}),l=cd(e.model,this.config.modelCascade?.pairs??ea),u=this.precioConocido(e.model,i),d=l?this.precioConocido(l,i):void 0,p=ad(d,u),h=X(de(
|
|
1409
|
+
{tenant:n.tenantId,scope:n.authorizationScope,contract:n.contractId,schema:n.schemaVersion,fuerte:e.model,barato:l,tools:n.toolsetHash})),f=this.verjaDeCascada.estado(h),m={modo:s,modeloPedido:e.model,
|
|
1410
|
+
modeloServido:e.model,candidato:l,enruta:false,elegible:false,razon:c.razon,fuerza:c.fuerza,bucket:h,economia:p,observada:f&&f.enrutadas>0?f.escaladas/f.enrutadas:null,muestras:f?.enrutadas??0,precioBarato:d??
|
|
1411
|
+
null,tasaDeMuestreo:0},g=v=>(o.record("model-cascade",s==="on"?"not routed":"not eligible",{reason:v}),{...m,razon:v});if(!c.elegible)return g(c.razon);if(!l)return g(`no cheaper model is paired with \
|
|
1411
1412
|
"${e.model}"; declare one in createSavingsLayer({ modelCascade: { pairs } }) if your provider has one`);if(!p){let v=[...this.precioConocido(e.model,i)?[]:[e.model],...d?[]:[l]];return g(`no known pri\
|
|
1412
1413
|
ce for ${v.map(x=>`"${x}"`).join(" or ")||"this pair"}, so the arithmetic that decides whether routing pays cannot be run. The illustrative default price is deliberately NOT used here: it would approv\
|
|
1413
1414
|
e a pair nobody has priced. Pass \`costModels\` for both models to enable the cascade for them`)}if(!p.viable)return g(p.razon);let b=Math.min(1,Math.max(0,this.config.modelCascade?.shadowSampleRate??
|
|
1414
|
-
0));if(s==="shadow")return o.record("model-cascade","shadow",{candidateModel:l,costRatio:p.r,breakEvenEscalationRate:p.equilibrio,verifier:c.fuerza,workload:
|
|
1415
|
-
the model you asked for. The escalation rate is not a quality score \u2014 a well-formed answer with wrong content passes the verifier."}),{...
|
|
1416
|
-
verjaDeCascada.decidir(
|
|
1415
|
+
0));if(s==="shadow")return o.record("model-cascade","shadow",{candidateModel:l,costRatio:p.r,breakEvenEscalationRate:p.equilibrio,verifier:c.fuerza,workload:h,note:"measuring only: the request goes to\
|
|
1416
|
+
the model you asked for. The escalation rate is not a quality score \u2014 a well-formed answer with wrong content passes the verifier."}),{...m,elegible:true,razon:c.razon,tasaDeMuestreo:b};let y=this.
|
|
1417
|
+
verjaDeCascada.decidir(h,p);return y.enrutar?(this.avisar(`cascada:${e.model}->${l}`,`[bv-sala] model cascade ON: requests for "${e.model}" may be answered by "${l}" when a deterministic gate accepts \
|
|
1417
1418
|
the answer. The gate checks the SHAPE of the answer against your output contract, never its meaning, so a well-formed answer with wrong content is served and counted as a success. report.model always \
|
|
1418
1419
|
names the model that answered, and report.qualityStatus reads "bounded_degradation".`),o.record("model-cascade","routed",{candidateModel:l,costRatio:p.r,breakEvenEscalationRate:p.equilibrio,observedEscalationRate:y.
|
|
1419
|
-
observada,verifier:c.fuerza,workload:
|
|
1420
|
-
"off (gate)",{reason:y.razon,observedEscalationRate:y.observada,breakEvenEscalationRate:p.equilibrio}),{...
|
|
1421
|
-
this.assertLicensed();}exigirPalancas(){if(this.enSombra())throw new
|
|
1422
|
-
aid plan at ${
|
|
1423
|
-
return;let n=typeof e.status=="function"?e.status():void 0,r=typeof e.reason=="function"?e.reason():void 0;throw new
|
|
1424
|
-
this.config.silenceWarnings||
|
|
1420
|
+
observada,verifier:c.fuerza,workload:h,reason:y.razon}),{...m,modeloServido:l,enruta:true,elegible:true,razon:y.razon,observada:y.observada,muestras:y.muestras,tasaDeMuestreo:0}):(o.record("model-cascade",
|
|
1421
|
+
"off (gate)",{reason:y.razon,observedEscalationRate:y.observada,breakEvenEscalationRate:p.equilibrio}),{...m,elegible:true,razon:y.razon,observada:y.observada,muestras:y.muestras})}devOpen(){return false}exigirLicencia(){
|
|
1422
|
+
this.assertLicensed();}exigirPalancas(){if(this.enSombra())throw new Ke(`[bvsala] Batches are a savings lever, and the Measure license runs the layer in shadow mode: no lever is applied. Upgrade to a p\
|
|
1423
|
+
aid plan at ${zo} to submit batches. (license status: measure)`,"measure")}assertLicensed(){if(this.devOpen())return;let e=this.config.licenseGate;if(e&&typeof e.isActive=="function"){if(e.isActive())
|
|
1424
|
+
return;let n=typeof e.status=="function"?e.status():void 0,r=typeof e.reason=="function"?e.reason():void 0;throw new Ke(lp(n,r),n)}throw e?new Ke(zb(),"invalid"):new Ke(lp("none"),"none")}avisar(e,n){
|
|
1425
|
+
this.config.silenceWarnings||Ee(e,n);}avisarDeTruncado(e,n,r,o,i){let s=G(e),a=lr(e)||"(no contractId)",c=i?" The layer has NOTED it: the next requests for this contract will carry their value limits w\
|
|
1425
1426
|
ritten into the prompt, which is the only thing that can fix it without touching your cap. If it still gets cut off, the task does not fit the contract: widen the schema and raise the cap with it.":"",
|
|
1426
1427
|
l=o===null?" The schema does not bound the response (no `maxLength`/`maxItems`), so there is no way to know in advance how much it needs: bound it and the cap stops being a guess.":s==null?` The contr\
|
|
1427
1428
|
act allows ~${o} tokens and this request declares no cap, so the cut came from a PROVIDER cap (the Anthropic API requires \`max_tokens\` and the adapter sends 4096 by default). Declare \`maxOutputTokens\`\
|
|
@@ -1440,348 +1441,349 @@ er again. It is not on by default because it needs an embedder, which is your ow
|
|
|
1440
1441
|
la] This layer was given a `semanticCacheStore`, but this request does not ask for it, so the semantic cache was neither consulted nor written: every reworded question is paid to the provider and a ca\
|
|
1441
1442
|
librating cache collects no labels. Passing the cache to `createSavingsLayer` does not switch it on. Ask for it per request with `savings: { semanticCache: true }`, or on every request with `createSav\
|
|
1442
1443
|
ingsLayer({ semanticCacheStore, semanticCacheDefault: true })` \u2014 preferably with a cache built with `calibration`. If you switch it on per request on purpose, set `semanticCacheDefault: false` to say \
|
|
1443
|
-
so and this warning goes away."));}async generateOptimized(e,n={llamadas:0,falloDelProveedor:false,sinContador:0},r=null){if(this.assertLicensed(),this.enSombra())return this.generarEnSombra(e,n,r);let o=new
|
|
1444
|
-
this.now),i=new
|
|
1444
|
+
so and this warning goes away."));}async generateOptimized(e,n={llamadas:0,falloDelProveedor:false,sinContador:0},r=null){if(this.assertLicensed(),this.enSombra())return this.generarEnSombra(e,n,r);let o=new pt(
|
|
1445
|
+
this.now),i=new at,s=nn(e),a=It(s),c=e.savings??{};this.avisarDePalancasSinConfigurar(c),c.semanticCache&&c.semanticCache!=="include-agentic"&&this.deps.semanticCache&&up(s,a)&&this.avisar("semantica-\
|
|
1445
1446
|
agentica-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 \
|
|
1446
1447
|
neither consulted nor written for it. That is the default: two runs of an agent loop can differ only in what a tool returned, and the guard under the similarity score cannot see that. The exact cache \
|
|
1447
1448
|
is unaffected. To include agentic requests, set `savings.semanticCache: "include-agentic"` after measuring it on your own traffic.');let l=this.now(),u=this.decidirCascada(e,s,c,o,l),d=this.costModelFor(
|
|
1448
1449
|
u.modeloServido,l);o.record("canonicalize","done",{tenant:s.tenantId,contract:s.contractId}),o.record("policy",a.reasons.join("; ")||"no restrictions",{allowExactCache:a.allowExactCache,allowSemanticCache:a.
|
|
1449
|
-
allowSemanticCache,...a.sensitiveTopic!==null?{skipReason:"sensitive_topic",sensitiveTopic:a.sensitiveTopic}:{}});let p=this.tokensFor(this.assembleBaselinePrompt(e),e),
|
|
1450
|
-
baselineInput=p,i.baselineOutput=
|
|
1451
|
-
lver",v.resolver,{avoided:true}),this.finish(e,s,{text:v.text,data:v.data,storedAtMs:this.now()},"deterministic",i,d,o,
|
|
1452
|
-
model}))}let g=
|
|
1453
|
-
tored answer reads as a refusal written as text (text_refusal); it is not replayed",{skipReason:"text_refusal",rule:x});let
|
|
1454
|
-
cascada:u,toggles:c,huella:
|
|
1455
|
-
|
|
1456
|
-
{outputNotCredited:S.outputNotCredited}:{}}),this.finish(e,s,
|
|
1450
|
+
allowSemanticCache,...a.sensitiveTopic!==null?{skipReason:"sensitive_topic",sensitiveTopic:a.sensitiveTopic}:{}});let p=this.tokensFor(this.assembleBaselinePrompt(e),e),h=zs(e),f,m=()=>f??=ma(e);if(i.
|
|
1451
|
+
baselineInput=p,i.baselineOutput=h,i.baselineTools=e.tools?.length??0,c.deterministicResolvers!==false){let v=this.deps.resolvers.try(s);if(v)return i.avoidCall(p,this.tokensFor(v.text,e)),o.record("reso\
|
|
1452
|
+
lver",v.resolver,{avoided:true}),this.finish(e,s,{text:v.text,data:v.data,storedAtMs:this.now()},"deterministic",i,d,o,ar(),cr(),void 0,void 0,void 0,void 0,void 0,this.informeDeCascada(u,{servedModel:e.
|
|
1453
|
+
model}))}let g=rn(s,{servedModel:u.modeloServido});if(a.allowExactCache&&c.exactCache!==false){let v=await this.deps.exactCache.get(g),x=v?ir(v.text):null;x!==null&&o.record("exact-cache","ignored: the s\
|
|
1454
|
+
tored answer reads as a refusal written as text (text_refusal); it is not replayed",{skipReason:"text_refusal",rule:x});let E=x===null?v:null;if(E){let S=this.creditoPorReferencia(Id(E.meta),{request:e,
|
|
1455
|
+
cascada:u,toggles:c,huella:m,texto:E.text,claveLeida:g,calidad:()=>{let C=e.response?.schema;return !C||be(E.data,C).valid}});return S.ok?i.avoidCallByReference(S.credit):(i.avoidCall(p,this.tokensFor(
|
|
1456
|
+
E.text,e)),i.referenceRejected=S.reason),o.record("exact-cache","hit",{ageMs:this.now()-E.storedAtMs,basis:S.ok?"reference":"estimated",...S.ok?{}:{referenceRejected:S.reason},...S.ok&&S.outputNotCredited?
|
|
1457
|
+
{outputNotCredited:S.outputNotCredited}:{}}),this.finish(e,s,E,"exact",i,d,o,ar(),cr(),this.now()-E.storedAtMs,void 0,void 0,void 0,void 0,this.informeDeCascada(u))}o.record("exact-cache","miss");}let b=An(
|
|
1457
1458
|
s,{servedModel:u.modeloServido,deferrable:c.deferrable===true,toolDiscovery:c.toolDiscovery===true,...G(e)!=null?{maxOutputTokens:G(e)}:{}}),y=async()=>{try{return await this.expensivePath(n,e,s,a,c,i,d,o,
|
|
1458
|
-
g,p,u,r,l)}catch(v){throw (n.falloDelProveedor||n.llamadas>0)&&
|
|
1459
|
-
let
|
|
1460
|
-
|
|
1461
|
-
noReproducibles.has(v))return o.record("singleflight","not coalesced: the answer in flight cannot be replayed"),y();if(x){o.record("singleflight","coalesced",{key:b});let
|
|
1462
|
-
referenciasDeLider.get(v)??"absent",{request:e,cascada:u,toggles:c,huella:
|
|
1463
|
-
ed"});return this.asCoalescedFollower(v,p,this.tokensFor(v.text??"",e),d,e,
|
|
1464
|
-
i.semanticCache!=="include-agentic"&&this.deps.semanticCache&&
|
|
1465
|
-
i.semanticCache&&this.deps.semanticCache&&!
|
|
1466
|
-
deps.semanticCache,
|
|
1467
|
-
tored answer reads as a refusal written as text (text_refusal); it is not replayed",{skipReason:"text_refusal",rule:U});let H=U===null?
|
|
1468
|
-
answer.text,n)),c.record("semantic-cache","hit",{confidence:H.confidence,similarity:H.similarity}),this.finish(n,r,H.record.answer,"semantic",s,a,c,
|
|
1469
|
-
this.informeDeCascada(d,{servedModel:n.model}),void 0,void 0,void 0,{semantico:H});c.record("semantic-cache","miss",
|
|
1459
|
+
g,p,u,r,l)}catch(v){throw (n.falloDelProveedor||n.llamadas>0)&&jb(v),v}};if(a.allowSingleflight&&c.singleflight!==false){if(r){let E=this.deps.singleflight,S=typeof E.join=="function"?E.join(b):void 0;if(S){
|
|
1460
|
+
let C=await S;return this.noReproducibles.has(C)?(o.record("singleflight","not coalesced: the answer in flight cannot be replayed"),y()):(o.record("singleflight","coalesced",{key:b}),this.asCoalescedFollower(
|
|
1461
|
+
C,p,this.tokensFor(C.text??"",e),d,e))}return o.record("singleflight","skipped (streaming: a streamed request never leads)"),y()}let{value:v,coalesced:x}=await this.deps.singleflight.run(b,y);if(x&&this.
|
|
1462
|
+
noReproducibles.has(v))return o.record("singleflight","not coalesced: the answer in flight cannot be replayed"),y();if(x){o.record("singleflight","coalesced",{key:b});let E=this.creditoPorReferencia(this.
|
|
1463
|
+
referenciasDeLider.get(v)??"absent",{request:e,cascada:u,toggles:c,huella:m,texto:v.text??"",claveLeida:void 0,calidad:()=>v.report.constraints.structurallyValid!==false&&v.report.qualityStatus!=="reject\
|
|
1464
|
+
ed"});return this.asCoalescedFollower(v,p,this.tokensFor(v.text??"",e),d,e,E)}return v}return y()}async expensivePath(e,n,r,o,i,s,a,c,l,u,d,p,h){let f=this.entitled("semantic_cache"),m=null;if(i.semanticCache&&
|
|
1465
|
+
i.semanticCache!=="include-agentic"&&this.deps.semanticCache&&up(r,o)&&c.record("semantic-cache",'skipped: agentic traffic (default); set savings.semanticCache: "include-agentic" to include it'),o.allowSemanticCache&&
|
|
1466
|
+
i.semanticCache&&this.deps.semanticCache&&!f&&c.record("semantic-cache","degraded: feature not included in this license"),o.allowSemanticCache&&i.semanticCache&&this.deps.semanticCache&&f){let I=this.
|
|
1467
|
+
deps.semanticCache,L=I.calibrated?await I.lookup(r,{agentic:o.isAgentic}):{hit:await I.find(r),probe:null},U=L.hit?ir(L.hit.record.answer.text):null;U!==null&&c.record("semantic-cache","ignored: the s\
|
|
1468
|
+
tored answer reads as a refusal written as text (text_refusal); it is not replayed",{skipReason:"text_refusal",rule:U});let H=U===null?L.hit:null;if(m=L.probe,H)return s.avoidCall(u,this.tokensFor(H.record.
|
|
1469
|
+
answer.text,n)),c.record("semantic-cache","hit",{confidence:H.confidence,similarity:H.similarity}),this.finish(n,r,H.record.answer,"semantic",s,a,c,ar(),cr(),H.ageMs,H.confidence,void 0,void 0,void 0,
|
|
1470
|
+
this.informeDeCascada(d,{servedModel:n.model}),void 0,void 0,void 0,{semantico:H});c.record("semantic-cache","miss",m?{calibration:m.reason,score:m.score}:void 0);}let g=i.router===false,b=g?ar():this.deps.
|
|
1470
1471
|
router.classify(r);c.record("router",b.executionClass,{confidence:b.confidence,reason:b.reason});let y=this.planearBusquedaNativa(n,i,b.executionClass,g,d,a,c),v=y?y.seleccion:g?this.deps.toolSelector.
|
|
1471
1472
|
passthrough(n.tools):this.deps.toolSelector.select(r.normalizedText,n.tools,b.executionClass,r.toolsetHash);if(y||(this.avisarDeHerramientasPodadas(n,i,v,b.executionClass,g,d,a),this.avisarDeCatalogoGrande(
|
|
1472
|
-
n,i,v,d,a)),s.actualTools=v.tools.length,v.droppedIds.length){let
|
|
1473
|
-
l-selector",v.reason,{dropped:v.droppedIds,eliminatedTokens:
|
|
1473
|
+
n,i,v,d,a)),s.actualTools=v.tools.length,v.droppedIds.length){let I=new Set(v.droppedIds),L=(n.tools??[]).filter(U=>I.has(U.id)).reduce((U,H)=>U+this.tokensFor(ur(H),n),0);s.eliminate(L),c.record("too\
|
|
1474
|
+
l-selector",v.reason,{dropped:v.droppedIds,eliminatedTokens:L});}s.baselineRetrieval=this.config.retriever?b.rounds:0;let x=await Mr({execution:b.executionClass,query:r.normalizedText,maxRounds:n.retrieval?.
|
|
1474
1475
|
maxRounds??b.rounds,maxDocuments:n.retrieval?.maxDocuments??5},{...this.config.retriever?{retriever:this.config.retriever}:{},...this.config.reranker?{reranker:this.config.reranker}:{}});s.actualRetrieval=
|
|
1475
|
-
x.rounds,x.retrievedCount>0&&c.record("retrieval",`kept ${x.keptCount}/${x.retrievedCount}`,{rounds:x.rounds});let
|
|
1476
|
+
x.rounds,x.retrievedCount>0&&c.record("retrieval",`kept ${x.keptCount}/${x.retrievedCount}`,{rounds:x.rounds});let E=cr(),S=[...n.messages],C=Ia(n.messages),A=false,T=x.docs.length>0?{role:"system",content:`\
|
|
1476
1477
|
Retrieved context \u2014 answer using only this evidence and cite sources by [id]:
|
|
1477
1478
|
|
|
1478
|
-
`+x.docs.map((
|
|
1479
|
-
${
|
|
1479
|
+
`+x.docs.map((I,L)=>`[${I.source??I.id??`doc${L+1}`}]
|
|
1480
|
+
${I.text}`).join(`
|
|
1480
1481
|
|
|
1481
|
-
`)}:null,R=
|
|
1482
|
-
structuredData!==void 0){let
|
|
1483
|
-
tokenizer}:{}});let U=this.tokensFor(
|
|
1484
|
-
`:"")+
|
|
1485
|
-
disabled; sent compact JSON"});}if(
|
|
1486
|
-
{},
|
|
1487
|
-
{}},H=0,re=0;for(let
|
|
1488
|
-
ue=0,Z=0,
|
|
1489
|
-
content}),
|
|
1490
|
-
tokensFor(this.assemblePromptText(
|
|
1491
|
-
compressorCostTokens});Z>=ue?
|
|
1492
|
-
|
|
1493
|
-
prefixRewritten:A}),s.compressionReport={originalTokens:ue,compressedTokens:Z,protectedSpans:H,fidelityPassed:true};}if(i.elision!==false&&o.allowElision&&this.entitled("tool_result_elision")){let
|
|
1494
|
-
indices.length>0){let
|
|
1495
|
-
s.elididoLocal+=U),c.record("elision","applied",{elided:
|
|
1496
|
-
ool_result over the age\xD7size threshold"});}let $=
|
|
1497
|
-
aded: feature not included in this license"),$&&o.allowCompression&&this.entitled("long_context_compression")){let
|
|
1498
|
-
compactados){let
|
|
1499
|
-
aplicadas)
|
|
1500
|
-
ied":"skipped",{compacted:
|
|
1501
|
-
cacheWriteMultiplier,cacheReadMultiplier:
|
|
1502
|
-
now and re-read on every later turn"});}let O=n.response?.schema,
|
|
1503
|
-
null;
|
|
1504
|
-
schemaTokensCompact:
|
|
1505
|
-
breakEvenOutputDeltaTokens:
|
|
1506
|
-
deps.constraintBackends):{backend:"none",reason:"no output contract"};c.record("constraints",j.backend,{reason:j.reason});let q=y?{tools:y.prefijo,setIsStable:v.setIsStable}:v,
|
|
1507
|
-
!y,Y=this.config.cacheBreakpointStore?await this.cargarEspejo(n,d.modeloServido,S,q,
|
|
1508
|
-
e.llamadas>0);let
|
|
1509
|
-
{},...F?{schema:F}:{},...G(n)!=null?{maxOutputTokens:G(n)}:{},...n.temperature!=null?{temperature:n.temperature}:{},...n.seed!=null?{seed:n.seed}:{},...n.reasoningEffort!=null?{reasoningEffort:n.
|
|
1510
|
-
{},...i.deferrable?{deferrable:true}:{},...B.explicita?{explicitCacheWrites:true}:{},...y?{toolSearch:y.plan}:{},constraintBackend:j.backend},
|
|
1511
|
-
mensajesDePrefijo,promptCacheKey:B.huella,...B.colocacion&&!B.explicita&&(B.colocacion.cola||B.colocacion.ttl!=="5m")?{cachePlacement:{tail:B.colocacion.cola,ttl:B.colocacion.ttl}}:
|
|
1512
|
-
true&&B.colocacion?{cacheDiagnostics:{previousMessageId:B.colocacion.coincidencia?.idDelProveedor??null}}:{}}:{}},
|
|
1513
|
-
|
|
1514
|
-
the cheaper tier had no capacity; repeated once at the standard tier and price, as configured with priceLevers.onCapacityError: "standard"'});let{deferrable:
|
|
1515
|
-
let
|
|
1516
|
-
resent?.results??0,resentTools:
|
|
1517
|
-
the adapter did not report what the search did"}),s.actualLlm+=1;let
|
|
1518
|
-
true,
|
|
1519
|
-
toolCalls?.length??0)>0});this.verjaDeCascada.registrar(d.bucket,!
|
|
1520
|
-
|
|
1521
|
-
1,
|
|
1522
|
-
outputTokens,
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
this.tokensFor(this.assemblePromptText(S,
|
|
1527
|
-
estimatorExact=this.estimatorEsExacto(n),
|
|
1528
|
-
0),s.nativeCacheMarkedByLayer=!
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
ttl==="1h"?
|
|
1532
|
-
"prefix-cache","measured",{cacheRead:
|
|
1533
|
-
B,
|
|
1534
|
-
{model:d.candidato,...
|
|
1535
|
-
toolCalls?.length??0)>0});this.verjaDeCascada.registrar(d.bucket,!H.acepta);let re=H.acepta?
|
|
1536
|
-
mple accepted":"sample escalated",{candidateModel:d.candidato,reason:H.motivo,sampleCost:
|
|
1537
|
-
ved. The escalation rate it feeds is a money figure, not a quality one"});}catch(
|
|
1538
|
-
String(
|
|
1539
|
-
|
|
1540
|
-
wrapped valid JSON in prose or a markdown fence; it was extracted locally instead of paying a repair call"})),!
|
|
1541
|
-
th",re=
|
|
1542
|
-
output can satisfy it, a retry is a wasted call",errors:
|
|
1543
|
-
NOT retried (it would be a paid call for the same failure). Fix the schema's `pattern`."),
|
|
1544
|
-
r-skipped",{reason:(
|
|
1545
|
-
same model would be refused, and may be billed, again",model:
|
|
1546
|
-
Z=
|
|
1547
|
-
in",maxOutputTokens:G(n)??null,outputTokens:
|
|
1548
|
-
{outcome:"skipped",skipReason:"output_truncated"};}else if(!
|
|
1482
|
+
`)}:null,R=lr(n),M=G(n),w=M!=null?Math.floor(M*3.2):null,P=this.contratosQueIncumplen.has(R)?Pa(n.response?.schema,"",w):"";if(P&&dr(S,{role:"system",content:`JSON limits (not API-enforced): ${P}`}),n.
|
|
1483
|
+
structuredData!==void 0){let I=JSON.stringify(n.structuredData),L=this.tokensFor(I,n);if(i.serialization!==false){E=this.deps.formatSelector.choose(n.structuredData,{model:n.model,...n.tokenizer?{tokenizer:n.
|
|
1484
|
+
tokenizer}:{}});let U=this.tokensFor(E.encoded+E.instruction,n);s.compress(L,U),dr(S,{role:"system",content:(E.instruction?E.instruction+`
|
|
1485
|
+
`:"")+E.encoded}),c.record("serialization",E.chosen,{reason:E.reason,jsonTokens:L,chosenTokens:U});}else dr(S,{role:"system",content:I}),c.record("serialization","json-compact",{reason:"format selector\
|
|
1486
|
+
disabled; sent compact JSON"});}if(T&&dr(S,T),(i.compression===true||i.compression==="auto")&&o.allowCompression&&this.config.compressor&&this.entitled("long_context_compression")){let I=this.config.compressionEconomics??
|
|
1487
|
+
{},L=No(n.model,I),U={compressorCostTokens:I.compressorCostTokens??0,...I.minimumContextTokens!=null?{minimumContextTokens:I.minimumContextTokens}:{},...I.minimumNetTokens!=null?{minimumNetTokens:I.minimumNetTokens}:
|
|
1488
|
+
{}},H=0,re=0;for(let fe of S)fe.role==="system"?H+=1:re+=this.tokensFor(fe.content,n);let ot=this.tokensFor(this.assemblePromptText(S,v.tools),n),pe=zn({...U,contextTokens:re,projectedEliminable:re}),
|
|
1489
|
+
ue=0,Z=0,Me=false,Ie=pe.reason;if(pe.compress){let fe=[];for(let te of S){if(te.role==="system"){fe.push(te);continue}let Pn=this.tokensFor(te.content,n),In=await this.config.compressor.compress({text:te.
|
|
1490
|
+
content}),Za=!In.skipped&&In.fidelityPassed&&Nc(te.content,In.compressed),Xa=Za?this.tokensFor(In.compressed,n):Pn;Za&&Xa<Pn?(fe.push({...te,content:In.compressed}),ue+=Pn,Z+=Xa):fe.push(te);}let it=this.
|
|
1491
|
+
tokensFor(this.assemblePromptText(fe,v.tools),n),Se=zn({...U,contextTokens:re,projectedEliminable:ue-Z}),xr=xd({originalTokens:ot,compressedTokens:it,tier:L,...I.prefix?{prefix:I.prefix}:{},compressorCostTokens:U.
|
|
1492
|
+
compressorCostTokens});Z>=ue?Ie="no fidelity-passed net reduction":Se.compress?xr.comprimir?(Me=true,Ie=xr.razon,A=fe.slice(0,C).some((te,Pn)=>te.content!==S[Pn]?.content),S=fe,s.compress(ue,Z)):Ie=xr.razon:
|
|
1493
|
+
Ie=Se.reason;}Me||(ue=0,Z=0),c.record("compression",Me?"applied":"skipped",{reason:Ie,before:ue,after:Z,contextTokens:re,promptTokens:ot,cacheTierMinimum:L.minimumCacheTokens,protectedSystemMessages:H,
|
|
1494
|
+
prefixRewritten:A}),s.compressionReport={originalTokens:ue,compressedTokens:Z,protectedSpans:H,fidelityPassed:true};}if(i.elision!==false&&o.allowElision&&this.entitled("tool_result_elision")){let I=yd(S);if(I.
|
|
1495
|
+
indices.length>0){let L=this.tokensFor(ua,n),U=0;for(let H of I.indices){let re=this.tokensFor(S[H].content,n);U+=Math.max(0,re-L);}(I.indices.some(H=>H<C)&&(A=true),S=kd(S,I.indices),s.eliminate(U),
|
|
1496
|
+
s.elididoLocal+=U),c.record("elision","applied",{elided:I.indices.length,eliminatedTokens:U,grossBytes:I.bytesOriginales,live:Ca});}else c.record("elision","skipped",{reason:"no old/large t\
|
|
1497
|
+
ool_result over the age\xD7size threshold"});}let $=Yb(this.config.toolOutputCompaction,i.toolOutputCompaction);if($&&!this.entitled("long_context_compression")&&c.record("tool-output-compaction","degr\
|
|
1498
|
+
aded: feature not included in this license"),$&&o.allowCompression&&this.entitled("long_context_compression")){let I=qc(S,$),L=0,U=0,H=0,re=0,ot={};if(I.compactados.length>0){let ue=S.slice();for(let Z of I.
|
|
1499
|
+
compactados){let Me=S[Z.indice],Ie=this.tokensFor(Me.content,n),fe=this.tokensFor(Z.texto,n);ue[Z.indice]={...Me,content:Z.texto},L+=Ie,U+=fe,Z.enLaCola?H+=Math.max(0,Ie-fe):re+=Math.max(0,Ie-fe);for(let it of Z.
|
|
1500
|
+
aplicadas)ot[it]=(ot[it]??0)+1;}S=ue,s.compress(L,U),s.compactedLocal+=Math.max(0,L-U);}let pe=No(n.model,this.config.compressionEconomics);c.record("tool-output-compaction",I.compactados.length>0?"appl\
|
|
1501
|
+
ied":"skipped",{compacted:I.compactados.length,before:L,after:U,tailSavedTokens:H,replayedSavedTokens:re,transforms:ot,fileViewsKeptVerbatim:I.vistasDeFichero,exceptedTools:I.exceptuados,cacheWriteMultiplier:pe.
|
|
1502
|
+
cacheWriteMultiplier,cacheReadMultiplier:pe.cacheReadMultiplier,note:"counted in tokens.compressedInput only; never priced into savings or commission. each tail token saved is one token fewer written \
|
|
1503
|
+
now and re-read on every later turn"});}let O=n.response?.schema,D=O&&i.outputCodebook===true?md(O,I=>this.tokensFor(I,n),a,{evidencia:this.memoriaDelCodebook.resolver(d.modeloServido,lr(n),i.outputCodebookMeasuredOutputDeltaTokens)}):
|
|
1504
|
+
null;D&&c.record("output-codebook",D.applied?"applied":"skipped",{reason:D.reason,...D.applied?{renamedKeys:D.plan.renamedKeys,codedEnumValues:D.plan.codedEnumValues,schemaTokensOriginal:D.plan.schemaTokensOriginal,
|
|
1505
|
+
schemaTokensCompact:D.plan.schemaTokensCompact,modelledShapeSavingTokens:D.plan.modelledShapeSavingTokens,measuredOutputDeltaTokens:D.plan.measuredOutputDeltaTokens,outputDeltaProvenance:D.plan.outputDeltaProvenance,
|
|
1506
|
+
breakEvenOutputDeltaTokens:D.plan.breakEvenOutputDeltaTokens,netSavingUsd:D.plan.netSavingUsd,pricedForModel:d.modeloServido}:{}});let F=D?.applied?D.plan.compactSchema:O,j=F?zr(d.modeloServido,F,this.
|
|
1507
|
+
deps.constraintBackends):{backend:"none",reason:"no output contract"};c.record("constraints",j.backend,{reason:j.reason});let q=y?{tools:y.prefijo,setIsStable:v.setIsStable}:v,J=i.toolDiscovery===true&&
|
|
1508
|
+
!y,Y=this.config.cacheBreakpointStore?await this.cargarEspejo(n,d.modeloServido,S,q,J):null,B=this.decidirMarcadoDeCache(n,d.modeloServido,S,q,J,A?Ia(S,true):C,c,Y),Re=this.now();if(p?.senal.aborted)throw new Te(
|
|
1509
|
+
e.llamadas>0);let ee=y?this.sinDescubrimientoPorBusquedaNativa(i,v.tools,c):await this.descubrirHerramientas(e,n,i,v.tools,S,s,a,c),Kt=ee.tools;s.actualTools=Kt.length;let hr={messages:S,...Kt.length?
|
|
1510
|
+
{tools:Kt}:{},...F?{schema:F}:{},...G(n)!=null?{maxOutputTokens:G(n)}:{},...n.temperature!=null?{temperature:n.temperature}:{},...n.seed!=null?{seed:n.seed}:{},...n.reasoningEffort!=null?{reasoningEffort:n.
|
|
1511
|
+
reasoningEffort}:{},...i.deferrable?{deferrable:true}:{},...B.explicita?{explicitCacheWrites:true}:{},...y?{toolSearch:y.plan}:{},constraintBackend:j.backend},gr={model:d.modeloServido,...hr,...B.marcar?{
|
|
1512
|
+
stablePrefixMessages:B.mensajesDePrefijo,promptCacheKey:B.huella,...B.colocacion&&!B.explicita&&(B.colocacion.cola||B.colocacion.ttl!=="5m")?{cachePlacement:{tail:B.colocacion.cola,ttl:B.colocacion.ttl}}:
|
|
1513
|
+
{},...this.config.cacheMissDiagnostics===true&&B.colocacion?{cacheDiagnostics:{previousMessageId:B.colocacion.coincidencia?.idDelProveedor??null}}:{}}:{}},_,Ha=false,Mp={...e};try{_=p?await this.llamarProveedorEnStream(
|
|
1514
|
+
gr,e,p):await this.llamarProveedor(gr,e);}catch(I){if(!this.respaldaFaltaDeCapacidad(i,I,p))throw I;Object.assign(e,Mp),Ha=true,c.record("deferred-tier","capacity-fallback",{error:I instanceof Error?I.message.
|
|
1515
|
+
slice(0,200):String(I),reason:'the cheaper tier had no capacity; repeated once at the standard tier and price, as configured with priceLevers.onCapacityError: "standard"'});let{deferrable:L,...U}=gr;_=
|
|
1516
|
+
await this.llamarProveedor(U,e);}let $p=Gr(_),Np=_.servedServiceTier;y&&c.record("tool-search","provider",{searches:_.toolSearch?.searches??null,loaded:_.toolSearch?.loaded??[],errors:_.toolSearch?.errors??
|
|
1517
|
+
0,resentResults:_.toolSearch?.resent?.results??0,resentTools:_.toolSearch?.resent?.tools??[],reason:_.toolSearch?"what the provider's tool search did in this call; its cost is in the provider's counte\
|
|
1518
|
+
r and credited to no ledger":"the adapter did not report what the search did"}),s.actualLlm+=1;let oi=I=>{if(!D?.applied)return I;let L=et(I);return L.ok?JSON.stringify(D.plan.expand(L.value)):I},he=oi(
|
|
1519
|
+
_.text),qe=_.usage,jp=_.unbilledRefusal===true,Wa={..._.providerMessageId?{id:_.providerMessageId}:{},..._.cacheDiagnostics?{diagnostico:_.cacheDiagnostics}:{}},nt=false;if(d.enruta){let I=na({texto:he,schema:O,
|
|
1520
|
+
finishReason:_.finishReason,pidioHerramientas:(_.toolCalls?.length??0)>0});this.verjaDeCascada.registrar(d.bucket,!I.acepta),c.record("model-cascade",I.acepta?"accepted":"escalating",{servedModel:d.modeloServido,
|
|
1521
|
+
reason:I.motivo,checks:I.comprobaciones}),I.acepta||(nt=true,s.cascadeAttempt(_.usage,_.unbilledRefusal===true?{inputPer1k:0,outputPer1k:0,cachedInputPer1k:0}:d.precioBarato??a,B.marcar&&B.cacheWriteMultiplier>
|
|
1522
|
+
1?1:Fn(d.modeloServido)),s.actualLlm+=1,_=await this.llamarProveedor({model:n.model,...hr},e),he=oi(_.text));}let Le=nt?n.model:d.modeloServido,En=nt?this.costModelFor(n.model,h):a;s.actualInput+=_.usage.
|
|
1523
|
+
inputTokens,s.actualOutput+=_.usage.outputTokens,_.unbilledRefusal===true&&s.unbilledCall(_.usage);let Bp=_.usage,zp=_.servedServiceTier,Fp=_.structuredNatively===true,br=Gr(_),qp=ol(this.config.provider),
|
|
1524
|
+
Ga;D?.applied&&c.record("output-codebook",et(_.text).ok?"expanded":"not-expanded (response was not JSON)",et(_.text).ok?{localOutputTokensCompact:this.tokensFor(_.text,n),localOutputTokensExpanded:this.
|
|
1525
|
+
tokensFor(he,n),creditedLedger:"none",note:"local count of the served answer in both shapes; not credited to any ledger"}:{}),O&&j.backend==="provider-native"&&_.structuredNatively===false&&(j={backend:"\
|
|
1526
|
+
none",reason:"provider did not enforce the contract natively; the schema travelled in the prompt and the layer is the only validator"},c.record("constraints","none",{downgradedFrom:"provider-native",reason:j.
|
|
1527
|
+
reason})),s.sentInputLocal=this.tokensFor(this.assemblePromptText(S,Kt),n),s.removedInputLocal=Math.max(0,u-s.sentInputLocal-s.elididoLocal-s.compactedLocal);let Up=s.sentInputLocal;s.sentInputLocal+=
|
|
1528
|
+
ee.tokensLocalesDelSondeo,s.estimatorExact=this.estimatorEsExacto(n),_.usage.cachedInputTokens&&s.providerCached(_.usage.cachedInputTokens),_.unbilledRefusal!==true&&s.nativeCacheWrite(_.usage.cacheWriteInputTokens??
|
|
1529
|
+
0,_.usage.cacheWrite1hInputTokens??0),s.nativeCacheMarkedByLayer=!nt&&B.marcar;let Ka=Fn(Le),Vp=!nt&&B.marcar&&B.cacheWriteMultiplier>1;if(Ka>1&&!Vp&&_.unbilledRefusal!==true&&(_.usage.cacheWriteInputTokens??
|
|
1530
|
+
0)>0&&s.providerCacheWritePremium(_.usage.cacheWriteInputTokens??0,Ka,En),B.marcar&&qe.complete===false)c.record("prefix-cache","not measured: the provider reported no usage for this call");else if(B.marcar&&
|
|
1531
|
+
jp)c.record("prefix-cache","not measured: the marked call was a refusal the provider does not bill");else if(B.marcar){let I=Math.max(0,qe.cacheWriteInputTokens??0),L=Math.min(I,Math.max(0,qe.cacheWrite1hInputTokens??
|
|
1532
|
+
(B.colocacion?.ttl==="1h"?I:0)));s.cacheWritePremium(I-L,B.cacheWriteMultiplier,d.precioBarato??a),L>0&&s.cacheWritePremium(L,qn(d.modeloServido),d.precioBarato??a),this.verjaDeCache.registrar(B.claveDeVerja,
|
|
1533
|
+
qe),c.record("prefix-cache","measured",{cacheRead:qe.cachedInputTokens??0,cacheWritePremiumTokens:qe.cacheWriteInputTokens??0,...L>0?{cacheWrite1hTokens:L}:{}});}B.colocacion?.conAlmacen?await this.apuntarEnElAlmacen(
|
|
1534
|
+
B,qe,c,Wa):B.colocacion&&this.apuntarEnElEspejo(B,qe,c,this.espejoDeCache,Wa);let Jt=null;if(d.modo==="shadow"&&d.elegible&&d.candidato&&d.precioBarato&&Kb(l,d.tasaDeMuestreo))try{let I=await this.llamarProveedor(
|
|
1535
|
+
{model:d.candidato,...hr},e);s.actualLlm+=1;let L=s.extraCostUsd;s.cascadeAttempt(I.usage,d.precioBarato,Fn(d.candidato));let U=oi(I.text),H=na({texto:U,schema:O,finishReason:I.finishReason,pidioHerramientas:(I.
|
|
1536
|
+
toolCalls?.length??0)>0});this.verjaDeCascada.registrar(d.bucket,!H.acepta);let re=H.acepta?ud(U,he):null;Jt={coste:s.extraCostUsd-L,divergio:re?re.divergen:null},c.record("model-cascade",H.acepta?"sa\
|
|
1537
|
+
mple accepted":"sample escalated",{candidateModel:d.candidato,reason:H.motivo,sampleCost:Jt.coste,...re?{diverged:re.divergen,divergence:re.motivo}:{},note:"measurement only: this answer was NEVER ser\
|
|
1538
|
+
ved. The escalation rate it feeds is a money figure, not a quality one"});}catch(I){c.record("model-cascade","sample failed (measurement only; the answer is unaffected)",{error:I instanceof Error?I.message:
|
|
1539
|
+
String(I)});}let vr=he,Ct=true,Ue={},Tt=(_.toolCalls?.length??0)>0;if(Tt&&(Ct=null,O&&c.record("validation","n/a: model requested tool calls (the output contract applies to the final answer)")),O&&!Tt){let I=et(
|
|
1540
|
+
he),L=I.ok?be(I.value,O):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},U=false;I.ok&&I.rescatado!=null&&L.valid&&(he=I.rescatado,U=true,c.record("validation","rescued-locally",{reason:"the model \
|
|
1541
|
+
wrapped valid JSON in prose or a markdown fence; it was extracted locally instead of paying a repair call"})),!L.valid&&Jb(L.errors)&&this.contratosQueIncumplen.add(lr(n));let H=_.finishReason==="leng\
|
|
1542
|
+
th",re=Ta(_),ot=!L.valid&&L.errors.some(pe=>/not a valid regular expression/.test(pe.message));if(!L.valid&&ot)c.record("validation","repair-skipped",{reason:"schema defect (uncompilable pattern); no \
|
|
1543
|
+
output can satisfy it, a retry is a wasted call",errors:L.errors}),this.avisar("esquema-roto","[bvsala] The response contract has a `pattern` that is not a valid regex, so no response can satisfy it. \
|
|
1544
|
+
NOT retried (it would be a paid call for the same failure). Fix the schema's `pattern`."),Ue.reparacion={outcome:"skipped",skipReason:"schema_defect"};else if(!L.valid&&re)c.record("validation","repai\
|
|
1545
|
+
r-skipped",{reason:(_.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\
|
|
1546
|
+
same model would be refused, and may be billed, again",model:Le}),Ue.reparacion={outcome:"skipped",skipReason:"provider_refusal"};else if(!L.valid&&H){let pe=pd(O,Me=>this.tokensFor(Me,n)),ue=G(n)??null,
|
|
1547
|
+
Z=pe!==null&&ue!=null&&pe<=ue;Z&&this.contratosQueIncumplen.add(lr(n)),c.record("validation","repair-skipped",{reason:"output truncated by maxOutputTokens; a retry with the same cap would truncate aga\
|
|
1548
|
+
in",maxOutputTokens:G(n)??null,outputTokens:_.usage.outputTokens,model:Le,...pe!==null?{schemaAllowsTokens:pe}:{},learnedValueLimits:Z}),this.avisarDeTruncado(n,Le,_.usage.outputTokens,pe,Z),Ue.reparacion=
|
|
1549
|
+
{outcome:"skipped",skipReason:"output_truncated"};}else if(!L.valid&&j.backend==="none"){let pe=L.errors.slice(0,5).map(te=>`- ${te.path}: ${te.message}`).join(`
|
|
1549
1550
|
`),ue=[{role:"user",content:`Your previous reply did not satisfy the required JSON contract.
|
|
1550
1551
|
|
|
1551
1552
|
Previous reply:
|
|
1552
|
-
${
|
|
1553
|
+
${he}
|
|
1553
1554
|
|
|
1554
1555
|
Problems found:
|
|
1555
|
-
${
|
|
1556
|
+
${pe}
|
|
1556
1557
|
|
|
1557
|
-
Return ONLY the corrected JSON object. Keep the same content; fix only what is listed.`}],Z=this.tokensFor(this.assemblePromptText(ue),n),
|
|
1558
|
-
round(
|
|
1559
|
-
Se.baselineEstimate>0&&Se.actual+
|
|
1560
|
-
d as-is and reported as invalid",errors:
|
|
1561
|
-
ot satisfy the output contract, and repairing it would have cost MORE than sending this request without the layer at all (baseline ~$${Se.baselineEstimate}, already spent ~$${Se.actual}, repair ~$${
|
|
1558
|
+
Return ONLY the corrected JSON object. Keep the same content; fix only what is listed.`}],Z=this.tokensFor(this.assemblePromptText(ue),n),Me=s.sentInputLocal>0?s.actualInput/s.sentInputLocal:1,Ie=Math.
|
|
1559
|
+
round(Me*Z),fe=Math.min(_.usage.outputTokens,G(n)??Number.POSITIVE_INFINITY),it=Ie/1e3*En.inputPer1k+fe/1e3*En.outputPer1k,Se=this.config.skipRepairAboveBaseline?s.estimateCost(En):void 0;if(Se!=null&&
|
|
1560
|
+
Se.baselineEstimate>0&&Se.actual+it>Se.baselineEstimate&&Se!=null)c.record("validation","repair-skipped",{reason:"repairing would cost more than not using the layer at all; the invalid answer is serve\
|
|
1561
|
+
d as-is and reported as invalid",errors:L.errors,baselineUsd:Se.baselineEstimate,actualUsd:Se.actual,repairEstimateUsd:it}),this.avisar("reparacion-mas-cara-que-el-baseline",`[bvsala] The answer did n\
|
|
1562
|
+
ot satisfy the output contract, and repairing it would have cost MORE than sending this request without the layer at all (baseline ~$${Se.baselineEstimate}, already spent ~$${Se.actual}, repair ~$${it.
|
|
1562
1563
|
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\
|
|
1563
|
-
s and an output contract; see the adapter warning for the cheaper shapes.`),
|
|
1564
|
-
attempt",{errors:
|
|
1565
|
-
|
|
1566
|
-
O):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},
|
|
1567
|
-
|
|
1568
|
-
desenvuelto:U},c.record("validation",
|
|
1569
|
-
i,
|
|
1570
|
-
basis:"estimated"}:{},creditedLedger:"none",reason:Pe.reason}),
|
|
1571
|
-
{servedTier:
|
|
1572
|
-
!
|
|
1573
|
-
compressedInput:s.compressedInput,elididoLocal:s.elididoLocal,sentLocalSinSondeo:
|
|
1574
|
-
busquedaNativa:y!==null,hayEsquema:O!=null,esquemaNativo:
|
|
1575
|
-
!0,piezasDelAdaptador:
|
|
1576
|
-
n)});}catch{ye="fingerprint-failed";}let
|
|
1577
|
-
layerInsertions,...ye.reasoningTokens!==void 0?{reasoningTokens:ye.reasoningTokens}:{},exactCache:
|
|
1578
|
-
call turn (an action request must not be replayed from cache)":
|
|
1579
|
-
alf an answer would bill it as a 100% avoided call':
|
|
1580
|
-
"content_filter" / a refusal message'+(
|
|
1581
|
-
provider may not have billed":
|
|
1564
|
+
s and an output contract; see the adapter warning for the cheaper shapes.`),Ue.reparacion={outcome:"skipped",skipReason:"would_cost_more_than_no_layer"};else {s.retries=1,c.record("validation","repair-\
|
|
1565
|
+
attempt",{errors:L.errors}),_=await this.llamarProveedor({model:Le,messages:ue,schema:O,...G(n)!=null?{maxOutputTokens:G(n)}:{}},e),Ga=_.usage,s.actualLlm+=1,s.actualInput+=_.usage.inputTokens,s.actualOutput+=
|
|
1566
|
+
_.usage.outputTokens,s.repairOutput+=_.usage.outputTokens,s.repairInput+=_.usage.inputTokens,_.unbilledRefusal===true&&s.unbilledCall(_.usage),s.sentInputLocal+=Z,he=_.text;let te=et(he);L=te.ok?be(te.value,
|
|
1567
|
+
O):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},te.ok&&(vr=te.value,te.rescatado!=null&&L.valid&&(he=te.rescatado)),Ue.reparacion={outcome:L.valid?"repaired":"still_invalid"};}}else I.ok&&(vr=
|
|
1568
|
+
I.value);Ct=L.valid,!L.valid&&Ue.reparacion===void 0&&(Ue.reparacion={outcome:"skipped",skipReason:"decode_time_constraint"}),Ue.validacion={resultado:L.valid?"passed":"failed",errores:L.errors.length,
|
|
1569
|
+
desenvuelto:U},c.record("validation",Ct?"valid":"invalid");}let Hp=this.now()-Re,Wp=Vb(vr),Yt={text:he,data:vr,rendered:Wp,storedAtMs:this.now()},ge=this.informeDeDiferido(i,_,Le,Ha),Pe=this.informeDeEscrituras(
|
|
1570
|
+
i,$p,qe,Np,d.modeloServido,B.marcar,B.explicitaPorColocador);Pe&&c.record("cache-writes",Pe.mode,{breakpoints:Pe.breakpoints,...Pe.avoidedWritePremium?{avoidedWritePremium:Pe.avoidedWritePremium.amount,
|
|
1571
|
+
basis:"estimated"}:{},creditedLedger:"none",reason:Pe.reason}),ge&&c.record("deferred-tier",ge.credited?"credited":"not-credited",{...ge.requestedTier?{requestedTier:ge.requestedTier}:{},...ge.servedTier?
|
|
1572
|
+
{servedTier:ge.servedTier}:{},creditedLedger:"none",reason:ge.reason});let Gp=ee.aplicado,ii=_.finishReason==="length",yr=_.replayable===false,kr=Ta(_),Cn=kr||Tt?null:ir(he),Tn=o.sensitiveTopic,Zt=Ct!==false&&
|
|
1573
|
+
!Tt&&!Gp&&!ii&&!yr&&!kr&&Cn===null&&Tn===null,Ja=this.generateId(),ye;try{ye=Pd({contadorSimulado:Ui(this.config.provider),origen:qp,usoPrimario:Bp,usoReparacion:Ga,tierServido:zp,eliminatedInput:s.eliminatedInput,
|
|
1574
|
+
compressedInput:s.compressedInput,elididoLocal:s.elididoLocal,sentLocalSinSondeo:Up,baselineInput:u,codebookAplicado:D?.applied===!0,tokensDelSondeo:ee.tokensLocalesDelSondeo,sondeoAplicado:ee.aplicado,
|
|
1575
|
+
busquedaNativa:y!==null,hayEsquema:O!=null,esquemaNativo:Fp,esquemaEnFormatoNativo:br?.esquemaEnFormatoNativo===!0&&F===O,esquemaEstricto:br?.esquemaEstricto===!0,esquemaPorPrompt:br?.esquemaPorPrompt===
|
|
1576
|
+
!0,piezasDelAdaptador:br?.piezasDelAdaptador??0,modeloPedido:n.model,modeloServido:Le,cacheable:Zt,mensajesDeLaCapa:S.length-n.messages.length,requestId:Ja,at:this.now(),textoServido:he,huella:()=>ma(
|
|
1577
|
+
n)});}catch{ye="fingerprint-failed";}let Ya=Zt&&o.allowExactCache&&i.exactCache!==false;typeof ye=="object"?c.record("reference","written",{inputTokens:ye.inputTokens,outputTokens:ye.outputTokens,layerInsertions:ye.
|
|
1578
|
+
layerInsertions,...ye.reasoningTokens!==void 0?{reasoningTokens:ye.reasoningTokens}:{},exactCache:Ya}):c.record("reference","not-written",{reason:ye});try{Zt||c.record("cache-write",Tt?"skipped: tool-\
|
|
1579
|
+
call turn (an action request must not be replayed from cache)":Ct===!1?"skipped: response fails its output contract":ii?'skipped: answer cut off by the output cap (finish_reason "length"); replaying h\
|
|
1580
|
+
alf an answer would bill it as a 100% avoided call':yr?"skipped: the provider answer carries content this layer cannot replay":kr?'skipped: the provider refused (stop_reason "refusal" / finish_reason \
|
|
1581
|
+
"content_filter" / a refusal message'+(_.finishReasonDetail!==void 0?`; provider reason: ${_.finishReasonDetail}`:"")+"); a refusal is not an answer, and replaying it would credit an avoided call the \
|
|
1582
|
+
provider may not have billed":Cn!==null?Cn==="redirection"?"skipped: the answer redirects to professional or crisis help instead of answering (text_refusal, redirection); it was measured and served as\
|
|
1582
1583
|
usual, but it is not an answer to replay or to credit as an avoided call":"skipped: the answer reads as a refusal written as text (text_refusal); it was measured and served as usual, but a refusal is\
|
|
1583
|
-
not an answer to replay or to credit as an avoided call":
|
|
1584
|
-
d from a cache or credited as an avoided call`:"skipped: answered with a reduced tool view (tool discovery), so it must not be replayed",!
|
|
1585
|
-
rule:
|
|
1586
|
-
await this.deps.exactCache.set(
|
|
1587
|
-
await this.deps.semanticCache.store(r,
|
|
1588
|
-
deps.semanticCache&&(
|
|
1589
|
-
semantic-calibration","no label: the cache would not store this answer"));}catch(
|
|
1590
|
-
callsWithoutUsage=e.sinContador;let
|
|
1591
|
-
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
|
|
1592
|
-
{requestedTier:
|
|
1593
|
-
nts as not billed), so no tier discount is credited"}:
|
|
1594
|
-
|
|
1595
|
-
{sampled:true,sampleCost:
|
|
1596
|
-
{}})
|
|
1597
|
-
noReproducibles.add(
|
|
1598
|
-
|
|
1599
|
-
decision:d}=this.decidirBusquedaParaEstaPeticion(e,c,r,o,i,s);if(a.record("tool-search",d.aplicar?"native":"selector",{mode:c.modo,
|
|
1600
|
-
tokensDiferidos,alwaysLoaded:d.siempreCargadas,...d.ahorroDelPrefijo!=null?{prefixSavingPerRequest:d.ahorroDelPrefijo}:{},...d.costeDeUnaBusqueda!=
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
e.tools??[],r==="TOOL_ACTION",o),c=
|
|
1604
|
-
null,cascadaActiva:i.modo!=="off",precio:s,lecturaDeCache:this.lecturaDeCacheDe(i.modeloServido,s)});return {candidatas:a,decision:c}}lecturaDeCacheDe(e,n){let r=
|
|
1584
|
+
not an answer to replay or to credit as an avoided call":Tn!==null?`skipped: the request touches a sensitive topic (sensitive_topic, ${Tn}); it was measured and served as usual, but it is not replaye\
|
|
1585
|
+
d from a cache or credited as an avoided call`:"skipped: answered with a reduced tool view (tool discovery), so it must not be replayed",!Tt&&Ct!==!1&&!ii&&!yr&&!kr?Cn!==null?{skipReason:"text_refusal",
|
|
1586
|
+
rule:Cn}:Tn!==null?{skipReason:"sensitive_topic",category:Tn}:void 0:void 0);let I=nt?rn(r,{servedModel:Le}):l;if(Ya){let U=this.config.exactCacheTtlMs??864e5,H=o.maxCacheAgeMs==null?U:Math.min(U,o.maxCacheAgeMs);
|
|
1587
|
+
await this.deps.exactCache.set(I,typeof ye=="object"?{...Yt,meta:{...Yt.meta??{},reference:{...ye,cacheKey:I}}}:Yt,H);}let L=Le!==n.model;Zt&&!L&&o.allowSemanticCache&&i.semanticCache&&this.deps.semanticCache?
|
|
1588
|
+
await this.deps.semanticCache.store(r,Yt):Zt&&L&&i.semanticCache&&c.record("cache-write","semantic write skipped: a cheaper model answered, and this cache keys on the model the caller asked for"),m&&this.
|
|
1589
|
+
deps.semanticCache&&(Zt&&!L&&o.allowSemanticCache&&i.semanticCache?(c.record("semantic-calibration","label requested",{reason:m.reason,score:m.score}),this.deps.semanticCache.observe(m,Yt)):c.record("\
|
|
1590
|
+
semantic-calibration","no label: the cache would not store this answer"));}catch(I){c.record("cache-write","failed (non-fatal; answer already served)",{error:I instanceof Error?I.message:String(I)});}s.
|
|
1591
|
+
callsWithoutUsage=e.sinContador;let Rn=_.unbilledRefusal===true;Rn&&(s.servedUnbilledRefusal=true,c.record("cost","unbilled refusal: measured at 0, no saving credited",{reason:"the provider documents a re\
|
|
1592
|
+
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 Kp=Rn&&ge?.credited?{...ge.requestedTier?
|
|
1593
|
+
{requestedTier:ge.requestedTier}:{},...ge.servedTier?{servedTier:ge.servedTier}:{},credited:false,creditedLedger:"none",latency:ge.latency,reason:"the provider did not bill this call (a refusal it docume\
|
|
1594
|
+
nts as not billed), so no tier discount is credited"}:ge,Jp=Rn&&Pe?.avoidedWritePremium?{mode:Pe.mode,breakpoints:Pe.breakpoints,reason:Pe.reason}:Pe,rt=this.finish(n,r,Yt,"miss",s,En,c,b,E,void 0,void 0,
|
|
1595
|
+
Ct,j.backend,Hp,this.informeDeCascada(d,{servedModel:Le,...d.enruta?{escalated:nt}:{},...d.elegible&&d.precioBarato&&!Rn?{estimatedSwapSaving:Gb(s,nt,d.precioBarato,this.costModelFor(n.model,h))}:{},...Jt?
|
|
1596
|
+
{sampled:true,sampleCost:Ht(Jt.coste),...Jt.divergio!==null?{divergedOnSample:Jt.divergio}:{}}:{},...s.cascadeInput>0||s.cascadeOutput>0?{cascadeInputTokens:s.cascadeInput,cascadeOutputTokens:s.cascadeOutput}:
|
|
1597
|
+
{}}),Kp,Ja,Jp,{...Ue,final:{..._.finishReason!==void 0?{finishReason:_.finishReason}:{},..._.finishReasonDetail!==void 0?{finishReasonDetail:_.finishReasonDetail}:{},...G(n)!=null?{topeDelLlamante:G(n)}:
|
|
1598
|
+
{}}});return typeof ye=="object"&&this.referenciasDeLider.set(rt,ye),yr&&this.noReproducibles.add(rt),Rn&&this.negativasSinCobro.add(rt),Tt&&(rt.toolCalls=_.toolCalls),_.finishReason!==void 0&&(rt.finishReason=
|
|
1599
|
+
_.finishReason),_.finishReasonDetail!==void 0&&(rt.finishReasonDetail=_.finishReasonDetail),_.refusal!==void 0&&(rt.refusal=_.refusal),rt}planearBusquedaNativa(e,n,r,o,i,s,a){let c=_i(n.toolSearch),l=e.
|
|
1600
|
+
tools??[];if(c.modo==="off"||l.length===0)return null;let{candidatas:u,decision:d}=this.decidirBusquedaParaEstaPeticion(e,c,r,o,i,s);if(a.record("tool-search",d.aplicar?"native":"selector",{mode:c.modo,
|
|
1601
|
+
variant:d.variante,reason:d.razon,deferred:d.diferidas,deferredTokens:d.tokensDiferidos,alwaysLoaded:d.siempreCargadas,...d.ahorroDelPrefijo!=null?{prefixSavingPerRequest:d.ahorroDelPrefijo}:{},...d.costeDeUnaBusqueda!=
|
|
1602
|
+
null?{worstCaseSearchCost:d.costeDeUnaBusqueda}:{}}),!d.aplicar)return null;let p=new Set(u.map(m=>m.id)),h=new Set(d.siempreCargadas),f=c.siempreCargadas.filter(m=>l.some(g=>g.id===m));return {seleccion:{
|
|
1603
|
+
tools:u,droppedIds:l.filter(m=>!p.has(m.id)).map(m=>m.id),reason:d.razon,setIsStable:f.every(m=>p.has(m))},prefijo:u.filter(m=>h.has(m.id)),plan:{variant:d.variante,alwaysLoaded:d.siempreCargadas}}}decidirBusquedaParaEstaPeticion(e,n,r,o,i,s){
|
|
1604
|
+
let a=Cc(e.tools??[],r==="TOOL_ACTION",o),c=Ai({opciones:n,capacidad:Jr(this.config.provider),modelo:i.modeloServido,herramientas:a.map(l=>({id:l.id,tokens:this.tokensFor(ur(l),e)})),hayContrato:e.response?.
|
|
1605
|
+
schema!=null,cascadaActiva:i.modo!=="off",precio:s,lecturaDeCache:this.lecturaDeCacheDe(i.modeloServido,s)});return {candidatas:a,decision:c}}lecturaDeCacheDe(e,n){let r=Ra(e,this.config.compressionEconomics)?.
|
|
1605
1606
|
cacheReadMultiplier??1,o=n.cachedInputPer1k!=null&&n.inputPer1k>0?n.cachedInputPer1k/n.inputPer1k:void 0;return o!=null?Math.min(o,r):r}sinDescubrimientoPorBusquedaNativa(e,n,r){return e.toolDiscovery===
|
|
1606
1607
|
true&&r.record("tool-discovery","skipped (native tool search applies)",{reason:"the provider's tool search already keeps unused schemas out of the prompt, with no second call and without moving the cach\
|
|
1607
1608
|
ed prefix"}),{tools:n,tokensLocalesDelSondeo:0,aplicado:false}}avisarDeHerramientasPodadas(e,n,r,o,i,s,a){let c=e.tools??[],l="herramientas-podadas-por-el-selector";if(r.droppedIds.length===0||this.config.
|
|
1608
|
-
silenceWarnings||
|
|
1609
|
+
silenceWarnings||Qc(l))return;let u=_i(n.toolSearch),d=f=>this.decidirBusquedaParaEstaPeticion(e,{...u,modo:f},o,i,s,a).decision,p=d("auto"),h="";p.aplicar?h=' This provider and model also support nat\
|
|
1609
1610
|
ive tool search, and it would pay here: `savings: { toolSearch: "auto" }` sends every tool deferred and lets the model search, without breaking the prompt cache.':d("always").aplicar&&(p.ahorroDelPrefijo!=
|
|
1610
|
-
null&&p.costeDeUnaBusqueda!=null?
|
|
1611
|
+
null&&p.costeDeUnaBusqueda!=null?h=` Native tool search is available here, but \`toolSearch: "auto"\` would keep the selector for this request: deferring the catalogue saves about $${p.ahorroDelPrefijo.
|
|
1611
1612
|
toFixed(6)} per request with a warm cache, less than one worst-case search ($${p.costeDeUnaBusqueda.toFixed(6)}). \`toolSearch: "always"\` makes every tool reachable anyway, at up to $${(p.costeDeUnaBusqueda-
|
|
1612
|
-
p.ahorroDelPrefijo).toFixed(6)} more per request that searches.`:
|
|
1613
|
+
p.ahorroDelPrefijo).toFixed(6)} more per request that searches.`:Jr(this.config.provider)==="compatible"&&(h=' This adapter is not talking to the provider\'s own API host, so `toolSearch: "auto"` would\
|
|
1613
1614
|
keep the selector; if your proxy forwards the tool search blocks, `toolSearch: "always"` sends every tool deferred and lets the model search.')),this.avisar(l,`[bv-sala] The tool selector sent ${r.tools.
|
|
1614
1615
|
length} of ${c.length} tools, chosen by the \`intents\`/\`risk\` your tools declare: the model cannot call the other ${r.droppedIds.length} in that request (they are listed in the report's \`tool-selec\
|
|
1615
|
-
tor\` trace). A catalogue with no \`intents\` and no \`risk\`, or \`savings: { router: false }\`, is sent whole.`+
|
|
1616
|
-
this.config.silenceWarnings||n.toolSearch!==void 0||r.tools.length<
|
|
1617
|
-
variante:"bm25"},capacidad:s,modelo:o.modeloServido,herramientas:r.tools.map(c=>({id:c.id,tokens:this.tokensFor(
|
|
1616
|
+
tor\` trace). A catalogue with no \`intents\` and no \`risk\`, or \`savings: { router: false }\`, is sent whole.`+h);}catalogoGrandeAvisado=false;avisarDeCatalogoGrande(e,n,r,o,i){if(this.catalogoGrandeAvisado||
|
|
1617
|
+
this.config.silenceWarnings||n.toolSearch!==void 0||r.tools.length<Ar.herramientas)return;let s=Jr(this.config.provider);s===void 0||!Ii(o.modeloServido)||!Ai({opciones:{modo:"auto",siempreCargadas:[],
|
|
1618
|
+
variante:"bm25"},capacidad:s,modelo:o.modeloServido,herramientas:r.tools.map(c=>({id:c.id,tokens:this.tokensFor(ur(c),e)})),hayContrato:e.response?.schema!=null,cascadaActiva:o.modo!=="off",precio:i,lecturaDeCache:this.
|
|
1618
1619
|
lecturaDeCacheDe(o.modeloServido,i)}).aplicar||(this.catalogoGrandeAvisado=true,this.avisar("catalogo-grande-con-busqueda-nativa",`[bv-sala] This request sent all ${r.tools.length} of its tools in the p\
|
|
1619
1620
|
rompt: since 0.4.33 tools are pruned by relevance only if you set \`new ToolSelector({ maxTools })\`. This provider and model support native tool search, and it would pay off here: \`savings: { toolSearc\
|
|
1620
1621
|
h: "auto" }\` sends every tool deferred, lets the model search, and keeps the prompt cache.`));}async descubrirHerramientas(e,n,r,o,i,s,a,c){let l={tools:o,tokensLocalesDelSondeo:0,aplicado:false};if(r.toolDiscovery!==
|
|
1621
|
-
true)return l;if(o.length<2)return c.record("tool-discovery","skipped (nothing to discover)",{candidates:o.length}),l;let u=g=>this.tokensFor(
|
|
1622
|
-
assemblePromptText(i),n),esquemasCompletos:o.reduce((g,b)=>g+u(b),0),descriptoresLigeros:d.reduce((g,b)=>g+u(b),0),esquemasDeLaSegunda:
|
|
1623
|
-
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}),l;let f
|
|
1624
|
-
assemblePromptText(i,d),n);try{
|
|
1622
|
+
true)return l;if(o.length<2)return c.record("tool-discovery","skipped (nothing to discover)",{candidates:o.length}),l;let u=g=>this.tokensFor(ur(g),n),d=o.map(Ed),p=Sd({promptTokens:this.tokensFor(this.
|
|
1623
|
+
assemblePromptText(i),n),esquemasCompletos:o.reduce((g,b)=>g+u(b),0),descriptoresLigeros:d.reduce((g,b)=>g+u(b),0),esquemasDeLaSegunda:Td(o.map(g=>({risk:g.risk,tokens:u(g)})),3),salidaFinal:zs(n),salidaDelSondeo:96,
|
|
1624
|
+
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}),l;let h,f=this.tokensFor(this.
|
|
1625
|
+
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}:{},
|
|
1625
1626
|
...n.reasoningEffort!=null?{reasoningEffort:n.reasoningEffort}:{}},e);}catch(g){return c.record("tool-discovery","failed (falling back to a single call with every schema)",{error:g instanceof Error?g.message:
|
|
1626
|
-
String(g)}),l}s.actualLlm+=1,s.actualInput+=
|
|
1627
|
-
[]).map(g=>g.name),o,3);return
|
|
1628
|
-
{}}),{tools:o,tokensLocalesDelSondeo:
|
|
1629
|
-
{unknownNames:
|
|
1630
|
-
elegible,reason:e.razon,verifier:e.fuerza,creditedLedger:"none",...e.candidato?{candidateModel:e.candidato}:{},...e.economia?{costRatio:
|
|
1631
|
-
targetEscalationRate:
|
|
1632
|
-
if(e.deferrable!==true)return;let i=
|
|
1627
|
+
String(g)}),l}s.actualLlm+=1,s.actualInput+=h.usage.inputTokens,s.actualOutput+=h.usage.outputTokens,s.discoveryInput+=h.usage.inputTokens,s.discoveryOutput+=h.usage.outputTokens;let m=Cd((h.toolCalls??
|
|
1628
|
+
[]).map(g=>g.name),o,3);return m.reconocidos.length===0?(c.record("tool-discovery","degraded: probe named no known tool",{finishReason:h.finishReason??null,...m.ignorados.length?{unknownNames:m.ignorados}:
|
|
1629
|
+
{}}),{tools:o,tokensLocalesDelSondeo:f,aplicado:false}):(c.record("tool-discovery","applied (two provider calls)",{chosen:m.reconocidos,sent:m.tools.map(g=>g.id),candidates:o.length,...m.ignorados.length?
|
|
1630
|
+
{unknownNames:m.ignorados}:{}}),{tools:m.tools,tokensLocalesDelSondeo:f,aplicado:true})}informeDeCascada(e,n={}){if(e.modo!=="off")return {mode:e.modo,servedModel:n.servedModel??e.modeloServido,eligible:e.
|
|
1631
|
+
elegible,reason:e.razon,verifier:e.fuerza,creditedLedger:"none",...e.candidato?{candidateModel:e.candidato}:{},...e.economia?{costRatio:sr(e.economia.r),breakEvenEscalationRate:sr(e.economia.equilibrio),
|
|
1632
|
+
targetEscalationRate:sr(e.economia.escaladoMaximo)}:{},...e.bucket?{workload:e.bucket}:{},...e.observada!=null?{escalationRate:sr(e.observada),escalationSamples:e.muestras}:{},...n,requestedModel:e.modeloPedido}}informeDeDiferido(e,n,r,o=false){
|
|
1633
|
+
if(e.deferrable!==true)return;let i=Gr(n),s=i?.origen??null,a=n.servedServiceTier;if(o)return {...$t(this.config.provider)!==void 0?{requestedTier:We}:{},...a?{servedTier:a}:{},credited:false,capacityFallback:true,
|
|
1633
1634
|
creditedLedger:"none",latency:"the cheaper tier refused the request for lack of capacity, and it was repeated once at the standard tier: the wait is the refused attempt plus a standard-tier call.",reason:'\
|
|
1634
1635
|
the cheaper tier had no capacity (HTTP 429 or 503), so, as configured with priceLevers.onCapacityError: "standard", the request was repeated once at the standard tier and price; the refused attempt is\
|
|
1635
|
-
not counted as a call and nothing is credited'};let c=n.requestedServiceTier,l={...c?{requestedTier:c}:{},...a?{servedTier:a}:{},credited:false,creditedLedger:"none",latency
|
|
1636
|
-
...l,reason:
|
|
1637
|
-
ok){let p=d.motivo==="no-tier-price"&&s==="openai"&&
|
|
1638
|
-
()":"";return {...l,reason:
|
|
1639
|
-
appliedCost:
|
|
1636
|
+
not counted as a call and nothing is credited'};let c=n.requestedServiceTier,l={...c?{requestedTier:c}:{},...a?{servedTier:a}:{},credited:false,creditedLedger:"none",latency:Yc(c,s),reason:""};if(!c)return {
|
|
1637
|
+
...l,reason:Jc};let u=this.precioDelCliente(r),d=Hr({modelo:r,uso:n.usage,tierServido:a,origen:s,...i?.tierLeidoDe?{tierLeidoDe:i.tierLeidoDe}:{},...u?{precioDelCliente:u}:{},ahoraMs:this.now()});if(!d.
|
|
1638
|
+
ok){let p=d.motivo==="no-tier-price"&&s==="openai"&&Kc(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\
|
|
1639
|
+
()":"";return {...l,reason:Wb(d.motivo,c,a)+p}}return {...l,credited:true,discountRate:sr(d.factorEfectivo),estimatedTierSaving:d.importe,tierSaving:{amount:d.importe,basis:d.basis,standardCost:Ht(d.costeEstandar),
|
|
1640
|
+
appliedCost:Ht(d.costeAplicado),pricesCheckedOn:d.consultado,basisReason:d.motivoBasis},reason:`the provider reports serving the "${a}" tier; this call's usage was priced at the standard and at the "${a}\
|
|
1640
1641
|
" published rate cards, component by component (${(d.factorEfectivo*100).toFixed(1)}% of standard). The discount stacks with provider prefix caching rather than replacing it`}}informeDeEscrituras(e,n,r,o,i,s,a=false){
|
|
1641
|
-
if(e.standalone!==true&&!a)return;let c=n?.cacheExplicita;if(!c){let g
|
|
1642
|
-
t",breakpoints:0,reason:
|
|
1642
|
+
if(e.standalone!==true&&!a)return;let c=n?.cacheExplicita;if(!c){let g=$t(this.config.provider),b="the provider chose where to write its prompt cache, as it does by default";return {mode:"provider-defaul\
|
|
1643
|
+
t",breakpoints:0,reason:Lt(i,"openai")?g===void 0?`this provider is not one of this package's adapters, so nothing attests explicit prompt-cache control on it: ${b}`:g!=="openai"?`explicit prompt-cach\
|
|
1643
1644
|
e control only exists on OpenAI's own API, and this endpoint is not it: ${b}`:`model "${i}" has no list price of its own here, so the layer cannot tell whether writing its prefix pays: ${b}`:`model "${i}\
|
|
1644
1645
|
" is not an OpenAI model that bills prompt-cache writes above the input rate, so there was no write premium to avoid: ${b}`}}let l=c.puntos,u=(a?`Chosen by cacheBreakpoints: "auto" because continuatio\
|
|
1645
1646
|
ns of this traffic within 30 minutes were measured below the write premium's break-even (see the prefix-cache-placement trace). `:"")+"Trade-off: repeats and continuations of this exact prompt lose th\
|
|
1646
1647
|
e cache reads the provider default would have given them.",d=l===1?"explicit mode: the provider wrote its prompt cache only at the end of the stable prefix, so the rest of this request was billed at t\
|
|
1647
1648
|
he input rate with no cache-write charge. "+u:(s?"explicit mode with no breakpoint: the message at the prefix boundary cannot carry one":"explicit mode with no breakpoint: there was no stable prefix w\
|
|
1648
|
-
orth writing, or the measured hit rate on it did not pay for the write premium")+", so the provider neither wrote nor read its prompt cache for this request. "+u,p=o?
|
|
1649
|
-
|
|
1650
|
-
void 0;if(!
|
|
1651
|
-
{}});return {mode:"explicit",breakpoints:l,avoidedWritePremium:{amount:
|
|
1649
|
+
orth writing, or the measured hit rate on it did not pay for the write premium")+", so the provider neither wrote nor read its prompt cache for this request. "+u,p=o?Un("openai",o,i,this.now()):void 0,
|
|
1650
|
+
h=qr(i),f=p&&p.cacheWritePer1k!==void 0?{inputPer1k:p.inputPer1k,cacheWritePer1k:p.cacheWritePer1k,consultado:p.consultado}:h?{inputPer1k:h.inputPer1k,cacheWritePer1k:h.cacheWritePer1k,consultado:void 0}:
|
|
1651
|
+
void 0;if(!f||r.complete===false)return {mode:"explicit",breakpoints:l,reason:d};let m=Xc({uso:r,fila:{inputPer1k:f.inputPer1k,cacheWritePer1k:f.cacheWritePer1k},...f.consultado?{consultado:f.consultado}:
|
|
1652
|
+
{}});return {mode:"explicit",breakpoints:l,avoidedWritePremium:{amount:m.importe,basis:"estimated",standardCost:Ht(m.costeEstandar),appliedCost:Ht(m.costeAplicado),pricesCheckedOn:m.consultado,basisReason:m.
|
|
1652
1653
|
tokensOrdinarios>0&&r.inputTokens>=1024?"estimated: the provider default was not run for this request. This is the write premium the default would have charged on the tokens after the last breakpoint;\
|
|
1653
1654
|
it does not subtract the cache reads the default could have given a later repeat":"estimated: below the provider's minimum cacheable length (or with nothing written past the breakpoint) the default w\
|
|
1654
1655
|
ould not have charged a write premium either"},reason:d}}escriturasSinLlamada(e){if(e.savings?.standalone===true)return {mode:"provider-default",breakpoints:0,reason:"no provider call was made, so nothin\
|
|
1655
1656
|
g was written to or read from the provider's prompt cache for this request"}}respaldaFaltaDeCapacidad(e,n,r){return e.deferrable!==true||r!==null||this.config.priceLevers?.onCapacityError!=="standard"||
|
|
1656
|
-
|
|
1657
|
+
$t(this.config.provider)===void 0?false:n instanceof Error&&/^provider (429|503)\b/.test(n.message)}diferidoSinLlamada(e){if(e.savings?.deferrable===true)return {credited:false,creditedLedger:"none",latency:"n\
|
|
1657
1658
|
ot applicable: no provider call was made for this request.",reason:"no provider call was made, so no processing tier was served and none is credited; the call was avoided outright, which is worth more\
|
|
1658
|
-
than any tier discount on it"}}finish(e,n,r,o,i,s,a,c,l,u,d,p,
|
|
1659
|
-
ailed",errores:
|
|
1660
|
-
e),
|
|
1661
|
-
0&&o.actualLlm>0&&!o.servedUnbilledRefusal?
|
|
1662
|
-
...o.nativeCacheMarkedByLayer!==null?{marcadoPorLaCapa:o.nativeCacheMarkedByLayer}:{},contadorCompleto:o.callsWithoutUsage===0}):void 0,
|
|
1663
|
-
requestId:g??this.generateId(),model:
|
|
1659
|
+
than any tier discount on it"}}finish(e,n,r,o,i,s,a,c,l,u,d,p,h="none",f=0,m,g,b,y,v){let x=e.response?.schema,E,S=p===null?null:p??(x?(()=>{let T=be(r.data,x);return E={resultado:T.valid?"passed":"f\
|
|
1660
|
+
ailed",errores:T.errors.length,desenvuelto:false},T.valid})():true),C=E&&!v?.validacion?{...v,validacion:E}:v,A=this.buildReport(e,n,o,i,s,a,c,l,u,d,S,h,f,m,g??this.diferidoSinLlamada(e),b,y??this.escriturasSinLlamada(
|
|
1661
|
+
e),C);return {requestId:A.requestId,data:r.data,text:r.text,...r.rendered!==void 0?{rendered:r.rendered}:{},report:A}}buildReport(e,n,r,o,i,s,a,c,l,u,d,p,h,f,m,g,b,y){let v=o.estimateCost(i),x=o.avoidedLlm===
|
|
1662
|
+
0&&o.actualLlm>0&&!o.servedUnbilledRefusal?Xu(f?.servedModel??e.model,i,{leidos:Math.max(0,o.providerCachedInput-o.unbilledCachedInput),escritos:o.nativeCacheWriteInput,escritos1h:o.nativeCacheWrite1hInput,
|
|
1663
|
+
...o.nativeCacheMarkedByLayer!==null?{marcadoPorLaCapa:o.nativeCacheMarkedByLayer}:{},contadorCompleto:o.callsWithoutUsage===0}):void 0,E=s.elapsed(),S=f!=null&&f.servedModel!==f.requestedModel;return {
|
|
1664
|
+
requestId:g??this.generateId(),model:f?.servedModel??e.model,calls:{baselineLlm:o.baselineLlm,actualLlm:o.actualLlm,avoidedLlm:o.avoidedLlm,baselineRetrieval:o.baselineRetrieval,actualRetrieval:o.actualRetrieval,
|
|
1664
1665
|
baselineTools:o.baselineTools,actualTools:o.actualTools,retries:o.retries},tokens:{baselineInput:o.baselineInput,actualInput:o.actualInput,eliminatedInput:o.eliminatedInput,compressedInput:o.compressedInput,
|
|
1665
1666
|
baselineOutput:o.publishedBaselineOutput,actualOutput:o.actualOutput,eliminatedOutput:o.eliminatedOutput,...o.providerCachedInput?{providerCachedInput:o.providerCachedInput}:{}},cache:{result:r,...u!==
|
|
1666
1667
|
void 0?{confidence:u}:{},...l!==void 0?{ageMs:l}:{},...o.reference?{reference:{...o.reference}}:{},...o.referenceRejected?{referenceRejected:o.referenceRejected}:{}},routing:{executionClass:a.executionClass,
|
|
1667
1668
|
confidence:a.confidence,rounds:o.actualRetrieval,reason:a.reason},serialization:{chosen:c.chosen,candidateTokens:c.candidateTokens,instructionOverheadTokens:c.instructionOverheadTokens},...o.compressionReport?
|
|
1668
|
-
{compression:o.compressionReport}:{},constraints:{backend:p,schemaVersion:n.schemaVersion,...d===null?{}:{structurallyValid:d}},qualityStatus:
|
|
1669
|
-
backend:p,hayEsquema:e.response?.schema!=null,ageMs:l,cascada:
|
|
1670
|
-
n).requiresFreshData}:{},...r==="semantic"&&y?.semantico?{semanticScore:y.semantico.similarity}:{}},cost:v,latencyMs:{total:
|
|
1671
|
-
let r=new
|
|
1672
|
-
origen:"fail_open"})).result}async llamadaDirecta(e,n,r){let o=r.origen==="measure",i=new
|
|
1673
|
-
"none"};}let c=e.response?.schema,l=[...e.messages];e.structuredData!==void 0&&
|
|
1669
|
+
{compression:o.compressionReport}:{},constraints:{backend:p,schemaVersion:n.schemaVersion,...d===null?{}:{structurallyValid:d}},qualityStatus:Hb(r,d,S),qualityLedger:Dd({cacheResult:r,structurallyValid:d,
|
|
1670
|
+
backend:p,hayEsquema:e.response?.schema!=null,ageMs:l,cascada:f,hechos:y}),...f?{modelCascade:f}:{},...m?{deferred:m}:{},...b?{cacheWrites:b}:{},...x?{nativeSavings:x}:{},quality:{...r!=="miss"?{freshnessPassed:!It(
|
|
1671
|
+
n).requiresFreshData}:{},...r==="semantic"&&y?.semantico?{semanticScore:y.semantico.similarity}:{}},cost:v,latencyMs:{total:E,preprocessing:Math.max(0,E-h),provider:h},traces:s.all()}}async failOpenDirect(e,n){
|
|
1672
|
+
let r=new pt(this.now);return r.record("fail-open","internal optimizer error \u2014 bypassed to a direct provider call",{error:n instanceof Error?n.message:String(n)}),(await this.llamadaDirecta(e,r,{
|
|
1673
|
+
origen:"fail_open"})).result}async llamadaDirecta(e,n,r){let o=r.origen==="measure",i=new at,s=this.costModelFor(e.model),a;try{a=nn(e);}catch{a={schemaVersion:e.response?.version??e.response?.contractId??
|
|
1674
|
+
"none"};}let c=e.response?.schema,l=[...e.messages];e.structuredData!==void 0&&dr(l,{role:"system",content:JSON.stringify(e.structuredData)});let u=this.now(),d={model:e.model,messages:l,...e.tools?.length?
|
|
1674
1675
|
{tools:e.tools}:{},...c?{schema:c}:{},...G(e)!=null?{maxOutputTokens:G(e)}:{},...e.temperature!=null?{temperature:e.temperature}:{},...e.seed!=null?{seed:e.seed}:{},...e.reasoningEffort!=null?{reasoningEffort:e.
|
|
1675
|
-
reasoningEffort}:{}},p=r.origen==="measure"?r.sumidero?await this.llamarProveedorEnStream(d,r.testigo,r.sumidero):await this.llamarProveedor(d,r.testigo):await this.config.provider.generate(d),
|
|
1676
|
+
reasoningEffort}:{}},p=r.origen==="measure"?r.sumidero?await this.llamarProveedorEnStream(d,r.testigo,r.sumidero):await this.llamarProveedor(d,r.testigo):await this.config.provider.generate(d),h=this.
|
|
1676
1677
|
now()-u;i.baselineLlm=1,i.actualLlm=1,i.actualInput=p.usage.inputTokens,i.actualOutput=p.usage.outputTokens,i.baselineInput=p.usage.inputTokens,i.baselineOutput=p.usage.outputTokens,p.usage.cachedInputTokens&&
|
|
1677
1678
|
i.providerCached(p.usage.cachedInputTokens),p.unbilledRefusal===true?(i.unbilledCall(p.usage),i.servedUnbilledRefusal=true):(i.nativeCacheWrite(p.usage.cacheWriteInputTokens??0,p.usage.cacheWrite1hInputTokens??
|
|
1678
|
-
0),i.nativeCacheMarkedByLayer=false);let
|
|
1679
|
-
false&&(i.callsWithoutUsage=1);let
|
|
1680
|
-
length??0)>0;if(y&&(g=null),c&&!y){let x=
|
|
1681
|
-
e,a,"miss",i,s,n,
|
|
1682
|
-
|
|
1683
|
-
"the Measure license runs the layer in shadow mode: the request goes to the provider unchanged, so no cheaper tier
|
|
1684
|
-
this request went out on the direct fail-open path, which asks for no cheaper tier: that tier can be refused for
|
|
1685
|
-
wrong trade"}:void 0,void 0,e.savings?.standalone===true?{mode:"provider-default",breakpoints:0,reason:o?"the Measure
|
|
1686
|
-
|
|
1687
|
-
cache, as it does by default"}:void 0,b);return {result:{requestId:v.requestId,data:
|
|
1688
|
-
void 0?{finishReasonDetail:p.finishReasonDetail}:{},...p.refusal!==void 0?{refusal:p.refusal}:{},report:v},
|
|
1689
|
-
this.avisar("licencia-medir",
|
|
1690
|
-
{},s=null,a=null,c=null;try{let S=
|
|
1691
|
-
!0,...G(e)!=null?{maxOutputTokens:G(e)}:{}}));}catch{o.record("measure","no
|
|
1692
|
-
this.memoriaDeSombra.
|
|
1693
|
-
c);}let{result:
|
|
1694
|
-
true&&
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
traces=o.all(),
|
|
1698
|
-
r),a.referenceRejected=s.reason);let c=a.estimateCost(o),l=this.generateId(),
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
{}},cache:{result:"singleflight",...a.reference?{reference:{...a.reference}}:
|
|
1702
|
-
cost:c}}}creditoPorReferencia(e,n){if(typeof e=="string")return {ok:false,
|
|
1703
|
-
|
|
1704
|
-
model),topeDeSalida:G(n.request),diferible:n.toggles.deferrable===!0})}catch{
|
|
1705
|
-
let o=e.map(i=>i.content);r!==void 0&&
|
|
1679
|
+
0),i.nativeCacheMarkedByLayer=false);let f=Fn(e.model);f>1&&p.unbilledRefusal!==true&&(p.usage.cacheWriteInputTokens??0)>0&&i.providerCacheWritePremium(p.usage.cacheWriteInputTokens??0,f,s),p.usage.complete===
|
|
1680
|
+
false&&(i.callsWithoutUsage=1);let m=p.text,g=true,b={...o?{}:{origen:"fail_open"},final:{...p.finishReason!==void 0?{finishReason:p.finishReason}:{},...p.finishReasonDetail!==void 0?{finishReasonDetail:p.
|
|
1681
|
+
finishReasonDetail}:{},...G(e)!=null?{topeDelLlamante:G(e)}:{}}},y=(p.toolCalls?.length??0)>0;if(y&&(g=null),c&&!y){let x=et(p.text),E=x.ok?be(x.value,c).errors.length:1;g=E===0,b.validacion={resultado:g?
|
|
1682
|
+
"passed":"failed",errores:E,desenvuelto:false},x.ok&&(m=x.value);}let v=this.buildReport(e,a,"miss",i,s,n,ar(),cr(),void 0,void 0,g,"none",h,void 0,e.savings?.deferrable===true?{credited:false,creditedLedger:"\
|
|
1683
|
+
none",latency:o?"unchanged: on the Measure license (shadow mode) no processing tier is requested, so this request was scheduled exactly as an ordinary one.":"unchanged: the fail-open path asks for no \
|
|
1684
|
+
processing tier, so this request was scheduled exactly as an ordinary one.",reason:o?"the Measure license runs the layer in shadow mode: the request goes to the provider unchanged, so no cheaper tier \
|
|
1685
|
+
is asked for; upgrade to a paid plan to turn the lever on":"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 la\
|
|
1686
|
+
ck of capacity, and trading availability for a discount on a last-resort call is the wrong trade"}:void 0,void 0,e.savings?.standalone===true?{mode:"provider-default",breakpoints:0,reason:o?"the Measure\
|
|
1687
|
+
license runs the layer in shadow mode: the request went out unchanged, so the provider chose where to write its prompt cache, as it does by default":"the optimizer failed and this request went out un\
|
|
1688
|
+
changed on the direct fail-open path, so the provider chose where to write its prompt cache, as it does by default"}:void 0,b);return {result:{requestId:v.requestId,data:m,text:p.text,...y?{toolCalls:p.
|
|
1689
|
+
toolCalls}:{},...p.finishReason!==void 0?{finishReason:p.finishReason}:{},...p.finishReasonDetail!==void 0?{finishReasonDetail:p.finishReasonDetail}:{},...p.refusal!==void 0?{refusal:p.refusal}:{},report:v},
|
|
1690
|
+
response:p}}enSombra(){try{return this.config.licenseGate?.plan?.()==="measure"}catch{return false}}async generarEnSombra(e,n,r){this.avisar("licencia-medir",Ld);let o=new pt(this.now);o.record("measure",
|
|
1691
|
+
"shadow mode (Measure license): the request goes to the provider unchanged and nothing is served from cache");let i=e.savings??{},s=null,a=null,c=null;try{let S=nn(e);s=It(S),s.allowExactCache&&i.exactCache!==
|
|
1692
|
+
!1&&(a=rn(S)),s.allowSingleflight&&i.singleflight!==!1&&(c=An(S,{deferrable:i.deferrable===!0,toolDiscovery:i.toolDiscovery===!0,...G(e)!=null?{maxOutputTokens:G(e)}:{}}));}catch{o.record("measure","no\
|
|
1693
|
+
shadow estimate: the request could not be keyed");}let l=this.now(),u=a!==null&&this.memoriaDeSombra.vista(a,l),d=!u&&c!==null&&this.memoriaDeSombra.hayEnVuelo(c),p=c!==null&&!r;p&&this.memoriaDeSombra.
|
|
1694
|
+
entrar(c);let h;try{h=await this.llamadaDirecta(e,o,{origen:"measure",testigo:n,sumidero:r});}finally{p&&this.memoriaDeSombra.salir(c);}let{result:f,response:m}=h,g=(m.toolCalls?.length??0)>0,b=Ta(m);if(a!==
|
|
1695
|
+
null&&s!==null&&f.report.constraints.structurallyValid!==false&&!g&&m.finishReason!=="length"&&m.replayable!==false&&!b&&m.unbilledRefusal!==true&&ir(m.text)===null&&s.sensitiveTopic===null){let S=this.config.
|
|
1696
|
+
exactCacheTtlMs??864e5,C=s.maxCacheAgeMs==null?S:Math.min(S,s.maxCacheAgeMs);this.memoriaDeSombra.anotar(a,this.now()+C);}let v=u?"exact-repeat":d?"in-flight-duplicate":null,x=f.report.cost.basis==="me\
|
|
1697
|
+
asured"&&m.unbilledRefusal!==true,E=v&&x?Md(Math.max(0,f.report.cost.actual)):0;return o.record("measure",v?`would have avoided this call (${v})`:"no simulated lever applies",{wouldHaveSavedUsd:E}),f.report.
|
|
1698
|
+
measure={mode:"shadow",applied:false,wouldHaveSaved:{usd:E,basis:"shadow",avoidedCall:v},notSimulated:[...Od],upgradeUrl:zo},f.report.traces=o.all(),f}asCoalescedFollower(e,n,r,o,i,s={ok:false,reason:"absen\
|
|
1699
|
+
t"}){let a=new at;this.negativasSinCobro.has(e)&&(a.servedUnbilledRefusal=true),s.ok?a.avoidCallByReference(s.credit):(a.avoidCall(n,r),a.referenceRejected=s.reason);let c=a.estimateCost(o),l=this.generateId(),
|
|
1700
|
+
u=this.diferidoSinLlamada(i),d=u?{deferred:u}:{},p=this.escriturasSinLlamada(i),{deferred:h,streaming:f,cacheWrites:m,nativeSavings:g,...b}=e.report;return {...e,requestId:l,report:{...b,requestId:l,calls:{
|
|
1701
|
+
...e.report.calls,actualLlm:0,avoidedLlm:1},tokens:{baselineInput:a.baselineInput,actualInput:a.actualInput,eliminatedInput:a.eliminatedInput,compressedInput:a.compressedInput,baselineOutput:a.publishedBaselineOutput,
|
|
1702
|
+
actualOutput:a.actualOutput,eliminatedOutput:a.eliminatedOutput,...a.providerCachedInput?{providerCachedInput:a.providerCachedInput}:{}},cache:{result:"singleflight",...a.reference?{reference:{...a.reference}}:
|
|
1703
|
+
a.referenceRejected?{referenceRejected:a.referenceRejected}:{}},...d,...p?{cacheWrites:p}:{},qualityLedger:Ad(e.report.qualityLedger),cost:c}}}creditoPorReferencia(e,n){if(typeof e=="string")return {ok:false,
|
|
1704
|
+
reason:e};let r;try{r=n.calidad();}catch{r=false;}try{return _d(e,{ahoraMs:this.now(),modeloPedido:n.request.model,modeloServido:n.cascada.modeloServido,huella:n.huella(),textoServidoSha256:X(n.texto),claveLeida:n.
|
|
1705
|
+
claveLeida,calidadOk:r,precio:this.precioDocumentado(n.request.model),determinista:Rd(n.request),salidaDelModelo:Ku(n.request.model),topeDeSalida:G(n.request),diferible:n.toggles.deferrable===!0})}catch{
|
|
1706
|
+
return {ok:false,reason:"different-request"}}}assembleBaselinePrompt(e){return this.assemblePromptText(e.messages,e.tools,e.structuredData)}assemblePromptText(e,n,r){let o=e.map(i=>i.content);r!==void 0&&
|
|
1707
|
+
o.push(JSON.stringify(r));for(let i of n??[])o.push(ur(i));return o.join(`
|
|
1706
1708
|
`)}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;
|
|
1707
1709
|
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(
|
|
1708
|
-
e)}precioConocido(e,n=this.now()){return this.precioDelCliente(e)??
|
|
1709
|
-
slice(o+1)];if(i)return i}}precioDocumentado(e){return this.precioDelCliente(e)??
|
|
1710
|
+
e)}precioConocido(e,n=this.now()){return this.precioDelCliente(e)??Xt(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.
|
|
1711
|
+
slice(o+1)];if(i)return i}}precioDocumentado(e){return this.precioDelCliente(e)??st(e,this.now())}costModelFor(e,n=this.now()){let r=this.precioConocido(e,n);return r||(this.config.defaultCostModel?this.
|
|
1710
1712
|
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. \
|
|
1711
|
-
Pass { costModels: { "${e}": { inputPer1k, outputPer1k } } }.`),
|
|
1712
|
-
n.value,t.schema).valid?"met":"missed"}function
|
|
1713
|
-
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=
|
|
1714
|
-
e.push(i);}return e}function
|
|
1715
|
-
n)o+=1;else if(c===r&&(o-=1,o===0))return t.slice(e,a+1)}}function
|
|
1716
|
-
dation";switch(t){case "deterministic":case "exact":return "exact";case "semantic":return "task_equivalent";default:return "not_verified"}}function
|
|
1713
|
+
Pass { costModels: { "${e}": { inputPer1k, outputPer1k } } }.`),Gu))}};function Fb(t,e){if((e.toolCalls?.length??0)>0||!t.schema)return "none";let n=et(typeof e.text=="string"?e.text:"");return n.ok&&be(
|
|
1714
|
+
n.value,t.schema).valid?"met":"missed"}function et(t){try{return {ok:!0,value:JSON.parse(t)}}catch{}for(let e of qb(t))try{return {ok:!0,value:JSON.parse(e),rescatado:e}}catch{continue}return {ok:false}}function qb(t){
|
|
1715
|
+
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=Ub(t,o);i&&
|
|
1716
|
+
e.push(i);}return e}function Ub(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===
|
|
1717
|
+
n)o+=1;else if(c===r&&(o-=1,o===0))return t.slice(e,a+1)}}function Vb(t){return typeof t=="string"?t:JSON.stringify(t,null,2)}function Hb(t,e,n=false){if(e===false)return "rejected";if(n)return "bounded_degra\
|
|
1718
|
+
dation";switch(t){case "deterministic":case "exact":return "exact";case "semantic":return "task_equivalent";default:return "not_verified"}}function Wb(t,e,n){switch(t){case "no-served-tier":return `asked the \
|
|
1717
1719
|
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\
|
|
1718
1720
|
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\
|
|
1719
1721
|
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\
|
|
1720
1722
|
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\
|
|
1721
1723
|
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\
|
|
1722
|
-
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
|
|
1723
|
-
round(t*1e6)/1e6}function
|
|
1724
|
-
return
|
|
1725
|
-
return false;let n=t.original;return
|
|
1726
|
-
reason:"n/a (short-circuited)",rounds:0}}function
|
|
1727
|
-
if(t==null||typeof t!="object")return "";let r=t,o=[],i=e||"the value",s=
|
|
1728
|
-
if(a!=null){let
|
|
1729
|
-
null&&o.push(`${i}>=${p}`),typeof r.pattern=="string"&&o.push(`${i} matches /${r.pattern}/`);let
|
|
1730
|
-
g&&o.push(g);}if(r.items!==void 0){let
|
|
1731
|
-
0,200):""}function
|
|
1732
|
-
test(e.message))}function
|
|
1733
|
-
for(let n=t.length-1;n>=0;n--)if(t[n].role==="user"){t.splice(n,0,e);return}t.push(e);}function
|
|
1734
|
-
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
|
|
1735
|
-
role==="user"){e=r;break}if(e<0)return false;if(e<t.length-1)return true;let n=0;for(let r=0;r<e;r++)t[r].role==="user"&&(n+=1);return n>=2}function
|
|
1736
|
-
let n=
|
|
1737
|
-
return {submit:(e,n)=>
|
|
1724
|
+
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 sr(t){return Math.
|
|
1725
|
+
round(t*1e6)/1e6}function Ht(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}function Gb(t,e,n,r){if(e)return Ht(-t.extraCostUsd);let o=i=>t.actualInput/1e3*i.inputPer1k+t.actualOutput/1e3*i.outputPer1k;
|
|
1726
|
+
return Ht(o(r)-o(n))}function Kb(t,e){if(!(e>0))return false;if(e>=1)return true;let n=X(`${t}:cascade-sample`);return Number.parseInt(n.slice(0,13),16)/2**52<e}function up(t,e){if(!e.isAgentic||e.allowSemanticCache)
|
|
1727
|
+
return false;let n=t.original;return It({...t,original:{...n,savings:{...n.savings??{},semanticCache:"include-agentic"}}}).allowSemanticCache}function ar(){return {executionClass:"NO_RETRIEVAL",confidence:1,
|
|
1728
|
+
reason:"n/a (short-circuited)",rounds:0}}function cr(){return {chosen:"json-compact",encoded:"",instruction:"",candidateTokens:{},instructionOverheadTokens:0,reason:"no structured payload"}}function Pa(t,e="",n=null){
|
|
1729
|
+
if(t==null||typeof t!="object")return "";let r=t,o=[],i=e||"the value",s=f=>typeof r[f]=="number"?r[f]:null,a=s("maxLength"),c=s("minLength"),l=s("maxItems"),u=s("minItems"),d=s("maximum"),p=s("minimum");
|
|
1730
|
+
if(a!=null){let f=n!=null?Math.min(a,n):a;o.push(`${i}<=${f}ch`);}c!=null&&o.push(`${i}>=${c}ch`),l!=null&&o.push(`${i}<=${l} items`),u!=null&&o.push(`${i}>=${u} items`),d!=null&&o.push(`${i}<=${d}`),p!=
|
|
1731
|
+
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[f,m]of Object.entries(h)){let g=Pa(m,e?`${e}.${f}`:f,n);
|
|
1732
|
+
g&&o.push(g);}if(r.items!==void 0){let f=Pa(r.items,`${i} entries`,n);f&&o.push(f);}return o.join("; ")}function lr(t){let e=t.response;return e?e.contractId??e.version??JSON.stringify(e.schema??{}).slice(
|
|
1733
|
+
0,200):""}function Ta(t){return fl(t.finishReason)||typeof t.refusal=="string"&&t.refusal!==""}function Jb(t){return t.some(e=>/exceeds maxItems|exceeds maxLength|match pattern|exceeds maximum|below minimum|below minLength|below minItems/.
|
|
1734
|
+
test(e.message))}function ur(t){return JSON.stringify({type:"function",function:{name:t.id,...t.description?{description:t.description}:{},parameters:t.parameters??{type:"object",properties:{}}}})}function dr(t,e){
|
|
1735
|
+
for(let n=t.length-1;n>=0;n--)if(t[n].role==="user"){t.splice(n,0,e);return}t.push(e);}function Yb(t,e){if(e===false)return null;let n=typeof t=="object"&&t!==null?t:{};return e===true||t?n:null}function Ia(t,e=false){
|
|
1736
|
+
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 Ia(t,true)}function Zb(t){let e=-1;for(let r=t.length-1;r>=0;r--)if(t[r].
|
|
1737
|
+
role==="user"){e=r;break}if(e<0)return false;if(e<t.length-1)return true;let n=0;for(let r=0;r<e;r++)t[r].role==="user"&&(n+=1);return n>=2}function dp(t){return t instanceof Error?t.name:typeof t}function Ra(t,e){
|
|
1738
|
+
let n=No(t,e);return n.cacheReadMultiplier<1?n:null}var hp={anthropic:{peticiones:1e5,bytes:256e6},openai:{peticiones:5e4,bytes:2e8}},Xb=/^[A-Za-z0-9_-]{1,64}$/,gp="/v1/chat/completions",Qb=new Set(["completed","failed","expired","cancelled"]);function bp(t){
|
|
1739
|
+
return {submit:(e,n)=>ev(t,e,n??{}),status:(e,n)=>av(t,e,n?.signal),results:(e,n)=>dv(t,e,n?.signal),cancel:(e,n)=>uv(t,e,n?.signal)}}function Ko(t){let e=dl(t.provider);if(!e)throw new Error("[bvsala]\
|
|
1738
1740
|
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===
|
|
1739
1741
|
"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\
|
|
1740
|
-
ini's own Files API). Nothing was sent.");return e}async function
|
|
1741
|
-
true&&r.protocolo==="anthropic",s=new TextEncoder,a=e.map(({customId:
|
|
1742
|
-
"anthropic"?{custom_id:
|
|
1743
|
-
a,r.protocolo,o),l=[],u=new Map,d=new Map;c.forEach((m
|
|
1744
|
-
b===void 0&&(b=l.length,l.push(g),u.set(y,b));}return {customId:
|
|
1745
|
-
submittedAt:new Date(t.now()).toISOString(),requests:p,schemas:l};for(let
|
|
1746
|
-
let g=
|
|
1747
|
-
ailed before any provider batch was created: ${
|
|
1748
|
-
or.job holds them.`,b,y,{cause:
|
|
1749
|
-
for(let[n,r]of t.entries()){let o=r?.customId;if(typeof o!="string"||!
|
|
1742
|
+
ini's own Files API). Nothing was sent.");return e}async function ev(t,e,n){t.exigirLicencia(),t.exigirPalancas?.();let r=Ko(t);tv(e);let o=nv(n.maxRequestsPerBatch,r.protocolo),i=n.cacheSharedPrefix===
|
|
1743
|
+
true&&r.protocolo==="anthropic",s=new TextEncoder,a=e.map(({customId:f,request:m})=>{let g;try{g=r.cuerpo(rv(m,i));}catch(v){throw new TypeError(`[bvsala] batch request "${f}": ${Ho(v)}`)}let b=r.protocolo===
|
|
1744
|
+
"anthropic"?{custom_id:f,params:g}:{custom_id:f,method:"POST",url:gp,body:g},y=JSON.stringify(b);return {customId:f,linea:b,bytes:s.encode(y).length,modelo:typeof g.model=="string"?g.model:m.model}}),c=ov(
|
|
1745
|
+
a,r.protocolo,o),l=[],u=new Map,d=new Map;c.forEach((f,m)=>f.forEach(g=>d.set(g.customId,m)));let p=e.map(({customId:f,request:m})=>{let g=m.response?.schema,b;if(g){let y=JSON.stringify(g);b=u.get(y),
|
|
1746
|
+
b===void 0&&(b=l.length,l.push(g),u.set(y,b));}return {customId:f,model:m.model,batch:d.get(f),...b!==void 0?{schema:b}:{}}}),h={kind:"bvsala.batch",version:1,provider:r.protocolo,endpoint:r.endpoint,batchIds:[],
|
|
1747
|
+
submittedAt:new Date(t.now()).toISOString(),requests:p,schemas:l};for(let f=0;f<c.length;f++)try{let m=r.protocolo==="anthropic"?await iv(r,c[f],n.signal):await sv(r,c[f],n.signal);h.batchIds.push(m);}catch(m){
|
|
1748
|
+
let g=h.batchIds.length,b={...h,batchIds:[...h.batchIds],requests:h.requests.filter(v=>v.batch<g)},y=h.requests.filter(v=>v.batch>=g).map(v=>v.customId);throw new Po(g===0?`[bvsala] batch submission f\
|
|
1749
|
+
ailed before any provider batch was created: ${Ho(m)}.`:`[bvsala] batch submission failed after ${g} of ${c.length} provider batches were created: ${Ho(m)}. The created batches run and are billed; err\
|
|
1750
|
+
or.job holds them.`,b,y,{cause:m})}return h}function tv(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;
|
|
1751
|
+
for(let[n,r]of t.entries()){let o=r?.customId;if(typeof o!="string"||!Xb.test(o))throw new TypeError(`[bvsala] batch request #${n}: customId must be 1 to 64 letters, digits, "_" or "-" (got ${JSON.stringify(
|
|
1750
1752
|
o)}).`);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(
|
|
1751
1753
|
i.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(`[\
|
|
1752
1754
|
bvsala] 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(`[bvsal\
|
|
1753
|
-
a] batch request "${o}": structuredData is serialized by the layer's pipeline, which batches skip. Put the payload in the messages instead.`)}}function
|
|
1754
|
-
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
|
|
1755
|
+
a] batch request "${o}": structuredData is serialized by the layer's pipeline, which batches skip. Put the payload in the messages instead.`)}}function nv(t,e){let n=hp[e].peticiones;if(t===void 0)return n;
|
|
1756
|
+
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 rv(t,e){let n=0;for(;n<t.messages.length&&
|
|
1755
1757
|
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}:{},...G(t)!=null?{maxOutputTokens:G(
|
|
1756
|
-
t)}:{},...t.temperature!=null?{temperature:t.temperature}:{},...t.seed!=null?{seed:t.seed}:{},...t.reasoningEffort!=null?{reasoningEffort:t.reasoningEffort}:{},...e&&n>0?{stablePrefixMessages:n}:{}}}function
|
|
1757
|
-
let r=
|
|
1758
|
+
t)}:{},...t.temperature!=null?{temperature:t.temperature}:{},...t.seed!=null?{seed:t.seed}:{},...t.reasoningEffort!=null?{reasoningEffort:t.reasoningEffort}:{},...e&&n>0?{stablePrefixMessages:n}:{}}}function ov(t,e,n){
|
|
1759
|
+
let r=hp[e],o=new Map;for(let a of t){let c=e==="openai"?a.modelo:"",l=o.get(c);l?l.push(a):o.set(c,[a]);}let i=e==="anthropic"?15:0,s=[];for(let a of o.values()){let c=[],l=i;for(let u of a){let d=u.bytes+
|
|
1758
1760
|
1;if(i+d>r.bytes)throw new TypeError(`[bvsala] batch request "${u.customId}" is ${u.bytes} bytes, larger than a whole ${e} batch may be. Send it with generate() instead.`);c.length>0&&(c.length>=n||l+
|
|
1759
|
-
d>r.bytes)&&(s.push(c),c=[],l=i),c.push(u),l+=d;}c.length>0&&s.push(c);}return s}async function
|
|
1760
|
-
{}});return
|
|
1761
|
+
d>r.bytes)&&(s.push(c),c=[],l=i),c.push(u),l+=d;}c.length>0&&s.push(c);}return s}async function iv(t,e,n){let r=await pr(t,"/messages/batches",{method:"POST",json:{requests:e.map(o=>o.linea)},...n?{signal:n}:
|
|
1762
|
+
{}});return Aa(r,"Message Batch")}async function sv(t,e,n){let r=e.map(a=>JSON.stringify(a.linea)).join(`
|
|
1761
1763
|
`)+`
|
|
1762
|
-
`,o=new FormData;o.append("purpose","batch"),o.append("file",new Blob([r],{type:"application/jsonl"}),"bvsala-batch.jsonl");let i=await
|
|
1763
|
-
t,"/batches",{method:"POST",json:{input_file_id:
|
|
1764
|
-
let r=
|
|
1765
|
-
filter(c=>c.batch===o).length;r.push(t.protocolo==="anthropic"?
|
|
1766
|
-
return {id:t,estado:r,terminado:r==="ended",cancelando:r==="canceling",cuentas:{processing:
|
|
1767
|
-
function
|
|
1764
|
+
`,o=new FormData;o.append("purpose","batch"),o.append("file",new Blob([r],{type:"application/jsonl"}),"bvsala-batch.jsonl");let i=await pr(t,"/files",{method:"POST",form:o,...n?{signal:n}:{}}),s=await pr(
|
|
1765
|
+
t,"/batches",{method:"POST",json:{input_file_id:Aa(i,"file"),endpoint:gp,completion_window:"24h"},...n?{signal:n}:{}});return Aa(s,"batch")}async function av(t,e,n){t.exigirLicencia(),t.exigirPalancas?.();
|
|
1766
|
+
let r=Ko(t);Oa(e,r);let o=await Wo(r,e,n);return vp(e,o)}async function Wo(t,e,n){let r=[];for(let[o,i]of e.batchIds.entries()){let s=await pr(t,La(t,i),{method:"GET",...n?{signal:n}:{}}),a=e.requests.
|
|
1767
|
+
filter(c=>c.batch===o).length;r.push(t.protocolo==="anthropic"?cv(i,s):lv(i,s,a));}return r}function cv(t,e){let n=le(e),r=typeof n.processing_status=="string"?n.processing_status:"unknown",o=le(n.request_counts);
|
|
1768
|
+
return {id:t,estado:r,terminado:r==="ended",cancelando:r==="canceling",cuentas:{processing:St(o.processing),succeeded:St(o.succeeded),errored:St(o.errored),canceled:St(o.canceled),expired:St(o.expired)}}}
|
|
1769
|
+
function lv(t,e,n){let r=le(e),o=typeof r.status=="string"?r.status:"unknown",i=le(r.request_counts),s=St(i.total)||n,a=St(i.completed),c=St(i.failed),l=Math.max(0,s-a-c),u=Qb.has(o),d=o==="failed"?{processing:0,
|
|
1768
1770
|
succeeded:0,errored:s,canceled:0,expired:0}:{processing:u?0:l,succeeded:a,errored:c+(o==="completed"?l:0),canceled:o==="cancelled"?l:0,expired:o==="expired"?l:0},p=Array.isArray(le(r.errors).data)?le(
|
|
1769
|
-
r.errors).data.map(
|
|
1771
|
+
r.errors).data.map(h=>le(h).message).filter(h=>typeof h=="string"):[];return {id:t,estado:o,terminado:u,cancelando:o==="cancelling",cuentas:d,...typeof r.output_file_id=="string"&&r.output_file_id!==""?
|
|
1770
1772
|
{salida:r.output_file_id}:{},...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"}:{}}}
|
|
1771
|
-
function
|
|
1773
|
+
function vp(t,e){let n={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+=
|
|
1772
1774
|
o.cuentas.canceled,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=>({
|
|
1773
|
-
id:o.id,status:o.estado}))}}async function
|
|
1774
|
-
/cancel`,{method:"POST",...n?{signal:n}:{}});return
|
|
1775
|
-
if(l.terminado)if(r.protocolo==="anthropic"){let u=await
|
|
1776
|
-
let d=await
|
|
1777
|
-
requests){let u=o[l.batch];if(!u.terminado){c+=1;continue}let d=l.schema!==void 0?e.schemas[l.schema]:void 0;a.push(
|
|
1778
|
-
e,a,c)}}function
|
|
1775
|
+
id:o.id,status:o.estado}))}}async function uv(t,e,n){t.exigirLicencia(),t.exigirPalancas?.();let r=Ko(t);Oa(e,r);let o=await Wo(r,e,n);for(let i of o)i.terminado||i.cancelando||await pr(r,`${La(r,i.id)}\
|
|
1776
|
+
/cancel`,{method:"POST",...n?{signal:n}:{}});return vp(e,await Wo(r,e,n))}async function dv(t,e,n){t.exigirLicencia(),t.exigirPalancas?.();let r=Ko(t);Oa(e,r);let o=await Wo(r,e,n),i=new Map;for(let l of o)
|
|
1777
|
+
if(l.terminado)if(r.protocolo==="anthropic"){let u=await Da(r,`${La(r,l.id)}/results`,{method:"GET",...n?{signal:n}:{}});for await(let d of mp(u))pv(i,d);}else for(let u of [l.salida,l.errores]){if(!u)continue;
|
|
1778
|
+
let d=await Da(r,`/files/${encodeURIComponent(u)}/content`,{method:"GET",...n?{signal:n}:{}});for await(let p of mp(d))fv(i,p);}let s=Math.max(t.now(),Date.parse(e.submittedAt)||0),a=[],c=0;for(let l of e.
|
|
1779
|
+
requests){let u=o[l.batch];if(!u.terminado){c+=1;continue}let d=l.schema!==void 0?e.schemas[l.schema]:void 0;a.push(mv(t,r,l,d,i.get(l.customId),u,s));}return {ended:o.every(l=>l.terminado),items:a,summary:bv(
|
|
1780
|
+
e,a,c)}}function pv(t,e){let n=le(e),r=n.custom_id;if(typeof r!="string"||t.has(r))return;let o=le(n.result);switch(o.type){case "succeeded":t.set(r,{tipo:"ok",cuerpo:o.message});return;case "errored":{
|
|
1779
1781
|
let i=le(le(o.error).error);t.set(r,{tipo:"errored",error:{type:typeof i.type=="string"?i.type:"error",message:typeof i.message=="string"?i.message:"the provider reported an error"}});return}case "canc\
|
|
1780
|
-
eled":t.set(r,{tipo:"canceled"});return;case "expired":t.set(r,{tipo:"expired"});return;default:return}}function
|
|
1782
|
+
eled":t.set(r,{tipo:"canceled"});return;case "expired":t.set(r,{tipo:"expired"});return;default:return}}function fv(t,e){let n=le(e),r=n.custom_id;if(typeof r!="string"||t.has(r))return;let o=n.error;if(o!=
|
|
1781
1783
|
null){let l=le(o),u=typeof l.code=="string"?l.code:"error";if(u==="batch_expired"){t.set(r,{tipo:"expired"});return}if(u==="batch_cancelled"||u==="batch_canceled"){t.set(r,{tipo:"canceled"});return}t.
|
|
1782
1784
|
set(r,{tipo:"errored",error:{type:u,message:typeof l.message=="string"?l.message:"the provider reported an error"}});return}let i=le(n.response),s=i.status_code,a=i.body;if(typeof s=="number"&&s>=200&&
|
|
1783
1785
|
s<300&&a!==void 0){t.set(r,{tipo:"ok",cuerpo:a});return}let c=le(le(a).error);t.set(r,{tipo:"errored",error:{type:typeof c.type=="string"?c.type:`http_${typeof s=="number"?s:"error"}`,message:typeof c.
|
|
1784
|
-
message=="string"?c.message:"the provider reported an error"}});}function
|
|
1786
|
+
message=="string"?c.message:"the provider reported an error"}});}function mv(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,
|
|
1785
1787
|
outcome:"errored",reason:`the provider rejected the whole batch before running it: ${i.fallo??"no reason given"}`,error:{type:"batch_failed",message:i.fallo??"the provider rejected the batch"}}:i.estado===
|
|
1786
1788
|
"expired"?{...a,outcome:"expired",reason:"the batch expired before this request ran: no answer and no usage"}:i.estado==="cancelled"?{...a,outcome:"canceled",reason:"the batch was canceled before this\
|
|
1787
1789
|
request ran: no answer and no usage"}:{...a,outcome:"missing",reason:"the provider returned no result line for this request; nothing is assumed about it"};switch(o.tipo){case "errored":return {...a,outcome:"\
|
|
@@ -1789,182 +1791,186 @@ errored",reason:`the provider could not run this request (${o.error.type}: ${o.e
|
|
|
1789
1791
|
...a,outcome:"canceled",reason:c?"canceled before 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:"\
|
|
1790
1792
|
expired",reason:c?"the batch reached its 24-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 exp\
|
|
1791
1793
|
ired: no answer and no usage"};}let l={model:n.model,messages:[],...r?{schema:r}:{}},u;try{u=e.leer(o.cuerpo,l);}catch(y){return {...a,outcome:"succeeded",reason:`the provider ran this req\
|
|
1792
|
-
uest but its answer could not be read (${
|
|
1793
|
-
|
|
1794
|
-
length>0?{toolCalls:u.toolCalls}:{},...u.finishReason?{finishReason:u.finishReason}:{},usage:u.usage,...p?{servedTier:p}:{}};if(!
|
|
1795
|
-
basis,standardCost:
|
|
1796
|
-
s usage was priced at the standard and at the batch published rate cards, component by component (${(
|
|
1797
|
-
0)return {};let n=
|
|
1794
|
+
uest but its answer could not be read (${Ho(y)}): nothing is credited`}}let d=hv(u,r),p=c?u.servedServiceTier:"batch",h=e.origen==="anthropic"||e.origen==="openai"?e.origen:null,f=vv(t.costModels,n.model),
|
|
1795
|
+
m=Hr({modelo:n.model,uso:u.usage,tierServido:p,origen:h,tierLeidoDe:c?"cuerpo":"lote",...f?{precioDelCliente:f}:{},ahoraMs:s}),g={...a,outcome:"succeeded",text:u.text,...d,...u.toolCalls&&u.toolCalls.
|
|
1796
|
+
length>0?{toolCalls:u.toolCalls}:{},...u.finishReason?{finishReason:u.finishReason}:{},usage:u.usage,...p?{servedTier:p}:{}};if(!m.ok)return {...g,reason:gv(m.motivo,p)};let b={amount:m.importe,basis:m.
|
|
1797
|
+
basis,standardCost:Go(m.costeEstandar),appliedCost:Go(m.costeAplicado),pricesCheckedOn:m.consultado,basisReason:m.motivoBasis};return {...g,tierSaving:b,reason:`billed at the "${p}" tier; this request'\
|
|
1798
|
+
s usage was priced at the standard and at the batch published rate cards, component by component (${(m.factorEfectivo*100).toFixed(1)}% of standard)`}}function hv(t,e){if(!e||(t.toolCalls?.length??0)>
|
|
1799
|
+
0)return {};let n=et(typeof t.text=="string"?t.text:"");return n.ok?be(n.value,e).valid?{data:n.value,contract:"met"}:{contract:"missed"}:{contract:"missed"}}function gv(t,e){switch(t){case "no-served-t\
|
|
1798
1800
|
ier":return "the provider reported no service tier for this 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\
|
|
1799
1801
|
this result, a tier this layer has no published rate for: nothing is credited`;case "standard-rate-tier":return `the provider reports the "${e}" tier for this result, which is not billed below the stan\
|
|
1800
1802
|
dard rate: nothing is credited`;case "no-tier-price":return "there is no published batch price for this model from this provider (or it has expired): nothing is credited";case "no-standard-price":return "\
|
|
1801
1803
|
this model has no list price of its own here, so there is no standard rate card to price the difference against: nothing is credited";case "incomplete-usage":return "the provider's usage for this result\
|
|
1802
|
-
is incomplete, so the difference cannot be priced: nothing is credited";case "no-difference":return "this result's usage costs the same at both published rate cards: nothing is credited"}}var
|
|
1803
|
-
let r=0,o=0,i=0,s=0,a=0,c=0,l=0,u=0n,d=0,p=0,
|
|
1804
|
-
(c+=1,b.basis==="measured"&&(l+=1),u+=BigInt(Math.round(b.amount*
|
|
1805
|
-
d",
|
|
1804
|
+
is incomplete, so the difference cannot be priced: nothing is credited";case "no-difference":return "this result's usage costs the same at both published rate cards: nothing is credited"}}var fp=1e10;function bv(t,e,n){
|
|
1805
|
+
let r=0,o=0,i=0,s=0,a=0,c=0,l=0,u=0n,d=0,p=0,h;for(let g of e){g.outcome==="succeeded"?r+=1:g.outcome==="errored"?o+=1:g.outcome==="canceled"?i+=1:g.outcome==="expired"?s+=1:a+=1;let b=g.tierSaving;b&&
|
|
1806
|
+
(c+=1,b.basis==="measured"&&(l+=1),u+=BigInt(Math.round(b.amount*fp)),d+=b.standardCost,p+=b.appliedCost,(!h||b.pricesCheckedOn<h)&&(h=b.pricesCheckedOn));}let f=c===0?"none":l===c?"measured":"estimate\
|
|
1807
|
+
d",m=`${r} of ${t.requests.length} requests succeeded`+(n>0?` (${n} still running)`:"")+`; ${c} were valued at the provider's standard and batch published rate cards`+(f==="none"?"":` (${f})`)+". Repo\
|
|
1806
1808
|
rted only: batch requests are not metered and 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,
|
|
1807
|
-
expired:s,missing:a,pending:n,credited:c,tierSaving:Number(u)/
|
|
1809
|
+
expired:s,missing:a,pending:n,credited:c,tierSaving:Number(u)/fp,standardCost:Go(d),appliedCost:Go(p),basis:f,...h?{pricesCheckedOn:h}:{},creditedLedger:"none",reason:m}}function Oa(t,e){let n=t;if(!n||
|
|
1808
1810
|
n.kind!=="bvsala.batch"||n.version!==1||!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.
|
|
1809
1811
|
length))throw new TypeError("[bvsala] 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\
|
|
1810
|
-
${n.provider} at ${n.endpoint}; this layer's provider is ${e.protocolo} at ${e.endpoint}. Read it with a layer configured like the one that submitted it.`)}function
|
|
1811
|
-
ropic"?`/messages/batches/${encodeURIComponent(e)}`:`/batches/${encodeURIComponent(e)}`}async function
|
|
1812
|
-
`provider ${r.status}: ${o}`)}return r}async function
|
|
1813
|
-
d no ${e} id`);return n}async function*
|
|
1814
|
-
`)){let a=
|
|
1815
|
-
`);for(;c>=0;){let l=
|
|
1816
|
-
`);}}o+=r.decode();let i=
|
|
1817
|
-
"/");return r>=0?t[e.slice(r+1)]:void 0}function le(t){return typeof t=="object"&&t!==null?t:{}}function
|
|
1818
|
-
Error?t.message:String(t)}function
|
|
1819
|
-
this.opts=e,this.pollIntervalMs=e.pollIntervalMs??
|
|
1812
|
+
${n.provider} at ${n.endpoint}; this layer's provider is ${e.protocolo} at ${e.endpoint}. Read it with a layer configured like the one that submitted it.`)}function La(t,e){return t.protocolo==="anth\
|
|
1813
|
+
ropic"?`/messages/batches/${encodeURIComponent(e)}`:`/batches/${encodeURIComponent(e)}`}async function Da(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(
|
|
1814
|
+
`provider ${r.status}: ${o}`)}return r}async function pr(t,e,n){return await(await Da(t,e,n)).json()}function Aa(t,e){let n=le(t).id;if(typeof n!="string"||n==="")throw new Error(`the provider returne\
|
|
1815
|
+
d no ${e} id`);return n}async function*mp(t){let e=t.body;if(!e||typeof e.getReader!="function"){for(let s of (await t.text()).split(`
|
|
1816
|
+
`)){let a=_a(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(`
|
|
1817
|
+
`);for(;c>=0;){let l=_a(o.slice(0,c));l!==void 0&&(yield l),o=o.slice(c+1),c=o.indexOf(`
|
|
1818
|
+
`);}}o+=r.decode();let i=_a(o);i!==void 0&&(yield i);}function _a(t){let e=t.trim();if(e!=="")try{return JSON.parse(e)}catch{return}}function vv(t,e){if(!t)return;let n=t[e];if(n)return n;let r=e.indexOf(
|
|
1819
|
+
"/");return r>=0?t[e.slice(r+1)]:void 0}function le(t){return typeof t=="object"&&t!==null?t:{}}function St(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.floor(t):0}function Ho(t){return t instanceof
|
|
1820
|
+
Error?t.message:String(t)}function Go(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}function yv(t){try{let e=new URL(t);return e.username="",e.password="",e.search="",e.hash="",e.toString()}catch{return "the configured licenseServerUrl"}}var kv=36e5,xv=7*86400,wv=3e4,Jo=class{opts;pollIntervalMs;refreshLeadSeconds;timer=null;enVuelo=false;parado=false;controller=null;credencialAvisada=new Set;currentExpiresAt;currentOrg;currentPlan;currentJti;constructor(e){
|
|
1821
|
+
this.opts=e,this.pollIntervalMs=e.pollIntervalMs??kv,this.refreshLeadSeconds=e.refreshLeadSeconds??xv;let n=kt(yt(e.initialToken),e.publicKey);this.currentExpiresAt=n.signatureValid&&n.payload?n.payload.
|
|
1820
1822
|
expires_at:0,this.currentOrg=n.signatureValid?n.payload?.org_id:void 0,this.currentPlan=n.signatureValid?n.payload?.plan:void 0,this.currentJti=n.signatureValid?n.payload?.jti:void 0;}start(){this.timer||
|
|
1821
1823
|
(this.checkNow(),this.timer=setInterval(()=>{this.checkNow();},this.pollIntervalMs),this.timer.unref?.());}stop(){this.parado=true,this.timer&&clearInterval(this.timer),this.timer=null,this.controller?.abort(),
|
|
1822
1824
|
this.controller=null;}avisarCredencialRechazada(e){this.credencialAvisada.has(e)||(this.credencialAvisada.add(e),console.warn(`[bv-sala] automatic pickup of the renewed license is failing with HTTP ${e}\
|
|
1823
|
-
at ${
|
|
1825
|
+
at ${yv(this.opts.url)}. Check 'serviceAccountKey' (rotated? from another organization?) and 'licenseServerUrl': until this works, the token will NOT renew itself and the SDK will stop operating when\
|
|
1824
1826
|
the grace period ends. (This warning is not muted by 'silenceWarnings'.)`));}nowSeconds(){return Math.floor((this.opts.now?this.opts.now():Date.now())/1e3)}async checkNow(){if(this.enVuelo||this.parado)
|
|
1825
1827
|
return false;let e=this.currentJti!==void 0&&this.opts.revocados?.snapshot().has(this.currentJti)===true;if(this.currentPlan!=="measure"&&!e&&this.currentExpiresAt-this.nowSeconds()>this.refreshLeadSeconds)
|
|
1826
|
-
return false;this.enVuelo=true;let n=new AbortController;this.controller=n;let r=setTimeout(()=>n.abort(),this.opts.requestTimeoutMs??
|
|
1828
|
+
return false;this.enVuelo=true;let n=new AbortController;this.controller=n;let r=setTimeout(()=>n.abort(),this.opts.requestTimeoutMs??wv);r.unref?.();try{let i=await(this.opts.fetchImpl??globalThis.fetch.bind(
|
|
1827
1829
|
globalThis))(this.opts.url,{signal:n.signal,headers:{authorization:`Bearer ${this.opts.serviceAccountKey}`,accept:"application/json"}});if(!i.ok)return (i.status===401||i.status===403||i.status===404)&&
|
|
1828
|
-
this.avisarCredencialRechazada(i.status),!1;this.credencialAvisada.clear();let s=await i.json();if(typeof s.token!="string")return !1;let a=
|
|
1830
|
+
this.avisarCredencialRechazada(i.status),!1;this.credencialAvisada.clear();let s=await i.json();if(typeof s.token!="string")return !1;let a=yt(s.token),c=kt(a,this.opts.publicKey);if(!c.signatureValid||
|
|
1829
1831
|
!c.payload)return !1;let l=this.currentPlan==="measure"&&c.payload.plan!=="measure",u=e&&c.payload.jti!==this.currentJti;return !l&&!u&&c.payload.expires_at<=this.currentExpiresAt||this.currentOrg&&c.payload.
|
|
1830
1832
|
org_id!==this.currentOrg||this.opts.revocados?.snapshot().has(c.payload.jti)||this.parado?!1:(this.currentExpiresAt=c.payload.expires_at,this.currentOrg=c.payload.org_id,this.currentPlan=c.payload.plan,
|
|
1831
|
-
this.currentJti=c.payload.jti,this.opts.onNewToken(a),!0)}catch{return false}finally{clearTimeout(r),this.controller===n&&(this.controller=null),this.enVuelo=false;}}};var
|
|
1832
|
-
1e3;function
|
|
1833
|
-
er"?e.ahora:Date.now();if(t.at>n+
|
|
1834
|
-
o.outputPer1k)||o.cachedInputPer1k!==void 0&&!
|
|
1833
|
+
this.currentJti=c.payload.jti,this.opts.onNewToken(a),!0)}catch{return false}finally{clearTimeout(r),this.controller===n&&(this.controller=null),this.enVuelo=false;}}};var yp=2e3,kp=200,Sv=200,Ev=10,Cv=1e7,Tv=5,Rv=48*3600*1e3,Ma=/^[A-Za-z0-9._:/-]{1,128}$/,wn=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0,fr=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=
|
|
1834
|
+
1e3;function Pv(t,e={}){if(!Ma.test(t.requestId)||!Ma.test(t.requestedModel)||!Ma.test(t.servedModel)||typeof t.at!="number"||!Number.isFinite(t.at)||t.at<1e12)return null;let n=typeof e?.ahora=="numb\
|
|
1835
|
+
er"?e.ahora:Date.now();if(t.at>n+Rv)return null;let r=t.optimized;if(!fr(r.cost)||!wn(r.inputTokens)||!wn(r.cachedInputTokens)||!wn(r.outputTokens))return null;let o=t.prices;if(!fr(o.inputPer1k)||!fr(
|
|
1836
|
+
o.outputPer1k)||o.cachedInputPer1k!==void 0&&!fr(o.cachedInputPer1k))return null;let i={basis:"verification",requestId:t.requestId,at:Math.floor(t.at),stratum:t.stratum,outcome:t.outcome,requestedModel:t.
|
|
1835
1837
|
requestedModel,servedModel:t.servedModel,cacheResult:t.cacheResult,optimizedCost:r.cost,optimizedInputTokens:r.inputTokens,optimizedCachedInputTokens:Math.min(r.cachedInputTokens,r.inputTokens),optimizedOutputTokens:r.
|
|
1836
|
-
outputTokens,inputPer1k:o.inputPer1k,...o.cachedInputPer1k!==void 0?{cachedInputPer1k:o.cachedInputPer1k}:{},outputPer1k:o.outputPer1k};if(t.outcome==="paired"){let s=t.naive;if(!s||!
|
|
1837
|
-
inputTokens)||!
|
|
1838
|
-
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
|
|
1839
|
-
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=
|
|
1840
|
-
push(n),this.pendientes.length>
|
|
1838
|
+
outputTokens,inputPer1k:o.inputPer1k,...o.cachedInputPer1k!==void 0?{cachedInputPer1k:o.cachedInputPer1k}:{},outputPer1k:o.outputPer1k};if(t.outcome==="paired"){let s=t.naive;if(!s||!fr(s.cost)||!wn(s.
|
|
1839
|
+
inputTokens)||!wn(s.cachedInputTokens)||!wn(s.outputTokens)||s.cachedInputTokens>s.inputTokens)return null;if(i.naiveCost=s.cost,i.naiveInputTokens=s.inputTokens,i.naiveCachedInputTokens=s.cachedInputTokens,
|
|
1840
|
+
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 Yo=class{o;flushIntervalMs;pendientes=[];conteos=new Map;reintentos=[];inflight=null;timer;fallosSeguidos=0;ultimoFallo=Number.
|
|
1841
|
+
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=Pv(e,{ahora:this.ahora()});}catch{n=null;}n&&(this.pendientes.
|
|
1842
|
+
push(n),this.pendientes.length>yp&&this.pendientes.splice(0,this.pendientes.length-yp),this.pendientes.length>=kp&&this.flushSiToca());}flushSiToca(){return this.reintentos.length>0&&this.ahora()-this.
|
|
1841
1843
|
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();},
|
|
1842
1844
|
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();
|
|
1843
1845
|
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;
|
|
1844
|
-
if(this.pendientes.length===0&&this.conteos.size===0)return null;let n=this.pendientes.splice(0,
|
|
1845
|
-
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??
|
|
1846
|
-
fetch;if(e)for(let n=0;n<
|
|
1847
|
-
Bearer ${this.o.serviceAccountKey}`,"content-type":"application/json",[
|
|
1848
|
-
this.ahora(),this.reencolar(n),this.avisarDeFallo(`the server responded ${r.status}`),!1):r.status===401||r.status===403?(this.o.silenceWarnings||
|
|
1846
|
+
if(this.pendientes.length===0&&this.conteos.size===0)return null;let n=this.pendientes.splice(0,kp),r=[];for(let[o,i]of this.conteos){if(r.length>=Sv)break;let[s="",a=""]=o.split("|"),c=Math.min(i,Cv);
|
|
1847
|
+
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??Pt)(),samples:n,counts:r}}async hacerFlush(){let e=this.o.fetchImpl??globalThis.
|
|
1848
|
+
fetch;if(e)for(let n=0;n<Tv&&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:`\
|
|
1849
|
+
Bearer ${this.o.serviceAccountKey}`,"content-type":"application/json",[wr]:`sdk/${Ve}`},body:JSON.stringify(n)});return r.ok?(this.fallosSeguidos=0,!0):r.status>=500?(this.fallosSeguidos++,this.ultimoFallo=
|
|
1850
|
+
this.ahora(),this.reencolar(n),this.avisarDeFallo(`the server responded ${r.status}`),!1):r.status===401||r.status===403?(this.o.silenceWarnings||Ee(`verification-auth-${r.status}`,`[bvsala] verificat\
|
|
1849
1851
|
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):
|
|
1850
1852
|
(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 \
|
|
1851
1853
|
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.
|
|
1852
|
-
reintentos.unshift(e);this.reintentos.length>
|
|
1854
|
+
reintentos.unshift(e);this.reintentos.length>Ev;)this.reintentos.pop();}avisarDeFallo(e){if(this.o.silenceWarnings)return;let n=this.fallosSeguidos;n<3||(n-3)%12!==0||console.warn(`[bvsala] verificatio\
|
|
1853
1855
|
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,
|
|
1854
|
-
conteos:this.conteos.size,reintentos:this.reintentos.length}}};var
|
|
1856
|
+
conteos:this.conteos.size,reintentos:this.reintentos.length}}};var $a=72*3600,Iv,xp=new Set(Object.values(Sr).flatMap(t=>t.flatMap(e=>[e,`openai/${e}`]))),wp="[bvsala] `gpt-tokenizer` is not installed, so token counts for OpenAI models are ESTIMATED with a built-\
|
|
1855
1857
|
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 \
|
|
1856
|
-
(`npm i gpt-tokenizer`) and the SDK loads it automatically.";function
|
|
1857
|
-
|
|
1858
|
-
void 0&&t.semanticCacheStore!==t.semanticCache?" Both were given and they differ: `semanticCacheStore` is the one in use.":""))
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
{
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
`)
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1858
|
+
(`npm i gpt-tokenizer`) and the SDK loads it automatically.";function FC(t){let e=(f,m)=>{t.silenceWarnings!==true&&Ee(f,m);},n=(f,m)=>{el()||e(f,m);};t.semanticCache!==void 0&&n("semanticCache-renombrado",
|
|
1859
|
+
"[bvsala] `createSavingsLayer({ semanticCache })` is deprecated: pass the store as `semanticCacheStore` (same value; `savings.semanticCache` on a request does not change). The old name is removed in 0\
|
|
1860
|
+
.5."+(t.semanticCacheStore!==void 0&&t.semanticCacheStore!==t.semanticCache?" Both were given and they differ: `semanticCacheStore` is the one in use.":""));t.licensePublicKey!==void 0&&n(
|
|
1861
|
+
"licensePublicKey-obsoleto","[bvsala] `createSavingsLayer({ licensePublicKey })` is deprecated and ignored: the published package always verifies `licenseKey` against BiVelio's embedded public key. Th\
|
|
1862
|
+
e option is removed in 0.5; delete it from your config."),t.licenseGate&&(e("licenseGate-ignorado","[bvsala] Ignoring the injected `licenseGate`: in the published package a license is only accepted\
|
|
1863
|
+
as a `licenseKey` verified against BiVelio's embedded public key, and the `licenseGate` option is removed in 0.5. Get yours at https://savings.bivelio.com/dashboard/install"),t={...t,licenseGate:void 0});
|
|
1864
|
+
let o={...t,tokenizer:t.tokenizer??di},i=t.tokenizer==null&&t.exactTokenizer!==false?Iv??=fi(di).catch(()=>false):Promise.resolve(true),s,a;if(t.licenseKey&&!t.licenseGate){let f=So;if(t.
|
|
1865
|
+
licenseServerUrl){let m=new xt,g=v=>mn(v,f,{revocation:m,...t.now?{now:t.now}:{},maxStalenessSeconds:t.licenseRevocation?.maxStalenessSeconds??$a}),b=g(t.licenseKey);o.licenseGate={isEntitled:v=>b.isEntitled(
|
|
1866
|
+
v),isActive:()=>b.isActive(),status:()=>b.status(),reason:()=>b.reason(),plan:()=>b.plan?.()};let y=`${t.licenseServerUrl.replace(/\/+$/,"")}/licenses/revocations`;s=new gn({url:y,publicKeyPem:f,snapshot:m,
|
|
1867
|
+
getRefreshAfter:()=>b.refreshAfter?.(),...t.now?{nowSeconds:()=>Math.floor(t.now()/1e3)}:{},...t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.licensePollIntervalSeconds!=null?{pollIntervalSeconds:t.
|
|
1868
|
+
licensePollIntervalSeconds}:{},...t.silenceWarnings!=null?{silenceWarnings:t.silenceWarnings}:{},...t.licenseRevocation??{}}),s.start(),t.serviceAccountKey&&t.licenseRefresh?.enabled!==false&&(a=new Jo({
|
|
1869
|
+
url:`${t.licenseServerUrl.replace(/\/+$/,"")}/api/license/current`,serviceAccountKey:t.serviceAccountKey,publicKey:f,initialToken:t.licenseKey,revocados:m,onNewToken:v=>{b=g(v);},...t.licenseFetch?{fetchImpl:t.
|
|
1870
|
+
licenseFetch}:{},...t.now?{now:t.now}:{},...t.licenseRefresh?.intervalMs!=null?{pollIntervalMs:t.licenseRefresh.intervalMs}:{},...t.licenseRefresh?.leadSeconds!=null?{refreshLeadSeconds:t.licenseRefresh.
|
|
1871
|
+
leadSeconds}:{}}),a.start());}else o.licenseGate=Co(t.licenseKey,f,t.now);}t.cacheBreakpointStore&&t.cacheBreakpoints!=="auto"&&e("almacen-de-colocacion-sin-auto",'[bv-sala] `cacheBreakpointStore` was g\
|
|
1872
|
+
iven but `cacheBreakpoints` is not "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.');
|
|
1873
|
+
let c=qo(t.verification);!c.activo&&c.motivo==="invalido"&&e("verificacion-invalida",Qd(t.verification));let l,u;if(c.activo){let f;if(t.serviceAccountKey&&t.metering?.enabled!==false)if(t.meteringUrl){let m=/^(.*)\/api\/metering\/usage\/?$/.
|
|
1874
|
+
exec(t.meteringUrl);m&&(f=`${m[1]}/api/metering/verification`);}else t.licenseServerUrl&&(f=`${t.licenseServerUrl.replace(/\/+$/,"")}/api/metering/verification`);if(!f&&!c.onCheck)e("verificacion-sin-d\
|
|
1875
|
+
estino",ep);else {f&&t.serviceAccountKey&&(l=new Yo({url:f,serviceAccountKey:t.serviceAccountKey,...t.meteringFetch?{fetchImpl:t.meteringFetch}:t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.now?{now:t.
|
|
1876
|
+
now}:{},...t.metering?.flushIntervalMs!=null?{flushIntervalMs:t.metering.flushIntervalMs}:{},...t.silenceWarnings!=null?{silenceWarnings:t.silenceWarnings}:{}}),l.start());let m=l;u={encolar:g=>m?.encolar(
|
|
1877
|
+
g),...m?{contar:(g,b)=>m.contar(g,b)}:{},enReposo:()=>m?.flushSiToca()},e(`verificacion-activa:${c.tasa}`,Xd(c.tasa));}}let d=new Vo(o,u?{verificacion:u}:{}),p;if(t.serviceAccountKey&&t.metering?.enabled!==
|
|
1878
|
+
false){let f=t.meteringUrl??(t.licenseServerUrl?`${t.licenseServerUrl.replace(/\/+$/,"")}/api/metering/usage`:void 0);if(f||e("clave-de-servicio-sin-servidor",'[bvsala] `serviceAccountKey` is set but the\
|
|
1879
|
+
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\
|
|
1880
|
+
rUrl: "https://savings.bivelio.com"` \u2014 or drop `serviceAccountKey` for a zero-network deployment.'),f){p=new Ft({url:f,serviceAccountKey:t.serviceAccountKey,surface:"sdk",...t.metering?.orgId?{orgId:t.
|
|
1881
|
+
metering.orgId}:{},...t.metering?.flushIntervalMs!=null?{flushIntervalMs:t.metering.flushIntervalMs}:{},...t.metering?.maxBatch!=null?{maxBatch:t.metering.maxBatch}:{},...t.metering?.maxBuffer!=null?{
|
|
1882
|
+
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.
|
|
1883
|
+
silenceWarnings!=null?{silenceWarnings:t.silenceWarnings}:{}});let m=t.metering?.ci??tr();if(t.metering?.seatId)p.setSeat(t.metering.seatId,m);else {let g=p;nr(t.serviceAccountKey).then(b=>g.setSeat(b,
|
|
1884
|
+
m)).catch(()=>{});}p.start();}}return {batches:bp({provider:o.provider,...o.costModels?{costModels:o.costModels}:{},exigirLicencia:()=>d.exigirLicencia(),exigirPalancas:()=>d.exigirPalancas(),now:o.now??
|
|
1885
|
+
Date.now}),generate:async f=>{let m=await i,g=await d.generate(f);if(!m&&xp.has(f.model)&&e("tokenizador-exacto-ausente",wp),p)try{p.record(g.report);}catch{}return g},generateStream:(f,m)=>{let g=d.generateStream(
|
|
1886
|
+
f,m??{},i);return g.result.then(async b=>{if(p)try{p.record(b.report);}catch{}!await i&&xp.has(f.model)&&e("tokenizador-exacto-ausente",wp);},()=>{}),g},close:()=>{d.cerrarVerificacion(),l?.stop(),s?.stop(),
|
|
1887
|
+
a?.stop(),p?.stop();}}}function Na(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.
|
|
1888
|
+
toFixed(10).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"");return e==="-0"?"0":e}function Sp(t,e){if(t==null)return "";if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`[bvsala] toCsv: \
|
|
1889
|
+
column "${e}" holds a non-finite number`);return Na(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\
|
|
1890
|
+
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 _v(t,e){
|
|
1891
|
+
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=>Sp(o,o)).join(",")];for(let o of t)r.push(n.map(
|
|
1892
|
+
i=>Sp(o[i],i)).join(","));return r.map(o=>`${o}\r
|
|
1893
|
+
`).join("")}var Ep={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:"\
|
|
1894
|
+
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 Cp(t){let e=t.
|
|
1895
|
+
indexOf("/");return e>0?t.slice(0,e):void 0}function ja(t){let e=Cp(t)?.toLowerCase();return e!==void 0&&Object.hasOwn(Ep,e)?Ep[e]:void 0}function Tp(t){return ja(t)?.otel??Cp(t)}function Rp(t){return ja(
|
|
1896
|
+
t)?.nombre}function Wt(t){return ja(t)?t.slice(t.indexOf("/")+1):t}var me={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.\
|
|
1892
1897
|
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\
|
|
1893
|
-
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"},
|
|
1894
|
-
request_sent`;function
|
|
1895
|
-
actual)}function V(t,e,n){(typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n))&&(t[e]=n);}function
|
|
1896
|
-
bivelio_basis:n.basis,bivelio_currency:e};
|
|
1898
|
+
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"},Pp="error.type",W="com.bivelio.",Ip=`${W}stream.\
|
|
1899
|
+
request_sent`;function tt(t){return t==="measured"||t==="reference"||t==="estimated"}function Sn(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}function _p(t){return Sn(t.cost.baselineEstimate-t.cost.
|
|
1900
|
+
actual)}function V(t,e,n){(typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n))&&(t[e]=n);}function Ba(t,e){let{cost:n,tokens:r,calls:o,cache:i}=t,s={bivelio_request_id:t.requestId,
|
|
1901
|
+
bivelio_basis:n.basis,bivelio_currency:e};tt(n.basis)&&(s.bivelio_baseline_cost=n.baselineEstimate,s.bivelio_actual_cost=n.actual,s[`bivelio_saved_${n.basis}`]=_p(t),s.bivelio_net_savings_ratio=n.netSavings),
|
|
1897
1902
|
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=
|
|
1898
1903
|
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];
|
|
1899
|
-
return s}function
|
|
1900
|
-
void 0&&V(e,
|
|
1901
|
-
|
|
1902
|
-
V(a,`${W}cost.actual`,r.actual),V(a,`${W}cost.saved.${r.basis}`,
|
|
1904
|
+
return s}function za(t){let e={};return V(e,me.modeloRespuesta,Wt(t.model)),tt(t.cost.basis)&&(V(e,me.entrada,t.tokens.actualInput),V(e,me.salida,t.tokens.actualOutput),t.tokens.providerCachedInput!==
|
|
1905
|
+
void 0&&V(e,me.lecturaDeCache,t.tokens.providerCachedInput)),e}function Zo(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`,
|
|
1906
|
+
Ve),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),tt(r.basis)&&(V(a,`${W}cost.baseline`,r.baselineEstimate),
|
|
1907
|
+
V(a,`${W}cost.actual`,r.actual),V(a,`${W}cost.saved.${r.basis}`,_p(t)),V(a,`${W}cost.net_savings_ratio`,r.netSavings),V(a,`${W}cost.eliminated_input_floor`,r.eliminatedInputFloorCost)),V(a,`${W}calls.\
|
|
1903
1908
|
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\
|
|
1904
1909
|
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,
|
|
1905
1910
|
`${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\
|
|
1906
1911
|
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),
|
|
1907
|
-
V(a,`${W}latency.provider_ms`,t.latencyMs?.provider);let l=e?.langfuse?.metadata||e?.datadog?.metadata?
|
|
1908
|
-
on.metadata.${u}`]=typeof d=="number"?
|
|
1909
|
-
metadata){let u={};for(let[d,p]of Object.entries(l))u[d.replace(/^bivelio_/,"")]=p;a["_dd.ml_obs.metadata"]=JSON.stringify({bivelio:u});}return a}var
|
|
1910
|
-
"function"}function
|
|
1911
|
-
ngsLayer: `tracer` must be an OpenTelemetry Tracer, a TracerProvider or the `trace` object of the OpenTelemetry API")}function
|
|
1912
|
-
test(e)?e:"_OTHER"}function
|
|
1913
|
-
isFinite(c)&&(r[a]=c);};i(
|
|
1914
|
-
s),r}function
|
|
1915
|
-
i?.delivery==="live"&&typeof i.firstEventMs=="number"&&Number.isFinite(i.firstEventMs)&&(o[
|
|
1916
|
-
try{if(t.isRecording?.()!==!1){let n={[
|
|
1912
|
+
V(a,`${W}latency.provider_ms`,t.latencyMs?.provider);let l=e?.langfuse?.metadata||e?.datadog?.metadata?Ba(t,n):void 0;if(l&&e?.langfuse?.metadata)for(let[u,d]of Object.entries(l))a[`langfuse.observati\
|
|
1913
|
+
on.metadata.${u}`]=typeof d=="number"?Na(d):d;if(e?.langfuse?.cost&&n==="USD"&&tt(r.basis)&&Number.isFinite(r.actual)&&(a["langfuse.observation.cost_details"]=JSON.stringify({total:r.actual})),l&&e?.datadog?.
|
|
1914
|
+
metadata){let u={};for(let[d,p]of Object.entries(l))u[d.replace(/^bivelio_/,"")]=p;a["_dd.ml_obs.metadata"]=JSON.stringify({bivelio:u});}return a}var Dv=2,Av=2,Ov="@bivelio/savings-layer";function Lv(t,e,n){try{if(t.isRecording?.()===!1)return;let r=Zo(e,n);n?.genAi&&Object.assign(r,za(e)),t.setAttributes(r);}catch{}}function Fa(t){return typeof t==
|
|
1915
|
+
"function"}function Mv(t){let e=t;if(e&&Fa(e.startActiveSpan))return e;if(e&&Fa(e.getTracer)){let n=e.getTracer(Ov,Ve);if(n&&Fa(n.startActiveSpan))return n}throw new TypeError("[bvsala] instrumentSavi\
|
|
1916
|
+
ngsLayer: `tracer` must be an OpenTelemetry Tracer, a TracerProvider or the `trace` object of the OpenTelemetry API")}function $v(t){let e=t?.name;return typeof e=="string"&&/^[A-Za-z_$][\w$.-]{0,127}$/.
|
|
1917
|
+
test(e)?e:"_OTHER"}function Nv(t,e,n){let r={[me.operacion]:"chat"},o=n??Tp(t.model);typeof o=="string"&&o!==""&&(r[me.proveedor]=o),r[me.modeloPedido]=Wt(t.model);let i=(a,c)=>{typeof c=="number"&&Number.
|
|
1918
|
+
isFinite(c)&&(r[a]=c);};i(me.temperatura,t.temperature),i(me.semilla,t.seed),i(me.maxTokens,G(t)),e&&(r[me.stream]=true);let s=t.context?.sessionId;return typeof s=="string"&&s!==""&&(r[me.conversacion]=
|
|
1919
|
+
s),r}function Dp(t,e,n){try{if(t.isRecording?.()!==!1){let r=e.report,o={...za(r),...Zo(r,n)};typeof e.finishReason=="string"&&e.finishReason!==""&&(o[me.motivosDeFin]=[e.finishReason]);let i=r.streaming;
|
|
1920
|
+
i?.delivery==="live"&&typeof i.firstEventMs=="number"&&Number.isFinite(i.firstEventMs)&&(o[me.primerTrozo]=i.firstEventMs/1e3),t.setAttributes(o);}}catch{}finally{try{t.end();}catch{}}}function qa(t,e){
|
|
1921
|
+
try{if(t.isRecording?.()!==!1){let n={[Pp]:$v(e)};e instanceof Te&&(n[Ip]=e.requestSent),t.setAttributes(n),t.setStatus?.({code:Av});}}catch{}finally{try{t.end();}catch{}}}function jv(t,e){let n=Mv(e?.tracer);
|
|
1917
1922
|
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!==
|
|
1918
|
-
void 0?{currency:e.currency}:{},...e.langfuse?{langfuse:e.langfuse}:{},...e.datadog?{datadog:e.datadog}:{}},o=e.providerName;function i(s,a,c,l){let u,d,p=false,
|
|
1919
|
-
at ${
|
|
1920
|
-
u={valor:l(
|
|
1921
|
-
then(l=>(
|
|
1922
|
-
model=="string"?
|
|
1923
|
-
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
|
|
1924
|
-
ust be "hour" or "day"`)}function
|
|
1925
|
-
USD"`)}function
|
|
1926
|
-
[bvsala] ${e}: invalid "at" for request ${String(t.report?.requestId)}: expected an ISO 8601 string, epoch milliseconds or a valid Date`);return r}function
|
|
1927
|
-
t/n)*n}function
|
|
1928
|
-
`[bvsala] ${r}: report ${n} has no finite number in ${e}`)}function
|
|
1929
|
-
la] ${n}: every record must be { at, report }`);let a=s.report,c=a.cost?.basis;if(c==="shadow")continue;if(!
|
|
1930
|
-
own cost basis`);let l=c,u=
|
|
1923
|
+
void 0?{currency:e.currency}:{},...e.langfuse?{langfuse:e.langfuse}:{},...e.datadog?{datadog:e.datadog}:{}},o=e.providerName;function i(s,a,c,l){let u,d,p=false,h;try{h=Nv(s,a,o);}catch{h=void 0;}let f=`ch\
|
|
1924
|
+
at ${Bv(s)}`;try{n.startActiveSpan(f,{kind:Dv,...h?{attributes:h}:{}},m=>{if(u)return u.valor;if(d)throw d.error;if(p){try{m.end();}catch{}return}let g;try{g=c();}catch(b){throw d={error:b},qa(m,b),b}try{
|
|
1925
|
+
u={valor:l(m,g)};}catch{u={valor:g};try{m.end();}catch{}}return u.valor});}catch{}if(d)throw d.error;return u?u.valor:(p=true,c())}return {batches:t.batches,generate(s){return i(s,false,()=>t.generate(s),(a,c)=>c.
|
|
1926
|
+
then(l=>(Dp(a,l,r),l),l=>{throw qa(a,l),l}))},generateStream(s,a){return i(s,true,()=>t.generateStream(s,a),(c,l)=>(l.result.then(u=>Dp(c,u,r),u=>qa(c,u)),l))},close(){t.close();}}}function Bv(t){try{return typeof t.
|
|
1927
|
+
model=="string"?Wt(t.model):""}catch{return ""}}function zv(t,e){let n=e?.currency??"USD",r={model:Wt(t.model),metadata:Ba(t,n)};if(tt(t.cost.basis)){let{actualInput:o,actualOutput:i,providerCachedInput:s}=t.tokens,a={input:Math.max(0,o-(s??0)),output:i};
|
|
1928
|
+
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 Ap=["measured","reference","estimated","unmeasured"],Ua=36e5,Op=24*Ua;function Xo(t,e){if(t===void 0)return "day";if(t==="hour"||t==="day")return t;throw new TypeError(`[bvsala] ${e}: granularity m\
|
|
1929
|
+
ust be "hour" or "day"`)}function Qo(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 "\
|
|
1930
|
+
USD"`)}function Fv(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(`\
|
|
1931
|
+
[bvsala] ${e}: invalid "at" for request ${String(t.report?.requestId)}: expected an ISO 8601 string, epoch milliseconds or a valid Date`);return r}function qv(t,e){let n=e==="hour"?Ua:Op;return Math.floor(
|
|
1932
|
+
t/n)*n}function Uv(t,e){return t+(e==="hour"?Ua:Op)}function Et(t){return new Date(t).toISOString().replace(/\.\d{3}Z$/,"Z")}function xe(t,e,n,r){if(typeof t=="number"&&Number.isFinite(t))return t;throw new TypeError(
|
|
1933
|
+
`[bvsala] ${r}: report ${n} has no finite number in ${e}`)}function ei(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\
|
|
1934
|
+
la] ${n}: every record must be { at, report }`);let a=s.report,c=a.cost?.basis;if(c==="shadow")continue;if(!Ap.includes(c))throw new TypeError(`[bvsala] ${n}: report ${String(a.requestId)} has an unkn\
|
|
1935
|
+
own cost basis`);let l=c,u=qv(Fv(s,n),e),{clave:d,extra:p}=r(s,u),h=JSON.stringify([u,a.model,l,d]),f=o.get(h);f||(f={inicio:u,fin:Uv(u,e),modelo:a.model,basis:l,clave:d,extra:p,peticiones:0,llamadas:0,
|
|
1931
1936
|
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}},
|
|
1932
|
-
o.set(f
|
|
1933
|
-
xe(g?.baselineInput,"tokens.baselineInput",
|
|
1934
|
-
compressedInput+=xe(g?.compressedInput,"tokens.compressedInput",
|
|
1935
|
-
Output",
|
|
1936
|
-
"tokens.providerCachedInput",
|
|
1937
|
-
void 0&&(
|
|
1938
|
-
s.modelo>a.modelo?1:0)||i(s.basis)-i(a.basis)||(s.clave<a.clave?-1:s.clave>a.clave?1:0))}function
|
|
1939
|
-
measured:t.basis==="measured"?n:null,reference:t.basis==="reference"?n:null,estimated:t.basis==="estimated"?n:null,suelo:e&&t.suelo!==void 0?
|
|
1940
|
-
keys(t).sort().map(e=>[e,t[e]]))}function
|
|
1941
|
-
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
|
|
1937
|
+
o.set(h,f));let m=String(a.requestId);f.peticiones+=1,f.llamadas+=xe(a.calls?.actualLlm,"calls.actualLlm",m,n),f.evitadas+=xe(a.calls?.avoidedLlm,"calls.avoidedLlm",m,n);let g=a.tokens;if(f.tokens.baselineInput+=
|
|
1938
|
+
xe(g?.baselineInput,"tokens.baselineInput",m,n),f.tokens.actualInput+=xe(g?.actualInput,"tokens.actualInput",m,n),f.tokens.eliminatedInput+=xe(g?.eliminatedInput,"tokens.eliminatedInput",m,n),f.tokens.
|
|
1939
|
+
compressedInput+=xe(g?.compressedInput,"tokens.compressedInput",m,n),f.tokens.baselineOutput+=xe(g?.baselineOutput,"tokens.baselineOutput",m,n),f.tokens.actualOutput+=xe(g?.actualOutput,"tokens.actual\
|
|
1940
|
+
Output",m,n),f.tokens.eliminatedOutput+=xe(g?.eliminatedOutput,"tokens.eliminatedOutput",m,n),g.providerCachedInput!==void 0&&(f.tokens.providerCachedInput=(f.tokens.providerCachedInput??0)+xe(g.providerCachedInput,
|
|
1941
|
+
"tokens.providerCachedInput",m,n)),tt(l)){let b=xe(a.cost.baselineEstimate,"cost.baselineEstimate",m,n),y=xe(a.cost.actual,"cost.actual",m,n);f.baseline+=b,f.actual+=y,f.ahorro+=b-y,a.cost.eliminatedInputFloorCost!==
|
|
1942
|
+
void 0&&(f.suelo=(f.suelo??0)+xe(a.cost.eliminatedInputFloorCost,"cost.eliminatedInputFloorCost",m,n));}}let i=s=>Ap.indexOf(s);return [...o.values()].sort((s,a)=>s.inicio-a.inicio||(s.modelo<a.modelo?-1:
|
|
1943
|
+
s.modelo>a.modelo?1:0)||i(s.basis)-i(a.basis)||(s.clave<a.clave?-1:s.clave>a.clave?1:0))}function ti(t){let e=tt(t.basis),n=Sn(t.ahorro);return {baseline:e?Sn(t.baseline):null,actual:e?Sn(t.actual):null,
|
|
1944
|
+
measured:t.basis==="measured"?n:null,reference:t.basis==="reference"?n:null,estimated:t.basis==="estimated"?n:null,suelo:e&&t.suelo!==void 0?Sn(t.suelo):null}}function ni(t){return JSON.stringify(Object.
|
|
1945
|
+
keys(t).sort().map(e=>[e,t[e]]))}function ri(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[
|
|
1946
|
+
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 Vv=new Set(["periodStart","periodEnd","date","model","basis","currency","requests","providerCalls","avoidedCalls","baselineCost","actualCost","measuredSavings","referenceSavings","estimatedSavings",
|
|
1942
1947
|
"eliminatedInputFloorCost","baselineInputTokens","actualInputTokens","eliminatedInputTokens","compressedInputTokens","providerCachedInputTokens","baselineOutputTokens","actualOutputTokens","eliminated\
|
|
1943
|
-
OutputTokens","dimensions"]),
|
|
1944
|
-
keys(a))if(
|
|
1948
|
+
OutputTokens","dimensions"]),mr="toSavingsSeries";function Hv(t,e){let n=Xo(e?.granularity,mr),r=Qo(e?.currency,mr),o=e?.dimensions;return ei(t,n,mr,s=>{let a=o?ri(o(s),"dimensions",mr):{};for(let c of Object.
|
|
1949
|
+
keys(a))if(Vv.has(c))throw new TypeError(`[bvsala] ${mr}: dimension "${c}" repeats a column of the series`);return {clave:ni(a),extra:a}}).map(s=>{let a=ti(s),c=Et(s.inicio);return {periodStart:c,periodEnd:Et(
|
|
1945
1950
|
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,
|
|
1946
1951
|
referenceSavings:a.reference,estimatedSavings:a.estimated,eliminatedInputFloorCost:a.suelo,baselineInputTokens:s.tokens.baselineInput,actualInputTokens:s.tokens.actualInput,eliminatedInputTokens:s.tokens.
|
|
1947
1952
|
eliminatedInput,compressedInputTokens:s.tokens.compressedInput,providerCachedInputTokens:s.tokens.providerCachedInput??null,baselineOutputTokens:s.tokens.baselineOutput,actualOutputTokens:s.tokens.actualOutput,
|
|
1948
|
-
eliminatedOutputTokens:s.tokens.eliminatedOutput,dimensions:Object.freeze({...s.extra})}})}var we="toFocusRows",
|
|
1949
|
-
`[bvsala] ${we}: cannot determine the FOCUS ${r} for model "${n}". FOCUS allows no placeholder there: pass it in the options.`)}function
|
|
1953
|
+
eliminatedOutputTokens:s.tokens.eliminatedOutput,dimensions:Object.freeze({...s.extra})}})}var we="toFocusRows",Wv="BV-SALA savings ledger",Lp="bivelio/";function Gt(t){return typeof t=="string"&&t.trim()!==""}function Va(t,e,n,r){let o=typeof t=="function"?t(n):t??e;if(Gt(o))return o;throw new TypeError(
|
|
1954
|
+
`[bvsala] ${we}: cannot determine the FOCUS ${r} for model "${n}". FOCUS allows no placeholder there: pass it in the options.`)}function Gv(t,e,n){if(!n){let s=new Date(t);return {start:Date.UTC(s.getUTCFullYear(),
|
|
1950
1955
|
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;
|
|
1951
1956
|
if(!Number.isFinite(o)||!Number.isFinite(i)||o>=i)throw new TypeError(`[bvsala] ${we}: billingPeriod must return valid Dates with start before end`);if(t<o||e>i)throw new TypeError(`[bvsala] ${we}: bi\
|
|
1952
|
-
llingPeriod must contain the charge period it is given`);return {start:o,end:i}}function
|
|
1953
|
-
red`);let n
|
|
1954
|
-
Id must be a non-empty string or a function`);let c=e.serviceName??
|
|
1955
|
-
tion"?o(u):o;if(
|
|
1956
|
-
(
|
|
1957
|
-
startsWith(
|
|
1958
|
-
[
|
|
1959
|
-
p,d,"HostProviderName"),
|
|
1960
|
-
EffectiveCost:0,ListCost:0,ContractedCost:0,BillingCurrency:r,BillingAccountId:b.id,BillingAccountName:b.nombre,BillingPeriodStart:
|
|
1961
|
-
ChargePeriodEnd:
|
|
1962
|
-
Usage-Based",InvoiceIssuerName:
|
|
1957
|
+
llingPeriod must contain the charge period it is given`);return {start:o,end:i}}function Kv(t,e){if(!e||typeof e!="object")throw new TypeError(`[bvsala] ${we}: options with a billingAccountId are requi\
|
|
1958
|
+
red`);let n=Xo(e.granularity,we),r=Qo(e.currency,we),{billingAccountId:o,billingAccountName:i,subAccount:s,tags:a}=e;if(typeof o!="function"&&!Gt(o))throw new TypeError(`[bvsala] ${we}: billingAccount\
|
|
1959
|
+
Id must be a non-empty string or a function`);let c=e.serviceName??Wv;if(!Gt(c))throw new TypeError(`[bvsala] ${we}: serviceName must be a non-empty string`);return ei(t,n,we,u=>{let d=typeof o=="func\
|
|
1960
|
+
tion"?o(u):o;if(!Gt(d))throw new TypeError(`[bvsala] ${we}: billingAccountId returned no id for request ${String(u.report.requestId)}`);let p=typeof i=="function"?i(u):i,h=s?s(u):void 0;if(h!==void 0&&
|
|
1961
|
+
(!Gt(h?.id)||!Gt(h?.name)))throw new TypeError(`[bvsala] ${we}: subAccount must return { id, name } as non-empty strings, or undefined`);let f=ri(a?a(u):void 0,"tags",we);for(let g of Object.keys(f))if(g.
|
|
1962
|
+
startsWith(Lp))throw new TypeError(`[bvsala] ${we}: tag "${g}" uses the reserved "${Lp}" prefix`);let m={id:d,nombre:Gt(p)?p:null,subId:h?h.id:null,subNombre:h?h.name:null,tags:f};return {clave:JSON.stringify(
|
|
1963
|
+
[m.id,m.nombre,m.subId,m.subNombre,ni(f)]),extra:m}}).map(u=>{let d=u.modelo,p=Va(e.serviceProviderName,Rp(d),d,"ServiceProviderName"),h=Va(e.invoiceIssuerName,p,d,"InvoiceIssuerName"),f=Va(e.hostProviderName,
|
|
1964
|
+
p,d,"HostProviderName"),m=Gv(u.inicio,u.fin,e.billingPeriod),g=ti(u),b=u.extra,y={"bivelio/basis":u.basis,"bivelio/model":d};for(let v of Object.keys(b.tags).sort())y[v]=b.tags[v];return {BilledCost:0,
|
|
1965
|
+
EffectiveCost:0,ListCost:0,ContractedCost:0,BillingCurrency:r,BillingAccountId:b.id,BillingAccountName:b.nombre,BillingPeriodStart:Et(m.start),BillingPeriodEnd:Et(m.end),ChargePeriodStart:Et(u.inicio),
|
|
1966
|
+
ChargePeriodEnd:Et(u.fin),ChargeCategory:"Adjustment",ChargeClass:null,ChargeDescription:`BV-SALA savings ledger for ${d} (basis: ${u.basis}). Not a charge: cost columns are 0 by design.`,ChargeFrequency:"\
|
|
1967
|
+
Usage-Based",InvoiceIssuerName:h,ServiceProviderName:p,HostProviderName:f,ServiceName:c,ServiceCategory:"AI and Machine Learning",ServiceSubcategory:"Generative AI",PricingQuantity:null,PricingUnit:null,
|
|
1963
1968
|
SubAccountId:b.subId,SubAccountName:b.subNombre,Tags:JSON.stringify(y),x_BiVelioBasis:u.basis,x_BiVelioModelId:d,x_BiVelioRequestCount:u.peticiones,x_BiVelioProviderCallCount:u.llamadas,x_BiVelioAvoidedCallCount:u.
|
|
1964
1969
|
evitadas,x_BiVelioBaselineCost:g.baseline,x_BiVelioActualCost:g.actual,x_BiVelioMeasuredSavings:g.measured,x_BiVelioReferenceSavings:g.reference,x_BiVelioEstimatedSavings:g.estimated,x_BiVelioEliminatedInputFloorCost:g.
|
|
1965
1970
|
suelo,x_BiVelioBaselineInputTokens:u.tokens.baselineInput,x_BiVelioActualInputTokens:u.tokens.actualInput,x_BiVelioEliminatedInputTokens:u.tokens.eliminatedInput,x_BiVelioCompressedInputTokens:u.tokens.
|
|
1966
1971
|
compressedInput,x_BiVelioProviderCachedInputTokens:u.tokens.providerCachedInput??null,x_BiVelioBaselineOutputTokens:u.tokens.baselineOutput,x_BiVelioActualOutputTokens:u.tokens.actualOutput,x_BiVelioEliminatedOutputTokens:u.
|
|
1967
|
-
tokens.eliminatedOutput}})}var
|
|
1972
|
+
tokens.eliminatedOutput}})}var Jv=nn,Yv=Dn,Zv=tn,Xv=X,Qv=de,ey=rn,ty=An,ny=So,ry=gn,oy=xt,iy=Bs,sy=er,ay=Co,cy=js,ly=Xn,uy=mn,dy=yt,py=Vu,fy=Qn,my=kt,hy=Eo,gy=Ft,by=nr,vy=tr,yy=$a,ky=Ro,xy=2592e6,wy=8,Sy=.95,Ey=at,Cy=pt,Ty=Mi,Ry=Li,
|
|
1973
|
+
Py=Mr,Iy=Ci,_y=Ti,Dy=jn,Ay=At,Oy=_t,Ly=Dt,My=Nn,$y=Pi,Ny=It,jy=Be,By=Tc,zy=zr,Fy=zn,qy=$c,Uy=sn,Vy=Pt;var FT=Rt,qT=Xt,UT=_n,VT=Rt,HT=Xt,WT=_n;/*! Bundled license information:
|
|
1968
1974
|
|
|
1969
1975
|
@noble/curves/utils.js:
|
|
1970
1976
|
@noble/curves/abstract/modular.js:
|
|
@@ -1972,4 +1978,4 @@ tokens.eliminatedOutput}})}var CE=wt,RE=Ft,PE=vn,_E=wt,DE=Ft,IE=vn;/*! Bundled l
|
|
|
1972
1978
|
@noble/curves/abstract/edwards.js:
|
|
1973
1979
|
@noble/curves/ed25519.js:
|
|
1974
1980
|
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
1975
|
-
*/export{
|
|
1981
|
+
*/export{Dl as AnthropicProvider,Ve as BV_SALA_VERSION,Po as BatchSubmitError,VT as CATALOGO,qi as COMPACTION_TRANSFORMS,lm as COMPACT_ROWS_INSTRUCTION,_e as CalibrationStateError,Gu as DEFAULT_COST_MODEL,yy as DEFAULT_MAX_STALENESS_SECONDS,vm as DEFAULT_MIN_SAVED_CHARS,ny as EMBEDDED_PUBLIC_KEY,pi as ExactTokenizer,Dr as ExecutionRouter,jr as FormatSelector,Hl as GoogleProvider,li as HeuristicEstimator,yc as InMemoryCacheBreakpointStore,Er as InMemoryExactCache,vc as InMemorySemanticCache,Oi as InMemoryToolSetFreezer,$f as LOCAL_EMBEDDING_THRESHOLD,Ke as LicenseError,lk as MODELOS_POR_CODIFICACION,Sr as MODELS_BY_ENCODING,Vi as MockProvider,bl as OpenAICompatibleProvider,WT as PRECIOS_AL_DIA,UT as PRICES_AS_OF,FT as PRICE_CATALOG,Yy as QUALITY_STATUSES,xy as REFERENCE_MAX_AGE_MS,wy as REFERENCE_MESSAGE_ALLOWANCE,Sy as REFERENCE_OUTPUT_SHARE,Ri as ResolverRegistry,ry as RevocationPoller,oy as RevocationSnapshot,Ey as SavingsLedger,Br as SchemaRegistry,Cr as Singleflight,Te as StreamAbortedError,ui as TokenizerRegistry,Lr as ToolSelector,Cy as TraceCollector,gc as UMBRAL_LOCAL,gy as UsageEmitter,Ty as adaptiveK,Uf as arithmeticResolver,ey as buildExactKey,ty as buildInflightKey,Mk as calibrateSemanticFloor,Jv as canonicalize,Ac as compactRowsSerializer,Fc as compactToolOutput,Nc as compresionFiel,iy as computeNextDelay,Iy as cosine,um as createCompactRowsSerializer,kc as createDefaultResolvers,Xy as createHandoff,Qx as createMockProvider,FC as createSavingsLayer,Lc as csvSerializer,Pc as decodeCompactRows,Ry as dedupe,di as defaultTokenizerRegistry,by as deriveSeatId,sy as deriveStatus,vy as detectCi,hc as embebedorLocal,fx as emptyState,sm as encodeCompactRows,$y as evalArithmetic,Ny as evaluatePolicy,Py as executeRetrievalPlan,ay as gateFromKey,en as heuristicEstimator,jv as instrumentSavingsLayer,cy as isKeyset,jy as isStrictCompatible,Rc as jsonCompactSerializer,_y as keyTokensMatch,ly as licenseKeyShape,qT as listPrice,uy as liveGateFromKey,jk as localEmbedding,mx as mergeDelta,Yv as modelFamilyOf,Dy as multisetEqual,Ay as negationCount,Vx as noopCompressor,dy as normalizeLicenseKey,Zv as normalizeText,Oy as numericTokens,HT as precioDeLista,By as projectContext,Nx as providerNativeBackend,es as quitarPrefijoDeProveedor,Vy as randomId,Lv as recordSavingsOnSpan,fi as registerExactTokenizer,uk as registrarTokenizadorExacto,em as renderState,zy as resolveConstraintBackend,ky as resolveDependencies,py as resolveLicense,My as sameAnswer,Zo as savingsSpanAttributes,Xv as sha256,Fy as shouldCompress,Qv as stableStringify,_v as toCsv,Kv as toFocusRows,zv as toLangfuseGeneration,Hv as toSavingsSeries,Uy as uniformColumns,be as validateAgainstSchema,mc as vectorLocal,fy as verifyCompactSignature,my as verifyLicenseToken,hy as verifyRevocationList,qy as withProtectedSpans,Ly as words};
|