@bivelio/savings-layer 0.4.30 → 0.4.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,47 +1,47 @@
1
1
  #!/usr/bin/env node
2
- import {spawn}from'child_process';import {existsSync,writeFileSync,mkdirSync,readFileSync}from'fs';import {homedir}from'os';import {join,dirname,posix,delimiter}from'path';import {fileURLToPath}from'url';import {randomUUID,createHash}from'crypto';import {createServer}from'http';import*as Ke from'zlib';import {connect}from'net';var Tn="context-management-2025-06-27";function Ir(){return {edits:[{type:"clear_tool_uses_20250919",trigger:{type:"input_tokens",value:5e4},keep:{type:"tool_uses",value:8},clear_at_least:{type:"input_tokens",value:5e3}}]}}var Yc=new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});function Zc(e){try{return Yc.decode(e)}catch{return null}}function Xc(e){return /^(?:0|[1-9]\d{0,9})$/.test(e)&&Number(e)<4294967295}function Qc(e){
3
- return e===32||e===10||e===13||e===9}function el(e){let t=e.length,n=[],r=0;for(;r<t;){let o=e.charCodeAt(r);if(o===123){n.push(new Set),r++;continue}if(o===91){n.push(null),r++;continue}if(o===125||o===
4
- 93){n.pop(),r++;continue}if(o===34){let i=r,s=false;for(r++;;){if(r>=t)return false;let c=e.charCodeAt(r);if(c===92){s=true,r+=2;continue}if(c===34)break;r++;}r++;let a=r;for(;a<t&&Qc(e.charCodeAt(a));)a++;if(a<
5
- t&&e.charCodeAt(a)===58){let c=e.slice(i+1,r-1);if(s)try{c=JSON.parse(e.slice(i,r));}catch{return false}if(Xc(c))return false;let l=n.at(-1);if(l){if(l.has(c))return false;l.add(c);}}continue}if(o===45||o>=48&&o<=57){
6
- let i=r;for(r++;r<t;){let a=e.charCodeAt(r);if(a>=48&&a<=57||a===46||a===101||a===69||a===43||a===45)r++;else break}let s=e.slice(i,r);if(String(Number(s))!==s)return false;continue}r++;}return true}function Cn(e,t){
7
- if(t!==void 0&&t!==""&&t!=="identity")return null;let n=Zc(e);if(n===null)return null;let r;try{r=JSON.parse(n);}catch{return null}return el(n)?r:null}function mi(e,t){try{let n=Cn(e,t);if(n===null||typeof n!="object"||Array.isArray(n)||typeof n.model!="string"||!Array.isArray(n.messages))return null;let r=nl(n.context_management),o=rl(n.context_management);
8
- return n.context_management=ol(n.context_management),{cuerpo:Buffer.from(JSON.stringify(n),"utf8"),nuestros:r,triggerDelCliente:o}}catch{return null}}function nl(e){let t=e!==null&&typeof e=="object"&&
9
- !Array.isArray(e)?e.edits:void 0,n=(Array.isArray(t)?t:[]).filter(r=>r!==null&&typeof r=="object"&&!Array.isArray(r)&&r.type===Pr);return pi(n)!==pi([Ir().edits[0]])}function rl(e){let t=e!==null&&typeof e==
10
- "object"&&!Array.isArray(e)?e.edits:void 0,n=(Array.isArray(t)?t:[]).filter(o=>o!==null&&typeof o=="object"&&!Array.isArray(o)&&o.type===Pr);if(n.length===0)return null;let r=Number.POSITIVE_INFINITY;
11
- for(let o of n){let i=o.trigger,s=i!==null&&typeof i=="object"&&i.type==="input_tokens"&&typeof i.value=="number"&&Number.isFinite(i.value)&&i.value>0?i.value:1e5;s<r&&(r=s);}return r}function pi(e){return JSON.
12
- stringify(e,(t,n)=>n!==null&&typeof n=="object"&&!Array.isArray(n)?Object.fromEntries(Object.keys(n).sort().map(r=>[r,n[r]])):n)}var Pr="clear_tool_uses_20250919",fi="clear_thinking_20251015";function ol(e){
13
- let t=Ir().edits[0],n=e!==null&&typeof e=="object"&&!Array.isArray(e)?{...e}:{},r=(Array.isArray(n.edits)?n.edits:[]).filter(s=>s!==null&&typeof s=="object"&&!Array.isArray(s)&&s.type!==Pr),o=r.filter(
14
- s=>s.type===fi),i=r.filter(s=>s.type!==fi);return {...n,edits:[...o,...i,t]}}function hi(e,t,n=false){let r=" (TTL tuning ON if your licence includes cache_ttl_tuning; fail-closed)",o=n?" \xB7 context elisio\
2
+ import {spawn}from'child_process';import {existsSync,writeFileSync,mkdirSync,readFileSync}from'fs';import {homedir}from'os';import {join,dirname,posix,delimiter}from'path';import {fileURLToPath}from'url';import {randomUUID,createHash}from'crypto';import {createServer}from'http';import*as Ye from'zlib';import {connect}from'net';var In="context-management-2025-06-27";function Lr(){return {edits:[{type:"clear_tool_uses_20250919",trigger:{type:"input_tokens",value:5e4},keep:{type:"tool_uses",value:8},clear_at_least:{type:"input_tokens",value:5e3}}]}}var al=new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});function cl(e){try{return al.decode(e)}catch{return null}}function ll(e){return /^(?:0|[1-9]\d{0,9})$/.test(e)&&Number(e)<4294967295}function ul(e){
3
+ return e===32||e===10||e===13||e===9}function dl(e){let t=e.length,n=[],r=0;for(;r<t;){let o=e.charCodeAt(r);if(o===123){n.push(new Set),r++;continue}if(o===91){n.push(null),r++;continue}if(o===125||o===
4
+ 93){n.pop(),r++;continue}if(o===34){let i=r,s=false;for(r++;;){if(r>=t)return false;let c=e.charCodeAt(r);if(c===92){s=true,r+=2;continue}if(c===34)break;r++;}r++;let a=r;for(;a<t&&ul(e.charCodeAt(a));)a++;if(a<
5
+ t&&e.charCodeAt(a)===58){let c=e.slice(i+1,r-1);if(s)try{c=JSON.parse(e.slice(i,r));}catch{return false}if(ll(c))return false;let l=n.at(-1);if(l){if(l.has(c))return false;l.add(c);}}continue}if(o===45||o>=48&&o<=57){
6
+ let i=r;for(r++;r<t;){let a=e.charCodeAt(r);if(a>=48&&a<=57||a===46||a===101||a===69||a===43||a===45)r++;else break}let s=e.slice(i,r);if(String(Number(s))!==s)return false;continue}r++;}return true}function Pn(e,t){
7
+ if(t!==void 0&&t!==""&&t!=="identity")return null;let n=cl(e);if(n===null)return null;let r;try{r=JSON.parse(n);}catch{return null}return dl(n)?r:null}function xi(e,t){try{let n=Pn(e,t);if(n===null||typeof n!="object"||Array.isArray(n)||typeof n.model!="string"||!Array.isArray(n.messages))return null;let r=fl(n.context_management),o=ml(n.context_management);
8
+ return n.context_management=hl(n.context_management),{cuerpo:Buffer.from(JSON.stringify(n),"utf8"),nuestros:r,triggerDelCliente:o}}catch{return null}}function fl(e){let t=e!==null&&typeof e=="object"&&
9
+ !Array.isArray(e)?e.edits:void 0,n=(Array.isArray(t)?t:[]).filter(r=>r!==null&&typeof r=="object"&&!Array.isArray(r)&&r.type===Mr);return yi(n)!==yi([Lr().edits[0]])}function ml(e){let t=e!==null&&typeof e==
10
+ "object"&&!Array.isArray(e)?e.edits:void 0,n=(Array.isArray(t)?t:[]).filter(o=>o!==null&&typeof o=="object"&&!Array.isArray(o)&&o.type===Mr);if(n.length===0)return null;let r=Number.POSITIVE_INFINITY;
11
+ for(let o of n){let i=o.trigger,s=i!==null&&typeof i=="object"&&i.type==="input_tokens"&&typeof i.value=="number"&&Number.isFinite(i.value)&&i.value>0?i.value:1e5;s<r&&(r=s);}return r}function yi(e){return JSON.
12
+ stringify(e,(t,n)=>n!==null&&typeof n=="object"&&!Array.isArray(n)?Object.fromEntries(Object.keys(n).sort().map(r=>[r,n[r]])):n)}var Mr="clear_tool_uses_20250919",ki="clear_thinking_20251015";function hl(e){
13
+ let t=Lr().edits[0],n=e!==null&&typeof e=="object"&&!Array.isArray(e)?{...e}:{},r=(Array.isArray(n.edits)?n.edits:[]).filter(s=>s!==null&&typeof s=="object"&&!Array.isArray(s)&&s.type!==Mr),o=r.filter(
14
+ s=>s.type===ki),i=r.filter(s=>s.type!==ki);return {...n,edits:[...o,...i,t]}}function wi(e,t,n=false){let r=" (TTL tuning ON if your licence includes cache_ttl_tuning; fail-closed)",o=n?" \xB7 context elisio\
15
15
  n dials FORCED ON BY HAND (BVSALA_GATEWAY_DIALES_ELISION=1): they measure as a net loss, R=4.05 vs R*=0.0127":" \xB7 context elision dials OFF";return e==="0"?{linea:"savings levers: OFF (BVSALA_GATEW\
16
16
  AY_ELISION=0) - no TTL tuning and no context elision dials; the licence channel stays open for the license status",aviso:false}:{linea:(e==="1"?"licence channel: OPEN (BVSALA_GATEWAY_ELISION=1)":"licen\
17
- ce channel: OPEN by default (=0 turns the levers off)")+r+o,aviso:n}}function gi(e){return e===void 0||e.trim()===""?Tn:e.split(",").map(n=>n.trim()).filter(
18
- n=>n.length>0).includes(Tn)?e:`${e},${Tn}`}function bi(e){let t=e.toLowerCase(),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function il(e){let t=/^gpt-(\d+)(?:\.(\d+))?(?![\d.])/.exec(e);if(!t)return false;let n=Number(t[1]),r=t[2]===void 0?0:
19
- Number(t[2]);return n>5||n===5&&r>=6}function Se(e){let t=bi(e);return t.startsWith("gpt-")||t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4")?il(t)?1.25:1:t.startsWith("gemini")?1:1.25}function An(e){let t=e.toLowerCase();return t.startsWith("claude")||t.startsWith("anthropic/")||bi(t).startsWith("claude")?2:Se(e)}var al=.3,cl=/^(custom|bash_|text_editor_|computer_|browser_|memory_)/;function $r(e){return Array.isArray(e.mcp_servers)&&e.mcp_servers.length>0?true:Array.isArray(e.tools)?e.tools.some(t=>{let n=t!==null&&
20
- typeof t=="object"?t.type:void 0;return typeof n=="string"&&!cl.test(n)}):false}var ll=4096,ul=(e,t)=>e==="cache_control"?void 0:t;function Dr(e){return e===void 0?"":JSON.stringify(e,ul)??""}function dl(e){
21
- return Array.isArray(e)?e.filter(t=>!(t!==null&&typeof t=="object"&&t.defer_loading===true)):e}function Or(e){return createHash("sha1").update(e).digest("base64url").slice(0,16)}function ct(e,t){let n=Cn(e,t);if(n===
22
- null||typeof n!="object"||Array.isArray(n))return null;let r=n;return typeof r.model!="string"||!Array.isArray(r.messages)?null:r}function vi(e){let t=Dr(e.system),n=Dr(dl(e.tools)),r=Array.isArray(e.
23
- messages)?e.messages.slice(0,ll):[],o=[],i=[];for(let s of r){let a=Dr(s);o.push(Or(a)),i.push(Buffer.byteLength(a,"utf8"));}return {system:Or(t),tools:Or(n),mensajes:o,bytes:i,bytesFijos:Buffer.byteLength(
24
- t,"utf8")+Buffer.byteLength(n,"utf8")}}function yi(e,t){if(e===void 0||e.system!==t.system||e.tools!==t.tools)return 1;let n=t.bytesFijos;for(let i of t.bytes)n+=i;if(n<=0)return 1;let r=0;for(;r<e.mensajes.
25
- length&&r<t.mensajes.length&&e.mensajes[r]===t.mensajes[r];)r++;let o=0;for(let i=r;i<t.bytes.length;i++)o+=t.bytes[i]??0;return o/n}function ki(e){let{fraccionNueva:t,umbral:n=al}=e;return t>=n}function pl(e,t){
26
- e.ttl==="1h"?(e.ttl="5m",t.rebajadas++):(e.ttl==="5m"||e.ttl===void 0)&&t.yaEran5m++;}var Jt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Lr=e=>Jt(e)&&Jt(e.cache_control)?e.cache_control:null,fl=8;
27
- function Rn(e,t,n,r){if(!(!Array.isArray(e)||r>fl))for(let o of e){let i=Lr(o);if(i&&n(i,t),!Jt(o))continue;Array.isArray(o.content)&&Rn(o.content,t,n,r+1);let s=o.source;Jt(s)&&s.type==="content"&&Array.
28
- isArray(s.content)&&Rn(s.content,t,n,r+1);}}function Nr(e,t){let n=Lr(e);if(n&&t(n,"raiz"),Rn(e.system,"system",t,0),Array.isArray(e.tools))for(let r of e.tools){let o=Lr(r);o&&t(o,"tools");}if(Array.isArray(
29
- e.messages)){let r=e.messages.length-1;e.messages.forEach((o,i)=>{Jt(o)&&Rn(o.content,i===r?"ultimoMensaje":"mensaje",t,0);});}}function xi(e,t){let n=Buffer.isBuffer(e)?ct(e,t):e;if(n===null)return null;
30
- try{let r={rebajadas:0,yaEran5m:0};return Nr(n,o=>pl(o,r)),r.rebajadas===0?null:{cuerpo:Buffer.from(JSON.stringify(n),"utf8"),rebajadas:r.rebajadas,yaEran5m:r.yaEran5m,herramientaDeServidor:$r(n)}}catch{
31
- return null}}var In=class{constructor(t=512,n=3600*1e3){this.maxEntradas=t;this.maxEdadMs=n;}maxEntradas;maxEdadMs;visto=new Map;ultima(t,n){let r=this.visto.get(t);if(r!==void 0){if(n-r.vistoMs>this.maxEdadMs){this.
17
+ ce channel: OPEN by default (=0 turns the levers off)")+r+o,aviso:n}}function Si(e){return e===void 0||e.trim()===""?In:e.split(",").map(n=>n.trim()).filter(
18
+ n=>n.length>0).includes(In)?e:`${e},${In}`}function Ei(e){let t=e.toLowerCase(),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function gl(e){let t=/^gpt-(\d+)(?:\.(\d+))?(?![\d.])/.exec(e);if(!t)return false;let n=Number(t[1]),r=t[2]===void 0?0:
19
+ Number(t[2]);return n>5||n===5&&r>=6}function _e(e){let t=Ei(e);return t.startsWith("gpt-")||t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4")?gl(t)?1.25:1:t.startsWith("gemini")?1:1.25}function Dn(e){let t=e.toLowerCase();return t.startsWith("claude")||t.startsWith("anthropic/")||Ei(t).startsWith("claude")?2:_e(e)}var vl=.3,yl=/^(custom|bash_|text_editor_|computer_|browser_|memory_)/;function Ur(e){return Array.isArray(e.mcp_servers)&&e.mcp_servers.length>0?true:Array.isArray(e.tools)?e.tools.some(t=>{let n=t!==null&&
20
+ typeof t=="object"?t.type:void 0;return typeof n=="string"&&!yl.test(n)}):false}var kl=4096,xl=(e,t)=>e==="cache_control"?void 0:t;function $r(e){return e===void 0?"":JSON.stringify(e,xl)??""}function wl(e){
21
+ return Array.isArray(e)?e.filter(t=>!(t!==null&&typeof t=="object"&&t.defer_loading===true)):e}function Nr(e){return createHash("sha1").update(e).digest("base64url").slice(0,16)}function dt(e,t){let n=Pn(e,t);if(n===
22
+ null||typeof n!="object"||Array.isArray(n))return null;let r=n;return typeof r.model!="string"||!Array.isArray(r.messages)?null:r}function _i(e){let t=$r(e.system),n=$r(wl(e.tools)),r=Array.isArray(e.
23
+ messages)?e.messages.slice(0,kl):[],o=[],i=[];for(let s of r){let a=$r(s);o.push(Nr(a)),i.push(Buffer.byteLength(a,"utf8"));}return {system:Nr(t),tools:Nr(n),mensajes:o,bytes:i,bytesFijos:Buffer.byteLength(
24
+ t,"utf8")+Buffer.byteLength(n,"utf8")}}function Ti(e,t){if(e===void 0||e.system!==t.system||e.tools!==t.tools)return 1;let n=t.bytesFijos;for(let i of t.bytes)n+=i;if(n<=0)return 1;let r=0;for(;r<e.mensajes.
25
+ length&&r<t.mensajes.length&&e.mensajes[r]===t.mensajes[r];)r++;let o=0;for(let i=r;i<t.bytes.length;i++)o+=t.bytes[i]??0;return o/n}function Ci(e){let{fraccionNueva:t,umbral:n=vl}=e;return t>=n}function Sl(e,t){
26
+ e.ttl==="1h"?(e.ttl="5m",t.rebajadas++):(e.ttl==="5m"||e.ttl===void 0)&&t.yaEran5m++;}var Xt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),jr=e=>Xt(e)&&Xt(e.cache_control)?e.cache_control:null,El=8;
27
+ function On(e,t,n,r){if(!(!Array.isArray(e)||r>El))for(let o of e){let i=jr(o);if(i&&n(i,t),!Xt(o))continue;Array.isArray(o.content)&&On(o.content,t,n,r+1);let s=o.source;Xt(s)&&s.type==="content"&&Array.
28
+ isArray(s.content)&&On(s.content,t,n,r+1);}}function Vr(e,t){let n=jr(e);if(n&&t(n,"raiz"),On(e.system,"system",t,0),Array.isArray(e.tools))for(let r of e.tools){let o=jr(r);o&&t(o,"tools");}if(Array.isArray(
29
+ e.messages)){let r=e.messages.length-1;e.messages.forEach((o,i)=>{Xt(o)&&On(o.content,i===r?"ultimoMensaje":"mensaje",t,0);});}}function Ai(e,t){let n=Buffer.isBuffer(e)?dt(e,t):e;if(n===null)return null;
30
+ try{let r={rebajadas:0,yaEran5m:0};return Vr(n,o=>Sl(o,r)),r.rebajadas===0?null:{cuerpo:Buffer.from(JSON.stringify(n),"utf8"),rebajadas:r.rebajadas,yaEran5m:r.yaEran5m,herramientaDeServidor:Ur(n)}}catch{
31
+ return null}}var Ln=class{constructor(t=512,n=3600*1e3){this.maxEntradas=t;this.maxEdadMs=n;}maxEntradas;maxEdadMs;visto=new Map;ultima(t,n){let r=this.visto.get(t);if(r!==void 0){if(n-r.vistoMs>this.maxEdadMs){this.
32
32
  visto.delete(t);return}return r.huella}}anotar(t,n,r){for(this.visto.delete(t),this.visto.set(t,{huella:n,vistoMs:r});this.visto.size>this.maxEntradas;){let o=this.visto.keys().next();if(o.done===true)break;
33
- this.visto.delete(o.value);}}get tamano(){return this.visto.size}};var jr="mid-conversation-output-config-2026-07-01",On=["low","medium","high","xhigh","max"],ml=new Set(["claude-fable-5-1","claude-mythos-5-1","claude-opus-5-5","claude-opus-5"]),wi={"claude-fable-5-1":"\
34
- high","claude-mythos-5-1":"high","claude-opus-5-5":"medium","claude-opus-5":"high"};function hl(e){return Ei(e)?wi[e]:void 0}function Si(e,t){let n=hl(e);return n!==void 0&&On.indexOf(t)<On.indexOf(n)}
35
- var Dn=On.filter(e=>Object.keys(wi).some(t=>Si(t,e)));function Ei(e){return ml.has(e)}function Br(e){return e!==void 0&&On.includes(e)}function gl(e){return {role:"system",content:[],output_config:{effort:e}}}
36
- function bl(e){if(e.output_config!==void 0&&e.output_config!==null)return true;let t=e.messages;return Array.isArray(t)?t.some(n=>typeof n=="object"&&n!==null&&n.output_config!==void 0):false}function _i(e,t,n){
37
- let r=ct(e,n);if(r===null||typeof r.model!="string"||!Ei(r.model)||!Si(r.model,t)||bl(r))return null;let o=r.messages;return Array.isArray(o)?(r.messages=[...o,gl(t)],{cuerpo:Buffer.from(JSON.stringify(
38
- r),"utf8"),nivel:t}):null}function Ti(e){return e===void 0||e.trim()===""?jr:e.split(",").map(n=>n.trim()).includes(jr)?e:`${e},${jr}`}function Ci(e,t,n){return e===void 0||e===""?{linea:`per-turn eff\
39
- ort: OFF (BVSALA_GATEWAY_ESFUERZO=${Dn.join("|")} turns it on)`,aviso:false}:Br(e)?Dn.includes(e)?n?{linea:`per-turn effort: ARMED at "${e}" (ON if your licence includes per_turn_effort; fail-closed). \
33
+ this.visto.delete(o.value);}}get tamano(){return this.visto.size}};var Fr="mid-conversation-output-config-2026-07-01",Nn=["low","medium","high","xhigh","max"],_l=new Set(["claude-fable-5-1","claude-mythos-5-1","claude-opus-5-5","claude-opus-5"]),Ri={"claude-fable-5-1":"\
34
+ high","claude-mythos-5-1":"high","claude-opus-5-5":"medium","claude-opus-5":"high"};function Tl(e){return Pi(e)?Ri[e]:void 0}function Ii(e,t){let n=Tl(e);return n!==void 0&&Nn.indexOf(t)<Nn.indexOf(n)}
35
+ var $n=Nn.filter(e=>Object.keys(Ri).some(t=>Ii(t,e)));function Pi(e){return _l.has(e)}function qr(e){return e!==void 0&&Nn.includes(e)}function Cl(e){return {role:"system",content:[],output_config:{effort:e}}}
36
+ function Al(e){if(e.output_config!==void 0&&e.output_config!==null)return true;let t=e.messages;return Array.isArray(t)?t.some(n=>typeof n=="object"&&n!==null&&n.output_config!==void 0):false}function Di(e,t,n){
37
+ let r=dt(e,n);if(r===null||typeof r.model!="string"||!Pi(r.model)||!Ii(r.model,t)||Al(r))return null;let o=r.messages;return Array.isArray(o)?(r.messages=[...o,Cl(t)],{cuerpo:Buffer.from(JSON.stringify(
38
+ r),"utf8"),nivel:t}):null}function Oi(e){return e===void 0||e.trim()===""?Fr:e.split(",").map(n=>n.trim()).includes(Fr)?e:`${e},${Fr}`}function Li(e,t,n){return e===void 0||e===""?{linea:`per-turn eff\
39
+ ort: OFF (BVSALA_GATEWAY_ESFUERZO=${$n.join("|")} turns it on)`,aviso:false}:qr(e)?$n.includes(e)?n?{linea:`per-turn effort: ARMED at "${e}" (ON if your licence includes per_turn_effort; fail-closed). \
40
40
  Only fable-5-1, mythos-5-1, opus-5-5 and opus-5, and only below the model's default effort (high; medium on opus-5-5${e==="medium"?", so opus-5-5 passes through unchanged at this level":""}); every ot\
41
41
  her request passes through unchanged. Does NOT reset the prefix cache: the dial is appended at the end and nothing earlier is rewritten. Not yet verified against the quality gate`,aviso:false}:{linea:"pe\
42
42
  r-turn effort: NOT ARMED - BVSALA_GATEWAY_ELISION=0 turns off the levers",aviso:true}:{linea:`per-turn effort: NOT ARMED \u2014 "${e}" is not below any supported model's default effort (high; medium on claude-opus-5-5),\
43
- so it could only leave the bill as it is or raise it. This lever only lowers effort: use ${Dn.join(" or ")}`,aviso:true}:{linea:`per-turn effort: NOT ARMED \u2014 "${e}" is not a level. Use one of: ${Dn.
44
- join(", ")}`,aviso:true}}var Yt={"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},
43
+ so it could only leave the bill as it is or raise it. This lever only lowers effort: use ${$n.join(" or ")}`,aviso:true}:{linea:`per-turn effort: NOT ARMED \u2014 "${e}" is not a level. Use one of: ${$n.
44
+ join(", ")}`,aviso:true}}var Qt={"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},
45
45
  "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,
46
46
  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},
47
47
  "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},
@@ -62,31 +62,31 @@ net-4":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-haiku-4-
62
62
  cachedInputPer1k:75e-6},"gemini-3.7-flash":{inputPer1k:75e-5,outputPer1k:.00375,cachedInputPer1k:75e-6},"gemini-3.6-flash":{inputPer1k:75e-5,outputPer1k:.00375,cachedInputPer1k:75e-6},"gemini-3.1-flas\
63
63
  h-lite":{inputPer1k:25e-5,outputPer1k:.0015,cachedInputPer1k:25e-6},"gemini-3-flash-preview":{inputPer1k:5e-4,outputPer1k:.003,cachedInputPer1k:5e-5},"gemini-3.5-flash":{inputPer1k:.0015,outputPer1k:.009,
64
64
  cachedInputPer1k:15e-5},"gemini-3.5-flash-lite":{inputPer1k:3e-4,outputPer1k:.0025,cachedInputPer1k:3e-5},"gemini-3.1-pro-preview":{inputPer1k:.002,outputPer1k:.012,cachedInputPer1k:2e-4},"gemini-2.5-\
65
- pro":{inputPer1k:.00125,outputPer1k:.01,cachedInputPer1k:125e-6},"gemini-2.5-flash":{inputPer1k:3e-4,outputPer1k:.0025,cachedInputPer1k:3e-5}},vl={"gemini-3.8-flash":{vigenteHasta:"2027-01-01"},"gemin\
66
- i-3.7-flash":{vigenteHasta:"2027-01-01"},"gemini-3.6-flash":{vigenteHasta:"2027-01-01"}},yl={"gemini-3.8-flash":[{vigenteDesde:"2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}],
65
+ pro":{inputPer1k:.00125,outputPer1k:.01,cachedInputPer1k:125e-6},"gemini-2.5-flash":{inputPer1k:3e-4,outputPer1k:.0025,cachedInputPer1k:3e-5}},Rl={"gemini-3.8-flash":{vigenteHasta:"2027-01-01"},"gemin\
66
+ i-3.7-flash":{vigenteHasta:"2027-01-01"},"gemini-3.6-flash":{vigenteHasta:"2027-01-01"}},Il={"gemini-3.8-flash":[{vigenteDesde:"2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}],
67
67
  "gemini-3.7-flash":[{vigenteDesde:"2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}],"gemini-3.6-flash":[{vigenteDesde:"2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,
68
- cachedInputPer1k:15e-5}}]},kl=Object.fromEntries(Object.keys(Yt).map(e=>[e,[{...vl[e],precio:Yt[e]},...yl[e]??[]]]));var xl=864e13;function Ai(e){let t=e instanceof Date?e.getTime():e,n=typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<=xl?t:Date.now();return new Date(n).toISOString().slice(0,10)}function Ri(e,t){
69
- for(let n of kl[e]??[])if(!(n.vigenteDesde!==void 0&&t<n.vigenteDesde)&&!(n.vigenteHasta!==void 0&&t>=n.vigenteHasta))return n.precio}function Ii(e,t,n){if(!n)return;let r=e[n];if(r)return r;let o=n.lastIndexOf("/"),i=o>=0?n.slice(o+1):n,s=e[i];if(s)return s;for(let a of t){if(!i.startsWith(a))continue;let c=i.charAt(a.length);if(c!==
70
- ""&&c!=="-"&&c!=="."&&c!=="_")continue;let l=i.slice(a.length+1);if(!(/^\d/.test(l)&&!/^\d{4}/.test(l)))return e[a]}}function Vr(e){return Object.keys(e).sort((t,n)=>n.length-t.length)}var wl=["o3-dee\
71
- 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"],Ur={...Yt,...Object.
72
- fromEntries(wl.map(e=>[e,null]))},Sl=Vr(Ur);function Te(e,t){let n=lt(e);return n===void 0?void 0:Ri(n,Ai(t))}var El=Object.fromEntries(Object.keys(Ur).map(e=>[e,Ur[e]===null?null:e]));function lt(e){
73
- return Ii(El,Sl,e)??void 0}var _l=/^\d{4}-?\d{2}-?\d{2}$/;function _t(e,t){let n=lt(e);if(n===void 0)return;let r=e.lastIndexOf("/"),o=r>=0?e.slice(r+1):e;if(!(n!==e&&n!==o&&!_l.test(o.slice(n.length+
74
- 1))))return Ri(n,Ai(t))}var Pi={"claude-fable-5":"claude-fable-5-1"};function Tl(e,t){let n=Te(e),r=Te(t);if(n===void 0||r===void 0||n.inputPer1k!==r.inputPer1k||n.outputPer1k!==r.outputPer1k||Se(e)!==Se(t))return false;let o=n.
75
- cachedInputPer1k??n.inputPer1k;return (r.cachedInputPer1k??r.inputPer1k)<o}function Cl(e){let t=lt(e);if(t===void 0||t!==e)return null;let n=Pi[t];return n===void 0||n===t||!Tl(t,n)?null:{solicitado:e,
76
- servido:n}}var Al=/(^|,)\s*context-1m/i;function Rl(e){let t=e.tool_choice;if(t===null||typeof t!="object")return false;let n=t.type;return n==="any"||n==="tool"}function Di(e,t,n={}){if(n.betas!==void 0&&
77
- Al.test(n.betas))return null;let r=ct(e,t);if(r===null||Rl(r))return null;let o=Cl(r.model);return o===null?null:(r.model=o.servido,{cuerpo:Buffer.from(JSON.stringify(r),"utf8"),cambio:o})}function Oi(e,t,n){
78
- let r=Object.entries(Pi).map(([o,i])=>`${o}\u2192${i}`).join(", ");return e!=="1"?{linea:"sibling model routing: OFF (BVSALA_GATEWAY_MODELO_HERMANO=1 turns it on)",aviso:false}:n?{linea:`sibling model \
68
+ cachedInputPer1k:15e-5}}]},Pl=Object.fromEntries(Object.keys(Qt).map(e=>[e,[{...Rl[e],precio:Qt[e]},...Il[e]??[]]]));var Dl=864e13;function Mi(e){let t=e instanceof Date?e.getTime():e,n=typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<=Dl?t:Date.now();return new Date(n).toISOString().slice(0,10)}function $i(e,t){
69
+ for(let n of Pl[e]??[])if(!(n.vigenteDesde!==void 0&&t<n.vigenteDesde)&&!(n.vigenteHasta!==void 0&&t>=n.vigenteHasta))return n.precio}function Ni(e,t,n){if(!n)return;let r=e[n];if(r)return r;let o=n.lastIndexOf("/"),i=o>=0?n.slice(o+1):n,s=e[i];if(s)return s;for(let a of t){if(!i.startsWith(a))continue;let c=i.charAt(a.length);if(c!==
70
+ ""&&c!=="-"&&c!=="."&&c!=="_")continue;let l=i.slice(a.length+1);if(!(/^\d/.test(l)&&!/^\d{4}/.test(l)))return e[a]}}function Hr(e){return Object.keys(e).sort((t,n)=>n.length-t.length)}var Ol=["o3-dee\
71
+ 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"],zr={...Qt,...Object.
72
+ fromEntries(Ol.map(e=>[e,null]))},Ll=Hr(zr);function Ae(e,t){let n=pt(e);return n===void 0?void 0:$i(n,Mi(t))}var Ml=Object.fromEntries(Object.keys(zr).map(e=>[e,zr[e]===null?null:e]));function pt(e){
73
+ return Ni(Ml,Ll,e)??void 0}var $l=/^\d{4}-?\d{2}-?\d{2}$/;function At(e,t){let n=pt(e);if(n===void 0)return;let r=e.lastIndexOf("/"),o=r>=0?e.slice(r+1):e;if(!(n!==e&&n!==o&&!$l.test(o.slice(n.length+
74
+ 1))))return $i(n,Mi(t))}var ji={"claude-fable-5":"claude-fable-5-1"};function Nl(e,t){let n=Ae(e),r=Ae(t);if(n===void 0||r===void 0||n.inputPer1k!==r.inputPer1k||n.outputPer1k!==r.outputPer1k||_e(e)!==_e(t))return false;let o=n.
75
+ cachedInputPer1k??n.inputPer1k;return (r.cachedInputPer1k??r.inputPer1k)<o}function jl(e){let t=pt(e);if(t===void 0||t!==e)return null;let n=ji[t];return n===void 0||n===t||!Nl(t,n)?null:{solicitado:e,
76
+ servido:n}}var Bl=/(^|,)\s*context-1m/i;function Ul(e){let t=e.tool_choice;if(t===null||typeof t!="object")return false;let n=t.type;return n==="any"||n==="tool"}function Bi(e,t,n={}){if(n.betas!==void 0&&
77
+ Bl.test(n.betas))return null;let r=dt(e,t);if(r===null||Ul(r))return null;let o=jl(r.model);return o===null?null:(r.model=o.servido,{cuerpo:Buffer.from(JSON.stringify(r),"utf8"),cambio:o})}function Ui(e,t,n){
78
+ let r=Object.entries(ji).map(([o,i])=>`${o}\u2192${i}`).join(", ");return e!=="1"?{linea:"sibling model routing: OFF (BVSALA_GATEWAY_MODELO_HERMANO=1 turns it on)",aviso:false}:n?{linea:`sibling model \
79
79
  routing: ARMED (${r}; ON if your licence includes sibling_model_routing; fail-closed). Changes the model you see in the response; cache reads cost 0.025\xD7 instead of 0.1\xD7 (list price). Turning it on mi\
80
80
  d-conversation pays one cold prefix write, once. If the provider rejects the rewritten request (400), it is re-sent unchanged once`,aviso:false}:{linea:"sibling model routing: NOT ARMED - BVSALA_GATEWAY_\
81
- ELISION=0 turns off the levers",aviso:true}}var Li=new Set;function G(e,t){Li.has(e)||(Li.add(e),console.warn(t));}var me="0.4.30",Fr="x-bvsala-version";var Tt=class{options;now;flushIntervalMs;maxBatch;maxBuffer;buffer=[];seatId;ci;timer;inflight=null;fallosSeguidos=0;constructor(t){this.options=t,this.now=t.now??(()=>Date.now()),this.flushIntervalMs=
81
+ ELISION=0 turns off the levers",aviso:true}}var Vi=new Set;function Y(e,t){Vi.has(e)||(Vi.add(e),console.warn(t));}var ge="0.4.31",Wr="x-bvsala-version";var Rt=class{options;now;flushIntervalMs;maxBatch;maxBuffer;buffer=[];seatId;ci;timer;inflight=null;fallosSeguidos=0;constructor(t){this.options=t,this.now=t.now??(()=>Date.now()),this.flushIntervalMs=
82
82
  t.flushIntervalMs??15e3,this.maxBatch=t.maxBatch??50,this.maxBuffer=t.maxBuffer??1e3,this.ci=t.ci??false;}setSeat(t,n){t&&(this.seatId=t),this.ci=n;}record(t){this.buffer.push({report:t,at:this.now()}),this.
83
83
  buffer.length>this.maxBuffer&&this.buffer.splice(0,this.buffer.length-this.maxBuffer),this.buffer.length>=this.maxBatch&&this.flush();}start(){this.timer||(this.timer=setInterval(()=>{this.flush();},this.
84
84
  flushIntervalMs),this.timer.unref?.());}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0),this.flush();}async stopAndDrain(t){this.timer&&(clearInterval(this.timer),this.timer=void 0);let n=t??
85
85
  Math.ceil(this.maxBuffer/this.maxBatch)+4,r=0;for(let o=0;o<n&&this.buffer.length>0;o++){let i=this.buffer.length;if(await this.flush(),r=this.buffer.length>=i?r+1:0,r>=2)break}}async flush(){if(this.
86
86
  inflight)return this.inflight;if(this.buffer.length!==0){this.inflight=this.hacerFlush();try{await this.inflight;}finally{this.inflight=null;}}}async hacerFlush(){let t=this.options.fetchImpl??globalThis.
87
87
  fetch;if(!t)return;let n=this.buffer.splice(0,this.maxBatch);try{let r=n.map(i=>this.toWire(i)),o=await t(this.options.url,{method:"POST",headers:{"content-type":"application/json",authorization:`Bear\
88
- er ${this.options.serviceAccountKey}`,[Fr]:`${this.options.surface??"sdk"}/${me}`},body:JSON.stringify(r)});o.ok?this.fallosSeguidos=0:o.status>=500?(this.fallosSeguidos++,this.requeue(n),this.avisarDeFallo(
89
- `the server responded ${o.status}`)):o.status===401||o.status===403?(G(`metering-auth-${o.status}`,`[bv-sala] usage reporting is being rejected with HTTP ${o.status} at ${this.options.url}. Check 'ser\
88
+ er ${this.options.serviceAccountKey}`,[Wr]:`${this.options.surface??"sdk"}/${ge}`},body:JSON.stringify(r)});o.ok?this.fallosSeguidos=0:o.status>=500?(this.fallosSeguidos++,this.requeue(n),this.avisarDeFallo(
89
+ `the server responded ${o.status}`)):o.status===401||o.status===403?(Y(`metering-auth-${o.status}`,`[bv-sala] usage reporting is being rejected with HTTP ${o.status} at ${this.options.url}. Check 'ser\
90
90
  viceAccountKey' (rotated? revoked? from another organization?). Until it works, no usage is reported: the dashboard will say it sees no traffic and billable seats will show zero.`),this.options.onAuthError?.(
91
91
  o.status)):(this.fallosSeguidos++,this.avisarDeFallo(o.status===404||o.status===405?`HTTP ${o.status}: the reporting URL looks wrong`:`the server rejected the batch with HTTP ${o.status}`));}catch(r){this.
92
92
  fallosSeguidos++,this.requeue(n),this.avisarDeFallo(r instanceof Error?r.message:"network error");}}avisarDeFallo(t){if(this.options.silenceWarnings)return;let n=this.fallosSeguidos;n<3||(n-3)%12!==0||
@@ -98,34 +98,34 @@ tokens.compressedInput,baselineOutputTokens:n.tokens.baselineOutput,actualOutput
98
98
  eliminatedInputFloorCost!==void 0&&Number.isFinite(n.cost.eliminatedInputFloorCost)&&n.cost.eliminatedInputFloorCost>0&&n.tokens.eliminatedInput>0?{eliminatedInputFloorCost:n.cost.eliminatedInputFloorCost}:
99
99
  {},baselineCost:n.cost.baselineEstimate,actualCost:n.cost.actual,netSavings:n.cost.netSavings,...n.cost.basis?{basis:n.cost.basis}:{},...n.cost.basis==="reference"&&n.cache.reference&&/^[A-Za-z0-9._:/-]{1,128}$/.
100
100
  test(n.cache.reference.requestId)&&Number.isInteger(n.cache.reference.at)?{referenceRequestId:n.cache.reference.requestId,referenceAt:n.cache.reference.at}:{},...n.attribution?.sessionId?{sessionId:n.
101
- attribution.sessionId}:{},...n.attribution?.agentId?{agentId:n.attribution.agentId}:{}}}};function Ln(){return globalThis.process}function Il(e){if(/^[0-9a-f]{12}$/.test(e)||/^\d{1,3}(\.\d{1,3}){3}$/.test(e)||/^ip-\d{1,3}(-\d{1,3}){3}$/i.test(e))return true;let t="[bcdfghjklmnpqrstvwxz2456789\
102
- ]";return new RegExp(`-${t}{8,10}-${t}{5}$`).test(e)}function Pl(e){return !!(e.AWS_LAMBDA_FUNCTION_NAME??e.LAMBDA_TASK_ROOT??e.VERCEL??e.VERCEL_ENV??e.K_SERVICE??e.FUNCTION_TARGET??e.FUNCTIONS_WORKER_RUNTIME??
103
- e.NETLIFY)}async function Dl(){if(Ln()?.execPath)try{let t=await import(["node","os"].join(":")),n=typeof t.hostname=="function"?t.hostname():"";return n.length>0?n:void 0}catch{return}}async function Ol(e,t=Dl){
104
- if(e.KUBERNETES_SERVICE_HOST||Pl(e))return;let n=e.HOSTNAME??e.COMPUTERNAME??await t();if(!(!n||Il(n)))return n}async function Ll(){let e=Ln();if(!e||!e.env)return;let t=e.env,n=await Ol(t),r=[e.platform,
105
- e.arch,e.execPath,n,t.USER??t.USERNAME??t.LOGNAME,t.HOME??t.USERPROFILE].filter(o=>typeof o=="string"&&o.length>0);return r.length?r.join("|"):void 0}var Ml=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTI\
106
- ONS","GITLAB_CI","CIRCLECI","TRAVIS","JENKINS_URL","BUILDKITE","TF_BUILD","TEAMCITY_VERSION","BITBUCKET_BUILD_NUMBER","CODEBUILD_BUILD_ID","HEROKU_TEST_RUN_ID","DRONE"];function Mn(){let e=Ln()?.env;if(!e)
107
- return false;for(let t of Ml){let n=e[t];if(n&&n!=="false"&&n!=="0")return true}return false}async function $l(e,t){let n=globalThis.crypto,r=new TextEncoder;if(n?.subtle)try{let s=await n.subtle.importKey("raw",
101
+ attribution.sessionId}:{},...n.attribution?.agentId?{agentId:n.attribution.agentId}:{}}}};function jn(){return globalThis.process}function Vl(e){if(/^[0-9a-f]{12}$/.test(e)||/^\d{1,3}(\.\d{1,3}){3}$/.test(e)||/^ip-\d{1,3}(-\d{1,3}){3}$/i.test(e))return true;let t="[bcdfghjklmnpqrstvwxz2456789\
102
+ ]";return new RegExp(`-${t}{8,10}-${t}{5}$`).test(e)}function Fl(e){return !!(e.AWS_LAMBDA_FUNCTION_NAME??e.LAMBDA_TASK_ROOT??e.VERCEL??e.VERCEL_ENV??e.K_SERVICE??e.FUNCTION_TARGET??e.FUNCTIONS_WORKER_RUNTIME??
103
+ e.NETLIFY)}async function ql(){if(jn()?.execPath)try{let t=await import(["node","os"].join(":")),n=typeof t.hostname=="function"?t.hostname():"";return n.length>0?n:void 0}catch{return}}async function zl(e,t=ql){
104
+ if(e.KUBERNETES_SERVICE_HOST||Fl(e))return;let n=e.HOSTNAME??e.COMPUTERNAME??await t();if(!(!n||Vl(n)))return n}async function Hl(){let e=jn();if(!e||!e.env)return;let t=e.env,n=await zl(t),r=[e.platform,
105
+ e.arch,e.execPath,n,t.USER??t.USERNAME??t.LOGNAME,t.HOME??t.USERPROFILE].filter(o=>typeof o=="string"&&o.length>0);return r.length?r.join("|"):void 0}var Wl=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTI\
106
+ ONS","GITLAB_CI","CIRCLECI","TRAVIS","JENKINS_URL","BUILDKITE","TF_BUILD","TEAMCITY_VERSION","BITBUCKET_BUILD_NUMBER","CODEBUILD_BUILD_ID","HEROKU_TEST_RUN_ID","DRONE"];function Bn(){let e=jn()?.env;if(!e)
107
+ return false;for(let t of Wl){let n=e[t];if(n&&n!=="false"&&n!=="0")return true}return false}async function Kl(e,t){let n=globalThis.crypto,r=new TextEncoder;if(n?.subtle)try{let s=await n.subtle.importKey("raw",
108
108
  r.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await n.subtle.sign("HMAC",s,r.encode(t));return [...new Uint8Array(a)].map(c=>c.toString(16).padStart(2,"0")).join("")}catch{}let o=2166136261,i=`${e}\
109
- |${t}`;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 $n(e){let n=Ln()?.env?.BVSALA_SEAT_ID;if(n&&Nl.test(n))return n;let r=await Ll();
110
- if(!r)return;let o=await $l(e,r);if(o)return `m-${o.slice(0,32)}`}var Nl=/^[A-Za-z0-9._:/-]{1,128}$/;function zr(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Nn(e,t=""){if(typeof e!="number"){let n=t&&
111
- `"${t}" `;throw new TypeError(`${n}expected number, got ${typeof e}`)}if(!Number.isSafeInteger(e)||e<0){let n=t&&`"${t}" `;throw new RangeError(`${n}expected integer >= 0, got ${e}`)}}function Ce(e,t,n=""){
112
- let r=zr(e),o=e?.length,i=t!==void 0;if(!r||i&&o!==t){let s=n&&`"${n}" `,a=i?` of length ${t}`:"",c=r?`length=${o}`:`type=${typeof e}`,l=s+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):
113
- new TypeError(l)}return e}function qr(e,t=true){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function $i(e,t){Ce(e,void 0,"digestInt\
114
- o() output");let n=t.outputLen;if(e.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function Zt(...e){for(let t=0;t<e.length;t++)e[t].fill(0);}function jn(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var Ni=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",jl=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Bn(e){if(Ce(e),Ni)return e.toHex();
115
- let t="";for(let n=0;n<e.length;n++)t+=jl[e[n]];return t}var Fe={_0:48,_9:57,A:65,F:70,a:97,f:102};function Mi(e){if(e>=Fe._0&&e<=Fe._9)return e-Fe._0;if(e>=Fe.A&&e<=Fe.F)return e-(Fe.A-10);if(e>=Fe.a&&
116
- e<=Fe.f)return e-(Fe.a-10)}function Xt(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);if(Ni)try{return Uint8Array.fromHex(e)}catch(o){throw o instanceof SyntaxError?
117
- new RangeError(o.message):o}let t=e.length,n=t/2;if(t%2)throw new RangeError("hex string expected, got unpadded hex of length "+t);let r=new Uint8Array(n);for(let o=0,i=0;o<n;o++,i+=2){let s=Mi(e.charCodeAt(
118
- i)),a=Mi(e.charCodeAt(i+1));if(s===void 0||a===void 0){let c=e[i]+e[i+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}r[o]=s*16+a;}return r}function Hr(...e){let t=0;for(let r=0;r<e.length;r++){let o=e[r];Ce(o),t+=o.length;}let n=new Uint8Array(t);for(let r=0,o=0;r<e.length;r++){let i=e[r];n.set(i,o),o+=i.length;}return n}function ji(e,t={}){let n=(o,i)=>e(i).update(o).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=o=>e(o),Object.assign(n,t),Object.freeze(n)}function Bi(e=32){
119
- Nn(e,"bytesLength");let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(e>65536)throw new RangeError(
120
- `"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}var Ui=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});var Un=class{blockLen;outputLen;canXOF=false;padOffset;isLE;buffer;view;finished=false;length=0;pos=0;destroyed=false;constructor(t,n,r,o){this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=
121
- new Uint8Array(t),this.view=jn(this.buffer);}update(t){qr(this),Ce(t);let{view:n,buffer:r,blockLen:o}=this,i=t.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=jn(t);for(;o<=i-s;s+=
122
- o)this.process(c,s);continue}r.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(n,0),this.pos=0);}return this.length+=t.length,this.roundClean(),this}digestInto(t){qr(this),
123
- $i(t,this),this.finished=true;let{buffer:n,view:r,blockLen:o,isLE:i}=this,{pos:s}=this;n[s++]=128,Zt(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(r,0),s=0);for(let u=s;u<o;u++)n[u]=0;r.setBigUint64(
124
- o-8,BigInt(this.length*8),i),this.process(r,0);let a=jn(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,d=this.get();if(l>d.length)throw new Error("_s\
109
+ |${t}`;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 Un(e){let n=jn()?.env?.BVSALA_SEAT_ID;if(n&&Gl.test(n))return n;let r=await Hl();
110
+ if(!r)return;let o=await Kl(e,r);if(o)return `m-${o.slice(0,32)}`}var Gl=/^[A-Za-z0-9._:/-]{1,128}$/;function Kr(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Vn(e,t=""){if(typeof e!="number"){let n=t&&
111
+ `"${t}" `;throw new TypeError(`${n}expected number, got ${typeof e}`)}if(!Number.isSafeInteger(e)||e<0){let n=t&&`"${t}" `;throw new RangeError(`${n}expected integer >= 0, got ${e}`)}}function Re(e,t,n=""){
112
+ let r=Kr(e),o=e?.length,i=t!==void 0;if(!r||i&&o!==t){let s=n&&`"${n}" `,a=i?` of length ${t}`:"",c=r?`length=${o}`:`type=${typeof e}`,l=s+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):
113
+ new TypeError(l)}return e}function Gr(e,t=true){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function qi(e,t){Re(e,void 0,"digestInt\
114
+ o() output");let n=t.outputLen;if(e.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function en(...e){for(let t=0;t<e.length;t++)e[t].fill(0);}function Fn(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var zi=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Jl=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function qn(e){if(Re(e),zi)return e.toHex();
115
+ let t="";for(let n=0;n<e.length;n++)t+=Jl[e[n]];return t}var He={_0:48,_9:57,A:65,F:70,a:97,f:102};function Fi(e){if(e>=He._0&&e<=He._9)return e-He._0;if(e>=He.A&&e<=He.F)return e-(He.A-10);if(e>=He.a&&
116
+ e<=He.f)return e-(He.a-10)}function tn(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);if(zi)try{return Uint8Array.fromHex(e)}catch(o){throw o instanceof SyntaxError?
117
+ new RangeError(o.message):o}let t=e.length,n=t/2;if(t%2)throw new RangeError("hex string expected, got unpadded hex of length "+t);let r=new Uint8Array(n);for(let o=0,i=0;o<n;o++,i+=2){let s=Fi(e.charCodeAt(
118
+ i)),a=Fi(e.charCodeAt(i+1));if(s===void 0||a===void 0){let c=e[i]+e[i+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}r[o]=s*16+a;}return r}function Jr(...e){let t=0;for(let r=0;r<e.length;r++){let o=e[r];Re(o),t+=o.length;}let n=new Uint8Array(t);for(let r=0,o=0;r<e.length;r++){let i=e[r];n.set(i,o),o+=i.length;}return n}function Hi(e,t={}){let n=(o,i)=>e(i).update(o).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=o=>e(o),Object.assign(n,t),Object.freeze(n)}function Wi(e=32){
119
+ Vn(e,"bytesLength");let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(e>65536)throw new RangeError(
120
+ `"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}var Ki=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});var zn=class{blockLen;outputLen;canXOF=false;padOffset;isLE;buffer;view;finished=false;length=0;pos=0;destroyed=false;constructor(t,n,r,o){this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=
121
+ new Uint8Array(t),this.view=Fn(this.buffer);}update(t){Gr(this),Re(t);let{view:n,buffer:r,blockLen:o}=this,i=t.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=Fn(t);for(;o<=i-s;s+=
122
+ o)this.process(c,s);continue}r.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(n,0),this.pos=0);}return this.length+=t.length,this.roundClean(),this}digestInto(t){Gr(this),
123
+ qi(t,this),this.finished=true;let{buffer:n,view:r,blockLen:o,isLE:i}=this,{pos:s}=this;n[s++]=128,en(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(r,0),s=0);for(let u=s;u<o;u++)n[u]=0;r.setBigUint64(
124
+ o-8,BigInt(this.length*8),i),this.process(r,0);let a=Fn(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,d=this.get();if(l>d.length)throw new Error("_s\
125
125
  ha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],i);}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let r=t.slice(0,n);return this.destroy(),r}_cloneInto(t){t||=new this.
126
- constructor,t.set(...this.get());let{blockLen:n,buffer:r,length:o,finished:i,destroyed:s,pos:a}=this;return t.destroyed=s,t.finished=i,t.length=o,t.pos=a,o%n&&t.buffer.set(r),t}clone(){return this._cloneInto()}};var se=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Vn=BigInt(4294967295),Vi=BigInt(32);function Bl(e,t=false){return t?{h:Number(e&Vn),l:Number(e>>Vi&Vn)}:{h:Number(e>>Vi&Vn)|0,l:Number(e&Vn)|0}}function Fi(e,t=false){let n=e.length,r=new Uint32Array(n),
127
- o=new Uint32Array(n);for(let i=0;i<n;i++){let{h:s,l:a}=Bl(e[i],t);[r[i],o[i]]=[s,a];}return [r,o]}var Wr=(e,t,n)=>e>>>n,Kr=(e,t,n)=>e<<32-n|t>>>n,ut=(e,t,n)=>e>>>n|t<<32-n,dt=(e,t,n)=>e<<32-n|t>>>n,Qt=(e,t,n)=>e<<64-n|t>>>n-32,en=(e,t,n)=>e>>>n-32|t<<64-n;function Pe(e,t,n,r){let o=(t>>>0)+(r>>>0);return {h:e+n+(o/2**32|0)|0,l:o|0}}var zi=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),qi=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Hi=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Wi=(e,t,n,r,o)=>t+
128
- n+r+o+(e/2**32|0)|0,Ki=(e,t,n,r,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(o>>>0),Gi=(e,t,n,r,o,i)=>t+n+r+o+i+(e/2**32|0)|0;var Ji=Fi(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242",
126
+ constructor,t.set(...this.get());let{blockLen:n,buffer:r,length:o,finished:i,destroyed:s,pos:a}=this;return t.destroyed=s,t.finished=i,t.length=o,t.pos=a,o%n&&t.buffer.set(r),t}clone(){return this._cloneInto()}};var ce=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Hn=BigInt(4294967295),Gi=BigInt(32);function Yl(e,t=false){return t?{h:Number(e&Hn),l:Number(e>>Gi&Hn)}:{h:Number(e>>Gi&Hn)|0,l:Number(e&Hn)|0}}function Ji(e,t=false){let n=e.length,r=new Uint32Array(n),
127
+ o=new Uint32Array(n);for(let i=0;i<n;i++){let{h:s,l:a}=Yl(e[i],t);[r[i],o[i]]=[s,a];}return [r,o]}var Yr=(e,t,n)=>e>>>n,Zr=(e,t,n)=>e<<32-n|t>>>n,ft=(e,t,n)=>e>>>n|t<<32-n,mt=(e,t,n)=>e<<32-n|t>>>n,nn=(e,t,n)=>e<<64-n|t>>>n-32,rn=(e,t,n)=>e>>>n-32|t<<64-n;function Oe(e,t,n,r){let o=(t>>>0)+(r>>>0);return {h:e+n+(o/2**32|0)|0,l:o|0}}var Yi=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Zi=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Xi=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Qi=(e,t,n,r,o)=>t+
128
+ n+r+o+(e/2**32|0)|0,es=(e,t,n,r,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(o>>>0),ts=(e,t,n,r,o,i)=>t+n+r+o+i+(e/2**32|0)|0;var ns=Ji(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242",
129
129
  "0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc6\
130
130
  8b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","\
131
131
  0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3\
@@ -133,611 +133,643 @@ c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a6
133
133
  x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5d\
134
134
  efb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0x\
135
135
  eada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c1\
136
- 00d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),Vl=Ji[0],Fl=Ji[1],Xe=new Uint32Array(80),Qe=new Uint32Array(80),Gr=class extends Un{constructor(t){
136
+ 00d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),Xl=ns[0],Ql=ns[1],et=new Uint32Array(80),tt=new Uint32Array(80),Xr=class extends zn{constructor(t){
137
137
  super(128,t,16,false);}get(){let{Ah:t,Al:n,Bh:r,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:l,El:d,Fh:u,Fl:p,Gh:f,Gl:g,Hh:b,Hl:h}=this;return [t,n,r,o,i,s,a,c,l,d,u,p,f,g,b,h]}set(t,n,r,o,i,s,a,c,l,d,u,p,f,g,b,h){this.Ah=
138
138
  t|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=d|0,this.Fh=u|0,this.Fl=p|0,this.Gh=f|0,this.Gl=g|0,this.Hh=b|0,this.Hl=h|0;}process(t,n){for(let x=0;x<
139
- 16;x++,n+=4)Xe[x]=t.getUint32(n),Qe[x]=t.getUint32(n+=4);for(let x=16;x<80;x++){let y=Xe[x-15]|0,A=Qe[x-15]|0,R=ut(y,A,1)^ut(y,A,8)^Wr(y,A,7),I=dt(y,A,1)^dt(y,A,8)^Kr(y,A,7),D=Xe[x-2]|0,N=Qe[x-2]|0,H=ut(
140
- D,N,19)^Qt(D,N,61)^Wr(D,N,6),Y=dt(D,N,19)^en(D,N,61)^Kr(D,N,6),E=Hi(I,Y,Qe[x-7],Qe[x-16]),C=Wi(E,R,H,Xe[x-7],Xe[x-16]);Xe[x]=C|0,Qe[x]=E|0;}let{Ah:r,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:d,Eh:u,El:p,Fh:f,Fl:g,
141
- Gh:b,Gl:h,Hh:v,Hl:k}=this;for(let x=0;x<80;x++){let y=ut(u,p,14)^ut(u,p,18)^Qt(u,p,41),A=dt(u,p,14)^dt(u,p,18)^en(u,p,41),R=u&f^~u&b,I=p&g^~p&h,D=Ki(k,A,I,Fl[x],Qe[x]),N=Gi(D,v,y,R,Vl[x],Xe[x]),H=D|0,
142
- Y=ut(r,o,28)^Qt(r,o,34)^Qt(r,o,39),E=dt(r,o,28)^en(r,o,34)^en(r,o,39),C=r&i^r&a^i&a,O=o&s^o&c^s&c;v=b|0,k=h|0,b=f|0,h=g|0,f=u|0,g=p|0,{h:u,l:p}=Pe(l|0,d|0,N|0,H|0),l=a|0,d=c|0,a=i|0,c=s|0,i=r|0,s=o|0;
143
- let $=zi(H,E,O);r=qi($,N,Y,C),o=$|0;}(({h:r,l:o}=Pe(this.Ah|0,this.Al|0,r|0,o|0))),{h:i,l:s}=Pe(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Pe(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:d}=Pe(this.Dh|0,this.Dl|0,l|0,
144
- d|0),{h:u,l:p}=Pe(this.Eh|0,this.El|0,u|0,p|0),{h:f,l:g}=Pe(this.Fh|0,this.Fl|0,f|0,g|0),{h:b,l:h}=Pe(this.Gh|0,this.Gl|0,b|0,h|0),{h:v,l:k}=Pe(this.Hh|0,this.Hl|0,v|0,k|0),this.set(r,o,i,s,a,c,l,d,u,
145
- p,f,g,b,h,v,k);}roundClean(){Zt(Xe,Qe);}destroy(){this.destroyed=true,Zt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}},Jr=class extends Gr{Ah=se[0]|0;Al=se[1]|0;Bh=se[2]|0;Bl=se[3]|0;Ch=se[4]|0;Cl=se[5]|
146
- 0;Dh=se[6]|0;Dl=se[7]|0;Eh=se[8]|0;El=se[9]|0;Fh=se[10]|0;Fl=se[11]|0;Gh=se[12]|0;Gl=se[13]|0;Hh=se[14]|0;Hl=se[15]|0;constructor(){super(64);}};var Fn=ji(()=>new Jr,Ui(3));var X=(e,t,n)=>Ce(e,t,n),Zr=Nn,Xr=Bn,De=(...e)=>Hr(...e),Yi=e=>Xt(e),Hn=zr,Zi=e=>Bi(e),qn=BigInt(0),Yr=BigInt(1);function Ct(e,t=""){if(typeof e!="boolean"){let n=t&&`"${t}" `;throw new TypeError(n+"e\
147
- xpected boolean, got type="+typeof e)}return e}function zl(e){if(typeof e=="bigint"){if(!zn(e))throw new RangeError("positive bigint expected, got "+e)}else Zr(e);return e}function ze(e,t=""){if(typeof e!=
148
- "number"){let n=t&&`"${t}" `;throw new TypeError(n+"expected number, got type="+typeof e)}if(!Number.isSafeInteger(e)){let n=t&&`"${t}" `;throw new RangeError(n+"expected safe integer, got "+e)}}function Xi(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);return e===""?qn:BigInt("0x"+e)}function Qr(e){return Xi(Bn(e))}function qe(e){return Xi(Bn(tn(Ce(e)).reverse()))}
149
- function eo(e,t){if(Nn(t),t===0)throw new RangeError("zero length");e=zl(e);let n=e.toString(16);if(n.length>t*2)throw new RangeError("number too large");return Xt(n.padStart(t*2,"0"))}function Qi(e,t){
150
- return eo(e,t).reverse()}function es(e,t){if(e=X(e),t=X(t),e.length!==t.length)return false;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function tn(e){return Uint8Array.from(X(e))}var zn=e=>typeof e=="bigint"&&qn<=e;function ql(e,t,n){return zn(e)&&zn(t)&&zn(n)&&t<=e&&e<n}function to(e,t,n,r){if(!ql(t,n,r))throw new RangeError(
151
- "expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function no(e){if(e<qn)throw new Error("expected non-negative bigint, got "+e);let t;for(t=0;e>qn;e>>=Yr,t+=1);return t}var ts=e=>(Yr<<BigInt(e))-Yr;function pt(e,t={},n={}){if(Object.prototype.toString.call(e)!=="[object Object]")throw new TypeError("expected valid options object");function r(i,s,a){if(!a&&s!=="function"&&!Object.hasOwn(e,i))throw new TypeError(
139
+ 16;x++,n+=4)et[x]=t.getUint32(n),tt[x]=t.getUint32(n+=4);for(let x=16;x<80;x++){let y=et[x-15]|0,R=tt[x-15]|0,P=ft(y,R,1)^ft(y,R,8)^Yr(y,R,7),D=mt(y,R,1)^mt(y,R,8)^Zr(y,R,7),L=et[x-2]|0,B=tt[x-2]|0,K=ft(
140
+ L,B,19)^nn(L,B,61)^Yr(L,B,6),X=mt(L,B,19)^rn(L,B,61)^Zr(L,B,6),E=Xi(D,X,tt[x-7],tt[x-16]),A=Qi(E,P,K,et[x-7],et[x-16]);et[x]=A|0,tt[x]=E|0;}let{Ah:r,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:d,Eh:u,El:p,Fh:f,Fl:g,
141
+ Gh:b,Gl:h,Hh:v,Hl:k}=this;for(let x=0;x<80;x++){let y=ft(u,p,14)^ft(u,p,18)^nn(u,p,41),R=mt(u,p,14)^mt(u,p,18)^rn(u,p,41),P=u&f^~u&b,D=p&g^~p&h,L=es(k,R,D,Ql[x],tt[x]),B=ts(L,v,y,P,Xl[x],et[x]),K=L|0,
142
+ X=ft(r,o,28)^nn(r,o,34)^nn(r,o,39),E=mt(r,o,28)^rn(r,o,34)^rn(r,o,39),A=r&i^r&a^i&a,M=o&s^o&c^s&c;v=b|0,k=h|0,b=f|0,h=g|0,f=u|0,g=p|0,{h:u,l:p}=Oe(l|0,d|0,B|0,K|0),l=a|0,d=c|0,a=i|0,c=s|0,i=r|0,s=o|0;
143
+ let j=Yi(K,E,M);r=Zi(j,B,X,A),o=j|0;}(({h:r,l:o}=Oe(this.Ah|0,this.Al|0,r|0,o|0))),{h:i,l:s}=Oe(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Oe(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:d}=Oe(this.Dh|0,this.Dl|0,l|0,
144
+ d|0),{h:u,l:p}=Oe(this.Eh|0,this.El|0,u|0,p|0),{h:f,l:g}=Oe(this.Fh|0,this.Fl|0,f|0,g|0),{h:b,l:h}=Oe(this.Gh|0,this.Gl|0,b|0,h|0),{h:v,l:k}=Oe(this.Hh|0,this.Hl|0,v|0,k|0),this.set(r,o,i,s,a,c,l,d,u,
145
+ p,f,g,b,h,v,k);}roundClean(){en(et,tt);}destroy(){this.destroyed=true,en(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}},Qr=class extends Xr{Ah=ce[0]|0;Al=ce[1]|0;Bh=ce[2]|0;Bl=ce[3]|0;Ch=ce[4]|0;Cl=ce[5]|
146
+ 0;Dh=ce[6]|0;Dl=ce[7]|0;Eh=ce[8]|0;El=ce[9]|0;Fh=ce[10]|0;Fl=ce[11]|0;Gh=ce[12]|0;Gl=ce[13]|0;Hh=ce[14]|0;Hl=ce[15]|0;constructor(){super(64);}};var Wn=Hi(()=>new Qr,Ki(3));var ee=(e,t,n)=>Re(e,t,n),to=Vn,no=qn,Le=(...e)=>Jr(...e),rs=e=>tn(e),Jn=Kr,os=e=>Wi(e),Gn=BigInt(0),eo=BigInt(1);function It(e,t=""){if(typeof e!="boolean"){let n=t&&`"${t}" `;throw new TypeError(n+"\
147
+ expected boolean, got type="+typeof e)}return e}function eu(e){if(typeof e=="bigint"){if(!Kn(e))throw new RangeError("positive bigint expected, got "+e)}else to(e);return e}function We(e,t=""){if(typeof e!=
148
+ "number"){let n=t&&`"${t}" `;throw new TypeError(n+"expected number, got type="+typeof e)}if(!Number.isSafeInteger(e)){let n=t&&`"${t}" `;throw new RangeError(n+"expected safe integer, got "+e)}}function is(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);return e===""?Gn:BigInt("0x"+e)}function ro(e){return is(qn(e))}function Ke(e){return is(qn(on(Re(e)).reverse()))}
149
+ function oo(e,t){if(Vn(t),t===0)throw new RangeError("zero length");e=eu(e);let n=e.toString(16);if(n.length>t*2)throw new RangeError("number too large");return tn(n.padStart(t*2,"0"))}function ss(e,t){
150
+ return oo(e,t).reverse()}function as(e,t){if(e=ee(e),t=ee(t),e.length!==t.length)return false;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function on(e){return Uint8Array.from(ee(e))}var Kn=e=>typeof e=="bigint"&&Gn<=e;function tu(e,t,n){return Kn(e)&&Kn(t)&&Kn(n)&&t<=e&&e<n}function io(e,t,n,r){if(!tu(t,n,r))throw new RangeError(
151
+ "expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function so(e){if(e<Gn)throw new Error("expected non-negative bigint, got "+e);let t;for(t=0;e>Gn;e>>=eo,t+=1);return t}var cs=e=>(eo<<BigInt(e))-eo;function ht(e,t={},n={}){if(Object.prototype.toString.call(e)!=="[object Object]")throw new TypeError("expected valid options object");function r(i,s,a){if(!a&&s!=="function"&&!Object.hasOwn(e,i))throw new TypeError(
152
152
  `param "${i}" is invalid: expected own property`);let c=e[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.
153
- entries(i).forEach(([a,c])=>r(a,c,s));o(t,false),o(n,true);}var ro=()=>{throw new Error("not implemented")};var ae=BigInt(0),re=BigInt(1),ft=BigInt(2),is=BigInt(3),ss=BigInt(4),as=BigInt(5),Hl=BigInt(7),cs=BigInt(8),Wl=BigInt(9),ls=BigInt(16);function J(e,t){if(t<=ae)throw new Error("mod: expected positive \
154
- modulus, got "+t);let n=e%t;return n>=ae?n:t+n}function Ae(e,t,n){if(t<ae)throw new Error("pow2: expected non-negative exponent, got "+t);let r=e;for(;t-- >ae;)r*=r,r%=n;return r}function ns(e,t){if(e===ae)throw new Error("invert: expected non-zer\
155
- o number");if(t<=ae)throw new Error("invert: expected positive modulus, got "+t);let n=J(e,t),r=t,o=ae,s=re;for(;n!==ae;){let l=r/n,d=r-n*l,u=o-s*l;r=n,n=d,o=s,s=u;}if(r!==re)
156
- throw new Error("invert: does not exist");return J(o,t)}function oo(e,t,n){let r=e;if(!r.eql(r.sqr(t),n))throw new Error("Cannot find square root")}function us(e,t){let n=e,r=(n.ORDER+re)/ss,o=n.pow(t,
157
- r);return oo(n,o,t),o}function Kl(e,t){let n=e,r=(n.ORDER-as)/cs,o=n.mul(t,ft),i=n.pow(o,r),s=n.mul(t,i),a=n.mul(n.mul(s,ft),i),c=n.mul(s,n.sub(a,n.ONE));return oo(n,c,t),c}function Gl(e){let t=Jn(e),
158
- n=ds(e),r=n(t,t.neg(t.ONE)),o=n(t,r),i=n(t,t.neg(r)),s=(e+Hl)/ls;return((a,c)=>{let l=a,d=l.pow(c,s),u=l.mul(d,r),p=l.mul(d,o),f=l.mul(d,i),g=l.eql(l.sqr(u),c),b=l.eql(l.sqr(p),c);d=l.cmov(d,u,g),u=l.
159
- cmov(f,p,b);let h=l.eql(l.sqr(u),c),v=l.cmov(d,u,h);return oo(l,v,c),v})}function ds(e){if(e<is)throw new Error("sqrt is not defined for small field");let t=e-re,n=0;for(;t%ft===ae;)t/=ft,n++;let r=ft,
160
- o=Jn(e);for(;rs(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return us;let i=o.pow(r,t),s=(t+re)/ft;return function(c,l){let d=c;if(d.is0(l))return l;
161
- if(rs(d,l)!==1)throw new Error("Cannot find square root");let u=n,p=d.mul(d.ONE,i),f=d.pow(l,t),g=d.pow(l,s);for(;!d.eql(f,d.ONE);){if(d.is0(f))return d.ZERO;let b=1,h=d.sqr(f);for(;!d.eql(h,d.ONE);)if(b++,
162
- h=d.sqr(h),b===u)throw new Error("Cannot find square root");let v=re<<BigInt(u-b-1),k=d.pow(p,v);u=b,p=d.sqr(k),f=d.mul(f,p),g=d.mul(g,k);}return g}}function Jl(e){return e%ss===is?us:e%cs===as?Kl:e%ls===
163
- Wl?Gl(e):ds(e)}var He=(e,t)=>(J(e,t)&re)===re,Yl=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ps(e){let t={ORDER:"bigint",
164
- BYTES:"number",BITS:"number"},n=Yl.reduce((r,o)=>(r[o]="function",r),t);if(pt(e,n),ze(e.BYTES,"BYTES"),ze(e.BITS,"BITS"),e.BYTES<1||e.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(e.
165
- ORDER<=re)throw new Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function Zl(e,t,n){let r=e;if(n<ae)throw new Error("invalid exponent, negatives unsupported");if(n===ae)return r.ONE;
166
- if(n===re)return t;let o=r.ONE,i=t;for(;n>ae;)n&re&&(o=r.mul(o,i)),i=r.sqr(i),n>>=re;return o}function Gn(e,t,n=false){let r=e,o=new Array(t.length).fill(n?r.ZERO:void 0),i=t.reduce((a,c,l)=>r.is0(c)?a:(o[l]=
167
- a,r.mul(a,c)),r.ONE),s=r.inv(i);return t.reduceRight((a,c,l)=>r.is0(c)?a:(o[l]=r.mul(a,o[l]),r.mul(a,c)),s),o}function rs(e,t){let n=e,r=(n.ORDER-re)/ft,o=n.pow(t,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 Xl(e,t){if(t!==void 0&&Zr(t),e<=ae)throw new Error("invalid n length: expected positive n, got "+e);if(t!==void 0&&t<1)throw new Error("invalid n length: expected positive bit length, got "+t);
168
- let n=no(e);if(t!==void 0&&t<n)throw new Error(`invalid n length: expected bit length (${n}) >= n.length (${t})`);let r=t!==void 0?t:n,o=Math.ceil(r/8);return {nBitLength:r,nByteLength:o}}var os=new WeakMap,
169
- Kn=class{ORDER;BITS;BYTES;isLE;ZERO=ae;ONE=re;_lengths;_mod;constructor(t,n={}){if(t<=re)throw new Error("invalid field: expected ORDER > 1, got "+t);let r;this.isLE=false,n!=null&&typeof n=="object"&&(typeof n.
153
+ entries(i).forEach(([a,c])=>r(a,c,s));o(t,false),o(n,true);}var ao=()=>{throw new Error("not implemented")};var le=BigInt(0),ie=BigInt(1),gt=BigInt(2),ps=BigInt(3),fs=BigInt(4),ms=BigInt(5),nu=BigInt(7),hs=BigInt(8),ru=BigInt(9),gs=BigInt(16);function Z(e,t){if(t<=le)throw new Error("mod: expected positive \
154
+ modulus, got "+t);let n=e%t;return n>=le?n:t+n}function Ie(e,t,n){if(t<le)throw new Error("pow2: expected non-negative exponent, got "+t);let r=e;for(;t-- >le;)r*=r,r%=n;return r}function ls(e,t){if(e===le)throw new Error("invert: expected non-zer\
155
+ o number");if(t<=le)throw new Error("invert: expected positive modulus, got "+t);let n=Z(e,t),r=t,o=le,s=ie;for(;n!==le;){let l=r/n,d=r-n*l,u=o-s*l;r=n,n=d,o=s,s=u;}if(r!==ie)
156
+ throw new Error("invert: does not exist");return Z(o,t)}function co(e,t,n){let r=e;if(!r.eql(r.sqr(t),n))throw new Error("Cannot find square root")}function bs(e,t){let n=e,r=(n.ORDER+ie)/fs,o=n.pow(t,
157
+ r);return co(n,o,t),o}function ou(e,t){let n=e,r=(n.ORDER-ms)/hs,o=n.mul(t,gt),i=n.pow(o,r),s=n.mul(t,i),a=n.mul(n.mul(s,gt),i),c=n.mul(s,n.sub(a,n.ONE));return co(n,c,t),c}function iu(e){let t=Qn(e),
158
+ n=vs(e),r=n(t,t.neg(t.ONE)),o=n(t,r),i=n(t,t.neg(r)),s=(e+nu)/gs;return((a,c)=>{let l=a,d=l.pow(c,s),u=l.mul(d,r),p=l.mul(d,o),f=l.mul(d,i),g=l.eql(l.sqr(u),c),b=l.eql(l.sqr(p),c);d=l.cmov(d,u,g),u=l.
159
+ cmov(f,p,b);let h=l.eql(l.sqr(u),c),v=l.cmov(d,u,h);return co(l,v,c),v})}function vs(e){if(e<ps)throw new Error("sqrt is not defined for small field");let t=e-ie,n=0;for(;t%gt===le;)t/=gt,n++;let r=gt,
160
+ o=Qn(e);for(;us(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return bs;let i=o.pow(r,t),s=(t+ie)/gt;return function(c,l){let d=c;if(d.is0(l))return l;
161
+ if(us(d,l)!==1)throw new Error("Cannot find square root");let u=n,p=d.mul(d.ONE,i),f=d.pow(l,t),g=d.pow(l,s);for(;!d.eql(f,d.ONE);){if(d.is0(f))return d.ZERO;let b=1,h=d.sqr(f);for(;!d.eql(h,d.ONE);)if(b++,
162
+ h=d.sqr(h),b===u)throw new Error("Cannot find square root");let v=ie<<BigInt(u-b-1),k=d.pow(p,v);u=b,p=d.sqr(k),f=d.mul(f,p),g=d.mul(g,k);}return g}}function su(e){return e%fs===ps?bs:e%hs===ms?ou:e%gs===
163
+ ru?iu(e):vs(e)}var Ge=(e,t)=>(Z(e,t)&ie)===ie,au=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ys(e){let t={ORDER:"bigint",
164
+ BYTES:"number",BITS:"number"},n=au.reduce((r,o)=>(r[o]="function",r),t);if(ht(e,n),We(e.BYTES,"BYTES"),We(e.BITS,"BITS"),e.BYTES<1||e.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(e.
165
+ ORDER<=ie)throw new Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function cu(e,t,n){let r=e;if(n<le)throw new Error("invalid exponent, negatives unsupported");if(n===le)return r.ONE;
166
+ if(n===ie)return t;let o=r.ONE,i=t;for(;n>le;)n&ie&&(o=r.mul(o,i)),i=r.sqr(i),n>>=ie;return o}function Xn(e,t,n=false){let r=e,o=new Array(t.length).fill(n?r.ZERO:void 0),i=t.reduce((a,c,l)=>r.is0(c)?a:(o[l]=
167
+ a,r.mul(a,c)),r.ONE),s=r.inv(i);return t.reduceRight((a,c,l)=>r.is0(c)?a:(o[l]=r.mul(a,o[l]),r.mul(a,c)),s),o}function us(e,t){let n=e,r=(n.ORDER-ie)/gt,o=n.pow(t,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 lu(e,t){if(t!==void 0&&to(t),e<=le)throw new Error("invalid n length: expected positive n, got "+e);if(t!==void 0&&t<1)throw new Error("invalid n length: expected positive bit length, got "+t);
168
+ let n=so(e);if(t!==void 0&&t<n)throw new Error(`invalid n length: expected bit length (${n}) >= n.length (${t})`);let r=t!==void 0?t:n,o=Math.ceil(r/8);return {nBitLength:r,nByteLength:o}}var ds=new WeakMap,
169
+ Zn=class{ORDER;BITS;BYTES;isLE;ZERO=le;ONE=ie;_lengths;_mod;constructor(t,n={}){if(t<=ie)throw new Error("invalid field: expected ORDER > 1, got "+t);let r;this.isLE=false,n!=null&&typeof n=="object"&&(typeof n.
170
170
  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.
171
- freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:i}=Xl(t,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2\
172
- 048 bytes");this.ORDER=t,this.BITS=o,this.BYTES=i,Object.freeze(this);}create(t){return J(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new TypeError("invalid field element: expected bigint, got\
173
- "+typeof t);return ae<=t&&t<this.ORDER}is0(t){return t===ae}isValidNot0(t){return !this.is0(t)&&this.isValid(t)}isOdd(t){return (t&re)===re}neg(t){return J(-t,this.ORDER)}eql(t,n){return t===n}sqr(t){return J(
174
- t*t,this.ORDER)}add(t,n){return J(t+n,this.ORDER)}sub(t,n){return J(t-n,this.ORDER)}mul(t,n){return J(t*n,this.ORDER)}pow(t,n){return Zl(this,t,n)}div(t,n){return J(t*ns(n,this.ORDER),this.ORDER)}sqrN(t){
175
- return t*t}addN(t,n){return t+n}subN(t,n){return t-n}mulN(t,n){return t*n}inv(t){return ns(t,this.ORDER)}sqrt(t){let n=os.get(this);return n||os.set(this,n=Jl(this.ORDER)),n(this,t)}toBytes(t){return this.
176
- isLE?Qi(t,this.BYTES):eo(t,this.BYTES)}fromBytes(t,n=false){X(t);let{_lengths:r,BYTES:o,isLE:i,ORDER:s,_mod:a}=this;if(r){if(t.length<1||!r.includes(t.length)||t.length>o)throw new Error("Field.fromBytes\
177
- : expected "+r+" bytes, got "+t.length);let l=new Uint8Array(o);l.set(t,i?0:l.length-t.length),t=l;}if(t.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);let c=i?qe(t):
178
- Qr(t);if(a&&(c=J(c,s)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return Gn(this,t)}cmov(t,n,r){return Ct(r,"condition"),r?n:t}};Object.
179
- freeze(Kn.prototype);function Jn(e,t={}){return new Kn(e,t)}var Yn=BigInt(0),co=BigInt(1);function fs(e,t){let n=t.negate();return e?n:t}function Xn(e,t){let n=Gn(e.Fp,t.map(r=>r.Z));return t.map((r,o)=>e.fromAffine(r.toAffine(n[o])))}function bs(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)
180
- throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function io(e,t){bs(e,t);let n=Math.ceil(t/e)+1,r=2**(e-1),o=2**e,i=ts(e),s=BigInt(e);return {windows:n,windowSize:r,mask:i,maxNumber:o,
181
- shiftBy:s}}function ms(e,t,n){let{windowSize:r,mask:o,maxNumber:i,shiftBy:s}=n,a=Number(e&o),c=e>>s;a>r&&(a-=i,c+=co);let l=t*r,d=l+Math.abs(a)-1,u=a===0,p=a<0,f=t%2!==0;return {nextN:c,offset:d,isZero:u,
182
- isNeg:p,isNegF:f,offsetF:l}}var so=new WeakMap,vs=new WeakMap;function ao(e){return vs.get(e)||1}function hs(e){if(e!==Yn)throw new Error("invalid wNAF")}var Zn=class{BASE;ZERO;Fn;bits;constructor(t,n){this.BASE=t.BASE,this.ZERO=
183
- t.ZERO,this.Fn=t.Fn,this.bits=n;}_unsafeLadder(t,n,r=this.ZERO){let o=t;for(;n>Yn;)n&co&&(r=r.add(o)),o=o.double(),n>>=co;return r}precomputeWindow(t,n){let{windows:r,windowSize:o}=io(n,this.bits),i=[],
171
+ freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:i}=lu(t,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2\
172
+ 048 bytes");this.ORDER=t,this.BITS=o,this.BYTES=i,Object.freeze(this);}create(t){return Z(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new TypeError("invalid field element: expected bigint, got\
173
+ "+typeof t);return le<=t&&t<this.ORDER}is0(t){return t===le}isValidNot0(t){return !this.is0(t)&&this.isValid(t)}isOdd(t){return (t&ie)===ie}neg(t){return Z(-t,this.ORDER)}eql(t,n){return t===n}sqr(t){return Z(
174
+ t*t,this.ORDER)}add(t,n){return Z(t+n,this.ORDER)}sub(t,n){return Z(t-n,this.ORDER)}mul(t,n){return Z(t*n,this.ORDER)}pow(t,n){return cu(this,t,n)}div(t,n){return Z(t*ls(n,this.ORDER),this.ORDER)}sqrN(t){
175
+ return t*t}addN(t,n){return t+n}subN(t,n){return t-n}mulN(t,n){return t*n}inv(t){return ls(t,this.ORDER)}sqrt(t){let n=ds.get(this);return n||ds.set(this,n=su(this.ORDER)),n(this,t)}toBytes(t){return this.
176
+ isLE?ss(t,this.BYTES):oo(t,this.BYTES)}fromBytes(t,n=false){ee(t);let{_lengths:r,BYTES:o,isLE:i,ORDER:s,_mod:a}=this;if(r){if(t.length<1||!r.includes(t.length)||t.length>o)throw new Error("Field.fromByte\
177
+ s: expected "+r+" bytes, got "+t.length);let l=new Uint8Array(o);l.set(t,i?0:l.length-t.length),t=l;}if(t.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);let c=i?Ke(t):
178
+ ro(t);if(a&&(c=Z(c,s)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return Xn(this,t)}cmov(t,n,r){return It(r,"condition"),r?n:t}};Object.
179
+ freeze(Zn.prototype);function Qn(e,t={}){return new Zn(e,t)}var er=BigInt(0),fo=BigInt(1);function ks(e,t){let n=t.negate();return e?n:t}function nr(e,t){let n=Xn(e.Fp,t.map(r=>r.Z));return t.map((r,o)=>e.fromAffine(r.toAffine(n[o])))}function Es(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)
180
+ throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function lo(e,t){Es(e,t);let n=Math.ceil(t/e)+1,r=2**(e-1),o=2**e,i=cs(e),s=BigInt(e);return {windows:n,windowSize:r,mask:i,maxNumber:o,
181
+ shiftBy:s}}function xs(e,t,n){let{windowSize:r,mask:o,maxNumber:i,shiftBy:s}=n,a=Number(e&o),c=e>>s;a>r&&(a-=i,c+=fo);let l=t*r,d=l+Math.abs(a)-1,u=a===0,p=a<0,f=t%2!==0;return {nextN:c,offset:d,isZero:u,
182
+ isNeg:p,isNegF:f,offsetF:l}}var uo=new WeakMap,_s=new WeakMap;function po(e){return _s.get(e)||1}function ws(e){if(e!==er)throw new Error("invalid wNAF")}var tr=class{BASE;ZERO;Fn;bits;constructor(t,n){this.BASE=t.BASE,this.ZERO=
183
+ t.ZERO,this.Fn=t.Fn,this.bits=n;}_unsafeLadder(t,n,r=this.ZERO){let o=t;for(;n>er;)n&fo&&(r=r.add(o)),o=o.double(),n>>=fo;return r}precomputeWindow(t,n){let{windows:r,windowSize:o}=lo(n,this.bits),i=[],
184
184
  s=t,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(t,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,i=this.BASE,
185
- s=io(t,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:l,isZero:d,isNeg:u,isNegF:p,offsetF:f}=ms(r,a,s);r=c,d?i=i.add(fs(p,n[f])):o=o.add(fs(u,n[l]));}return hs(r),{p:o,f:i}}wNAFUnsafe(t,n,r,o=this.
186
- ZERO){let i=io(t,this.bits);for(let s=0;s<i.windows&&r!==Yn;s++){let{nextN:a,offset:c,isZero:l,isNeg:d}=ms(r,s,i);if(r=a,!l){let u=n[c];o=o.add(d?u.negate():u);}}return hs(r),o}getPrecomputes(t,n,r){let o=so.
187
- get(n);return o||(o=this.precomputeWindow(n,t),t!==1&&(typeof r=="function"&&(o=r(o)),so.set(n,o))),o}cached(t,n,r){let o=ao(t);return this.wNAF(o,this.getPrecomputes(o,t,r),n)}unsafe(t,n,r,o){let i=ao(
188
- t);return i===1?this._unsafeLadder(t,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,t,r),n,o)}createCache(t,n){bs(n,this.bits),vs.set(t,n),so.delete(t);}hasCache(t){return ao(t)!==1}};function gs(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return ps(t),t}else return Jn(e,{isLE:n})}function ys(e,t,n={},r){if(r===void 0&&(r=e==="edwar\
189
- ds"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(let c of ["p","n","h"]){let l=t[c];if(!(typeof l=="bigint"&&l>Yn))throw new Error(`CURVE.${c} must be positive bigint`)}
190
- let o=gs(t.p,n.Fp,r),i=gs(t.n,n.Fn,r),a=["Gx","Gy","a","d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.
191
- freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:i}}function ks(e,t){return function(r){let o=e(r);return {secretKey:o,publicKey:t(o)}}}var et=BigInt(0),oe=BigInt(1),lo=BigInt(2),Ql=BigInt(8);function eu(e,t,n,r){let o=e.sqr(n),i=e.sqr(r),s=e.add(e.mul(t.a,o),i),a=e.add(e.ONE,e.mul(t.d,e.mul(o,i)));return e.eql(s,a)}function xs(e,t={}){
192
- let n=t,r=ys("edwards",e,n,n.FpFnLE),{Fp:o,Fn:i}=r,s=r.CURVE,{h:a}=s;pt(n,{},{uvRatio:"function"});let c=lo<<BigInt(i.BYTES*8)-oe,l=b=>o.create(b),d=n.uvRatio===void 0?(b,h)=>{try{return {isValid:!0,value:o.
193
- sqrt(o.div(b,h))}}catch{return {isValid:false,value:et}}}:n.uvRatio;if(!eu(o,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function u(b,h,v=false){let k=v?oe:et;return to("coordinate "+b,
194
- h,k,c),h}function p(b){if(!(b instanceof f))throw new Error("EdwardsPoint expected")}class f{static BASE=new f(s.Gx,s.Gy,oe,l(s.Gx*s.Gy));static ZERO=new f(et,oe,oe,et);static Fp=o;static Fn=i;X;Y;Z;T;constructor(h,v,k,x){
185
+ s=lo(t,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:l,isZero:d,isNeg:u,isNegF:p,offsetF:f}=xs(r,a,s);r=c,d?i=i.add(ks(p,n[f])):o=o.add(ks(u,n[l]));}return ws(r),{p:o,f:i}}wNAFUnsafe(t,n,r,o=this.
186
+ ZERO){let i=lo(t,this.bits);for(let s=0;s<i.windows&&r!==er;s++){let{nextN:a,offset:c,isZero:l,isNeg:d}=xs(r,s,i);if(r=a,!l){let u=n[c];o=o.add(d?u.negate():u);}}return ws(r),o}getPrecomputes(t,n,r){let o=uo.
187
+ get(n);return o||(o=this.precomputeWindow(n,t),t!==1&&(typeof r=="function"&&(o=r(o)),uo.set(n,o))),o}cached(t,n,r){let o=po(t);return this.wNAF(o,this.getPrecomputes(o,t,r),n)}unsafe(t,n,r,o){let i=po(
188
+ t);return i===1?this._unsafeLadder(t,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,t,r),n,o)}createCache(t,n){Es(n,this.bits),_s.set(t,n),uo.delete(t);}hasCache(t){return po(t)!==1}};function Ss(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return ys(t),t}else return Qn(e,{isLE:n})}function Ts(e,t,n={},r){if(r===void 0&&(r=e==="edwar\
189
+ ds"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(let c of ["p","n","h"]){let l=t[c];if(!(typeof l=="bigint"&&l>er))throw new Error(`CURVE.${c} must be positive bigint`)}
190
+ let o=Ss(t.p,n.Fp,r),i=Ss(t.n,n.Fn,r),a=["Gx","Gy","a","d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.
191
+ freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:i}}function Cs(e,t){return function(r){let o=e(r);return {secretKey:o,publicKey:t(o)}}}var nt=BigInt(0),se=BigInt(1),mo=BigInt(2),uu=BigInt(8);function du(e,t,n,r){let o=e.sqr(n),i=e.sqr(r),s=e.add(e.mul(t.a,o),i),a=e.add(e.ONE,e.mul(t.d,e.mul(o,i)));return e.eql(s,a)}function As(e,t={}){
192
+ let n=t,r=Ts("edwards",e,n,n.FpFnLE),{Fp:o,Fn:i}=r,s=r.CURVE,{h:a}=s;ht(n,{},{uvRatio:"function"});let c=mo<<BigInt(i.BYTES*8)-se,l=b=>o.create(b),d=n.uvRatio===void 0?(b,h)=>{try{return {isValid:!0,value:o.
193
+ sqrt(o.div(b,h))}}catch{return {isValid:false,value:nt}}}:n.uvRatio;if(!du(o,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function u(b,h,v=false){let k=v?se:nt;return io("coordinate "+b,
194
+ h,k,c),h}function p(b){if(!(b instanceof f))throw new Error("EdwardsPoint expected")}class f{static BASE=new f(s.Gx,s.Gy,se,l(s.Gx*s.Gy));static ZERO=new f(nt,se,se,nt);static Fp=o;static Fn=i;X;Y;Z;T;constructor(h,v,k,x){
195
195
  this.X=u("x",h),this.Y=u("y",v),this.Z=u("z",k,true),this.T=u("t",x),Object.freeze(this);}static CURVE(){return s}static fromAffine(h){if(h instanceof f)throw new Error("extended point not allowed");let{
196
- x:v,y:k}=h||{};return u("x",v),u("y",k),new f(v,k,oe,l(v*k))}static fromBytes(h,v=false){let k=o.BYTES,{a:x,d:y}=s;h=tn(X(h,k,"point")),Ct(v,"zip215");let A=tn(h),R=h[k-1];A[k-1]=R&-129;let I=qe(A),D=v?c:
197
- o.ORDER;to("point.y",I,et,D);let N=l(I*I),H=l(N-oe),Y=l(y*N-x),{isValid:E,value:C}=d(H,Y);if(!E)throw new Error("bad point: invalid y coordinate");let O=(C&oe)===oe,$=(R&128)!==0;if(!v&&C===et&&$)throw new Error(
198
- "bad point: x=0 and x_0=1");return $!==O&&(C=l(-C)),f.fromAffine({x:C,y:I})}static fromHex(h,v=false){return f.fromBytes(Yi(h),v)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(h=8,v=true){
199
- return g.createCache(this,h),v||this.multiply(lo),this}assertValidity(){let h=this,{a:v,d:k}=s;if(h.is0())throw new Error("bad point: ZERO");let{X:x,Y:y,Z:A,T:R}=h,I=l(x*x),D=l(y*y),N=l(A*A),H=l(N*N),
200
- Y=l(I*v),E=l(N*l(Y+D)),C=l(H+l(k*l(I*D)));if(E!==C)throw new Error("bad point: equation left != right (1)");let O=l(x*y),$=l(A*R);if(O!==$)throw new Error("bad point: equation left != right (2)")}equals(h){
201
- p(h);let{X:v,Y:k,Z:x}=this,{X:y,Y:A,Z:R}=h,I=l(v*R),D=l(y*x),N=l(k*R),H=l(A*x);return I===D&&N===H}is0(){return this.equals(f.ZERO)}negate(){return new f(l(-this.X),this.Y,this.Z,l(-this.T))}double(){
202
- let{a:h}=s,{X:v,Y:k,Z:x}=this,y=l(v*v),A=l(k*k),R=l(lo*l(x*x)),I=l(h*y),D=v+k,N=l(l(D*D)-y-A),H=I+A,Y=H-R,E=I-A,C=l(N*Y),O=l(H*E),$=l(N*E),Q=l(Y*H);return new f(C,O,Q,$)}add(h){p(h);let{a:v,d:k}=s,{X:x,
203
- Y:y,Z:A,T:R}=this,{X:I,Y:D,Z:N,T:H}=h,Y=l(x*I),E=l(y*D),C=l(R*k*H),O=l(A*N),$=l((x+y)*(I+D)-Y-E),Q=O-C,Z=O+C,be=l(E-v*Y),ve=l($*Q),je=l(Z*be),Je=l($*be),m=l(Q*Z);return new f(ve,je,m,Je)}subtract(h){return p(
204
- h),this.add(h.negate())}multiply(h){if(!i.isValidNot0(h))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:v,f:k}=g.cached(this,h,x=>Xn(f,x));return Xn(f,[v,k])[0]}multiplyUnsafe(h){
205
- if(!i.isValid(h))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return h===et?f.ZERO:this.is0()||h===oe?this:g.unsafe(this,h,v=>Xn(f,v))}isSmallOrder(){return this.clearCofactor().
206
- is0()}isTorsionFree(){return g.unsafe(this,s.n).is0()}toAffine(h){let v=this,k=h,{X:x,Y:y,Z:A}=v,R=v.is0();k==null&&(k=R?Ql:o.inv(A));let I=l(x*k),D=l(y*k),N=o.mul(A,k);if(R)return {x:et,y:oe};if(N!==oe)
207
- throw new Error("invZ was invalid");return {x:I,y:D}}clearCofactor(){return a===oe?this:this.multiplyUnsafe(a)}toBytes(){let{x:h,y:v}=this.toAffine(),k=o.toBytes(v);return k[k.length-1]|=h&oe?128:0,k}toHex(){
208
- return Xr(this.toBytes())}toString(){return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let g=new Zn(f,i.BITS);return i.BITS>=8&&f.BASE.precompute(8),Object.freeze(f.prototype),Object.freeze(f),f}var Qn=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(t){
209
- this.ep=t;}static fromBytes(t){ro();}static fromHex(t){ro();}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity();}toAffine(t){
210
- return this.ep.toAffine(t)}toHex(){return Xr(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return true}isSmallOrder(){return false}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){
196
+ x:v,y:k}=h||{};return u("x",v),u("y",k),new f(v,k,se,l(v*k))}static fromBytes(h,v=false){let k=o.BYTES,{a:x,d:y}=s;h=on(ee(h,k,"point")),It(v,"zip215");let R=on(h),P=h[k-1];R[k-1]=P&-129;let D=Ke(R),L=v?
197
+ c:o.ORDER;io("point.y",D,nt,L);let B=l(D*D),K=l(B-se),X=l(y*B-x),{isValid:E,value:A}=d(K,X);if(!E)throw new Error("bad point: invalid y coordinate");let M=(A&se)===se,j=(P&128)!==0;if(!v&&A===nt&&j)throw new Error(
198
+ "bad point: x=0 and x_0=1");return j!==M&&(A=l(-A)),f.fromAffine({x:A,y:D})}static fromHex(h,v=false){return f.fromBytes(rs(h),v)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(h=8,v=true){
199
+ return g.createCache(this,h),v||this.multiply(mo),this}assertValidity(){let h=this,{a:v,d:k}=s;if(h.is0())throw new Error("bad point: ZERO");let{X:x,Y:y,Z:R,T:P}=h,D=l(x*x),L=l(y*y),B=l(R*R),K=l(B*B),
200
+ X=l(D*v),E=l(B*l(X+L)),A=l(K+l(k*l(D*L)));if(E!==A)throw new Error("bad point: equation left != right (1)");let M=l(x*y),j=l(R*P);if(M!==j)throw new Error("bad point: equation left != right (2)")}equals(h){
201
+ p(h);let{X:v,Y:k,Z:x}=this,{X:y,Y:R,Z:P}=h,D=l(v*P),L=l(y*x),B=l(k*P),K=l(R*x);return D===L&&B===K}is0(){return this.equals(f.ZERO)}negate(){return new f(l(-this.X),this.Y,this.Z,l(-this.T))}double(){
202
+ let{a:h}=s,{X:v,Y:k,Z:x}=this,y=l(v*v),R=l(k*k),P=l(mo*l(x*x)),D=l(h*y),L=v+k,B=l(l(L*L)-y-R),K=D+R,X=K-P,E=D-R,A=l(B*X),M=l(K*E),j=l(B*E),te=l(X*K);return new f(A,M,te,j)}add(h){p(h);let{a:v,d:k}=s,{
203
+ X:x,Y:y,Z:R,T:P}=this,{X:D,Y:L,Z:B,T:K}=h,X=l(x*D),E=l(y*L),A=l(P*k*K),M=l(R*B),j=l((x+y)*(D+L)-X-E),te=M-A,Q=M+A,ye=l(E-v*X),ke=l(j*te),Ue=l(Q*ye),Xe=l(j*ye),m=l(te*Q);return new f(ke,Ue,m,Xe)}subtract(h){
204
+ return p(h),this.add(h.negate())}multiply(h){if(!i.isValidNot0(h))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:v,f:k}=g.cached(this,h,x=>nr(f,x));return nr(f,[v,k])[0]}multiplyUnsafe(h){
205
+ if(!i.isValid(h))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return h===nt?f.ZERO:this.is0()||h===se?this:g.unsafe(this,h,v=>nr(f,v))}isSmallOrder(){return this.clearCofactor().
206
+ is0()}isTorsionFree(){return g.unsafe(this,s.n).is0()}toAffine(h){let v=this,k=h,{X:x,Y:y,Z:R}=v,P=v.is0();k==null&&(k=P?uu:o.inv(R));let D=l(x*k),L=l(y*k),B=o.mul(R,k);if(P)return {x:nt,y:se};if(B!==se)
207
+ throw new Error("invZ was invalid");return {x:D,y:L}}clearCofactor(){return a===se?this:this.multiplyUnsafe(a)}toBytes(){let{x:h,y:v}=this.toAffine(),k=o.toBytes(v);return k[k.length-1]|=h&se?128:0,k}toHex(){
208
+ return no(this.toBytes())}toString(){return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let g=new tr(f,i.BITS);return i.BITS>=8&&f.BASE.precompute(8),Object.freeze(f.prototype),Object.freeze(f),f}var rr=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(t){
209
+ this.ep=t;}static fromBytes(t){ao();}static fromHex(t){ao();}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity();}toAffine(t){
210
+ return this.ep.toAffine(t)}toHex(){return no(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return true}isSmallOrder(){return false}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){
211
211
  return this.assertSame(t),this.init(this.ep.subtract(t.ep))}multiply(t){return this.init(this.ep.multiply(t))}multiplyUnsafe(t){return this.init(this.ep.multiplyUnsafe(t))}double(){return this.init(this.
212
- ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,n){return this.ep.precompute(t,n),this}};function ws(e,t,n={}){if(typeof t!="function")throw new Error('"hash" function param is r\
213
- equired');let r=t,o=n;pt(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:i}=o,{BASE:s,Fp:a,Fn:c}=e,l=r.
214
- outputLen,d=2*a.BYTES;if(l!==void 0&&(ze(l,"hash.outputLen"),l!==d))throw new Error(`hash.outputLen must be ${d}, got ${l}`);let u=o.randomBytes===void 0?Zi:o.randomBytes,p=o.adjustScalarBytes===void 0?
215
- E=>E:o.adjustScalarBytes,f=o.domain===void 0?(E,C,O)=>{if(Ct(O,"phflag"),C.length||O)throw new Error("Contexts/pre-hash are not supported");return E}:o.domain;function g(E){return c.create(qe(E))}function b(E){
216
- let C=I.secretKey;X(E,I.secretKey,"secretKey");let O=X(r(E),2*C,"hashedSecretKey"),$=p(O.slice(0,C)),Q=O.slice(C,2*C),Z=g($);return {head:$,prefix:Q,scalar:Z}}function h(E){let{head:C,prefix:O,scalar:$}=b(
217
- E),Q=s.multiply($),Z=Q.toBytes();return {head:C,prefix:O,scalar:$,point:Q,pointBytes:Z}}function v(E){return h(E).pointBytes}function k(E=Uint8Array.of(),...C){let O=De(...C);return g(r(f(O,X(E,void 0,
218
- "context"),!!i)))}function x(E,C,O={}){E=X(E,void 0,"message"),i&&(E=i(E));let{prefix:$,scalar:Q,pointBytes:Z}=h(C),be=k(O.context,$,E),ve=s.multiply(be).toBytes(),je=k(O.context,ve,Z,E),Je=c.create(be+
219
- je*Q);if(!c.isValid(Je))throw new Error("sign failed: invalid s");let m=De(ve,c.toBytes(Je));return X(m,I.signature,"result")}let y={zip215:o.zip215};function A(E,C,O,$=y){let{context:Q}=$,Z=$.zip215===
220
- void 0?!!y.zip215:$.zip215,be=I.signature;E=X(E,be,"signature"),C=X(C,void 0,"message"),O=X(O,I.publicKey,"publicKey"),Z!==void 0&&Ct(Z,"zip215"),i&&(C=i(C));let ve=be/2,je=E.subarray(0,ve),Je=qe(E.subarray(
221
- ve,be)),m,_,L;try{m=e.fromBytes(O,Z),_=e.fromBytes(je,Z),L=s.multiplyUnsafe(Je);}catch{return false}if(!Z&&m.isSmallOrder())return false;let B=k(Q,je,O,C);return _.add(m.multiplyUnsafe(B)).subtract(L).clearCofactor().
222
- is0()}let R=a.BYTES,I={secretKey:R,publicKey:R,signature:2*R,seed:R};function D(E){return E=E===void 0?u(I.seed):E,X(E,I.seed,"seed")}function N(E){return Hn(E)&&E.length===I.secretKey}function H(E,C){
223
- try{return !!e.fromBytes(E,C===void 0?y.zip215:C)}catch{return false}}let Y={getExtendedPublicKey:h,randomSecretKey:D,isValidSecretKey:N,isValidPublicKey:H,toMontgomery(E){let{y:C}=e.fromBytes(E),O=I.publicKey,
224
- $=O===32;if(!$&&O!==57)throw new Error("only defined for 25519 and 448");let Q=$?a.div(oe+C,oe-C):a.div(C-oe,C+oe);return a.toBytes(Q)},toMontgomerySecret(E){let C=I.secretKey;X(E,C);let O=r(E.subarray(
225
- 0,C));return p(O).subarray(0,C)}};return Object.freeze(I),Object.freeze(Y),Object.freeze({keygen:ks(D,v),getPublicKey:v,sign:x,verify:A,utils:Y,Point:e,lengths:I})}var ru=BigInt(0),We=BigInt(1),Es=BigInt(2);var ou=BigInt(5),iu=BigInt(8),At=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),ho={p:At,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:iu,
212
+ ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,n){return this.ep.precompute(t,n),this}};function Rs(e,t,n={}){if(typeof t!="function")throw new Error('"hash" function param is r\
213
+ equired');let r=t,o=n;ht(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:i}=o,{BASE:s,Fp:a,Fn:c}=e,l=r.
214
+ outputLen,d=2*a.BYTES;if(l!==void 0&&(We(l,"hash.outputLen"),l!==d))throw new Error(`hash.outputLen must be ${d}, got ${l}`);let u=o.randomBytes===void 0?os:o.randomBytes,p=o.adjustScalarBytes===void 0?
215
+ E=>E:o.adjustScalarBytes,f=o.domain===void 0?(E,A,M)=>{if(It(M,"phflag"),A.length||M)throw new Error("Contexts/pre-hash are not supported");return E}:o.domain;function g(E){return c.create(Ke(E))}function b(E){
216
+ let A=D.secretKey;ee(E,D.secretKey,"secretKey");let M=ee(r(E),2*A,"hashedSecretKey"),j=p(M.slice(0,A)),te=M.slice(A,2*A),Q=g(j);return {head:j,prefix:te,scalar:Q}}function h(E){let{head:A,prefix:M,scalar:j}=b(
217
+ E),te=s.multiply(j),Q=te.toBytes();return {head:A,prefix:M,scalar:j,point:te,pointBytes:Q}}function v(E){return h(E).pointBytes}function k(E=Uint8Array.of(),...A){let M=Le(...A);return g(r(f(M,ee(E,void 0,
218
+ "context"),!!i)))}function x(E,A,M={}){E=ee(E,void 0,"message"),i&&(E=i(E));let{prefix:j,scalar:te,pointBytes:Q}=h(A),ye=k(M.context,j,E),ke=s.multiply(ye).toBytes(),Ue=k(M.context,ke,Q,E),Xe=c.create(
219
+ ye+Ue*te);if(!c.isValid(Xe))throw new Error("sign failed: invalid s");let m=Le(ke,c.toBytes(Xe));return ee(m,D.signature,"result")}let y={zip215:o.zip215};function R(E,A,M,j=y){let{context:te}=j,Q=j.zip215===
220
+ void 0?!!y.zip215:j.zip215,ye=D.signature;E=ee(E,ye,"signature"),A=ee(A,void 0,"message"),M=ee(M,D.publicKey,"publicKey"),Q!==void 0&&It(Q,"zip215"),i&&(A=i(A));let ke=ye/2,Ue=E.subarray(0,ke),Xe=Ke(E.
221
+ subarray(ke,ye)),m,_,$;try{m=e.fromBytes(M,Q),_=e.fromBytes(Ue,Q),$=s.multiplyUnsafe(Xe);}catch{return false}if(!Q&&m.isSmallOrder())return false;let V=k(te,Ue,M,A);return _.add(m.multiplyUnsafe(V)).subtract($).
222
+ clearCofactor().is0()}let P=a.BYTES,D={secretKey:P,publicKey:P,signature:2*P,seed:P};function L(E){return E=E===void 0?u(D.seed):E,ee(E,D.seed,"seed")}function B(E){return Jn(E)&&E.length===D.secretKey}
223
+ function K(E,A){try{return !!e.fromBytes(E,A===void 0?y.zip215:A)}catch{return false}}let X={getExtendedPublicKey:h,randomSecretKey:L,isValidSecretKey:B,isValidPublicKey:K,toMontgomery(E){let{y:A}=e.fromBytes(
224
+ E),M=D.publicKey,j=M===32;if(!j&&M!==57)throw new Error("only defined for 25519 and 448");let te=j?a.div(se+A,se-A):a.div(A-se,A+se);return a.toBytes(te)},toMontgomerySecret(E){let A=D.secretKey;ee(E,
225
+ A);let M=r(E.subarray(0,A));return p(M).subarray(0,A)}};return Object.freeze(D),Object.freeze(X),Object.freeze({keygen:Cs(L,v),getPublicKey:v,sign:x,verify:R,utils:X,Point:e,lengths:D})}var mu=BigInt(0),Je=BigInt(1),Ps=BigInt(2);var hu=BigInt(5),gu=BigInt(8),Pt=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),yo={p:Pt,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:gu,
226
226
  a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6d\
227
- c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function su(e){let t=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),i=At,a=e*e%
228
- i*e%i,c=Ae(a,Es,i)*a%i,l=Ae(c,We,i)*e%i,d=Ae(l,ou,i)*l%i,u=Ae(d,t,i)*d%i,p=Ae(u,n,i)*u%i,f=Ae(p,r,i)*p%i,g=Ae(f,o,i)*f%i,b=Ae(g,o,i)*f%i,h=Ae(b,t,i)*d%i;return {pow_p_5_8:Ae(h,Es,i)*e%i,b2:a}}function au(e){
229
- return e[0]&=248,e[31]&=127,e[31]|=64,e}var po=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function go(e,t){let n=At,r=J(t*t*t,n),o=J(r*r*t,n),i=su(e*o).pow_p_5_8,
230
- s=J(e*r*i,n),a=J(t*s*s,n),c=s,l=J(s*po,n),d=a===e,u=a===J(-e,n),p=a===J(-e*po,n);return d&&(s=c),(u||p)&&(s=l),He(s,n)&&(s=J(-s,n)),{isValid:d||u,value:s}}var nt=xs(ho,{uvRatio:go}),tt=nt.Fp,Cs=nt.Fn;function cu(e){return ws(nt,Fn,Object.assign({adjustScalarBytes:au,zip215:true},e))}var As=cu({});var fo=po;BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");var uu=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt(
231
- "1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var _s=e=>go(We,e),fu=BigInt("0x7\
232
- fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),mo=e=>tt.create(qe(e)&fu);var rt=class e extends Qn{static BASE=new e(
233
- nt.BASE);static ZERO=new e(nt.ZERO);static Fp=tt;static Fn=Cs;constructor(t){super(t);}static fromAffine(t){return new e(nt.fromAffine(t))}assertSame(t){if(!(t instanceof e))throw new Error("RistrettoP\
234
- oint expected")}init(t){return new e(t)}static fromBytes(t){Ce(t,32);let{a:n,d:r}=ho,o=At,i=y=>tt.create(y),s=mo(t);if(!es(tt.toBytes(s),t)||He(s,o))throw new Error("invalid ristretto255 encoding 1");
235
- let a=i(s*s),c=i(We+n*a),l=i(We-n*a),d=i(c*c),u=i(l*l),p=i(n*r*d-u),{isValid:f,value:g}=_s(i(p*u)),b=i(g*l),h=i(g*b*p),v=i((s+s)*b);He(v,o)&&(v=i(-v));let k=i(c*h),x=i(v*k);if(!f||He(x,o)||k===ru)throw new Error(
236
- "invalid ristretto255 encoding 2");return new e(new nt(v,k,We,x))}static fromHex(t){return e.fromBytes(Xt(t))}toBytes(){let{X:t,Y:n,Z:r,T:o}=this.ep,i=At,s=h=>tt.create(h),a=s(s(r+n)*s(r-n)),c=s(t*n),
237
- l=s(c*c),{value:d}=_s(s(a*l)),u=s(d*a),p=s(d*c),f=s(u*p*o),g;if(He(o*f,i)){let h=s(n*fo),v=s(t*fo);t=h,n=v,g=s(u*uu);}else g=p;He(t*f,i)&&(n=s(-n));let b=s((r-n)*g);return He(b,i)&&(b=s(-b)),tt.toBytes(
238
- b)}equals(t){this.assertSame(t);let{X:n,Y:r}=this.ep,{X:o,Y:i}=t.ep,s=l=>tt.create(l),a=s(n*i)===s(r*o),c=s(r*i)===s(n*o);return a||c}is0(){return this.equals(e.ZERO)}};Object.freeze(rt.BASE);Object.freeze(
239
- rt.ZERO);Object.freeze(rt.prototype);Object.freeze(rt);var mt=`-----BEGIN PUBLIC KEY-----
227
+ c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function bu(e){let t=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),i=Pt,a=e*e%
228
+ i*e%i,c=Ie(a,Ps,i)*a%i,l=Ie(c,Je,i)*e%i,d=Ie(l,hu,i)*l%i,u=Ie(d,t,i)*d%i,p=Ie(u,n,i)*u%i,f=Ie(p,r,i)*p%i,g=Ie(f,o,i)*f%i,b=Ie(g,o,i)*f%i,h=Ie(b,t,i)*d%i;return {pow_p_5_8:Ie(h,Ps,i)*e%i,b2:a}}function vu(e){
229
+ return e[0]&=248,e[31]&=127,e[31]|=64,e}var go=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function ko(e,t){let n=Pt,r=Z(t*t*t,n),o=Z(r*r*t,n),i=bu(e*o).pow_p_5_8,
230
+ s=Z(e*r*i,n),a=Z(t*s*s,n),c=s,l=Z(s*go,n),d=a===e,u=a===Z(-e,n),p=a===Z(-e*go,n);return d&&(s=c),(u||p)&&(s=l),Ge(s,n)&&(s=Z(-s,n)),{isValid:d||u,value:s}}var ot=As(yo,{uvRatio:ko}),rt=ot.Fp,Ls=ot.Fn;function yu(e){return Rs(ot,Wn,Object.assign({adjustScalarBytes:vu,zip215:true},e))}var Ms=yu({});var bo=go;BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");var xu=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt(
231
+ "1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var Ds=e=>ko(Je,e),Eu=BigInt("0x7\
232
+ fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),vo=e=>rt.create(Ke(e)&Eu);var it=class e extends rr{static BASE=new e(
233
+ ot.BASE);static ZERO=new e(ot.ZERO);static Fp=rt;static Fn=Ls;constructor(t){super(t);}static fromAffine(t){return new e(ot.fromAffine(t))}assertSame(t){if(!(t instanceof e))throw new Error("RistrettoP\
234
+ oint expected")}init(t){return new e(t)}static fromBytes(t){Re(t,32);let{a:n,d:r}=yo,o=Pt,i=y=>rt.create(y),s=vo(t);if(!as(rt.toBytes(s),t)||Ge(s,o))throw new Error("invalid ristretto255 encoding 1");
235
+ let a=i(s*s),c=i(Je+n*a),l=i(Je-n*a),d=i(c*c),u=i(l*l),p=i(n*r*d-u),{isValid:f,value:g}=Ds(i(p*u)),b=i(g*l),h=i(g*b*p),v=i((s+s)*b);Ge(v,o)&&(v=i(-v));let k=i(c*h),x=i(v*k);if(!f||Ge(x,o)||k===mu)throw new Error(
236
+ "invalid ristretto255 encoding 2");return new e(new ot(v,k,Je,x))}static fromHex(t){return e.fromBytes(tn(t))}toBytes(){let{X:t,Y:n,Z:r,T:o}=this.ep,i=Pt,s=h=>rt.create(h),a=s(s(r+n)*s(r-n)),c=s(t*n),
237
+ l=s(c*c),{value:d}=Ds(s(a*l)),u=s(d*a),p=s(d*c),f=s(u*p*o),g;if(Ge(o*f,i)){let h=s(n*bo),v=s(t*bo);t=h,n=v,g=s(u*xu);}else g=p;Ge(t*f,i)&&(n=s(-n));let b=s((r-n)*g);return Ge(b,i)&&(b=s(-b)),rt.toBytes(
238
+ b)}equals(t){this.assertSame(t);let{X:n,Y:r}=this.ep,{X:o,Y:i}=t.ep,s=l=>rt.create(l),a=s(n*i)===s(r*o),c=s(r*i)===s(n*o);return a||c}is0(){return this.equals(e.ZERO)}};Object.freeze(it.BASE);Object.freeze(
239
+ it.ZERO);Object.freeze(it.prototype);Object.freeze(it);var bt=`-----BEGIN PUBLIC KEY-----
240
240
  MCowBQYDK2VwAyEAWBiklf0kmDIVmM7nMiCxwiEAkwQIiqWGuRiRDJonsFY=
241
- -----END PUBLIC KEY-----`;function Rs(e){let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function bo(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.
242
- length%4?"=".repeat(4-t.length%4):"";return Rs(t+n)}function hu(e){let t=e.replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=Rs(t);return n.subarray(n.length-32)}var gu=new TextEncoder,Is=new TextDecoder;
243
- function vo(e){return typeof e=="object"&&e!==null&&"keys"in e}function Rt(e){let t=e.trim(),n=/^(["'])([\s\S]*)\1$/.exec(t);return n&&(t=n[2].trim()),t=t.replace(/^bearer\s+/i,""),t.trim()}var bu=/^[A-Za-z0-9_-]+$/;
244
- function Ps(e){let t=e.split(".");return t.length===3&&t.every(n=>bu.test(n))}function rn(e){return e===""?"empty":Ps(e)?"token":"malformed"}function on(e,t){if(!Ps(e))return {ok:false,reason:"malformed t\
245
- oken"};let n=e.split("."),r=n[0],o=n[1],i=n[2],s;try{s=JSON.parse(Is.decode(bo(r)));}catch{return {ok:false,reason:"header is not valid JSON"}}let a;if(vo(t)){let d=typeof s.kid=="string"?s.kid:t.defaultKid,
246
- u=t.keys[d];if(!u)return {ok:false,reason:`unknown key id "${d}"`};a=u;}else {if(!t)return {ok:false,reason:"no verification key"};a=t;}let c;try{if(c=hu(a),c.length!==32)return {ok:!1,reason:"invalid public key"}}catch{
247
- return {ok:false,reason:"invalid public key"}}let l=false;try{l=As.verify(bo(i),gu.encode(`${r}.${o}`),c);}catch{return {ok:false,reason:"signature verification error"}}return l?{ok:true,header:s,payloadBytes:bo(o)}:
248
- {ok:false,reason:"bad signature"}}function yo(e,t){let n=on(e,t);if(!n.ok||!n.payloadBytes)return {signatureValid:false,...n.reason?{reason:n.reason}:{}};try{return {signatureValid:!0,payload:JSON.parse(Is.decode(
249
- n.payloadBytes))}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function er(e,t,n){if(n?.has(e.jti))return "revoked";let r=e.expires_at+e.grace_days*86400;return t<=e.expires_at?"\
250
- active":t<=r?"grace":"expired"}var Ds="BVSALA-REVOC",vu=300,yu=new TextDecoder;function Os(e,t,n={}){let r=l=>({ok:false,seq:-1,asOf:0,revoked:new Set,reason:l}),o=on(e,t);if(!o.ok||!o.payloadBytes)return r(o.reason??"bad signature");
251
- if(o.header?.typ!==Ds)return r(`unexpected token type "${String(o.header?.typ??"")}" (want ${Ds})`);let i;try{i=JSON.parse(yu.decode(o.payloadBytes));}catch{return r("payload is not valid JSON")}if(typeof i.
241
+ -----END PUBLIC KEY-----`;function $s(e){let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function xo(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.
242
+ length%4?"=".repeat(4-t.length%4):"";return $s(t+n)}function Tu(e){let t=e.replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=$s(t);return n.subarray(n.length-32)}var Cu=new TextEncoder,Ns=new TextDecoder;
243
+ function wo(e){return typeof e=="object"&&e!==null&&"keys"in e}function Dt(e){let t=e.trim(),n=/^(["'])([\s\S]*)\1$/.exec(t);return n&&(t=n[2].trim()),t=t.replace(/^bearer\s+/i,""),t.trim()}var Au=/^[A-Za-z0-9_-]+$/;
244
+ function js(e){let t=e.split(".");return t.length===3&&t.every(n=>Au.test(n))}function an(e){return e===""?"empty":js(e)?"token":"malformed"}function cn(e,t){if(!js(e))return {ok:false,reason:"malformed t\
245
+ oken"};let n=e.split("."),r=n[0],o=n[1],i=n[2],s;try{s=JSON.parse(Ns.decode(xo(r)));}catch{return {ok:false,reason:"header is not valid JSON"}}let a;if(wo(t)){let d=typeof s.kid=="string"?s.kid:t.defaultKid,
246
+ u=t.keys[d];if(!u)return {ok:false,reason:`unknown key id "${d}"`};a=u;}else {if(!t)return {ok:false,reason:"no verification key"};a=t;}let c;try{if(c=Tu(a),c.length!==32)return {ok:!1,reason:"invalid public key"}}catch{
247
+ return {ok:false,reason:"invalid public key"}}let l=false;try{l=Ms.verify(xo(i),Cu.encode(`${r}.${o}`),c);}catch{return {ok:false,reason:"signature verification error"}}return l?{ok:true,header:s,payloadBytes:xo(o)}:
248
+ {ok:false,reason:"bad signature"}}function So(e,t){let n=cn(e,t);if(!n.ok||!n.payloadBytes)return {signatureValid:false,...n.reason?{reason:n.reason}:{}};try{return {signatureValid:!0,payload:JSON.parse(Ns.decode(
249
+ n.payloadBytes))}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function or(e,t,n){if(n?.has(e.jti))return "revoked";let r=e.expires_at+e.grace_days*86400;return t<=e.expires_at?"\
250
+ active":t<=r?"grace":"expired"}var Bs="BVSALA-REVOC",Ru=300,Iu=new TextDecoder;function Us(e,t,n={}){let r=l=>({ok:false,seq:-1,asOf:0,revoked:new Set,reason:l}),o=cn(e,t);if(!o.ok||!o.payloadBytes)return r(o.reason??"bad signature");
251
+ if(o.header?.typ!==Bs)return r(`unexpected token type "${String(o.header?.typ??"")}" (want ${Bs})`);let i;try{i=JSON.parse(Iu.decode(o.payloadBytes));}catch{return r("payload is not valid JSON")}if(typeof i.
252
252
  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.
253
- nowSeconds??Math.floor(Date.now()/1e3),c=n.maxSkewSeconds??vu;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 It=class{_seq=-1;_asOf=0;_lastContactAt=0;set=new Set;get seq(){
253
+ nowSeconds??Math.floor(Date.now()/1e3),c=n.maxSkewSeconds??Ru;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 Ot=class{_seq=-1;_asOf=0;_lastContactAt=0;set=new Set;get seq(){
254
254
  return this._seq}get asOf(){return this._asOf}get lastContactAt(){return this._lastContactAt}markContact(t){t>this._lastContactAt&&(this._lastContactAt=t);}has(t){return this.set.has(t)}snapshot(){return this.
255
255
  set}apply(t){if(t.seq<this._seq)return false;let n=this.set.size;for(let i of t.revoked)this.set.add(i);let r=this.set.size>n,o=t.seq>this._seq;return t.seq>this._seq&&(this._seq=t.seq),t.asOf>this._asOf&&
256
- (this._asOf=t.asOf),r||o}};function tr(e,t,n){let r=()=>Math.floor((n.now?n.now():Date.now())/1e3),o=n.startedAt??r(),i=Rt(e),s=rn(i),a=s==="token"?yo(i,t):{signatureValid:false,reason:s},c=a.signatureValid?a.payload:void 0,l=new Set(
257
- c?.features??[]),d=()=>{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 f=c.expires_at+c.grace_days*
256
+ (this._asOf=t.asOf),r||o}};function ir(e,t,n){let r=()=>Math.floor((n.now?n.now():Date.now())/1e3),o=n.startedAt??r(),i=Dt(e),s=an(i),a=s==="token"?So(i,t):{signatureValid:false,reason:s},c=a.signatureValid?a.payload:void 0,l=new Set(
257
+ c?.features??[]),d=()=>{if(s==="empty")return "none";if(!c)return "invalid";let p=or(c,r(),n.revocation.snapshot());if(n.maxStalenessSeconds!=null&&(p==="active"||p==="grace")){let f=c.expires_at+c.grace_days*
258
258
  86400,g=Math.min(o,f),b=Math.max(n.revocation.lastContactAt,g);if(r()-b>n.maxStalenessSeconds)return "stale"}return p},u=()=>{let p=d();return p==="active"||p==="grace"};return {isEntitled:p=>u()&&l.has(
259
- p),isActive:()=>u(),status:d,reason:()=>c?void 0:a.reason,refreshAfter:()=>{if(c)return Math.min(c.expires_at,r()+86400)}}}var Pt={pollIntervalSeconds:900,floorSeconds:300,maxIntervalSeconds:3600,jitterRatio:.1,maxSkewSeconds:300,requestTimeoutMs:3e4},Ls=3,ku=12;function xu(e){let t=e.random??Math.random,n;if(e.consecutiveFailures>
259
+ p),isActive:()=>u(),status:d,reason:()=>c?void 0:a.reason,refreshAfter:()=>{if(c)return Math.min(c.expires_at,r()+86400)}}}var Lt={pollIntervalSeconds:900,floorSeconds:300,maxIntervalSeconds:3600,jitterRatio:.1,maxSkewSeconds:300,requestTimeoutMs:3e4},Vs=3,Pu=12;function Du(e){let t=e.random??Math.random,n;if(e.consecutiveFailures>
260
260
  0){let o=Math.pow(2,Math.min(e.consecutiveFailures,4));n=Math.min(e.maxIntervalSeconds,e.floorSeconds*o);}else {let o=e.refreshAfter!=null?e.refreshAfter-e.nowSeconds:e.pollIntervalSeconds,i=o<0?e.pollIntervalSeconds:
261
- o;n=Math.min(e.pollIntervalSeconds,Math.max(e.floorSeconds,i));}let r=1+(t()*2-1)*e.jitterRatio;return Math.max(e.floorSeconds,n*r)}var wu=10,sn=class{constructor(t){this.opts=t;}opts;timer=null;controller=null;consecutiveFailures=0;stopped=false;started=false;lastEtag=null;consecutive304=0;now(){
261
+ o;n=Math.min(e.pollIntervalSeconds,Math.max(e.floorSeconds,i));}let r=1+(t()*2-1)*e.jitterRatio;return Math.max(e.floorSeconds,n*r)}var Ou=10,ln=class{constructor(t){this.opts=t;}opts;timer=null;controller=null;consecutiveFailures=0;stopped=false;started=false;lastEtag=null;consecutive304=0;now(){
262
262
  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 t=this.resolveFetch();
263
263
  if(!t){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"});
264
- return}let n=new AbortController;this.controller=n;let r=this.opts.requestTimeoutMs??Pt.requestTimeoutMs,o=setTimeout(()=>n.abort(),r);o.unref?.();let i={accept:"application/json"};this.lastEtag&&(i["\
264
+ return}let n=new AbortController;this.controller=n;let r=this.opts.requestTimeoutMs??Lt.requestTimeoutMs,o=setTimeout(()=>n.abort(),r);o.unref?.();let i={accept:"application/json"};this.lastEtag&&(i["\
265
265
  if-none-match"]=this.lastEtag);try{let s=await t(this.opts.url,{signal:n.signal,headers:i});if(s.status===304){this.consecutiveFailures=0,this.opts.snapshot.markContact(this.now()),this.opts.onEvent?.(
266
- {type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=wu&&(this.consecutive304=0,this.lastEtag=null);return}if(this.consecutive304=0,!s.ok)throw new Error(`revocat\
267
- 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=Os(c.list,this.opts.publicKeyPem,{minSeq:this.
268
- opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??Pt.maxSkewSeconds});if(!l.ok){let u=l.reason??"rejected";this.opts.onEvent?.({type:"rejected",reason:u}),this.avisar(`r\
266
+ {type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=Ou&&(this.consecutive304=0,this.lastEtag=null);return}if(this.consecutive304=0,!s.ok)throw new Error(`revocat\
267
+ 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=Us(c.list,this.opts.publicKeyPem,{minSeq:this.
268
+ opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??Lt.maxSkewSeconds});if(!l.ok){let u=l.reason??"rejected";this.opts.onEvent?.({type:"rejected",reason:u}),this.avisar(`r\
269
269
  echazada:${u}`,`[bv-sala] the revocation list does NOT verify (${u}). The last known-good list is kept, so revocations ALREADY known still apply, but new ones are not arriving. Check ${this.opts.url}.`);
270
270
  return}a&&(this.lastEtag=a),this.opts.snapshot.markContact(this.now());let d=this.opts.snapshot.apply(l);this.opts.onEvent?.(d?{type:"applied",seq:l.seq,size:this.opts.snapshot.snapshot().size}:{type:"\
271
271
  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.
272
- silenceWarnings??this.opts.silenciarAvisos)}avisar(t,n){this.callado()||G(`poller:${this.opts.url}:${t}`,n);}avisarFalloDeRed(t){if(this.callado())return;let n=this.consecutiveFailures;if(n<Ls||(n-Ls)%
273
- ku!==0)return;let r=t instanceof Error?t.message:String(t);console.warn(`[bv-sala] could not reach the revocation server ${n} times in a row (${r}). The license KEEPS working and known revocations sti\
272
+ silenceWarnings??this.opts.silenciarAvisos)}avisar(t,n){this.callado()||Y(`poller:${this.opts.url}:${t}`,n);}avisarFalloDeRed(t){if(this.callado())return;let n=this.consecutiveFailures;if(n<Vs||(n-Vs)%
273
+ Pu!==0)return;let r=t instanceof Error?t.message:String(t);console.warn(`[bv-sala] could not reach the revocation server ${n} times in a row (${r}). The license KEEPS working and known revocations sti\
274
274
  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)
275
- return;let t=xu({refreshAfter:this.opts.getRefreshAfter?.(),nowSeconds:this.now(),consecutiveFailures:this.consecutiveFailures,floorSeconds:this.opts.floorSeconds??Pt.floorSeconds,pollIntervalSeconds:this.
276
- opts.pollIntervalSeconds??Pt.pollIntervalSeconds,maxIntervalSeconds:this.opts.maxIntervalSeconds??Pt.maxIntervalSeconds,jitterRatio:this.opts.jitterRatio??Pt.jitterRatio,...this.opts.random?{random:this.
275
+ return;let t=Du({refreshAfter:this.opts.getRefreshAfter?.(),nowSeconds:this.now(),consecutiveFailures:this.consecutiveFailures,floorSeconds:this.opts.floorSeconds??Lt.floorSeconds,pollIntervalSeconds:this.
276
+ opts.pollIntervalSeconds??Lt.pollIntervalSeconds,maxIntervalSeconds:this.opts.maxIntervalSeconds??Lt.maxIntervalSeconds,jitterRatio:this.opts.jitterRatio??Lt.jitterRatio,...this.opts.random?{random:this.
277
277
  opts.random}:{}});this.timer=setTimeout(()=>{this.pollOnce().finally(()=>this.schedule());},t*1e3),this.timer.unref?.();}stop(){this.stopped=true,this.timer&&(clearTimeout(this.timer),this.timer=null),this.
278
- controller?.abort();}};var Su="https://developers.openai.com/api/docs/pricing",Eu="https://ai.google.dev/gemini-api/docs/pricing",ko="2026-09-27",P=e=>({...e,fuente:Su,consultado:ko}),Oe=e=>({...e,fuente:Eu,consultado:ko}),
279
- _u="https://platform.claude.com/docs/en/about-claude/pricing",ce=e=>({...e,fuente:_u,consultado:ko});({openai:{flex:{"gpt-5":P({inputPer1k:625e-6,cachedInputPer1k:625e-7,outputPer1k:.005}),"gpt-5-mi\
280
- ni":P({inputPer1k:125e-6,cachedInputPer1k:125e-7,outputPer1k:.001}),"gpt-5-nano":P({inputPer1k:25e-6,cachedInputPer1k:25e-7,outputPer1k:2e-4}),"gpt-5.2":P({inputPer1k:875e-6,cachedInputPer1k:875e-7,outputPer1k:.007}),
281
- "gpt-5.4":P({inputPer1k:.00125,cachedInputPer1k:13e-5,outputPer1k:.0075,largo:{estandar:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225},tier:{inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.01125}}}),
282
- "gpt-5.4-mini":P({inputPer1k:375e-6,cachedInputPer1k:375e-7,outputPer1k:.00225}),"gpt-5.4-nano":P({inputPer1k:1e-4,cachedInputPer1k:1e-5,outputPer1k:625e-6}),"gpt-5.5":P({inputPer1k:.0025,cachedInputPer1k:25e-5,
283
- outputPer1k:.015,largo:{estandar:{inputPer1k:.01,cachedInputPer1k:.001,outputPer1k:.045},tier:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225}}}),"gpt-5.6-luna":P({inputPer1k:1e-4,cachedInputPer1k:1e-5,
278
+ controller?.abort();}};var Lu="https://developers.openai.com/api/docs/pricing",Mu="https://ai.google.dev/gemini-api/docs/pricing",Eo="2026-09-27",O=e=>({...e,fuente:Lu,consultado:Eo}),Me=e=>({...e,fuente:Mu,consultado:Eo}),
279
+ $u="https://platform.claude.com/docs/en/about-claude/pricing",ue=e=>({...e,fuente:$u,consultado:Eo});({openai:{flex:{"gpt-5":O({inputPer1k:625e-6,cachedInputPer1k:625e-7,outputPer1k:.005}),"gpt-5-mi\
280
+ ni":O({inputPer1k:125e-6,cachedInputPer1k:125e-7,outputPer1k:.001}),"gpt-5-nano":O({inputPer1k:25e-6,cachedInputPer1k:25e-7,outputPer1k:2e-4}),"gpt-5.2":O({inputPer1k:875e-6,cachedInputPer1k:875e-7,outputPer1k:.007}),
281
+ "gpt-5.4":O({inputPer1k:.00125,cachedInputPer1k:13e-5,outputPer1k:.0075,largo:{estandar:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225},tier:{inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.01125}}}),
282
+ "gpt-5.4-mini":O({inputPer1k:375e-6,cachedInputPer1k:375e-7,outputPer1k:.00225}),"gpt-5.4-nano":O({inputPer1k:1e-4,cachedInputPer1k:1e-5,outputPer1k:625e-6}),"gpt-5.5":O({inputPer1k:.0025,cachedInputPer1k:25e-5,
283
+ outputPer1k:.015,largo:{estandar:{inputPer1k:.01,cachedInputPer1k:.001,outputPer1k:.045},tier:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225}}}),"gpt-5.6-luna":O({inputPer1k:1e-4,cachedInputPer1k:1e-5,
284
284
  cacheWritePer1k:125e-6,outputPer1k:6e-4,largo:{estandar:{inputPer1k:4e-4,cachedInputPer1k:4e-5,cacheWritePer1k:5e-4,outputPer1k:.0018},tier:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,
285
- outputPer1k:9e-4}}}),"gpt-5.6-sol":P({inputPer1k:.002,cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.01,largo:{estandar:{inputPer1k:.008,cachedInputPer1k:8e-4,cacheWritePer1k:.01,outputPer1k:.03},
286
- tier:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.015}},vigenteHasta:"2026-11-21"}),"gpt-5.6-terra":P({inputPer1k:.001,cachedInputPer1k:1e-4,cacheWritePer1k:.00125,outputPer1k:.006,
287
- largo:{estandar:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.018},tier:{inputPer1k:.002,cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.009}}}),o3:P({inputPer1k:.001,
288
- cachedInputPer1k:25e-5,outputPer1k:.004}),"o4-mini":P({inputPer1k:55e-5,cachedInputPer1k:138e-6,outputPer1k:.0022}),"gpt-6-astra":P({inputPer1k:.005,cachedInputPer1k:5e-4,cacheWritePer1k:.00625,outputPer1k:.025,
289
- largo:{estandar:{inputPer1k:.02,cachedInputPer1k:.002,cacheWritePer1k:.025,outputPer1k:.075},tier:{inputPer1k:.01,cachedInputPer1k:.001,cacheWritePer1k:.0125,outputPer1k:.0375}}}),"gpt-6-sol":P({inputPer1k:.001,
285
+ outputPer1k:9e-4}}}),"gpt-5.6-sol":O({inputPer1k:.002,cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.01,largo:{estandar:{inputPer1k:.008,cachedInputPer1k:8e-4,cacheWritePer1k:.01,outputPer1k:.03},
286
+ tier:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.015}},vigenteHasta:"2026-11-21"}),"gpt-5.6-terra":O({inputPer1k:.001,cachedInputPer1k:1e-4,cacheWritePer1k:.00125,outputPer1k:.006,
287
+ largo:{estandar:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.018},tier:{inputPer1k:.002,cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.009}}}),o3:O({inputPer1k:.001,
288
+ cachedInputPer1k:25e-5,outputPer1k:.004}),"o4-mini":O({inputPer1k:55e-5,cachedInputPer1k:138e-6,outputPer1k:.0022}),"gpt-6-astra":O({inputPer1k:.005,cachedInputPer1k:5e-4,cacheWritePer1k:.00625,outputPer1k:.025,
289
+ largo:{estandar:{inputPer1k:.02,cachedInputPer1k:.002,cacheWritePer1k:.025,outputPer1k:.075},tier:{inputPer1k:.01,cachedInputPer1k:.001,cacheWritePer1k:.0125,outputPer1k:.0375}}}),"gpt-6-sol":O({inputPer1k:.001,
290
290
  cachedInputPer1k:1e-4,cacheWritePer1k:.00125,outputPer1k:.005,largo:{estandar:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.015},tier:{inputPer1k:.002,cachedInputPer1k:2e-4,
291
- cacheWritePer1k:.0025,outputPer1k:.0075}}}),"gpt-6-luna":P({inputPer1k:5e-5,cachedInputPer1k:5e-6,cacheWritePer1k:625e-7,outputPer1k:25e-5,largo:{estandar:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,
292
- outputPer1k:75e-5},tier:{inputPer1k:1e-4,cachedInputPer1k:1e-5,cacheWritePer1k:125e-6,outputPer1k:375e-6}}})},batch:{"gpt-6-astra":P({inputPer1k:.005,cachedInputPer1k:5e-4,cacheWritePer1k:.00625,outputPer1k:.025,
293
- largo:{estandar:{inputPer1k:.02,cachedInputPer1k:.002,cacheWritePer1k:.025,outputPer1k:.075},tier:{inputPer1k:.01,cachedInputPer1k:.001,cacheWritePer1k:.0125,outputPer1k:.0375}}}),"gpt-6-sol":P({inputPer1k:.001,
291
+ cacheWritePer1k:.0025,outputPer1k:.0075}}}),"gpt-6-luna":O({inputPer1k:5e-5,cachedInputPer1k:5e-6,cacheWritePer1k:625e-7,outputPer1k:25e-5,largo:{estandar:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,
292
+ outputPer1k:75e-5},tier:{inputPer1k:1e-4,cachedInputPer1k:1e-5,cacheWritePer1k:125e-6,outputPer1k:375e-6}}})},batch:{"gpt-6-astra":O({inputPer1k:.005,cachedInputPer1k:5e-4,cacheWritePer1k:.00625,outputPer1k:.025,
293
+ largo:{estandar:{inputPer1k:.02,cachedInputPer1k:.002,cacheWritePer1k:.025,outputPer1k:.075},tier:{inputPer1k:.01,cachedInputPer1k:.001,cacheWritePer1k:.0125,outputPer1k:.0375}}}),"gpt-6-sol":O({inputPer1k:.001,
294
294
  cachedInputPer1k:1e-4,cacheWritePer1k:.00125,outputPer1k:.005,largo:{estandar:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.015},tier:{inputPer1k:.002,cachedInputPer1k:2e-4,
295
- cacheWritePer1k:.0025,outputPer1k:.0075}}}),"gpt-6-luna":P({inputPer1k:5e-5,cachedInputPer1k:5e-6,cacheWritePer1k:625e-7,outputPer1k:25e-5,largo:{estandar:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,
296
- outputPer1k:75e-5},tier:{inputPer1k:1e-4,cachedInputPer1k:1e-5,cacheWritePer1k:125e-6,outputPer1k:375e-6}}}),"gpt-5.6-sol":P({inputPer1k:.002,cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.01,
295
+ cacheWritePer1k:.0025,outputPer1k:.0075}}}),"gpt-6-luna":O({inputPer1k:5e-5,cachedInputPer1k:5e-6,cacheWritePer1k:625e-7,outputPer1k:25e-5,largo:{estandar:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,
296
+ outputPer1k:75e-5},tier:{inputPer1k:1e-4,cachedInputPer1k:1e-5,cacheWritePer1k:125e-6,outputPer1k:375e-6}}}),"gpt-5.6-sol":O({inputPer1k:.002,cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.01,
297
297
  largo:{estandar:{inputPer1k:.008,cachedInputPer1k:8e-4,cacheWritePer1k:.01,outputPer1k:.03},tier:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.015}},vigenteHasta:"2026-11-21"}),
298
- "gpt-5.6-terra":P({inputPer1k:.001,cachedInputPer1k:1e-4,cacheWritePer1k:.00125,outputPer1k:.006,largo:{estandar:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.018},tier:{inputPer1k:.002,
299
- cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.009}}}),"gpt-5.6-luna":P({inputPer1k:1e-4,cachedInputPer1k:1e-5,cacheWritePer1k:125e-6,outputPer1k:6e-4,largo:{estandar:{inputPer1k:4e-4,cachedInputPer1k:4e-5,
300
- cacheWritePer1k:5e-4,outputPer1k:.0018},tier:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,outputPer1k:9e-4}}}),"gpt-5.5":P({inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.015,largo:{
301
- estandar:{inputPer1k:.01,cachedInputPer1k:.001,outputPer1k:.045},tier:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225}}}),"gpt-5.4":P({inputPer1k:.00125,cachedInputPer1k:13e-5,outputPer1k:.0075,
302
- largo:{estandar:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225},tier:{inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.01125}}}),"gpt-5.4-mini":P({inputPer1k:375e-6,cachedInputPer1k:375e-7,
303
- outputPer1k:.00225}),"gpt-5.4-nano":P({inputPer1k:1e-4,cachedInputPer1k:1e-5,outputPer1k:625e-6}),"gpt-5.2":P({inputPer1k:875e-6,cachedInputPer1k:875e-7,outputPer1k:.007}),"gpt-5":P({inputPer1k:625e-6,
304
- cachedInputPer1k:625e-7,outputPer1k:.005}),"gpt-5-mini":P({inputPer1k:125e-6,cachedInputPer1k:125e-7,outputPer1k:.001}),"gpt-5-nano":P({inputPer1k:25e-6,cachedInputPer1k:25e-7,outputPer1k:2e-4}),"gpt-\
305
- 4.1":P({inputPer1k:.001,outputPer1k:.004}),"gpt-4.1-mini":P({inputPer1k:2e-4,outputPer1k:8e-4}),"gpt-4.1-nano":P({inputPer1k:5e-5,outputPer1k:2e-4}),"gpt-4o":P({inputPer1k:.00125,outputPer1k:.005}),"g\
306
- pt-4o-mini":P({inputPer1k:75e-6,outputPer1k:3e-4}),o3:P({inputPer1k:.001,outputPer1k:.004}),"o4-mini":P({inputPer1k:55e-5,outputPer1k:.0022}),"o3-mini":P({inputPer1k:55e-5,outputPer1k:.0022}),"o3-pro":P(
307
- {inputPer1k:.01,outputPer1k:.04})}},anthropic:{batch:{"claude-fable-5-1":ce({inputPer1k:.005,cachedInputPer1k:125e-6,cacheWritePer1k:.00625,outputPer1k:.025}),"claude-mythos-5-1":ce({inputPer1k:.005,cachedInputPer1k:125e-6,
308
- cacheWritePer1k:.00625,outputPer1k:.025}),"claude-fable-5":ce({inputPer1k:.005,cachedInputPer1k:5e-4,cacheWritePer1k:.00625,outputPer1k:.025}),"claude-mythos-5":ce({inputPer1k:.005,cachedInputPer1k:5e-4,
309
- cacheWritePer1k:.00625,outputPer1k:.025}),"claude-opus-5-5":ce({inputPer1k:.002,cachedInputPer1k:1e-4,cacheWritePer1k:.0025,outputPer1k:.01}),"claude-opus-5":ce({inputPer1k:.0025,cachedInputPer1k:25e-5,
310
- cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-8":ce({inputPer1k:.0025,cachedInputPer1k:25e-5,cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-7":ce({inputPer1k:.0025,cachedInputPer1k:25e-5,
311
- cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-6":ce({inputPer1k:.0025,cachedInputPer1k:25e-5,cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-5":ce({inputPer1k:.0025,cachedInputPer1k:25e-5,
312
- cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4":ce({inputPer1k:.0075,cachedInputPer1k:75e-5,cacheWritePer1k:.009375,outputPer1k:.0375}),"claude-sonnet-5":ce({inputPer1k:.001,cachedInputPer1k:1e-4,
313
- cacheWritePer1k:.00125,outputPer1k:.005}),"claude-sonnet-4-6":ce({inputPer1k:.0015,cachedInputPer1k:15e-5,cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-sonnet-4-5":ce({inputPer1k:.0015,cachedInputPer1k:15e-5,
314
- cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-sonnet-4":ce({inputPer1k:.0015,cachedInputPer1k:15e-5,cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-haiku-4-5":ce({inputPer1k:5e-4,cachedInputPer1k:5e-5,
315
- cacheWritePer1k:625e-6,outputPer1k:.0025}),"claude-3-5-haiku":ce({inputPer1k:4e-4,cachedInputPer1k:4e-5,cacheWritePer1k:5e-4,outputPer1k:.002})}},google:{flex:{"gemini-3.7-flash":Oe({inputPer1k:375e-6,
316
- outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.5-flash":Oe({inputPer1k:75e-5,outputPer1k:.0045,cachedInputPer1k:8e-5}),"gemini-3.5-flash-lite":Oe({inputPer1k:15e-5,outputPer1k:.00125,
317
- cachedInputPer1k:2e-5}),"gemini-3.1-pro-preview":Oe({inputPer1k:.001,outputPer1k:.006,cachedInputPer1k:2e-4,largo:{estandar:{inputPer1k:.004,outputPer1k:.018,cachedInputPer1k:4e-4},tier:{inputPer1k:.002,
318
- outputPer1k:.009,cachedInputPer1k:4e-4}}}),"gemini-2.5-pro":Oe({inputPer1k:625e-6,outputPer1k:.005,cachedInputPer1k:125e-6,largo:{estandar:{inputPer1k:.0025,outputPer1k:.015,cachedInputPer1k:25e-5},tier:{
319
- inputPer1k:.00125,outputPer1k:.0075,cachedInputPer1k:25e-5}}}),"gemini-2.5-flash":Oe({inputPer1k:15e-5,outputPer1k:.00125,cachedInputPer1k:3e-5}),"gemini-3.8-flash":Oe({inputPer1k:375e-6,outputPer1k:.001875,
320
- cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.6-flash":Oe({inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.1-flash-lite":Oe({inputPer1k:125e-6,
321
- outputPer1k:75e-5,cachedInputPer1k:125e-7}),"gemini-3-flash-preview":Oe({inputPer1k:25e-5,outputPer1k:.0015,cachedInputPer1k:5e-5})}}});var Ms={flex:.5,default:1,auto:1,priority:1,fast:1,scale:1,standard:1,batch:.5};Math.min(...Object.values(Ms).filter(e=>e<1));function nr(e){if(e==null||e==="")return null;let t=Ms[e];return t==null?{servido:e,factor:null,conDescuento:false}:{servido:e,factor:t,conDescuento:t<1}}var Pu={"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.\
298
+ "gpt-5.6-terra":O({inputPer1k:.001,cachedInputPer1k:1e-4,cacheWritePer1k:.00125,outputPer1k:.006,largo:{estandar:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.018},tier:{inputPer1k:.002,
299
+ cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.009}}}),"gpt-5.6-luna":O({inputPer1k:1e-4,cachedInputPer1k:1e-5,cacheWritePer1k:125e-6,outputPer1k:6e-4,largo:{estandar:{inputPer1k:4e-4,cachedInputPer1k:4e-5,
300
+ cacheWritePer1k:5e-4,outputPer1k:.0018},tier:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,outputPer1k:9e-4}}}),"gpt-5.5":O({inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.015,largo:{
301
+ estandar:{inputPer1k:.01,cachedInputPer1k:.001,outputPer1k:.045},tier:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225}}}),"gpt-5.4":O({inputPer1k:.00125,cachedInputPer1k:13e-5,outputPer1k:.0075,
302
+ largo:{estandar:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225},tier:{inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.01125}}}),"gpt-5.4-mini":O({inputPer1k:375e-6,cachedInputPer1k:375e-7,
303
+ outputPer1k:.00225}),"gpt-5.4-nano":O({inputPer1k:1e-4,cachedInputPer1k:1e-5,outputPer1k:625e-6}),"gpt-5.2":O({inputPer1k:875e-6,cachedInputPer1k:875e-7,outputPer1k:.007}),"gpt-5":O({inputPer1k:625e-6,
304
+ cachedInputPer1k:625e-7,outputPer1k:.005}),"gpt-5-mini":O({inputPer1k:125e-6,cachedInputPer1k:125e-7,outputPer1k:.001}),"gpt-5-nano":O({inputPer1k:25e-6,cachedInputPer1k:25e-7,outputPer1k:2e-4}),"gpt-\
305
+ 4.1":O({inputPer1k:.001,outputPer1k:.004}),"gpt-4.1-mini":O({inputPer1k:2e-4,outputPer1k:8e-4}),"gpt-4.1-nano":O({inputPer1k:5e-5,outputPer1k:2e-4}),"gpt-4o":O({inputPer1k:.00125,outputPer1k:.005}),"g\
306
+ pt-4o-mini":O({inputPer1k:75e-6,outputPer1k:3e-4}),o3:O({inputPer1k:.001,outputPer1k:.004}),"o4-mini":O({inputPer1k:55e-5,outputPer1k:.0022}),"o3-mini":O({inputPer1k:55e-5,outputPer1k:.0022}),"o3-pro":O(
307
+ {inputPer1k:.01,outputPer1k:.04})}},anthropic:{batch:{"claude-fable-5-1":ue({inputPer1k:.005,cachedInputPer1k:125e-6,cacheWritePer1k:.00625,outputPer1k:.025}),"claude-mythos-5-1":ue({inputPer1k:.005,cachedInputPer1k:125e-6,
308
+ cacheWritePer1k:.00625,outputPer1k:.025}),"claude-fable-5":ue({inputPer1k:.005,cachedInputPer1k:5e-4,cacheWritePer1k:.00625,outputPer1k:.025}),"claude-mythos-5":ue({inputPer1k:.005,cachedInputPer1k:5e-4,
309
+ cacheWritePer1k:.00625,outputPer1k:.025}),"claude-opus-5-5":ue({inputPer1k:.002,cachedInputPer1k:1e-4,cacheWritePer1k:.0025,outputPer1k:.01}),"claude-opus-5":ue({inputPer1k:.0025,cachedInputPer1k:25e-5,
310
+ cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-8":ue({inputPer1k:.0025,cachedInputPer1k:25e-5,cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-7":ue({inputPer1k:.0025,cachedInputPer1k:25e-5,
311
+ cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-6":ue({inputPer1k:.0025,cachedInputPer1k:25e-5,cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-5":ue({inputPer1k:.0025,cachedInputPer1k:25e-5,
312
+ cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4":ue({inputPer1k:.0075,cachedInputPer1k:75e-5,cacheWritePer1k:.009375,outputPer1k:.0375}),"claude-sonnet-5":ue({inputPer1k:.001,cachedInputPer1k:1e-4,
313
+ cacheWritePer1k:.00125,outputPer1k:.005}),"claude-sonnet-4-6":ue({inputPer1k:.0015,cachedInputPer1k:15e-5,cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-sonnet-4-5":ue({inputPer1k:.0015,cachedInputPer1k:15e-5,
314
+ cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-sonnet-4":ue({inputPer1k:.0015,cachedInputPer1k:15e-5,cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-haiku-4-5":ue({inputPer1k:5e-4,cachedInputPer1k:5e-5,
315
+ cacheWritePer1k:625e-6,outputPer1k:.0025}),"claude-3-5-haiku":ue({inputPer1k:4e-4,cachedInputPer1k:4e-5,cacheWritePer1k:5e-4,outputPer1k:.002})}},google:{flex:{"gemini-3.7-flash":Me({inputPer1k:375e-6,
316
+ outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.5-flash":Me({inputPer1k:75e-5,outputPer1k:.0045,cachedInputPer1k:8e-5}),"gemini-3.5-flash-lite":Me({inputPer1k:15e-5,outputPer1k:.00125,
317
+ cachedInputPer1k:2e-5}),"gemini-3.1-pro-preview":Me({inputPer1k:.001,outputPer1k:.006,cachedInputPer1k:2e-4,largo:{estandar:{inputPer1k:.004,outputPer1k:.018,cachedInputPer1k:4e-4},tier:{inputPer1k:.002,
318
+ outputPer1k:.009,cachedInputPer1k:4e-4}}}),"gemini-2.5-pro":Me({inputPer1k:625e-6,outputPer1k:.005,cachedInputPer1k:125e-6,largo:{estandar:{inputPer1k:.0025,outputPer1k:.015,cachedInputPer1k:25e-5},tier:{
319
+ inputPer1k:.00125,outputPer1k:.0075,cachedInputPer1k:25e-5}}}),"gemini-2.5-flash":Me({inputPer1k:15e-5,outputPer1k:.00125,cachedInputPer1k:3e-5}),"gemini-3.8-flash":Me({inputPer1k:375e-6,outputPer1k:.001875,
320
+ cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.6-flash":Me({inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.1-flash-lite":Me({inputPer1k:125e-6,
321
+ outputPer1k:75e-5,cachedInputPer1k:125e-7}),"gemini-3-flash-preview":Me({inputPer1k:25e-5,outputPer1k:.0015,cachedInputPer1k:5e-5})}}});var Fs={flex:.5,default:1,auto:1,priority:1,fast:1,scale:1,standard:1,batch:.5};Math.min(...Object.values(Fs).filter(e=>e<1));function sr(e){if(e==null||e==="")return null;let t=Fs[e];return t==null?{servido:e,factor:null,conDescuento:false}:{servido:e,factor:t,conDescuento:t<1}}var Fu={"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.\
322
322
  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\
323
323
  .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,
324
324
  "claude-opus-4-8":false,"claude-opus-5":true,"claude-opus-5-5":true,"claude-opus-4":false,"claude-sonnet-4-5":false,"claude-sonnet-4-6":false,"claude-sonnet-5":true,"claude-fable-5":true,"claude-fable-5-1":true,"claude-myt\
325
325
  hos-5-1":true,"claude-mythos-5":true,"claude-sonnet-4":false,"claude-haiku-4-5":false,"claude-3-5-sonnet":false,"claude-3-5-haiku":false,"claude-3-opus":false,"gemini-3.8-flash":true,"gemini-3.7-flash":true,"gemini-3.6-flas\
326
- h":true,"gemini-3.1-flash-lite":true,"gemini-3-flash-preview":true,"gemini-3.5-flash":true,"gemini-3.5-flash-lite":true,"gemini-3.1-pro-preview":true,"gemini-2.5-pro":true,"gemini-2.5-flash":true},Du=new Set(["claude\
327
- -opus-4-7","claude-opus-4-8"]),Ou=[/^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($|[-_.])/,
328
- /^qwq/,/^qwen3/,/^glm-(4\.[5-9]|[5-9])/,/magistral/];function xo(e){let t=e.lastIndexOf("/"),n=(t>=0?e.slice(t+1):e).toLowerCase();if(Ou.some(i=>i.test(n)))return "reasoning-model";let r=lt(e);if(r===void 0)
329
- return "unclassified-model";let o=Pu[r];if(o===true)return "reasoning-model";if(o!==false)return "unclassified-model";if(Du.has(r))return "temperature-ignored"}var Dt=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0;function wo(e){if(!Array.isArray(e))return null;let t={input:0,output:0,cacheRead:0,cacheWrite:0,cacheWrite1h:0,iteraciones:0};for(let n of e){
330
- if(n===null||typeof n!="object")continue;let r=n;if(r.type!=="compaction")continue;t.iteraciones++,t.input+=Dt(r.input_tokens),t.output+=Dt(r.output_tokens),t.cacheRead+=Dt(r.cache_read_input_tokens);
331
- let o=r.cache_creation,i=Dt(o?.ephemeral_5m_input_tokens),s=Dt(o?.ephemeral_1h_input_tokens),a=typeof r.cache_creation_input_tokens=="number"?Dt(r.cache_creation_input_tokens):i+s;t.cacheWrite+=a,t.cacheWrite1h+=
332
- Math.min(s,a);}return t.iteraciones>0?t:null}var Lu=new Set([null,"cyber","general_harms"]);function rr(e){if(e.stopReason!=="refusal")return false;let t=e.stopDetails;if(t===null||typeof t!="object"||Array.isArray(t))return false;let n=t;if(n.type!=="r\
333
- efusal"||!("category"in n))return false;let r=n.category;return !(r!==null&&typeof r!="string"||!Lu.has(r)||e.bloques!==0||e.outputTokens!==0||Array.isArray(e.iterations)&&e.iterations.length>1)}var or=class{decoder;resto="";crPendiente=false;alPrincipio=true;datos="";evento="";ultimoId;push(t){let n=typeof t=="string"?t:(this.decoder??=new TextDecoder("utf-8")).decode(t,{stream:true});return this.procesar(
326
+ h":true,"gemini-3.1-flash-lite":true,"gemini-3-flash-preview":true,"gemini-3.5-flash":true,"gemini-3.5-flash-lite":true,"gemini-3.1-pro-preview":true,"gemini-2.5-pro":true,"gemini-2.5-flash":true},qu=new Set(["claude\
327
+ -opus-4-7","claude-opus-4-8"]),zu=[/^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($|[-_.])/,
328
+ /^qwq/,/^qwen3/,/^glm-(4\.[5-9]|[5-9])/,/magistral/];function _o(e){let t=e.lastIndexOf("/"),n=(t>=0?e.slice(t+1):e).toLowerCase();if(zu.some(i=>i.test(n)))return "reasoning-model";let r=pt(e);if(r===void 0)
329
+ return "unclassified-model";let o=Fu[r];if(o===true)return "reasoning-model";if(o!==false)return "unclassified-model";if(qu.has(r))return "temperature-ignored"}var Mt=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0;function To(e){if(!Array.isArray(e))return null;let t={input:0,output:0,cacheRead:0,cacheWrite:0,cacheWrite1h:0,iteraciones:0};for(let n of e){
330
+ if(n===null||typeof n!="object")continue;let r=n;if(r.type!=="compaction")continue;t.iteraciones++,t.input+=Mt(r.input_tokens),t.output+=Mt(r.output_tokens),t.cacheRead+=Mt(r.cache_read_input_tokens);
331
+ let o=r.cache_creation,i=Mt(o?.ephemeral_5m_input_tokens),s=Mt(o?.ephemeral_1h_input_tokens),a=typeof r.cache_creation_input_tokens=="number"?Mt(r.cache_creation_input_tokens):i+s;t.cacheWrite+=a,t.cacheWrite1h+=
332
+ Math.min(s,a);}return t.iteraciones>0?t:null}var Hu=new Set([null,"cyber","general_harms"]);function ar(e){if(e.stopReason!=="refusal")return false;let t=e.stopDetails;if(t===null||typeof t!="object"||Array.isArray(t))return false;let n=t;if(n.type!=="r\
333
+ efusal"||!("category"in n))return false;let r=n.category;return !(r!==null&&typeof r!="string"||!Hu.has(r)||e.bloques!==0||e.outputTokens!==0||Array.isArray(e.iterations)&&e.iterations.length>1)}var Wu="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\
334
+ able","do not feel comfortable","'d rather not","would rather not","don't think i can","do not think i can"].join("|")+")",Ku="(?:help(?! but)|assist|provide|comply|fulfil|fulfill|create|write|generat\
335
+ e|produce|give|share|support|engage|participate|answer|respond|discuss|offer|continue|draft|facilitate|contribute|go along|go into|walk you through|explain how|describe how|tell you how|teach|instruct\
336
+ |encourage|condone|endorse|promote|role-?play|pretend|do that|do this|do so|with that|with this|with your request|with this request|that request|this request)",Gu="i(?:'ll| will| must| need to|'d| wou\
337
+ ld)?(?: have to)? ?(?:respectfully |politely )?decline",Ju="(?:(?:that|this|it)(?:'s| is) not something i(?:'m| am)? ?(?:can|will|able to|comfortable)|(?:it|that|this)(?:'s| is| would be| would not be\
338
+ | wouldn't be) (?:not )?(?:appropriate|ethical|responsible) for me to|i(?:'m| am) not sure (?:that )?it(?:'s| is| would be) appropriate)",Yu="(?:(?:i'm |i am |i'm really |i am really |i'm so |really |\
339
+ so )?sorry|i apologi[sz]e|my apologies|apologies|unfortunately|regrettably|i'm afraid|i am afraid|as an ai|as a language model|as an assistant|i understand|i appreciate|thank you for|thanks for|while \
340
+ i understand|while i appreciate)",I="\\p{L}*",Zu="no (?:puedo|voy a|me es posible|estoy en condiciones de|me siento c\xF3mod[oa])",Xu=`(?:ayudar${I}|asistir${I}|proporcionar${I}|facilitar${I}|dar${I}|\
341
+ ofrecer${I}|crear${I}|escribir${I}|generar${I}|compartir${I}|cumplir|responder${I}|colaborar|participar|atender${I}|hacer eso|hacerlo|con eso|con esto|con esa|con esta|con tu)`,Qu="(?:lo siento|lo lam\
342
+ ento|siento|lamento|disculpa|disculpe|perd\xF3n|perdona|lamentablemente|desafortunadamente|me temo que|como (?:una )?(?:ia|inteligencia artificial|modelo de lenguaje|asistente)|entiendo)",ed="no (?:pu\
343
+ c|et puc|us puc|em sento c\xF2mod[ea]|estic en condicions de)",td=`(?:ajudar${I}|assistir${I}|proporcionar${I}|facilitar${I}|donar${I}|oferir${I}|crear${I}|escriure${I}|generar${I}|compartir${I}|compl\
344
+ ir|respondre${I}|col\xB7laborar|participar|fer aix\xF2|fer-ho|amb aix\xF2|amb aquesta|amb la teva)`,nd="(?:ho sento|ho lamento|em sap greu|disculpa|disculpeu|perdona|malauradament|lamentablement|disso\
345
+ rtadament|com a (?:ia|intel\xB7lig\xE8ncia artificial|model de llenguatge|assistent)|entenc)",rd="(?:je ne (?:peux|pourrai|pourrais|vais|souhaite)(?: malheureusement)? pas|je ne suis pas en mesure d[e\
346
+ ']|je refuse d[e'])",od="(?: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)",
347
+ id="(?:d\xE9sol\xE9e?|je suis d\xE9sol\xE9e?|je regrette|malheureusement|h\xE9las|je comprends|en tant qu'(?:ia|intelligence artificielle|mod\xE8le de langage|assistant))",sd="(?:ich (?:kann|werde|dar\
348
+ f|m\xF6chte)|(?:kann|werde|darf|m\xF6chte) ich)(?: \\p{L}+){0,4}? (?:nicht|keine\\p{L}*)(?: \\p{L}+){0,3}?",ad="(?:helfen|unterst\xFCtzen|bereitstellen|geben|erstellen|schreiben|generieren|beantworten|li\
349
+ efern|nachkommen|teilen|anbieten|erkl\xE4ren|behilflich sein)",cd="(?:es tut mir leid|tut mir leid|entschuldigung|entschuldige|leider|bedauerlicherweise|ich verstehe|als (?:eine )?(?:ki|k\xFCnstliche int\
350
+ elligenz|sprachmodell|assistent))",ld="non (?:posso|sono in grado di|riesco a|mi sento a mio agio (?:a|nel))",ud=`(?:aiutar${I}|assister${I}|fornir${I}|crear${I}|scriver${I}|generar${I}|condivider${I}\
351
+ |risponder${I}|dar${I}|offrir${I}|soddisfare|partecipare|farlo|fare questo|con questo|con questa)`,dd="(?:mi dispiace|spiacente|purtroppo|sfortunatamente|capisco|come (?:un'?\\s?)?(?:ia|intelligenza ar\
352
+ tificiale|modello linguistico|assistente))",pd="n\xE3o (?:posso|consigo|vou|sou capaz de|estou em condi\xE7\xF5es de|me sinto confort\xE1vel (?:em|a))",fd=`(?:ajudar${I}|auxiliar${I}|assistir${I}|forn\
353
+ ecer${I}|criar${I}|escrever${I}|gerar${I}|compartilhar${I}|partilhar${I}|dar${I}|oferecer${I}|responder${I}|atender${I}|cumprir|participar|fazer isso|com isso|com esse|com essa)`,md="(?:desculpe|descu\
354
+ lpa|sinto muito|lamento|infelizmente|entendo|compreendo|como (?:uma? )?(?:ia|intelig\xEAncia artificial|modelo de linguagem|assistente))",$t="(?:[\\s,]+[\\p{L}'\u2019-]+){0,4}?[\\s,]+",zs=[`${Wu}${$t}${Ku}`,
355
+ Gu,Ju,`${Zu}${$t}${Xu}`,"lamento no poder",`${ed}${$t}${td}`,`${rd}${$t}${od}`,`${sd} ${ad}`,`${ld}${$t}${ud}`,`${pd}${$t}${fd}`].join("|"),hd=[Yu,Qu,nd,id,cd,dd,md].join("|"),gd=new RegExp(`^(?:${zs}\
356
+ )(?![\\p{L}])`,"u"),bd=new RegExp(`^(?:${hd})(?![\\p{L}])`,"u"),qs=new RegExp(`(?:^|[^\\p{L}'])(?:${zs})(?![\\p{L}])`,"u");function vd(e){return e.slice(0,4*300).replace(/[‘’ʼ`´]/g,"'").toLowerCase().
357
+ replace(/\s+/g," ").trim().replace(/^[\s*#>_"'«“¿¡(\[-]+/u,"").trim()}function yd(e){let t=[...e.matchAll(/[.!?。](?:\s|$)/g)],n=t.length>=2?t[1].index+1:e.length;return e.slice(0,Math.min(n,240))}
358
+ function Co(e){if(typeof e!="string"||e==="")return null;let t=vd(e);if(t==="")return null;let n=yd(t);return gd.test(n)?"opens-with-refusal":bd.test(n)&&qs.test(n)?"apology-then-refusal":t.length<=300&&
359
+ qs.test(t)?"short-refusal":null}var cr=class{decoder;resto="";crPendiente=false;alPrincipio=true;datos="";evento="";ultimoId;push(t){let n=typeof t=="string"?t:(this.decoder??=new TextDecoder("utf-8")).decode(t,{stream:true});return this.procesar(
334
360
  n)}end(){let t=[];if(this.decoder){let n=this.decoder.decode();n!==""&&t.push(...this.procesar(n));}return this.resto!==""&&(this.linea(this.resto,t),this.resto=""),this.despachar(t),this.crPendiente=false,
335
361
  t}procesar(t){let n=[];if(t==="")return n;let r=t;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(
336
362
  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.
337
363
  crPendiente=true),o++,i=o;}return this.resto+=r.slice(i),n}linea(t,n){if(t===""){this.despachar(n);return}if(t.charCodeAt(0)===58)return;let r=t.indexOf(":"),o,i;switch(r===-1?(o=t,i=""):(o=t.slice(0,r),
338
364
  i=t.slice(r+1),i.charCodeAt(0)===32&&(i=i.slice(1))),o){case "data":this.datos+=i+`
339
365
  `;break;case "event":this.evento=i;break;case "id":i.includes("\0")||(this.ultimoId=i);break;}}despachar(t){if(this.datos===""){this.evento="";return}t.push({event:this.evento===""?"message":
340
- this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};var Le=class{resto="";uso=null;elisionObservada=null;paradaFinal=null;detallesDeParada=void 0;eventos={};observar(t){this.resto+=typeof t=="string"?t:t.toString("utf8");let n;for(;(n=this.resto.indexOf(
341
- `
366
+ this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};var $e=class{resto="";uso=null;elisionObservada=null;paradaFinal=null;detallesDeParada=void 0;texto=new dn;eventos={};observar(t){this.resto+=typeof t=="string"?t:t.toString("utf8");let n;for(;(n=this.
367
+ resto.indexOf(`
342
368
 
343
- `))>=0;){let r=this.resto.slice(0,n);this.resto=this.resto.slice(n+2);let o=/^event: (.+)$/m.exec(r)?.[1];if(o&&(this.eventos[o]=(this.eventos[o]??0)+1),o!=="message_start"&&o!=="message_delta")continue;
344
- let i=/^data: (.+)$/m.exec(r)?.[1];if(i)try{let s=JSON.parse(i);o==="message_delta"&&typeof s.delta?.stop_reason=="string"&&(this.paradaFinal=s.delta.stop_reason),o==="message_delta"&&s.delta&&"stop_d\
345
- etails"in s.delta&&(this.detallesDeParada=s.delta.stop_details);let a=js(s.context_management);a&&(this.elisionObservada=a);let c=s.usage??s.message?.usage;if(c){let l=c.cache_creation||this.uso?.cache_creation?
346
- {...this.uso?.cache_creation,...c.cache_creation}:void 0;this.uso={...this.uso,...c,...l?{cache_creation:l}:{}};}}catch{}}}usage(){return this.uso}usageFinal(){return (this.eventos.message_delta??0)>0?this.
347
- uso:null}elision(){return this.elisionObservada}negativa(){return this.paradaFinal==="refusal"}negativaNoCobrada(){let t=this.usageFinal();return t!==null&&rr({stopReason:this.paradaFinal,stopDetails:this.
348
- detallesDeParada,bloques:this.eventos.content_block_start??0,outputTokens:t.output_tokens,iterations:t.iterations})}};function Mu(e,t){if(!t||t.atribuible!==true||!(t.tokensLimpiadosToolUses>0))return 0;
349
- let n=e.cachedInputPer1k;return typeof n!="number"||!Number.isFinite(n)||n<=0?0:t.tokensLimpiadosToolUses/1e3*n}function js(e){if(e===null||typeof e!="object")return null;let t=e.applied_edits;if(!Array.
350
- isArray(t)||t.length===0)return null;let n=0,r=0;for(let o of t){let i=o.cleared_input_tokens;typeof i=="number"&&Number.isFinite(i)&&i>0&&(n+=i,o.type==="clear_tool_uses_20250919"&&(r+=i));}return {borrados:t.
351
- length,tokensLimpiados:n,tokensLimpiadosToolUses:r}}function Bs(e){try{let t=JSON.parse(typeof e=="string"?e:e.toString("utf8"));return js(t.context_management)}catch{return null}}var Ot=class{resto="";uso=null;final=null;negada=false;eventos={};observar(t){
369
+ `))>=0;){let r=this.resto.slice(0,n);this.resto=this.resto.slice(n+2);let o=/^event: (.+)$/m.exec(r)?.[1];if(o&&(this.eventos[o]=(this.eventos[o]??0)+1),o==="content_block_delta"&&!this.texto.lleno()){
370
+ let s=/^data: (.+)$/m.exec(r)?.[1];try{let a=s?JSON.parse(s):null;a?.delta?.type==="text_delta"&&this.texto.sumar(a.delta.text);}catch{}continue}if(o!=="message_start"&&o!=="message_delta")continue;let i=/^data: (.+)$/m.
371
+ exec(r)?.[1];if(i)try{let s=JSON.parse(i);o==="message_delta"&&typeof s.delta?.stop_reason=="string"&&(this.paradaFinal=s.delta.stop_reason),o==="message_delta"&&s.delta&&"stop_details"in s.delta&&(this.
372
+ detallesDeParada=s.delta.stop_details);let a=Ks(s.context_management);a&&(this.elisionObservada=a);let c=s.usage??s.message?.usage;if(c){let l=c.cache_creation||this.uso?.cache_creation?{...this.uso?.
373
+ cache_creation,...c.cache_creation}:void 0;this.uso={...this.uso,...c,...l?{cache_creation:l}:{}};}}catch{}}}usage(){return this.uso}usageFinal(){return (this.eventos.message_delta??0)>0?this.uso:null}elision(){
374
+ return this.elisionObservada}negativa(){return this.paradaFinal==="refusal"}textoInicial(){return this.texto.valor()}negativaNoCobrada(){let t=this.usageFinal();return t!==null&&ar({stopReason:this.paradaFinal,
375
+ stopDetails:this.detallesDeParada,bloques:this.eventos.content_block_start??0,outputTokens:t.output_tokens,iterations:t.iterations})}};function kd(e,t){if(!t||t.atribuible!==true||!(t.tokensLimpiadosToolUses>
376
+ 0))return 0;let n=e.cachedInputPer1k;return typeof n!="number"||!Number.isFinite(n)||n<=0?0:t.tokensLimpiadosToolUses/1e3*n}function Ks(e){if(e===null||typeof e!="object")return null;let t=e.applied_edits;
377
+ if(!Array.isArray(t)||t.length===0)return null;let n=0,r=0;for(let o of t){let i=o.cleared_input_tokens;typeof i=="number"&&Number.isFinite(i)&&i>0&&(n+=i,o.type==="clear_tool_uses_20250919"&&(r+=i));}
378
+ return {borrados:t.length,tokensLimpiados:n,tokensLimpiadosToolUses:r}}function Gs(e){try{let t=JSON.parse(typeof e=="string"?e:e.toString("utf8"));return Ks(t.context_management)}catch{return null}}var Nt=class{resto="";uso=null;final=null;negada=false;texto=new dn;eventos={};observar(t){
352
379
  this.resto+=typeof t=="string"?t:t.toString("utf8");let n;for(;(n=this.resto.indexOf(`
353
380
 
354
381
  `))>=0;){let r=this.resto.slice(0,n);this.resto=this.resto.slice(n+2);let o=/^event: (.+)$/m.exec(r)?.[1];o&&(this.eventos[o]=(this.eventos[o]??0)+1);let i=/^data: (.+)$/m.exec(r)?.[1];if(i)try{let s=JSON.
355
- parse(i),a=o??s.type;$u(a,s)&&(this.negada=!0);let c=a!==void 0&&Object.hasOwn($s,a)?$s[a]:void 0;if(c===void 0)continue;this.final=c;let l=s.response?.usage;if(!l)continue;c==="completed"?this.uso=ir(
356
- l):typeof l.input_tokens=="number"&&typeof l.output_tokens=="number"&&(this.uso=ir(l));}catch{}}}usage(){return this.uso}usageFinal(){return this.uso}estadoFinal(){return this.final}negativa(){return this.
357
- negada}};function $u(e,t){if(e==="response.refusal.delta"||e==="response.refusal.done")return true;if(t===null||typeof t!="object")return false;let n=t;return Us(n.part)||So([n.item])?true:n.response!==null&&typeof n.
358
- response=="object"&&So(n.response.output)}function Us(e){return e!==null&&typeof e=="object"&&e.type==="refusal"}function So(e){return Array.isArray(e)&&e.some(t=>{if(t===null||typeof t!="object")return false;
359
- let n=t.content;return Array.isArray(n)&&n.some(Us)})}var $s={"response.completed":"completed","response.incomplete":"incomplete","response.failed":"failed"};function ir(e){let t=Math.max(0,e.input_tokens??
360
- 0),n=Math.min(Math.max(0,e.input_tokens_details?.cached_tokens??0),t),r=Math.min(Math.max(0,e.input_tokens_details?.cache_write_tokens??0),t-n);return {input_tokens:t-n-r,output_tokens:Math.max(0,e.output_tokens??
361
- 0),cache_read_input_tokens:n,cache_creation_input_tokens:r}}function Vs(e){return !e||typeof e.prompt_tokens!="number"||typeof e.completion_tokens!="number"?null:ir({input_tokens:e.prompt_tokens,output_tokens:e.
362
- completion_tokens,input_tokens_details:{...e.prompt_tokens_details?.cached_tokens!==void 0?{cached_tokens:e.prompt_tokens_details.cached_tokens}:{},...e.prompt_tokens_details?.cache_write_tokens!==void 0?
363
- {cache_write_tokens:e.prompt_tokens_details.cache_write_tokens}:{}}})}var an=class{parser=new or;ultimoUso=null;vioUsoFinal=false;vioDone=false;filtrada=false;eventos={};observar(t){for(let n of this.parser.push(
364
- t))this.mensaje(n);}negativa(){return this.filtrada}usage(){return this.vioUsoFinal||this.vioDone?this.ultimoUso:null}usageFinal(){for(let t of this.parser.end())this.mensaje(t);return this.usage()}mensaje(t){
365
- if(t.data==="[DONE]"){this.vioDone=true,this.eventos.done=(this.eventos.done??0)+1;return}let n;try{n=JSON.parse(t.data);}catch{return}if(n===null||typeof n!="object"||(this.eventos.chunk=(this.eventos.chunk??
366
- 0)+1,Ks(n.choices)&&(this.filtrada=true),n.usage===null||typeof n.usage!="object"))return;let r=Vs(n.usage);r!==null&&(this.ultimoUso=r,Array.isArray(n.choices)&&n.choices.length===0&&(this.vioUsoFinal=
367
- true));}};function Fs(e,t,n){let r=e.cachedInputPer1k??e.inputPer1k;return t.entrada/1e3*e.inputPer1k+t.cacheLeida/1e3*r+(t.cacheEscrita-t.cacheEscrita1h)/1e3*e.inputPer1k*Se(n)+t.cacheEscrita1h/1e3*e.inputPer1k*
368
- 2+t.salida/1e3*e.outputPer1k}function zs(e,t,n){let r=n??Date.now(),o=Te(e,r);if(!o)return null;let i=wo(t.iterations),s=(t.input_tokens??0)+(i?.input??0),a=(t.output_tokens??0)+(i?.output??0),c=(t.cache_read_input_tokens??
369
- 0)+(i?.cacheRead??0),l=t.cache_creation,d=t.cache_creation_input_tokens??(l?.ephemeral_5m_input_tokens??0)+(l?.ephemeral_1h_input_tokens??0),u=d+(i?.cacheWrite??0),p=Math.min(Math.min(l?.ephemeral_1h_input_tokens??
370
- 0,d)+(i?.cacheWrite1h??0),u),f={entrada:s,salida:a,cacheLeida:c,cacheEscrita:u,cacheEscrita1h:p};return {costeUsd:Fs(o,f,e),precio:o,tokens:f,instante:r}}function qs(e,t){let r=Lt(e,t)?.model;return typeof r==
371
- "string"?r:""}function Lt(e,t){try{let n=e,r={maxOutputLength:Nu};switch((t??"").trim().toLowerCase()){case "gzip":case "x-gzip":n=Ke.gunzipSync(e,r);break;case "deflate":n=Ke.inflateSync(e,r);break;case "\
372
- br":n=Ke.brotliDecompressSync(e,r);break;case "zstd":{let o=Ke.zstdDecompressSync;if(typeof o!="function")return null;n=o(e,r);break}default:break}return JSON.parse(n.toString("utf8"))}catch{return null}}
373
- var Nu=5*1024*1024;function Hs(){return typeof Ke.zstdDecompressSync=="function"}function ju(e){try{return JSON.parse(typeof e=="string"?e:e.toString("utf8")).usage??null}catch{return null}}function sr(e,t){
374
- if(e==="/v1/messages")return ju(t);if(!ht(e))return null;try{let n=JSON.parse(typeof t=="string"?t:t.toString("utf8"));if(n===null||typeof n!="object")return null;if(e.endsWith("/chat/completions"))return Vs(
375
- n.usage);let r=n.usage;return r&&typeof r.input_tokens=="number"&&typeof r.output_tokens=="number"?ir(r):null}catch{return null}}function Ws(e,t){if(!e.endsWith("/responses"))return false;try{let n=JSON.parse(
376
- typeof t=="string"?t:t.toString("utf8"));return n!==null&&typeof n=="object"&&n.status==="failed"}catch{return false}}function Ks(e){let t=n=>{let r=n!==null&&typeof n=="object"?n.refusal:void 0;return typeof r==
377
- "string"&&r!==""};return Array.isArray(e)&&e.some(n=>{if(n===null||typeof n!="object")return false;let r=n;return r.finish_reason==="content_filter"||t(r.message)||t(r.delta)})}function Gs(e,t){if(e!=="/v\
378
- 1/messages"&&!e.endsWith("/chat/completions")&&!e.endsWith("/responses"))return false;try{let n=JSON.parse(typeof t=="string"?t:t.toString("utf8"));return n===null||typeof n!="object"?!1:e==="/v1/messages"?
379
- n.stop_reason==="refusal":e.endsWith("/chat/completions")?Ks(n.choices):So(n.output)}catch{return false}}function Eo(e,t){if(e!=="/v1/messages")return false;try{let n=JSON.parse(typeof t=="string"?t:t.toString(
380
- "utf8"));return n===null||typeof n!="object"?!1:rr({stopReason:n.stop_reason,stopDetails:n.stop_details,bloques:Array.isArray(n.content)?n.content.length:-1,outputTokens:n.usage?.output_tokens,iterations:n.
381
- usage?.iterations})}catch{return false}}function Js(e,t){let n=typeof t=="string"?t:t.toString("utf8"),r=i=>{if(i===null||typeof i!="object")return;let s=i,a=l=>l!==null&&typeof l=="object"?l.service_tier:
382
- void 0,c;return e==="/v1/messages"?(c=a(s.usage),c===void 0&&s.message!==null&&typeof s.message=="object"&&(c=a(s.message.usage))):e.endsWith("/chat/completions")?c=s.service_tier:e.endsWith("/respons\
383
- es")&&(c=s.service_tier,c===void 0&&s.response!==null&&typeof s.response=="object"&&(c=s.response.service_tier)),typeof c=="string"&&c!==""?c:void 0};try{return r(JSON.parse(n))}catch{}let o;for(let i of n.
384
- split(`
385
- `)){if(!i.startsWith("data:"))continue;let s=i.slice(5).trim();if(!(s===""||s==="[DONE]"))try{o=r(JSON.parse(s))??o;}catch{}}return o}function ht(e){return e==="/v1/messages"||e.endsWith("/chat/complet\
386
- ions")||e.endsWith("/responses")}var Bu=Buffer.from('"stream_options":{"include_usage":true},',"utf8");function Ys(e,t){let n=(t??"").trim().toLowerCase();if(n!==""&&n!=="identity")return {cuerpo:null,
382
+ parse(i),a=o??s.type;xd(a,s)&&(this.negada=!0),a==="response.output_text.delta"&&this.texto.sumar(s.delta);let c=a!==void 0&&Object.hasOwn(Hs,a)?Hs[a]:void 0;if(c===void 0)continue;this.final=c;let l=s.
383
+ response?.usage;if(!l)continue;c==="completed"?this.uso=lr(l):typeof l.input_tokens=="number"&&typeof l.output_tokens=="number"&&(this.uso=lr(l));}catch{}}}usage(){return this.uso}usageFinal(){return this.
384
+ uso}estadoFinal(){return this.final}negativa(){return this.negada}textoInicial(){return this.texto.valor()}};function xd(e,t){if(e==="response.refusal.delta"||e==="response.refusal.done")return true;if(t===
385
+ null||typeof t!="object")return false;let n=t;return Js(n.part)||Ro([n.item])?true:n.response!==null&&typeof n.response=="object"&&Ro(n.response.output)}function Js(e){return e!==null&&typeof e=="object"&&e.
386
+ type==="refusal"}function Ro(e){return Array.isArray(e)&&e.some(t=>{if(t===null||typeof t!="object")return false;let n=t.content;return Array.isArray(n)&&n.some(Js)})}var Hs={"response.completed":"complet\
387
+ ed","response.incomplete":"incomplete","response.failed":"failed"};function lr(e){let t=Math.max(0,e.input_tokens??0),n=Math.min(Math.max(0,e.input_tokens_details?.cached_tokens??0),t),r=Math.min(Math.
388
+ max(0,e.input_tokens_details?.cache_write_tokens??0),t-n);return {input_tokens:t-n-r,output_tokens:Math.max(0,e.output_tokens??0),cache_read_input_tokens:n,cache_creation_input_tokens:r}}function Ys(e){
389
+ return !e||typeof e.prompt_tokens!="number"||typeof e.completion_tokens!="number"?null:lr({input_tokens:e.prompt_tokens,output_tokens:e.completion_tokens,input_tokens_details:{...e.prompt_tokens_details?.
390
+ cached_tokens!==void 0?{cached_tokens:e.prompt_tokens_details.cached_tokens}:{},...e.prompt_tokens_details?.cache_write_tokens!==void 0?{cache_write_tokens:e.prompt_tokens_details.cache_write_tokens}:
391
+ {}}})}var un=class{parser=new cr;ultimoUso=null;vioUsoFinal=false;vioDone=false;filtrada=false;texto=new dn;eventos={};observar(t){for(let n of this.parser.push(t))this.mensaje(n);}textoInicial(){for(let t of this.
392
+ parser.end())this.mensaje(t);return this.texto.valor()}negativa(){return this.filtrada}usage(){return this.vioUsoFinal||this.vioDone?this.ultimoUso:null}usageFinal(){for(let t of this.parser.end())this.
393
+ mensaje(t);return this.usage()}mensaje(t){if(t.data==="[DONE]"){this.vioDone=true,this.eventos.done=(this.eventos.done??0)+1;return}let n;try{n=JSON.parse(t.data);}catch{return}if(n===null||typeof n!="ob\
394
+ ject")return;if(this.eventos.chunk=(this.eventos.chunk??0)+1,na(n.choices)&&(this.filtrada=true),Array.isArray(n.choices)&&!this.texto.lleno()){let o=n.choices[0];this.texto.sumar(o?.delta?.content);}if(n.
395
+ usage===null||typeof n.usage!="object")return;let r=Ys(n.usage);r!==null&&(this.ultimoUso=r,Array.isArray(n.choices)&&n.choices.length===0&&(this.vioUsoFinal=true));}};function Zs(e,t,n){let r=e.cachedInputPer1k??
396
+ e.inputPer1k;return t.entrada/1e3*e.inputPer1k+t.cacheLeida/1e3*r+(t.cacheEscrita-t.cacheEscrita1h)/1e3*e.inputPer1k*_e(n)+t.cacheEscrita1h/1e3*e.inputPer1k*2+t.salida/1e3*e.outputPer1k}function Xs(e,t,n){
397
+ let r=n??Date.now(),o=Ae(e,r);if(!o)return null;let i=To(t.iterations),s=(t.input_tokens??0)+(i?.input??0),a=(t.output_tokens??0)+(i?.output??0),c=(t.cache_read_input_tokens??0)+(i?.cacheRead??0),l=t.
398
+ cache_creation,d=t.cache_creation_input_tokens??(l?.ephemeral_5m_input_tokens??0)+(l?.ephemeral_1h_input_tokens??0),u=d+(i?.cacheWrite??0),p=Math.min(Math.min(l?.ephemeral_1h_input_tokens??0,d)+(i?.cacheWrite1h??
399
+ 0),u),f={entrada:s,salida:a,cacheLeida:c,cacheEscrita:u,cacheEscrita1h:p};return {costeUsd:Zs(o,f,e),precio:o,tokens:f,instante:r}}function Qs(e,t){let r=jt(e,t)?.model;return typeof r=="string"?r:""}function jt(e,t){
400
+ try{let n=e,r={maxOutputLength:wd};switch((t??"").trim().toLowerCase()){case "gzip":case "x-gzip":n=Ye.gunzipSync(e,r);break;case "deflate":n=Ye.inflateSync(e,r);break;case "br":n=Ye.brotliDecompressSync(
401
+ e,r);break;case "zstd":{let o=Ye.zstdDecompressSync;if(typeof o!="function")return null;n=o(e,r);break}default:break}return JSON.parse(n.toString("utf8"))}catch{return null}}var wd=5*1024*1024;function ea(){
402
+ return typeof Ye.zstdDecompressSync=="function"}function Sd(e){try{return JSON.parse(typeof e=="string"?e:e.toString("utf8")).usage??null}catch{return null}}function ur(e,t){if(e==="/v1/messages")return Sd(
403
+ t);if(!vt(e))return null;try{let n=JSON.parse(typeof t=="string"?t:t.toString("utf8"));if(n===null||typeof n!="object")return null;if(e.endsWith("/chat/completions"))return Ys(n.usage);let r=n.usage;return r&&
404
+ typeof r.input_tokens=="number"&&typeof r.output_tokens=="number"?lr(r):null}catch{return null}}function ta(e,t){if(!e.endsWith("/responses"))return false;try{let n=JSON.parse(typeof t=="string"?t:t.toString(
405
+ "utf8"));return n!==null&&typeof n=="object"&&n.status==="failed"}catch{return false}}function na(e){let t=n=>{let r=n!==null&&typeof n=="object"?n.refusal:void 0;return typeof r=="string"&&r!==""};return Array.
406
+ isArray(e)&&e.some(n=>{if(n===null||typeof n!="object")return false;let r=n;return r.finish_reason==="content_filter"||t(r.message)||t(r.delta)})}function ra(e,t){if(e!=="/v1/messages"&&!e.endsWith("/chat\
407
+ /completions")&&!e.endsWith("/responses"))return false;try{let n=JSON.parse(typeof t=="string"?t:t.toString("utf8"));return n===null||typeof n!="object"?!1:e==="/v1/messages"?n.stop_reason==="refusal":e.endsWith(
408
+ "/chat/completions")?na(n.choices):Ro(n.output)}catch{return false}}var Ao=1200,dn=class{t="";sumar(t){typeof t=="string"&&this.t.length<Ao&&(this.t=(this.t+t).slice(0,Ao));}lleno(){return this.t.length>=Ao}valor(){
409
+ return this.t}};function oa(e,t){try{let n=JSON.parse(typeof t=="string"?t:t.toString("utf8"));if(n===null||typeof n!="object")return "";let r=(o,i,s)=>Array.isArray(o)?o.filter(a=>a!==null&&typeof a==
410
+ "object"&&a.type===i).map(a=>a[s]).filter(a=>typeof a=="string").join(""):"";if(e==="/v1/messages")return r(n.content,"text","text");if(e.endsWith("/chat/completions")){let i=(Array.isArray(n.choices)?
411
+ n.choices[0]:void 0)?.message?.content;return typeof i=="string"?i:r(i,"text","text")}return e.endsWith("/responses")&&Array.isArray(n.output)?n.output.map(o=>o!==null&&typeof o=="object"?r(o.content,
412
+ "output_text","text"):"").join(""):""}catch{return ""}}function ia(e){return Co(e)!==null}function Io(e,t){if(e!=="/v1/messages")return false;try{let n=JSON.parse(typeof t=="string"?t:t.toString("utf8"));return n===
413
+ null||typeof n!="object"?!1:ar({stopReason:n.stop_reason,stopDetails:n.stop_details,bloques:Array.isArray(n.content)?n.content.length:-1,outputTokens:n.usage?.output_tokens,iterations:n.usage?.iterations})}catch{
414
+ return false}}function sa(e,t){let n=typeof t=="string"?t:t.toString("utf8"),r=i=>{if(i===null||typeof i!="object")return;let s=i,a=l=>l!==null&&typeof l=="object"?l.service_tier:void 0,c;return e==="/v1/\
415
+ messages"?(c=a(s.usage),c===void 0&&s.message!==null&&typeof s.message=="object"&&(c=a(s.message.usage))):e.endsWith("/chat/completions")?c=s.service_tier:e.endsWith("/responses")&&(c=s.service_tier,c===
416
+ void 0&&s.response!==null&&typeof s.response=="object"&&(c=s.response.service_tier)),typeof c=="string"&&c!==""?c:void 0};try{return r(JSON.parse(n))}catch{}let o;for(let i of n.split(`
417
+ `)){if(!i.startsWith("data:"))continue;let s=i.slice(5).trim();if(!(s===""||s==="[DONE]"))try{o=r(JSON.parse(s))??o;}catch{}}return o}function vt(e){return e==="/v1/messages"||e.endsWith("/chat/complet\
418
+ ions")||e.endsWith("/responses")}var Ed=Buffer.from('"stream_options":{"include_usage":true},',"utf8");function aa(e,t){let n=(t??"").trim().toLowerCase();if(n!==""&&n!=="identity")return {cuerpo:null,
387
419
  motivo:"comprimido"};let r;try{r=JSON.parse(e.toString("utf8").replace(/^\uFEFF/,""));}catch{return {cuerpo:null,motivo:"ilegible"}}if(r===null||typeof r!="object"||Array.isArray(r))return {cuerpo:null,motivo:"\
388
420
  ilegible"};let o=r;if(o.stream!==true)return {cuerpo:null,motivo:"no-stream"};if(o.stream_options?.include_usage===true)return {cuerpo:null,motivo:"ya-lo-pide"};if(o.stream_options!==void 0)return {cuerpo:null,
389
421
  motivo:"cliente-decide"};let i=0;for(;i<e.length;){let s=e[i];if(s===32||s===9||s===10||s===13){i++;continue}if(s===239&&e[i+1]===187&&e[i+2]===191){i+=3;continue}break}return e[i]!==123?{cuerpo:null,
390
- motivo:"ilegible"}:{cuerpo:Buffer.concat([e.subarray(0,i+1),Bu,e.subarray(i+1)]),motivo:"inyectado"}}function Zs(e,t){let n=Lt(e,t);if(n===null||typeof n!="object")return null;let r=n;return r.stream!==
391
- true?null:r.stream_options?.include_usage===true}function _o(e,t,n){if((t??"").split(",").some(r=>r.trim().startsWith("oauth-"))||e.startsWith("/backend-api/"))return true;try{let r=new URL(n).hostname.toLowerCase();
392
- return r==="chatgpt.com"||r.endsWith(".chatgpt.com")}catch{return false}}function Xs(e,t,n,r,o,i,s,a,c,l){return na(e,t,n,false,r,o,i,s,a,c,l===true)}var Uu=new Set(["auto","default","priority","standard_only"]);
393
- function Vu(e){if(e==null)return 1;if(typeof e!="string")return null;if(Uu.has(e))return 1;let t=nr(e);return t!==null&&t.conDescuento&&t.factor!==null?t.factor:null}function Fu(e){if(e===void 0)return 1;
394
- if(e==="scale")return null;let t=nr(e);return t!==null&&t.factor!==null?t.factor:null}function Qs(e,t,n,r,o){if(!n||!n.conContador)return {ok:false,reason:"no-primary-record"};if(n.suscripcion||o.suscripcion)
422
+ motivo:"ilegible"}:{cuerpo:Buffer.concat([e.subarray(0,i+1),Ed,e.subarray(i+1)]),motivo:"inyectado"}}function ca(e,t){let n=jt(e,t);if(n===null||typeof n!="object")return null;let r=n;return r.stream!==
423
+ true?null:r.stream_options?.include_usage===true}function Po(e,t,n){if((t??"").split(",").some(r=>r.trim().startsWith("oauth-"))||e.startsWith("/backend-api/"))return true;try{let r=new URL(n).hostname.toLowerCase();
424
+ return r==="chatgpt.com"||r.endsWith(".chatgpt.com")}catch{return false}}function la(e,t,n,r,o,i,s,a,c,l){return fa(e,t,n,false,r,o,i,s,a,c,l===true)}var _d=new Set(["auto","default","priority","standard_only"]);
425
+ function Td(e){if(e==null)return 1;if(typeof e!="string")return null;if(_d.has(e))return 1;let t=sr(e);return t!==null&&t.conDescuento&&t.factor!==null?t.factor:null}function Cd(e){if(e===void 0)return 1;
426
+ if(e==="scale")return null;let t=sr(e);return t!==null&&t.factor!==null?t.factor:null}function ua(e,t,n,r,o){if(!n||!n.conContador)return {ok:false,reason:"no-primary-record"};if(n.suscripcion||o.suscripcion)
395
427
  return {ok:false,reason:"subscription"};if(!n.proveedorOficial)return {ok:false,reason:"unofficial-upstream"};if(!n.intacta)return {ok:false,reason:"layer-changed-request"};if(n.fallida)return {ok:false,reason:"prima\
396
- ry-failed"};if(n.negativa===true)return {ok:false,reason:"primary-refused"};if(!o.entregada)return {ok:false,reason:"client-disconnected"};let i=r!==null&&typeof r=="object"&&!Array.isArray(r)?r:{},s=Vu(i.service_tier),
397
- a=Fu(o.tierServido);if(s===null||a===null)return {ok:false,reason:"service-tier"};let c=Math.min(s,a),l=_t(e,t.instante),d=l?.cachedInputPer1k;if(!l||typeof d!="number"||!Number.isFinite(d)||!(d>0)||!Number.
398
- isFinite(l.inputPer1k)||d>l.inputPer1k||!Number.isFinite(l.outputPer1k)||l.outputPer1k<0)return {ok:false,reason:"no-cached-price"};let u=t.tokens,p=u.entrada+u.cacheLeida+u.cacheEscrita,f=b=>Number.isInteger(
399
- b)&&b>=0;if(!f(u.entrada)||!f(u.cacheLeida)||!f(u.cacheEscrita)||!f(u.salida)||!(p>0))return {ok:false,reason:"no-credit"};let g=i.temperature===0&&xo(e)===void 0;return {ok:true,credit:{requestId:n.requestId,
400
- at:n.at,inputTokens:p,outputTokens:u.salida,creditedInputTokens:p,creditedOutputTokens:g?Math.floor(.95*u.salida):0,cachedInputPer1k:d,outputPer1k:l.outputPer1k,tierFactor:c}}}function To(e){return e.
401
- tierFactor*(e.creditedInputTokens/1e3*e.cachedInputPer1k+e.creditedOutputTokens/1e3*e.outputPer1k)}function ea(e,t,n,r,o,i){let s=o?To(o):0;return i===true||!o||!(s>0)||!Number.isFinite(s)?na(e,t,n,true,r,
402
- void 0,void 0,void 0,false,false,i===true):{requestId:e,model:t,...r&&(r.sessionId||r.agentId)?{attribution:r}:{},calls:{avoidedLlm:1,actualLlm:0},tokens:{baselineInput:o.creditedInputTokens,actualInput:0,eliminatedInput:0,
403
- compressedInput:0,baselineOutput:o.creditedOutputTokens,actualOutput:0,providerCachedInput:0},cache:{result:"singleflight",reference:o},cost:{baselineEstimate:s,actual:0,netSavings:1,basis:"reference"}}}
404
- function ta(e,t,n,r,o){return {requestId:e,model:t,...o&&(o.sessionId||o.agentId)?{attribution:o}:{},calls:{avoidedLlm:0,actualLlm:0},tokens:{baselineInput:0,actualInput:0,eliminatedInput:0,compressedInput:0,
405
- baselineOutput:0,actualOutput:0,providerCachedInput:0},cache:{result:"miss"},cost:{baselineEstimate:n,actual:r,netSavings:n>0?Math.max(-100,Math.min(1,(n-r)/n)):0,basis:"shadow"}}}function zu(e,t){let n=Te(
406
- e.solicitado,t.instante);return n===void 0?0:Math.max(0,Fs(n,t.tokens,e.solicitado)-t.costeUsd)}function na(e,t,n,r,o,i,s,a,c=false,l=false,d=false){d&&(n={...n,costeUsd:0});let u=n.tokens.entrada+n.tokens.cacheLeida+
407
- n.tokens.cacheEscrita,f=!r&&!c&&!l&&!d,g=n.tokens.cacheEscrita-n.tokens.cacheEscrita1h,b=f&&s&&s.rebajadas>0&&s.yaEran5m===0&&!s.herramientaDeServidor&&g>0?g/1e3*n.precio.inputPer1k*(2-1.25):0,h=f&&a?
408
- zu(a,n):0,v=n.costeUsd+b+h,k=b+h,x=r||l||d?0:Mu(n.precio,i);return {requestId:e,model:t,...o&&(o.sessionId||o.agentId)?{attribution:o}:{},calls:r?{avoidedLlm:1,actualLlm:0}:{avoidedLlm:0,actualLlm:1},tokens:{
409
- baselineInput:u,actualInput:r?0:u,eliminatedInput:r?0:i?.tokensLimpiados??0,compressedInput:0,baselineOutput:n.tokens.salida,actualOutput:r?0:n.tokens.salida,providerCachedInput:r?0:n.tokens.cacheLeida},
410
- cache:{result:r?"singleflight":"miss"},cost:r?{baselineEstimate:n.costeUsd,actual:0,netSavings:d?0:1,basis:"estimated"}:{baselineEstimate:v,actual:n.costeUsd,netSavings:v>0?Math.max(-100,Math.min(1,k/
411
- v)):0,basis:"measured",...x>0?{eliminatedInputFloorCost:x}:{}}}}var qu=1024,cn=120,Hu=8,Wu=256*1024,Ku=/error|exception|traceback|warn|fatal|fail|panic|assert|denied|refused|timeout|\bat\s+\S+:\d+/i,ia=/^\s*(export\s|import\s|function\s|class\s|interface\s|type\s|enum\s|def\s|fn\s|func\s|impl\s|struct\s|trait\s|package\s|module\s|@\w)/;
412
- function Gu(e){return Buffer.byteLength(typeof e=="string"?e:JSON.stringify(e??""))}function Ju(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t&&typeof t=="object"&&typeof t.text=="string"?
428
+ ry-failed"};if(n.negativa===true)return {ok:false,reason:"primary-refused"};if(n.negativaEnTexto===true)return {ok:false,reason:"primary-text-refusal"};if(!o.entregada)return {ok:false,reason:"client-disconnected"};let i=r!==
429
+ null&&typeof r=="object"&&!Array.isArray(r)?r:{},s=Td(i.service_tier),a=Cd(o.tierServido);if(s===null||a===null)return {ok:false,reason:"service-tier"};let c=Math.min(s,a),l=At(e,t.instante),d=l?.cachedInputPer1k;
430
+ if(!l||typeof d!="number"||!Number.isFinite(d)||!(d>0)||!Number.isFinite(l.inputPer1k)||d>l.inputPer1k||!Number.isFinite(l.outputPer1k)||l.outputPer1k<0)return {ok:false,reason:"no-cached-price"};let u=t.
431
+ tokens,p=u.entrada+u.cacheLeida+u.cacheEscrita,f=b=>Number.isInteger(b)&&b>=0;if(!f(u.entrada)||!f(u.cacheLeida)||!f(u.cacheEscrita)||!f(u.salida)||!(p>0))return {ok:false,reason:"no-credit"};let g=i.temperature===
432
+ 0&&_o(e)===void 0;return {ok:true,credit:{requestId:n.requestId,at:n.at,inputTokens:p,outputTokens:u.salida,creditedInputTokens:p,creditedOutputTokens:g?Math.floor(.95*u.salida):0,cachedInputPer1k:d,outputPer1k:l.
433
+ outputPer1k,tierFactor:c}}}function Do(e){return e.tierFactor*(e.creditedInputTokens/1e3*e.cachedInputPer1k+e.creditedOutputTokens/1e3*e.outputPer1k)}function da(e,t,n,r,o,i){let s=o?Do(o):0;return i===
434
+ true||!o||!(s>0)||!Number.isFinite(s)?fa(e,t,n,true,r,void 0,void 0,void 0,false,false,i===true):{requestId:e,model:t,...r&&(r.sessionId||r.agentId)?{attribution:r}:{},calls:{avoidedLlm:1,actualLlm:0},tokens:{baselineInput:o.
435
+ creditedInputTokens,actualInput:0,eliminatedInput:0,compressedInput:0,baselineOutput:o.creditedOutputTokens,actualOutput:0,providerCachedInput:0},cache:{result:"singleflight",reference:o},cost:{baselineEstimate:s,
436
+ actual:0,netSavings:1,basis:"reference"}}}function pa(e,t,n,r,o){return {requestId:e,model:t,...o&&(o.sessionId||o.agentId)?{attribution:o}:{},calls:{avoidedLlm:0,actualLlm:0},tokens:{baselineInput:0,actualInput:0,
437
+ eliminatedInput:0,compressedInput:0,baselineOutput:0,actualOutput:0,providerCachedInput:0},cache:{result:"miss"},cost:{baselineEstimate:n,actual:r,netSavings:n>0?Math.max(-100,Math.min(1,(n-r)/n)):0,basis:"\
438
+ shadow"}}}function Ad(e,t){let n=Ae(e.solicitado,t.instante);return n===void 0?0:Math.max(0,Zs(n,t.tokens,e.solicitado)-t.costeUsd)}function fa(e,t,n,r,o,i,s,a,c=false,l=false,d=false){d&&(n={...n,costeUsd:0});
439
+ let u=n.tokens.entrada+n.tokens.cacheLeida+n.tokens.cacheEscrita,f=!r&&!c&&!l&&!d,g=n.tokens.cacheEscrita-n.tokens.cacheEscrita1h,b=f&&s&&s.rebajadas>0&&s.yaEran5m===0&&!s.herramientaDeServidor&&g>0?g/
440
+ 1e3*n.precio.inputPer1k*(2-1.25):0,h=f&&a?Ad(a,n):0,v=n.costeUsd+b+h,k=b+h,x=r||l||d?0:kd(n.precio,i);return {requestId:e,model:t,...o&&(o.sessionId||o.agentId)?{attribution:o}:{},calls:r?{avoidedLlm:1,
441
+ actualLlm:0}:{avoidedLlm:0,actualLlm:1},tokens:{baselineInput:u,actualInput:r?0:u,eliminatedInput:r?0:i?.tokensLimpiados??0,compressedInput:0,baselineOutput:n.tokens.salida,actualOutput:r?0:n.tokens.salida,
442
+ providerCachedInput:r?0:n.tokens.cacheLeida},cache:{result:r?"singleflight":"miss"},cost:r?{baselineEstimate:n.costeUsd,actual:0,netSavings:d?0:1,basis:"estimated"}:{baselineEstimate:v,actual:n.costeUsd,
443
+ netSavings:v>0?Math.max(-100,Math.min(1,k/v)):0,basis:"measured",...x>0?{eliminatedInputFloorCost:x}:{}}}}var Rd=1024,pn=120,Id=8,Pd=256*1024,Dd=/error|exception|traceback|warn|fatal|fail|panic|assert|denied|refused|timeout|\bat\s+\S+:\d+/i,ga=/^\s*(export\s|import\s|function\s|class\s|interface\s|type\s|enum\s|def\s|fn\s|func\s|impl\s|struct\s|trait\s|package\s|module\s|@\w)/;
444
+ function Od(e){return Buffer.byteLength(typeof e=="string"?e:JSON.stringify(e??""))}function Ld(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t&&typeof t=="object"&&typeof t.text=="string"?
413
445
  t.text:"").join(`
414
- `):""}var Yu=/^\s*\d+[\t→]/;function sa(e){return e.replace(Yu,"")}function Zu(e){if(!e)return "otro";let t=e.split(`
415
- `),n=Math.max(1,t.length),r=0,o=0,i=0;for(let s of t){let a=sa(s);(/^[+-](?![+-])/.test(a)||a.startsWith("@@")||a.startsWith("diff --git"))&&(r+=1),ia.test(a)&&(o+=1),(/^\s*(\d{4}-\d{2}-\d{2}|\[\d|\d{2}:\d{2}:\d{2})/.
416
- test(a)||/\b(INFO|DEBUG|TRACE|WARN|ERROR)\b/.test(a))&&(i+=1);}return r/n>.25?"diff":i/n>.3?"log":o/n>.08?"codigo":"otro"}function Xu(e,t){if(t==="diff"||t==="otro")return Buffer.byteLength(e);let n=e.
446
+ `):""}var Md=/^\s*\d+[\t→]/;function ba(e){return e.replace(Md,"")}function $d(e){if(!e)return "otro";let t=e.split(`
447
+ `),n=Math.max(1,t.length),r=0,o=0,i=0;for(let s of t){let a=ba(s);(/^[+-](?![+-])/.test(a)||a.startsWith("@@")||a.startsWith("diff --git"))&&(r+=1),ga.test(a)&&(o+=1),(/^\s*(\d{4}-\d{2}-\d{2}|\[\d|\d{2}:\d{2}:\d{2})/.
448
+ test(a)||/\b(INFO|DEBUG|TRACE|WARN|ERROR)\b/.test(a))&&(i+=1);}return r/n>.25?"diff":i/n>.3?"log":o/n>.08?"codigo":"otro"}function Nd(e,t){if(t==="diff"||t==="otro")return Buffer.byteLength(e);let n=e.
417
449
  split(`
418
- `),r=new Set;for(let i=0;i<n.length;i++){let s=sa(n[i]);(t==="log"?Ku.test(s):ia.test(s))&&(r.add(i),t==="log"&&(i>0&&r.add(i-1),i<n.length-1&&r.add(i+1)));}let o=cn;for(let i of r)o+=Buffer.byteLength(
419
- n[i])+1;return Math.min(o,Buffer.byteLength(e))}var Qu=(e,t)=>e==="cache_control"?void 0:t;function ed(e){if(typeof e=="string")return `text:${e}`;if(!e||typeof e!="object"||Array.isArray(e))return `jso\
420
- n:${JSON.stringify(e??"")}`;let t=e;return t.type==="text"&&typeof t.text=="string"&&Object.keys(t).every(n=>n==="type"||n==="text"||n==="cache_control")?`text:${t.text}`:`json:${JSON.stringify(t,Qu)}`}
421
- function td(e){return createHash("sha256").update(ed(e)).digest("hex").slice(0,16)}function nd(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.cache_control;return !t||typeof t!="object"?null:
422
- t.ttl==="1h"?"1h":"5m"}function aa(e){let t=[],n=(r,o)=>{let i=Gu(o),s={clave:td(o),tipo:r,marca:nd(o),bytes:i,bytesV1:i,clase:"otro",esError:false};if(r.endsWith(":tool_result")&&o&&typeof o=="object"){
423
- let a=o;s.esError=a.is_error===true;let c=Ju(a.content);s.clase=Zu(c);let l=i-Buffer.byteLength(c);s.bytesV1=Math.min(i,Math.max(0,l)+Xu(c,s.clase));}t.push(s);};if(Array.isArray(e.tools))for(let r of e.tools)
450
+ `),r=new Set;for(let i=0;i<n.length;i++){let s=ba(n[i]);(t==="log"?Dd.test(s):ga.test(s))&&(r.add(i),t==="log"&&(i>0&&r.add(i-1),i<n.length-1&&r.add(i+1)));}let o=pn;for(let i of r)o+=Buffer.byteLength(
451
+ n[i])+1;return Math.min(o,Buffer.byteLength(e))}var jd=(e,t)=>e==="cache_control"?void 0:t;function Bd(e){if(typeof e=="string")return `text:${e}`;if(!e||typeof e!="object"||Array.isArray(e))return `jso\
452
+ n:${JSON.stringify(e??"")}`;let t=e;return t.type==="text"&&typeof t.text=="string"&&Object.keys(t).every(n=>n==="type"||n==="text"||n==="cache_control")?`text:${t.text}`:`json:${JSON.stringify(t,jd)}`}
453
+ function Ud(e){return createHash("sha256").update(Bd(e)).digest("hex").slice(0,16)}function Vd(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.cache_control;return !t||typeof t!="object"?null:
454
+ t.ttl==="1h"?"1h":"5m"}function va(e){let t=[],n=(r,o)=>{let i=Od(o),s={clave:Ud(o),tipo:r,marca:Vd(o),bytes:i,bytesV1:i,clase:"otro",esError:false};if(r.endsWith(":tool_result")&&o&&typeof o=="object"){
455
+ let a=o;s.esError=a.is_error===true;let c=Ld(a.content);s.clase=$d(c);let l=i-Buffer.byteLength(c);s.bytesV1=Math.min(i,Math.max(0,l)+Nd(c,s.clase));}t.push(s);};if(Array.isArray(e.tools))for(let r of e.tools)
424
456
  n("tools",r);if(Array.isArray(e.system))for(let r of e.system)n("system",r);else (e.system??void 0)!==void 0&&n("system",e.system);for(let r of Array.isArray(e.messages)?e.messages:[]){if(!r||typeof r!=
425
457
  "object"){n("?:invalido",r);continue}let o=r,i=typeof o.role=="string"?o.role:"?";if(typeof o.content=="string")n(`${i}:text`,o.content);else if(Array.isArray(o.content))for(let s of o.content)n(`${i}\
426
- :${s?.type??"?"}`,s);}return t}function rd(){return {nacimiento:new Map,turno:0,elididosV2m:new Set}}function od(e,t){let n=e.turno++;for(let r of t)e.nacimiento.has(r.clave)||e.nacimiento.set(r.clave,n);
427
- return n}function ca(e,t,n,r,o=Wu){let i=t.reduce((u,p,f)=>p.tipo.endsWith(":tool_result")?f:u,-1),s=(u,p)=>u.tipo.endsWith(":tool_result")&&u.bytes>=qu&&p!==i;return t.map((u,p)=>{if(!s(u,
428
- p))return {clave:u.clave,bytes:u.bytes};let f=r-(n.nacimiento.get(u.clave)??r);return f>=2&&f*u.bytes/1024>=Hu?{clave:`${u.clave}:e`,bytes:cn}:{clave:u.clave,bytes:u.bytes}});}function id(e,t){let n=Te(e,t);return n?{inputPer1k:n.inputPer1k,lecturaPer1k:n.cachedInputPer1k??n.inputPer1k,escrituraPer1k:n.inputPer1k*
429
- Se(e),escritura1hPer1k:n.inputPer1k*An(e)}:null}function ra(){return {lecturaUsd:0,escrituraUsd:0,entradaUsd:0,totalUsd:0,tokensLeidos:0,tokensEscritos:0,tokensEntrada:0,tokensInvalidados:0,invalidacionUsd:0}}
430
- var Ao={"1h":36e5,"5m":3e5},sd=20,ad=6e3,cd=2e4,Mt=class{constructor(t=cd){this.tope=t;}tope;entradas=new Map;get size(){return this.entradas.size}viva(t,n){let r=this.entradas.get(t);return r&&n<=r.expira?
431
- r:null}escribir(t,n,r){this.entradas.delete(t),this.entradas.set(t,{expira:n+Ao[r],ttl:r}),this.entradas.size>this.tope&&this.podar(n);}refrescar(t,n){let r=this.entradas.get(t);r&&(this.entradas.delete(
432
- t),this.entradas.set(t,{expira:n+Ao[r.ttl],ttl:r.ttl}));}podar(t){for(let[n,r]of this.entradas)t>r.expira&&this.entradas.delete(n);for(;this.entradas.size>this.tope;){let n=this.entradas.keys().next().
433
- value;if(n===void 0)break;this.entradas.delete(n);}}};function ld(e,t){let n=new Array(t.length),r=createHash("sha256").update(`model:${e}`).digest("hex");for(let o=0;o<t.length;o++)r=createHash("sha256").update(r).update(
434
- "|").update(t[o]).digest("hex").slice(0,32),n[o]=r;return n}function ud(e){let t=new Array(e.length),n=-1,r="";for(let o=0;o<e.length;o++){let i=e[o],s=i.endsWith(":tool_use")||i.endsWith(":tool_resul\
435
- t");s&&i===r||(n+=1),r=s?i:"",t[o]=n;}return t}function oa(e,t){return e.endsWith(":image")?Math.min(t,ad):t}var ln=class{constructor(t,n){this.transformar=t;this.cache=n??new Mt;}transformar;estado=rd();cache;previo=[];previoUltimoBp=-1;previoTtl="\
436
- 5m";hayPrevio=false;atPrevio=0;acumulado=ra();paso(t){let n=ra(),r=od(this.estado,t.bloques),o=id(t.model,t.at),i=this.transformar(t.bloques,this.estado,r);if(!o||t.entradaReal<=0||i.length===0)return this.
437
- previo=i,this.previoUltimoBp=-1,this.previoTtl="5m",this.hayPrevio=true,this.atPrevio=t.at,n;let s=i.map((y,A)=>t.bloques[A]?.tipo??""),a=i.map((y,A)=>t.bloques[A]?.marca??null),c=t.bloques.reduce((y,A)=>y+
438
- oa(A.tipo,A.bytes),0),l=c>0?t.entradaReal/c:0,d=i.map((y,A)=>oa(s[A],y.bytes)*l),u=ld(t.model,i.map(y=>y.clave)),p=ud(s),f=a.map((y,A)=>y?A:-1).filter(y=>y>=0);if(f.length===0){for(let y=0;y<i.length;y++)
458
+ :${s?.type??"?"}`,s);}return t}function Fd(){return {nacimiento:new Map,turno:0,elididosV2m:new Set}}function qd(e,t){let n=e.turno++;for(let r of t)e.nacimiento.has(r.clave)||e.nacimiento.set(r.clave,n);
459
+ return n}function ya(e,t,n,r,o=Pd){let i=t.reduce((u,p,f)=>p.tipo.endsWith(":tool_result")?f:u,-1),s=(u,p)=>u.tipo.endsWith(":tool_result")&&u.bytes>=Rd&&p!==i;return t.map((u,p)=>{if(!s(u,
460
+ p))return {clave:u.clave,bytes:u.bytes};let f=r-(n.nacimiento.get(u.clave)??r);return f>=2&&f*u.bytes/1024>=Id?{clave:`${u.clave}:e`,bytes:pn}:{clave:u.clave,bytes:u.bytes}});}function zd(e,t){let n=Ae(e,t);return n?{inputPer1k:n.inputPer1k,lecturaPer1k:n.cachedInputPer1k??n.inputPer1k,escrituraPer1k:n.inputPer1k*
461
+ _e(e),escritura1hPer1k:n.inputPer1k*Dn(e)}:null}function ma(){return {lecturaUsd:0,escrituraUsd:0,entradaUsd:0,totalUsd:0,tokensLeidos:0,tokensEscritos:0,tokensEntrada:0,tokensInvalidados:0,invalidacionUsd:0}}
462
+ var Lo={"1h":36e5,"5m":3e5},Hd=20,Wd=6e3,Kd=2e4,Bt=class{constructor(t=Kd){this.tope=t;}tope;entradas=new Map;get size(){return this.entradas.size}viva(t,n){let r=this.entradas.get(t);return r&&n<=r.expira?
463
+ r:null}escribir(t,n,r){this.entradas.delete(t),this.entradas.set(t,{expira:n+Lo[r],ttl:r}),this.entradas.size>this.tope&&this.podar(n);}refrescar(t,n){let r=this.entradas.get(t);r&&(this.entradas.delete(
464
+ t),this.entradas.set(t,{expira:n+Lo[r.ttl],ttl:r.ttl}));}podar(t){for(let[n,r]of this.entradas)t>r.expira&&this.entradas.delete(n);for(;this.entradas.size>this.tope;){let n=this.entradas.keys().next().
465
+ value;if(n===void 0)break;this.entradas.delete(n);}}};function Gd(e,t){let n=new Array(t.length),r=createHash("sha256").update(`model:${e}`).digest("hex");for(let o=0;o<t.length;o++)r=createHash("sha256").update(r).update(
466
+ "|").update(t[o]).digest("hex").slice(0,32),n[o]=r;return n}function Jd(e){let t=new Array(e.length),n=-1,r="";for(let o=0;o<e.length;o++){let i=e[o],s=i.endsWith(":tool_use")||i.endsWith(":tool_resul\
467
+ t");s&&i===r||(n+=1),r=s?i:"",t[o]=n;}return t}function ha(e,t){return e.endsWith(":image")?Math.min(t,Wd):t}var fn=class{constructor(t,n){this.transformar=t;this.cache=n??new Bt;}transformar;estado=Fd();cache;previo=[];previoUltimoBp=-1;previoTtl="\
468
+ 5m";hayPrevio=false;atPrevio=0;acumulado=ma();paso(t){let n=ma(),r=qd(this.estado,t.bloques),o=zd(t.model,t.at),i=this.transformar(t.bloques,this.estado,r);if(!o||t.entradaReal<=0||i.length===0)return this.
469
+ previo=i,this.previoUltimoBp=-1,this.previoTtl="5m",this.hayPrevio=true,this.atPrevio=t.at,n;let s=i.map((y,R)=>t.bloques[R]?.tipo??""),a=i.map((y,R)=>t.bloques[R]?.marca??null),c=t.bloques.reduce((y,R)=>y+
470
+ ha(R.tipo,R.bytes),0),l=c>0?t.entradaReal/c:0,d=i.map((y,R)=>ha(s[R],y.bytes)*l),u=Gd(t.model,i.map(y=>y.clave)),p=Jd(s),f=a.map((y,R)=>y?R:-1).filter(y=>y>=0);if(f.length===0){for(let y=0;y<i.length;y++)
439
471
  n.tokensEntrada+=d[y],n.entradaUsd+=d[y]/1e3*o.inputPer1k;return n.totalUsd=n.entradaUsd,this.previo=i,this.previoUltimoBp=-1,this.previoTtl="5m",this.hayPrevio=true,this.atPrevio=t.at,this.acumulado.tokensEntrada+=
440
- n.tokensEntrada,this.acumulado.entradaUsd+=n.entradaUsd,this.acumulado.totalUsd+=n.totalUsd,n}let g=-1;for(let y of f){let A=p[y]-(sd-1);for(let R=y;R>=0&&p[R]>=A;R--)if(this.cache.viva(u[R],t.at)){R>
441
- g&&(g=R);break}}for(let y=0;y<=g;y++)this.cache.refrescar(u[y],t.at);let b=f[f.length-1];for(let y of f)y>g&&this.cache.escribir(u[y],t.at,a[y]);let h=0,k=this.hayPrevio&&t.at-this.atPrevio>Ao[this.previoTtl]?
442
- []:this.previo.slice(g+1,this.previoUltimoBp+1),x=0;for(let y=0;y<i.length;y++){let A=i[y],R=d[y];if(y<=g){n.tokensLeidos+=R,n.lecturaUsd+=R/1e3*o.lecturaPer1k;continue}if(y>b){n.tokensEntrada+=R,n.entradaUsd+=
443
- R/1e3*o.inputPer1k;continue}for(;f[h]<y;)h+=1;let I=a[f[h]]==="1h"?o.escritura1hPer1k:o.escrituraPer1k;n.tokensEscritos+=R,n.escrituraUsd+=R/1e3*I;let D=x;for(;D<k.length&&k[D].clave!==A.clave;)D+=1;D<
444
- k.length&&(k[D].bytes===A.bytes&&(n.tokensInvalidados+=R,n.invalidacionUsd+=R/1e3*(I-o.lecturaPer1k)),x=D+1);}return this.previo=i,this.previoUltimoBp=b,this.previoTtl=a[b]??"5m",this.hayPrevio=true,this.
472
+ n.tokensEntrada,this.acumulado.entradaUsd+=n.entradaUsd,this.acumulado.totalUsd+=n.totalUsd,n}let g=-1;for(let y of f){let R=p[y]-(Hd-1);for(let P=y;P>=0&&p[P]>=R;P--)if(this.cache.viva(u[P],t.at)){P>
473
+ g&&(g=P);break}}for(let y=0;y<=g;y++)this.cache.refrescar(u[y],t.at);let b=f[f.length-1];for(let y of f)y>g&&this.cache.escribir(u[y],t.at,a[y]);let h=0,k=this.hayPrevio&&t.at-this.atPrevio>Lo[this.previoTtl]?
474
+ []:this.previo.slice(g+1,this.previoUltimoBp+1),x=0;for(let y=0;y<i.length;y++){let R=i[y],P=d[y];if(y<=g){n.tokensLeidos+=P,n.lecturaUsd+=P/1e3*o.lecturaPer1k;continue}if(y>b){n.tokensEntrada+=P,n.entradaUsd+=
475
+ P/1e3*o.inputPer1k;continue}for(;f[h]<y;)h+=1;let D=a[f[h]]==="1h"?o.escritura1hPer1k:o.escrituraPer1k;n.tokensEscritos+=P,n.escrituraUsd+=P/1e3*D;let L=x;for(;L<k.length&&k[L].clave!==R.clave;)L+=1;L<
476
+ k.length&&(k[L].bytes===R.bytes&&(n.tokensInvalidados+=P,n.invalidacionUsd+=P/1e3*(D-o.lecturaPer1k)),x=L+1);}return this.previo=i,this.previoUltimoBp=b,this.previoTtl=a[b]??"5m",this.hayPrevio=true,this.
445
477
  atPrevio=t.at,n.totalUsd=n.lecturaUsd+n.escrituraUsd+n.entradaUsd,this.acumulado.lecturaUsd+=n.lecturaUsd,this.acumulado.escrituraUsd+=n.escrituraUsd,this.acumulado.entradaUsd+=n.entradaUsd,this.acumulado.
446
478
  totalUsd+=n.totalUsd,this.acumulado.tokensLeidos+=n.tokensLeidos,this.acumulado.tokensEscritos+=n.tokensEscritos,this.acumulado.tokensEntrada+=n.tokensEntrada,this.acumulado.tokensInvalidados+=n.tokensInvalidados,
447
- this.acumulado.invalidacionUsd+=n.invalidacionUsd,n}};function la(e){return e.map(t=>({clave:t.clave,bytes:t.bytes}))}var pd=64,ar=class{cadenas=new Map;cachesPorModelo=new Map;observar(t){let n=t.uso.cache_creation_input_tokens??(t.uso.cache_creation?.ephemeral_5m_input_tokens??0)+(t.uso.cache_creation?.ephemeral_1h_input_tokens??
448
- 0),r=(t.uso.input_tokens??0)+(t.uso.cache_read_input_tokens??0)+n;if(r<=0)return null;let o={bloques:aa(t.cuerpo),at:t.at,model:t.model,entradaReal:r,escritura1h:(t.uso.cache_creation?.ephemeral_1h_input_tokens??
479
+ this.acumulado.invalidacionUsd+=n.invalidacionUsd,n}};function ka(e){return e.map(t=>({clave:t.clave,bytes:t.bytes}))}var Zd=64,dr=class{cadenas=new Map;cachesPorModelo=new Map;observar(t){let n=t.uso.cache_creation_input_tokens??(t.uso.cache_creation?.ephemeral_5m_input_tokens??0)+(t.uso.cache_creation?.ephemeral_1h_input_tokens??
480
+ 0),r=(t.uso.input_tokens??0)+(t.uso.cache_read_input_tokens??0)+n;if(r<=0)return null;let o={bloques:va(t.cuerpo),at:t.at,model:t.model,entradaReal:r,escritura1h:(t.uso.cache_creation?.ephemeral_1h_input_tokens??
449
481
  0)>0};if(o.bloques.length===0)return null;let i=this.cadenaPara(this.clave(t),t.model),s=i.base.paso(o),a=i.v0.paso(o);return s.totalUsd<=0&&a.totalUsd<=0?null:{baselineUsd:s.totalUsd,politicaUsd:a.totalUsd}}clave(t){
450
482
  if(t.sessionId)return `s:${t.sessionId}\xB7a:${t.agentId??""}\xB7${t.model}`;let n=Array.isArray(t.cuerpo.messages)?t.cuerpo.messages[0]:void 0;return `m:${createHash("sha256").update(JSON.stringify(n??null)).digest(
451
- "hex").slice(0,16)}\xB7${t.model}`}cachesDe(t){let n=this.cachesPorModelo.get(t);return n||(n={base:new Mt,v0:new Mt},this.cachesPorModelo.set(t,n)),n}cadenaPara(t,n){let r=this.cadenas.get(t);if(!r){
452
- let o=this.cachesDe(n);if(r={base:new ln(i=>la(i),o.base),v0:new ln((i,s,a)=>ca("v0",i,s,a),o.v0),ultimoUso:0},this.cadenas.set(t,r),this.cadenas.size>pd){let i=null,s=1/0;for(let[a,c]of this.cadenas)
453
- c.ultimoUso<s&&(s=c.ultimoUso,i=a);i!==null&&this.cadenas.delete(i);}}return r.ultimoUso=Date.now(),r}};var fd="[gateway] entitlements: BIVELIO_SERVICE_KEY is no longer recognised (HTTP 401): savings features disabled and usage is not being reported; create a new key at https://savings.bivelio.com/dashb\
454
- oard/install and relaunch",cr=class{url;clave;ttlMs;fetchImpl;log;features=new Set;razonDeBloqueo=null;validoHasta=0;enVuelo=null;avisado=false;constructor(t){this.url=t.url,this.clave=t.serviceAccountKey,
483
+ "hex").slice(0,16)}\xB7${t.model}`}cachesDe(t){let n=this.cachesPorModelo.get(t);return n||(n={base:new Bt,v0:new Bt},this.cachesPorModelo.set(t,n)),n}cadenaPara(t,n){let r=this.cadenas.get(t);if(!r){
484
+ let o=this.cachesDe(n);if(r={base:new fn(i=>ka(i),o.base),v0:new fn((i,s,a)=>ya("v0",i,s,a),o.v0),ultimoUso:0},this.cadenas.set(t,r),this.cadenas.size>Zd){let i=null,s=1/0;for(let[a,c]of this.cadenas)
485
+ c.ultimoUso<s&&(s=c.ultimoUso,i=a);i!==null&&this.cadenas.delete(i);}}return r.ultimoUso=Date.now(),r}};var Xd="[gateway] entitlements: BIVELIO_SERVICE_KEY is no longer recognised (HTTP 401): savings features disabled and usage is not being reported; create a new key at https://savings.bivelio.com/dashb\
486
+ oard/install and relaunch",pr=class{url;clave;ttlMs;fetchImpl;log;features=new Set;razonDeBloqueo=null;validoHasta=0;enVuelo=null;avisado=false;constructor(t){this.url=t.url,this.clave=t.serviceAccountKey,
455
487
  this.ttlMs=t.ttlMs??3e5,this.fetchImpl=t.fetchImpl??fetch,this.log=t.log??(()=>{}),this.refrescar();}tiene(t){return this.refrescarSiVencio(),this.features.has(t)}blockReason(){return this.refrescarSiVencio(),
456
488
  this.razonDeBloqueo}refrescar(){return this.enVuelo?this.enVuelo:(this.enVuelo=this.pedir().finally(()=>{this.enVuelo=null;}),this.enVuelo)}refrescarSiVencio(){Date.now()>this.validoHasta&&this.enVuelo===
457
489
  null&&this.refrescar();}async pedir(){try{let t=await this.fetchImpl(this.url,{method:"GET",headers:{authorization:`Bearer ${this.clave}`},signal:AbortSignal.timeout(1e4)});if(t.status===401){this.cerrar(
458
- "entitlements HTTP 401",fd);return}if(!t.ok){this.cerrar(`entitlements HTTP ${t.status}`);return}let n=await t.json();if(!Array.isArray(n.features)||!n.features.every(o=>typeof o=="string")){this.cerrar(
490
+ "entitlements HTTP 401",Xd);return}if(!t.ok){this.cerrar(`entitlements HTTP ${t.status}`);return}let n=await t.json();if(!Array.isArray(n.features)||!n.features.every(o=>typeof o=="string")){this.cerrar(
459
491
  "entitlements response has an unexpected shape");return}this.features=new Set(n.features),this.razonDeBloqueo=typeof n.reason=="string"&&n.reason.trim()!==""?n.reason.trim():null;let r=typeof n.refreshAfterSeconds==
460
492
  "number"&&n.refreshAfterSeconds>0?Math.min(n.refreshAfterSeconds*1e3,this.ttlMs):this.ttlMs;this.validoHasta=Date.now()+r,this.avisado=!1;}catch(t){this.cerrar(String(t));}}cerrar(t,n){this.features=new Set,
461
493
  this.validoHasta=Date.now()+Math.min(6e4,this.ttlMs),this.avisado||(this.avisado=true,this.log(n??`[gateway] entitlements unavailable (${t}) \u2014 savings features disabled (fail-closed); traffic keeps flow\
462
- ing`));}};var Io="https://savings.bivelio.com",fe="https://savings.bivelio.com/dashboard/account",gt="https://savings.bivelio.com/dashboard/install",md=1e4,hd=3e3,da=6e4,gd=36e5,bd=7*86400,vd=3e4,yd=86400,kd="B\
463
- VL";function Po(e){return mt}function xd(e){return vo(e)?Object.keys(e.keys??{}).length===0:e.trim()===""}var Ro=e=>typeof e=="string"&&e.trim()!=="",lr=e=>typeof e=="number"&&Number.
464
- isFinite(e);function wd(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let t=e;return Ro(t.jti)&&Ro(t.org_id)&&Ro(t.plan)&&lr(t.seats)&&lr(t.issued_at)&&lr(t.expires_at)&&lr(t.grace_days)&&
465
- t.grace_days>=0&&Array.isArray(t.features)&&t.features.every(n=>typeof n=="string")}function dr(e,t){try{let n=Rt(typeof e=="string"?e:""),r=rn(n);if(r==="empty")return {ok:!1,shape:"empty",reason:"emp\
466
- ty"};if(r==="malformed")return {ok:!1,shape:"malformed",reason:"malformed"};let o=on(n,t);if(!o.ok||!o.payloadBytes)return {ok:!1,shape:"token",reason:dn(o.reason??"bad signature")};let i=o.header?.typ;
467
- if(i!==kd)return {ok:!1,shape:"token",reason:`not a license token (typ ${dn(String(i??"none"))})`};let s;try{s=JSON.parse(new TextDecoder().decode(o.payloadBytes));}catch{return {ok:!1,shape:"token",reason:"\
468
- payload is not valid JSON"}}return wd(s)?{ok:!0,license:{token:n,payload:s}}:{ok:!1,shape:"token",reason:"license payload has the wrong field types"}}catch(n){return {ok:false,shape:"token",reason:`verifi\
469
- cation error: ${dn(String(n))}`}}}function $t(e,t,n){return er(e,Math.floor(t/1e3),n)}var Nt=e=>e==="active"||e==="grace";function dn(e,t=200){let n=e.replace(/[^\x20-\x7E]/g,"?");return n.length>t?`${n.
470
- slice(0,t)}...`:n}function Sd(e){return `${Number((e/1e3).toFixed(3))} s`}function Ed(e){let t=e,n=typeof t?.message=="string"&&t.message!==""?t.message:String(e),r=t?.cause,o=r&&typeof r.code=="string"?
471
- r.code:r&&typeof r.message=="string"?r.message:void 0;return o?`${n} (${o})`:n}async function pa(e){let t=`${e.licenseServerUrl.replace(/\/+$/,"")}/api/license/current`,n=c=>e.serviceAccountKey?c.split(
494
+ ing`));}};var $o="https://savings.bivelio.com",he="https://savings.bivelio.com/dashboard/account",yt="https://savings.bivelio.com/dashboard/install",Qd=1e4,ep=3e3,wa=6e4,tp=36e5,np=7*86400,rp=3e4,op=86400,ip="B\
495
+ VL";function No(e){return bt}function sp(e){return wo(e)?Object.keys(e.keys??{}).length===0:e.trim()===""}var Mo=e=>typeof e=="string"&&e.trim()!=="",fr=e=>typeof e=="number"&&Number.
496
+ isFinite(e);function ap(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let t=e;return Mo(t.jti)&&Mo(t.org_id)&&Mo(t.plan)&&fr(t.seats)&&fr(t.issued_at)&&fr(t.expires_at)&&fr(t.grace_days)&&
497
+ t.grace_days>=0&&Array.isArray(t.features)&&t.features.every(n=>typeof n=="string")}function hr(e,t){try{let n=Dt(typeof e=="string"?e:""),r=an(n);if(r==="empty")return {ok:!1,shape:"empty",reason:"emp\
498
+ ty"};if(r==="malformed")return {ok:!1,shape:"malformed",reason:"malformed"};let o=cn(n,t);if(!o.ok||!o.payloadBytes)return {ok:!1,shape:"token",reason:hn(o.reason??"bad signature")};let i=o.header?.typ;
499
+ if(i!==ip)return {ok:!1,shape:"token",reason:`not a license token (typ ${hn(String(i??"none"))})`};let s;try{s=JSON.parse(new TextDecoder().decode(o.payloadBytes));}catch{return {ok:!1,shape:"token",reason:"\
500
+ payload is not valid JSON"}}return ap(s)?{ok:!0,license:{token:n,payload:s}}:{ok:!1,shape:"token",reason:"license payload has the wrong field types"}}catch(n){return {ok:false,shape:"token",reason:`verifi\
501
+ cation error: ${hn(String(n))}`}}}function Ut(e,t,n){return or(e,Math.floor(t/1e3),n)}var Vt=e=>e==="active"||e==="grace";function hn(e,t=200){let n=e.replace(/[^\x20-\x7E]/g,"?");return n.length>t?`${n.
502
+ slice(0,t)}...`:n}function cp(e){return `${Number((e/1e3).toFixed(3))} s`}function lp(e){let t=e,n=typeof t?.message=="string"&&t.message!==""?t.message:String(e),r=t?.cause,o=r&&typeof r.code=="string"?
503
+ r.code:r&&typeof r.message=="string"?r.message:void 0;return o?`${n} (${o})`:n}async function Sa(e){let t=`${e.licenseServerUrl.replace(/\/+$/,"")}/api/license/current`,n=c=>e.serviceAccountKey?c.split(
472
504
  e.serviceAccountKey).join("[service key]"):c,r=new AbortController,o=false,i=setTimeout(()=>{o=true,r.abort();},e.timeoutMs);i.unref?.();let s=()=>r.abort();e.signal&&(e.signal.aborted?r.abort():e.signal.addEventListener(
473
- "abort",s,{once:true}));let a=c=>o?{kind:"unreachable",cause:`timed out after ${Sd(e.timeoutMs)}`}:{kind:"unreachable",cause:dn(n(`network error: ${Ed(c)}`))};try{let c=e.fetchImpl??globalThis.fetch,l;try{
505
+ "abort",s,{once:true}));let a=c=>o?{kind:"unreachable",cause:`timed out after ${cp(e.timeoutMs)}`}:{kind:"unreachable",cause:hn(n(`network error: ${lp(c)}`))};try{let c=e.fetchImpl??globalThis.fetch,l;try{
474
506
  l=await c(t,{method:"GET",headers:{authorization:`Bearer ${e.serviceAccountKey}`,accept:"application/json"},signal:r.signal});}catch(f){return a(f)}if(l.status===401)return {kind:"key-unknown"};if(l.status===
475
507
  404)return {kind:"no-license"};if(!l.ok)return {kind:"unreachable",cause:`HTTP ${l.status}`};let d;try{d=await l.json();}catch(f){return o||r.signal.aborted?a(f):{kind:"unreachable",cause:"unexpected res\
476
- ponse (no license token)"}}let u=d?.token;if(typeof u!="string"||u.trim()==="")return {kind:"unreachable",cause:"unexpected response (no license token)"};let p=dr(u,e.publicKey);return p.ok?{kind:"toke\
477
- n",license:p.license}:{kind:"not-verifying",reason:dn(p.reason)}}catch(c){return a(c)}finally{clearTimeout(i),e.signal?.removeEventListener("abort",s);}}function Re(e){try{return new Date(e*1e3).toISOString().
478
- slice(0,10)}catch{return "an unknown date"}}var pn=(e,t)=>e+t*yd,_d="WARNING: BIVELIO_LICENSE_KEY belongs to a different organization than BIVELIO_SERVICE_KEY and is ignored; the license of the service\
479
- key's organization is used. Unset BIVELIO_LICENSE_KEY or replace it with this organization's license key.",Td=e=>`WARNING: the license served by savings.bivelio.com does not verify against this build\
480
- 's BiVelio key (${e}); starting with BIVELIO_LICENSE_KEY. Update @bivelio/savings-layer (npm i -g @bivelio/savings-layer).`;function Cd(e,t={}){switch(e){case "no-public-key":return "this build has no e\
508
+ ponse (no license token)"}}let u=d?.token;if(typeof u!="string"||u.trim()==="")return {kind:"unreachable",cause:"unexpected response (no license token)"};let p=hr(u,e.publicKey);return p.ok?{kind:"toke\
509
+ n",license:p.license}:{kind:"not-verifying",reason:hn(p.reason)}}catch(c){return a(c)}finally{clearTimeout(i),e.signal?.removeEventListener("abort",s);}}function Pe(e){try{return new Date(e*1e3).toISOString().
510
+ slice(0,10)}catch{return "an unknown date"}}var gn=(e,t)=>e+t*op,up="WARNING: BIVELIO_LICENSE_KEY belongs to a different organization than BIVELIO_SERVICE_KEY and is ignored; the license of the service\
511
+ key's organization is used. Unset BIVELIO_LICENSE_KEY or replace it with this organization's license key.",dp=e=>`WARNING: the license served by savings.bivelio.com does not verify against this build\
512
+ 's BiVelio key (${e}); starting with BIVELIO_LICENSE_KEY. Update @bivelio/savings-layer (npm i -g @bivelio/savings-layer).`;function pp(e,t={}){switch(e){case "no-public-key":return "this build has no e\
481
513
  mbedded BiVelio verification key (it is running from source): install the published package (npm i -g @bivelio/savings-layer) or run pnpm build first.";case "service-key-missing":return `BIVELIO_SERVICE\
482
- _KEY is not set. The gateway needs two things and does not start without them: an active BiVelio subscription (${fe}) and its service key (bvk_..., created at ${gt}, step 2). Export the key and relaun\
514
+ _KEY is not set. The gateway needs two things and does not start without them: an active BiVelio subscription (${he}) and its service key (bvk_..., created at ${yt}, step 2). Export the key and relaun\
483
515
  ch: the license is collected with it automatically.`;case "service-key-malformed":return "BIVELIO_SERVICE_KEY does not look like a service key (service keys start with bvk_)."+(t.keyLooksLikeLicense?" I\
484
- t looks like a license key: that one goes in BIVELIO_LICENSE_KEY.":"")+` Create a service key at ${gt} (step 2), export it and relaunch.`;case "service-key-not-recognised":return `BIVELIO_SERVICE_KEY is\
485
- not recognised by savings.bivelio.com (HTTP 401): it was deleted or rotated, or it was copied incompletely. Create a new one at ${gt} (step 2), export it and relaunch.`;case "no-license":return `your o\
486
- rganization has no active BiVelio license, and the gateway does not start without one: there is no free tier. Subscribe at ${fe} and relaunch; the license is collected automatically with your service \
487
- key.`;case "license-expired":{let n=t.expiresAt??0;return `your BiVelio license expired on ${Re(n)} and its grace period ended on ${Re(pn(n,t.graceDays??0))}. Renew at ${fe} and relaunch.`+(t.cause?` (s\
516
+ t looks like a license key: that one goes in BIVELIO_LICENSE_KEY.":"")+` Create a service key at ${yt} (step 2), export it and relaunch.`;case "service-key-not-recognised":return `BIVELIO_SERVICE_KEY is\
517
+ not recognised by savings.bivelio.com (HTTP 401): it was deleted or rotated, or it was copied incompletely. Create a new one at ${yt} (step 2), export it and relaunch.`;case "no-license":return `your o\
518
+ rganization has no active BiVelio license, and the gateway does not start without one: there is no free tier. Subscribe at ${he} and relaunch; the license is collected automatically with your service \
519
+ key.`;case "license-expired":{let n=t.expiresAt??0;return `your BiVelio license expired on ${Pe(n)} and its grace period ended on ${Pe(gn(n,t.graceDays??0))}. Renew at ${he} and relaunch.`+(t.cause?` (s\
488
520
  avings.bivelio.com could not be reached to look for a renewed license: ${t.cause})`:"")}case "license-invalid":{let n=t.reason??"bad signature";return t.tokenSource==="savings.bivelio.com"?`the license\
489
521
  served by savings.bivelio.com does not verify against this build's BiVelio key (${n}). Update @bivelio/savings-layer (npm i -g @bivelio/savings-layer); if it persists, write to support@bivelio.com.`:
490
522
  t.shape==="malformed"?`BIVELIO_LICENSE_KEY is not a license key: a license key has three dot-separated parts and several hundred characters. Did you paste the bvk_ service key by mistake? That one goe\
491
- s in BIVELIO_SERVICE_KEY; the license key is the other value on ${gt}. Or unset BIVELIO_LICENSE_KEY: the gateway collects the license online by itself.`:`BIVELIO_LICENSE_KEY does not verify against th\
492
- is build's BiVelio key (${n}). Copy the WHOLE key again from ${gt}, or unset BIVELIO_LICENSE_KEY to collect it online; if it persists, update @bivelio/savings-layer or write to support@bivelio.com.`}case "\
523
+ s in BIVELIO_SERVICE_KEY; the license key is the other value on ${yt}. Or unset BIVELIO_LICENSE_KEY: the gateway collects the license online by itself.`:`BIVELIO_LICENSE_KEY does not verify against th\
524
+ is build's BiVelio key (${n}). Copy the WHOLE key again from ${yt}, or unset BIVELIO_LICENSE_KEY to collect it online; if it persists, update @bivelio/savings-layer or write to support@bivelio.com.`}case "\
493
525
  unreachable":return `could not collect your license from savings.bivelio.com (${t.cause??"unknown cause"}). The gateway does not start without a verified license. Check your connection and relaunch. If\
494
- savings.bivelio.com is down, export BIVELIO_LICENSE_KEY=<your license key> (from ${gt}) as a fallback: it is verified on this machine and used only when savings.bivelio.com cannot be reached, and it \
495
- must be replaced by hand every billing period.`}}function ua(e,t,n,r){let o=e.plan.toUpperCase(),i=e.grace_days,s=Re(e.expires_at),a=t==="online"?"collected with your service key and verified on this \
496
- machine":r?`from BIVELIO_LICENSE_KEY, verified on this machine (savings.bivelio.com unreachable: ${r})`:"from BIVELIO_LICENSE_KEY, verified on this machine";if(n==="grace"){let c=Re(pn(e.expires_at,i));
497
- return `license: ${o}, IN GRACE: expired on ${s}, keeps working until ${c}. Renew at ${fe} (${a})`}return `license: ${o}, active until ${s} (+${i} ${i===1?"day":"days"} grace), ${a}`}var Me=(e,t)=>({ok:false,
498
- code:e,message:Cd(e,t)});async function fa(e){let t=e.now??Date.now,n=Po();if(xd(n))return Me("no-public-key");let r=e.serviceAccountKey?.trim();if(!r)return Me("service-key-missing");if(!r.
499
- startsWith("bvk_"))return Me("service-key-malformed",{keyLooksLikeLicense:rn(Rt(r))==="token"});let o=null;if(e.licenseKey!==void 0){let c=dr(e.licenseKey,n);if(c.ok)o=c.license;else if(c.shape!=="emp\
500
- ty")return Me("license-invalid",{tokenSource:"BIVELIO_LICENSE_KEY",shape:c.shape,reason:c.reason})}let i=o!==null&&Nt($t(o.payload,t())),s=await pa({licenseServerUrl:e.licenseServerUrl,serviceAccountKey:r,
501
- publicKey:n,timeoutMs:e.timeoutMs??(i?hd:md),...e.fetchImpl?{fetchImpl:e.fetchImpl}:{}}),a=(c,l)=>{let d=$t(o.payload,t());return Nt(d)?{ok:true,license:o,source:"offline",status:d,line:ua(o.payload,"of\
502
- fline",d,c),lineIsWarning:true,warnings:l}:Me("license-expired",{expiresAt:o.payload.expires_at,graceDays:o.payload.grace_days,...c?{cause:c}:{}})};switch(s.kind){case "key-unknown":return Me("service-ke\
503
- y-not-recognised");case "no-license":return Me("no-license");case "token":{let c=s.license,l=$t(c.payload,t()),d=o&&o.payload.org_id!==c.payload.org_id?[_d]:[];return Nt(l)?{ok:true,license:c,source:"onli\
504
- ne",status:l,line:ua(c.payload,"online",l),lineIsWarning:l==="grace",warnings:d}:Me("license-expired",{expiresAt:c.payload.expires_at,graceDays:c.payload.grace_days})}case "not-verifying":return i?a(void 0,
505
- [Td(s.reason)]):Me("license-invalid",{tokenSource:"savings.bivelio.com",reason:s.reason});case "unreachable":return o?a(s.cause,[]):Me("unreachable",{cause:s.cause})}}var Ad=new Set(["expired","revoked",
506
- "no-license","blocked","invalid"]);function Do(e,t,n){let r=typeof t=="string"?t.trim():"";if(r!==""){let i="reported by savings.bivelio.com";return r==="license-revoked"?{serve:false,state:"revoked",detail:i}:
526
+ savings.bivelio.com is down, export BIVELIO_LICENSE_KEY=<your license key> (from ${yt}) as a fallback: it is verified on this machine and used only when savings.bivelio.com cannot be reached, and it \
527
+ must be replaced by hand every billing period.`}}function xa(e,t,n,r){let o=e.plan.toUpperCase(),i=e.grace_days,s=Pe(e.expires_at),a=t==="online"?"collected with your service key and verified on this \
528
+ machine":r?`from BIVELIO_LICENSE_KEY, verified on this machine (savings.bivelio.com unreachable: ${r})`:"from BIVELIO_LICENSE_KEY, verified on this machine";if(n==="grace"){let c=Pe(gn(e.expires_at,i));
529
+ return `license: ${o}, IN GRACE: expired on ${s}, keeps working until ${c}. Renew at ${he} (${a})`}return `license: ${o}, active until ${s} (+${i} ${i===1?"day":"days"} grace), ${a}`}var Ne=(e,t)=>({ok:false,
530
+ code:e,message:pp(e,t)});async function Ea(e){let t=e.now??Date.now,n=No();if(sp(n))return Ne("no-public-key");let r=e.serviceAccountKey?.trim();if(!r)return Ne("service-key-missing");if(!r.
531
+ startsWith("bvk_"))return Ne("service-key-malformed",{keyLooksLikeLicense:an(Dt(r))==="token"});let o=null;if(e.licenseKey!==void 0){let c=hr(e.licenseKey,n);if(c.ok)o=c.license;else if(c.shape!=="emp\
532
+ ty")return Ne("license-invalid",{tokenSource:"BIVELIO_LICENSE_KEY",shape:c.shape,reason:c.reason})}let i=o!==null&&Vt(Ut(o.payload,t())),s=await Sa({licenseServerUrl:e.licenseServerUrl,serviceAccountKey:r,
533
+ publicKey:n,timeoutMs:e.timeoutMs??(i?ep:Qd),...e.fetchImpl?{fetchImpl:e.fetchImpl}:{}}),a=(c,l)=>{let d=Ut(o.payload,t());return Vt(d)?{ok:true,license:o,source:"offline",status:d,line:xa(o.payload,"of\
534
+ fline",d,c),lineIsWarning:true,warnings:l}:Ne("license-expired",{expiresAt:o.payload.expires_at,graceDays:o.payload.grace_days,...c?{cause:c}:{}})};switch(s.kind){case "key-unknown":return Ne("service-ke\
535
+ y-not-recognised");case "no-license":return Ne("no-license");case "token":{let c=s.license,l=Ut(c.payload,t()),d=o&&o.payload.org_id!==c.payload.org_id?[up]:[];return Vt(l)?{ok:true,license:c,source:"onli\
536
+ ne",status:l,line:xa(c.payload,"online",l),lineIsWarning:l==="grace",warnings:d}:Ne("license-expired",{expiresAt:c.payload.expires_at,graceDays:c.payload.grace_days})}case "not-verifying":return i?a(void 0,
537
+ [dp(s.reason)]):Ne("license-invalid",{tokenSource:"savings.bivelio.com",reason:s.reason});case "unreachable":return o?a(s.cause,[]):Ne("unreachable",{cause:s.cause})}}var fp=new Set(["expired","revoked",
538
+ "no-license","blocked","invalid"]);function jo(e,t,n){let r=typeof t=="string"?t.trim():"";if(r!==""){let i="reported by savings.bivelio.com";return r==="license-revoked"?{serve:false,state:"revoked",detail:i}:
507
539
  r==="license-expired"?{serve:false,state:"expired",detail:i}:r==="no-license"?{serve:false,state:"no-license",detail:i}:{serve:false,state:"blocked",detail:i}}let o=e.status();return o==="active"||o==="grace"?
508
- {serve:true,state:o}:o==="expired"?{serve:false,state:"expired",detail:n?`grace period ended ${Re(pn(n.expires_at,n.grace_days))}`:"grace period ended"}:o==="revoked"?{serve:false,state:"revoked",detail:"lice\
509
- nse id revoked"}:{serve:false,state:"invalid",detail:"license no longer verifies"}}var un="requests already in flight were not interrupted";function Rd(e){switch(e){case "expired":return `bvsala gateway: t\
510
- he BiVelio license for this organization has expired. New requests are refused until it is renewed at ${fe}; ${un}.`;case "revoked":return `bvsala gateway: the BiVelio license for this organization is n\
511
- o longer active (revoked or cancelled). New requests are refused; ${un}. Check ${fe} or write to support@bivelio.com.`;case "no-license":return `bvsala gateway: this organization has no active BiVelio l\
512
- icense. New requests are refused until you subscribe at ${fe}; ${un}.`;case "blocked":return `bvsala gateway: savings.bivelio.com reports the BiVelio license for this organization as not active. New req\
513
- uests are refused; ${un}. Check ${fe}.`;case "invalid":return `bvsala gateway: the license loaded by this gateway no longer verifies. New requests are refused; ${un}. Relaunch the terminal; if it persis\
514
- ts, write to support@bivelio.com.`}}function ma(e){return JSON.stringify({type:"error",error:{type:"license_error",status:e,message:Rd(e)}})}var Id={expired:`Renew at ${fe}`,revoked:`Check ${fe} or wr\
515
- ite to support@bivelio.com`,"no-license":`Subscribe at ${fe}`,blocked:`Check ${fe}`,invalid:"Relaunch the terminal; if it persists, write to support@bivelio.com"};function ha(e,t,n){if(!t.serve)return e===
516
- t.state?null:`[bvsala gateway] license ${t.state} (${t.detail}): new requests are refused with HTTP 402; requests in flight are not touched. ${Id[t.state]}`;let r=Re(n.expires_at),o=Re(pn(n.expires_at,
517
- n.grace_days));return e!==null&&Ad.has(e)?t.state==="grace"?`[bvsala gateway] license in grace again (it expired on ${r} and keeps working until ${o}): serving new requests. Renew at ${fe}`:`[bvsala g\
518
- ateway] license ${t.state} again (expires ${r}): serving new requests`:t.state==="grace"&&e!=="grace"?`[bvsala gateway] license in grace: it expired on ${r} and keeps working until ${o}. Renew at ${fe}`:
519
- null}function Oo(e,t,n,r){return {license:e,gate:tr(e.token,t,{revocation:n,...r?{now:r}:{}})}}var ur=class{constructor(t){this.o=t;}o;timer=null;enVuelo=false;parado=false;ctrl=null;avisados=new Set;ahora(){
520
- return this.o.now?this.o.now():Date.now()}start(t={}){this.parado||this.timer!==null||(this.timer=setInterval(()=>{this.check();},this.o.intervalMs??gd),this.timer.unref?.(),t.checkNow&&this.check({force:true}));}stop(){
540
+ {serve:true,state:o}:o==="expired"?{serve:false,state:"expired",detail:n?`grace period ended ${Pe(gn(n.expires_at,n.grace_days))}`:"grace period ended"}:o==="revoked"?{serve:false,state:"revoked",detail:"lice\
541
+ nse id revoked"}:{serve:false,state:"invalid",detail:"license no longer verifies"}}var mn="requests already in flight were not interrupted";function mp(e){switch(e){case "expired":return `bvsala gateway: t\
542
+ he BiVelio license for this organization has expired. New requests are refused until it is renewed at ${he}; ${mn}.`;case "revoked":return `bvsala gateway: the BiVelio license for this organization is n\
543
+ o longer active (revoked or cancelled). New requests are refused; ${mn}. Check ${he} or write to support@bivelio.com.`;case "no-license":return `bvsala gateway: this organization has no active BiVelio l\
544
+ icense. New requests are refused until you subscribe at ${he}; ${mn}.`;case "blocked":return `bvsala gateway: savings.bivelio.com reports the BiVelio license for this organization as not active. New req\
545
+ uests are refused; ${mn}. Check ${he}.`;case "invalid":return `bvsala gateway: the license loaded by this gateway no longer verifies. New requests are refused; ${mn}. Relaunch the terminal; if it persis\
546
+ ts, write to support@bivelio.com.`}}function _a(e){return JSON.stringify({type:"error",error:{type:"license_error",status:e,message:mp(e)}})}var hp={expired:`Renew at ${he}`,revoked:`Check ${he} or wr\
547
+ ite to support@bivelio.com`,"no-license":`Subscribe at ${he}`,blocked:`Check ${he}`,invalid:"Relaunch the terminal; if it persists, write to support@bivelio.com"};function Ta(e,t,n){if(!t.serve)return e===
548
+ t.state?null:`[bvsala gateway] license ${t.state} (${t.detail}): new requests are refused with HTTP 402; requests in flight are not touched. ${hp[t.state]}`;let r=Pe(n.expires_at),o=Pe(gn(n.expires_at,
549
+ n.grace_days));return e!==null&&fp.has(e)?t.state==="grace"?`[bvsala gateway] license in grace again (it expired on ${r} and keeps working until ${o}): serving new requests. Renew at ${he}`:`[bvsala g\
550
+ ateway] license ${t.state} again (expires ${r}): serving new requests`:t.state==="grace"&&e!=="grace"?`[bvsala gateway] license in grace: it expired on ${r} and keeps working until ${o}. Renew at ${he}`:
551
+ null}function Bo(e,t,n,r){return {license:e,gate:ir(e.token,t,{revocation:n,...r?{now:r}:{}})}}var mr=class{constructor(t){this.o=t;}o;timer=null;enVuelo=false;parado=false;ctrl=null;avisados=new Set;ahora(){
552
+ return this.o.now?this.o.now():Date.now()}start(t={}){this.parado||this.timer!==null||(this.timer=setInterval(()=>{this.check();},this.o.intervalMs??tp),this.timer.unref?.(),t.checkNow&&this.check({force:true}));}stop(){
521
553
  this.parado=true,this.timer!==null&&(clearInterval(this.timer),this.timer=null),this.ctrl?.abort();}avisar(t,n){this.avisados.has(t)||(this.avisados.add(t),this.o.onWarning(n));}async check(t={}){if(this.
522
- enVuelo||this.parado)return false;let n=this.o.current(),r=Nt($t(n.payload,this.ahora(),this.o.revocation.snapshot())),o=n.payload.expires_at-Math.floor(this.ahora()/1e3);if(!t.force&&r&&o>(this.o.leadSeconds??
523
- bd))return false;this.enVuelo=true;let i=new AbortController;this.ctrl=i;try{let s=await pa({licenseServerUrl:this.o.licenseServerUrl,serviceAccountKey:this.o.serviceAccountKey,publicKey:this.o.publicKey,timeoutMs:this.
524
- o.timeoutMs??vd,signal:i.signal,...this.o.fetchImpl?{fetchImpl:this.o.fetchImpl}:{}});if(this.parado)return !1;let a=Re(pn(n.payload.expires_at,n.payload.grace_days));switch(s.kind){case "token":{let c=s.
525
- license.payload,l=this.o.revocation.snapshot();if(c.jti===n.payload.jti||this.o.revocation.has(c.jti)||!Nt($t(c,this.ahora(),l)))return !1;let d=Nt($t(n.payload,this.ahora(),l)),u=c.org_id!==n.payload.
554
+ enVuelo||this.parado)return false;let n=this.o.current(),r=Vt(Ut(n.payload,this.ahora(),this.o.revocation.snapshot())),o=n.payload.expires_at-Math.floor(this.ahora()/1e3);if(!t.force&&r&&o>(this.o.leadSeconds??
555
+ np))return false;this.enVuelo=true;let i=new AbortController;this.ctrl=i;try{let s=await Sa({licenseServerUrl:this.o.licenseServerUrl,serviceAccountKey:this.o.serviceAccountKey,publicKey:this.o.publicKey,timeoutMs:this.
556
+ o.timeoutMs??rp,signal:i.signal,...this.o.fetchImpl?{fetchImpl:this.o.fetchImpl}:{}});if(this.parado)return !1;let a=Pe(gn(n.payload.expires_at,n.payload.grace_days));switch(s.kind){case "token":{let c=s.
557
+ license.payload,l=this.o.revocation.snapshot();if(c.jti===n.payload.jti||this.o.revocation.has(c.jti)||!Vt(Ut(c,this.ahora(),l)))return !1;let d=Vt(Ut(n.payload,this.ahora(),l)),u=c.org_id!==n.payload.
526
558
  org_id,p=c.expires_at>n.payload.expires_at;return !u&&!p&&d?!1:(this.o.onAdopt(s.license),!0)}case "key-unknown":return this.avisar("key-unknown",`[bvsala gateway] license renewal: BIVELIO_SERVICE_KEY i\
527
- s no longer recognised (HTTP 401). This session keeps its current license until ${a}; create a new key at ${gt} and relaunch.`),!1;case "no-license":return this.avisar("no-license",`[bvsala gateway] li\
528
- cense renewal: savings.bivelio.com reports no active license for this organization (HTTP 404). This session keeps its current license until ${a}; subscribe or renew at ${fe}.`),!1;case "not-verifying":
559
+ s no longer recognised (HTTP 401). This session keeps its current license until ${a}; create a new key at ${yt} and relaunch.`),!1;case "no-license":return this.avisar("no-license",`[bvsala gateway] li\
560
+ cense renewal: savings.bivelio.com reports no active license for this organization (HTTP 404). This session keeps its current license until ${a}; subscribe or renew at ${he}.`),!1;case "not-verifying":
529
561
  return this.avisar(`not-verifying:${s.reason}`,`[bvsala gateway] license renewal: the license served by savings.bivelio.com does not verify against this build's BiVelio key (${s.reason}); update @bive\
530
- lio/savings-layer.`),!1;case "unreachable":return !1}return !1}catch{return false}finally{this.ctrl===i&&(this.ctrl=null),this.enVuelo=false;}}};function ga(e){let t=0,n=0;for(;;){let i=e.indexOf('"input_schema"',n);if(i<0)break;t+=1,n=i+14;}let r=0;for(n=0;;){let i=e.indexOf('"tool_reference"',n);if(i<0)break;r+=1,n=i+16;}let o=e.match(/"defer_loading"\s*:\s*true/g)?.
531
- length??0;return {definiciones:t,referencias:r,diferidas:o}}var Pd=40;function ba(e){return e.referencias>0||(e.diferidas??0)>0||e.definiciones<Pd?null:`[bvsala gateway] your client sends ${e.definiciones}\
562
+ lio/savings-layer.`),!1;case "unreachable":return !1}return !1}catch{return false}finally{this.ctrl===i&&(this.ctrl=null),this.enVuelo=false;}}};function Ca(e){let t=0,n=0;for(;;){let i=e.indexOf('"input_schema"',n);if(i<0)break;t+=1,n=i+14;}let r=0;for(n=0;;){let i=e.indexOf('"tool_reference"',n);if(i<0)break;r+=1,n=i+16;}let o=e.match(/"defer_loading"\s*:\s*true/g)?.
563
+ length??0;return {definiciones:t,referencias:r,diferidas:o}}var gp=40;function Aa(e){return e.referencias>0||(e.diferidas??0)>0||e.definiciones<gp?null:`[bvsala gateway] your client sends ${e.definiciones}\
532
564
  FULL tool definitions in every request and does not use tool search. With a proxy in front, Claude Code turns tool search off by default: \`bvsala claude\` turns it back on, but only in a NEW WINDOW. I\
533
- f you launched the terminal by hand, export ENABLE_TOOL_SEARCH=true. In our own corpus that block was 24.5% of input spend.`}var Lo=5*1024*1024,Od=["authorization","x-api-key","anthropic-version","anthropic-beta","api-key","openai-organization","openai-project"];function va(e,t,n,r=""){return createHash(
565
+ f you launched the terminal by hand, export ENABLE_TOOL_SEARCH=true. In our own corpus that block was 24.5% of input spend.`}var Uo=5*1024*1024,vp=["authorization","x-api-key","anthropic-version","anthropic-beta","api-key","openai-organization","openai-project"];function Ra(e,t,n,r=""){return createHash(
534
566
  "sha256").update(e).update(`
535
567
  `).update(t).update(`
536
568
  `).update(r).update(`
537
- `).update(n).digest("hex")}function ya(e){return Od.map(t=>`${t}=${e(t)??""}`).join(`
538
- `)}var pr=class{enVuelo=new Map;primarias=0;gemelas=0;registrar(t){if(this.enVuelo.has(t))return null;this.primarias+=1;let n,r=new Promise(a=>n=a);this.enVuelo.set(t,{promesa:r,resolver:n});let o=[],
539
- i=0,s=false;return {capturar:a=>{if(!s){if(i+=a.length,i>Lo){s=true,o.length=0;return}o.push(a);}},terminar:(a,c,l)=>{let d=!s&&a>=200&&a<300;this.enVuelo.get(t)?.resolver(d?{status:a,headers:c,chunks:o,...l?
569
+ `).update(n).digest("hex")}function Ia(e){return vp.map(t=>`${t}=${e(t)??""}`).join(`
570
+ `)}var gr=class{enVuelo=new Map;primarias=0;gemelas=0;registrar(t){if(this.enVuelo.has(t))return null;this.primarias+=1;let n,r=new Promise(a=>n=a);this.enVuelo.set(t,{promesa:r,resolver:n});let o=[],
571
+ i=0,s=false;return {capturar:a=>{if(!s){if(i+=a.length,i>Uo){s=true,o.length=0;return}o.push(a);}},terminar:(a,c,l)=>{let d=!s&&a>=200&&a<300;this.enVuelo.get(t)?.resolver(d?{status:a,headers:c,chunks:o,...l?
540
572
  {primaria:l}:{}}:null),this.enVuelo.delete(t);},abortar:()=>{this.enVuelo.get(t)?.resolver(null),this.enVuelo.delete(t);}}}async esperar(t){let n=this.enVuelo.get(t);if(!n)return null;let r=await n.promesa;
541
- return r&&(this.gemelas+=1),r}tieneEnVuelo(t){return this.enVuelo.has(t)}};var ka={openai:"https://api.openai.com",anthropic:"https://api.anthropic.com"};function xa(e){let t;try{t=new URL(e).origin;}catch{return false}return Object.values(ka).includes(t)}function wa(e){for(let t=0;t<
542
- e.length;t++){let n=e[t];if(n==="--upstream"){let r=e[t+1];return r!==void 0&&!r.startsWith("--")?r:null}if(n.startsWith("--upstream=")){let r=n.slice(11);return r.trim()!==""?r:null}}}function Ld(e){
543
- let t=e.trim();return /^(sk-|sk_|bvk_|rk_|pk_|key-)/i.test(t)||t.length>=32&&!/[\s:/.]/.test(t)?"(value hidden: it looks like a key)":`"${t.length>80?`${t.slice(0,80)}\u2026`:t}"`}function Sa(e){if(e.flag===
573
+ return r&&(this.gemelas+=1),r}tieneEnVuelo(t){return this.enVuelo.has(t)}};var Pa={openai:"https://api.openai.com",anthropic:"https://api.anthropic.com"};function Da(e){let t;try{t=new URL(e).origin;}catch{return false}return Object.values(Pa).includes(t)}function Oa(e){for(let t=0;t<
574
+ e.length;t++){let n=e[t];if(n==="--upstream"){let r=e[t+1];return r!==void 0&&!r.startsWith("--")?r:null}if(n.startsWith("--upstream=")){let r=n.slice(11);return r.trim()!==""?r:null}}}function yp(e){
575
+ let t=e.trim();return /^(sk-|sk_|bvk_|rk_|pk_|key-)/i.test(t)||t.length>=32&&!/[\s:/.]/.test(t)?"(value hidden: it looks like a key)":`"${t.length>80?`${t.slice(0,80)}\u2026`:t}"`}function La(e){if(e.flag===
544
576
  null)return {ok:false,error:"[bvsala gateway] --upstream needs a value: openai, anthropic or an origin URL such as https://api.openai.com"};let t,n;if(e.flag!==void 0)t=e.flag,n="flag";else if(e.env!==void 0&&
545
- e.env.trim()!=="")t=e.env,n="env";else return {ok:true,upstream:void 0,origen:"none"};let r=ka[t.trim().toLowerCase()];if(r!==void 0)return {ok:true,upstream:r,origen:n};let o={ok:false,error:`[bvsala gateway]\
546
- invalid upstream ${Ld(t)}: use openai, anthropic or an http(s) origin URL`},i;try{i=new URL(t.trim());}catch{return o}return i.protocol!=="http:"&&i.protocol!=="https:"?o:i.pathname!=="/"||i.search!==
577
+ e.env.trim()!=="")t=e.env,n="env";else return {ok:true,upstream:void 0,origen:"none"};let r=Pa[t.trim().toLowerCase()];if(r!==void 0)return {ok:true,upstream:r,origen:n};let o={ok:false,error:`[bvsala gateway]\
578
+ invalid upstream ${yp(t)}: use openai, anthropic or an http(s) origin URL`},i;try{i=new URL(t.trim());}catch{return o}return i.protocol!=="http:"&&i.protocol!=="https:"?o:i.pathname!=="/"||i.search!==
547
579
  ""||i.hash!==""?{ok:true,upstream:i.origin,origen:n,aviso:`[bvsala gateway] WARNING: the upstream path "${i.pathname}" is ignored: requests keep the path the client sends (for example /v1/chat/completio\
548
- ns), so put that prefix in the client's base URL instead.`}:{ok:true,upstream:i.origin,origen:n}}var Md="other reasons",fr=class{medidas=0;replicas=0;noMedidas=new Map;medida(){this.medidas++;}replica(){this.replicas++;}noMedida(t){let n=this.noMedidas.has(t)||this.noMedidas.size<50?t:Md;this.noMedidas.
549
- set(n,(this.noMedidas.get(n)??0)+1);}estado(){return {medidas:this.medidas,replicas:this.replicas,noMedidas:Object.fromEntries(this.noMedidas)}}};function Ea(e,t){let n=`[bvsala ${t}] metering in this r\
580
+ ns), so put that prefix in the client's base URL instead.`}:{ok:true,upstream:i.origin,origen:n}}var kp="other reasons",br=class{medidas=0;replicas=0;noMedidas=new Map;medida(){this.medidas++;}replica(){this.replicas++;}noMedida(t){let n=this.noMedidas.has(t)||this.noMedidas.size<50?t:kp;this.noMedidas.
581
+ set(n,(this.noMedidas.get(n)??0)+1);}estado(){return {medidas:this.medidas,replicas:this.replicas,noMedidas:Object.fromEntries(this.noMedidas)}}};function Ma(e,t){let n=`[bvsala ${t}] metering in this r\
550
582
  un:`,r=Object.entries(e.noMedidas).sort((a,c)=>c[1]-a[1]||a[0].localeCompare(c[0])),o=r.reduce((a,[,c])=>a+c,0);if(e.medidas===0&&e.replicas===0&&o===0)return `${n} no inference request went through th\
551
583
  e gateway. If the terminal did call a model, those calls went straight to the provider and were not metered: check its guide in docs/terminales/.`;let i=`${e.medidas} request(s) metered with the provi\
552
584
  der's usage`+(e.replicas>0?` \xB7 ${e.replicas} duplicate(s) answered with a replica, valued from the request that travelled`:"");if(o===0)return `${n} ${i}.`;let s=r.map(([a,c])=>`${c} \xD7 ${a}`).join(
553
- "; ");return `${n} ${i} \xB7 ${o} forwarded but NOT metered (nothing is estimated in their place): ${s}. What each reason means and what to do: docs/terminales/README.md.`}var fn="x-bvsala-report",$o="x-bvsala-request-id",$d="/_bvsala/",Nd="bvsala.gateway.report/1",_a="bvsala.gateway.status/1";var mr=/^[A-Za-z0-9._:-]{1,200}$/;function Ta(e){let t=(Array.isArray(e)?e[0]:e)?.trim().toLowerCase();return t==="1"||t==="true"}var hr=class{entradas=new Map;porRespuestaId=new Map;oyentes=new Set;capacidad;now;constructor(t={}){
585
+ "; ");return `${n} ${i} \xB7 ${o} forwarded but NOT metered (nothing is estimated in their place): ${s}. What each reason means and what to do: docs/terminales/README.md.`}var bn="x-bvsala-report",Fo="x-bvsala-request-id",xp="/_bvsala/",wp="bvsala.gateway.report/1",$a="bvsala.gateway.status/1";var vr=/^[A-Za-z0-9._:-]{1,200}$/;function Na(e){let t=(Array.isArray(e)?e[0]:e)?.trim().toLowerCase();return t==="1"||t==="true"}var yr=class{entradas=new Map;porRespuestaId=new Map;oyentes=new Set;capacidad;now;constructor(t={}){
554
586
  this.capacidad=Math.max(1,Math.floor(t.capacidad??1e3)),this.now=t.now??Date.now;}get tamano(){return this.entradas.size}get limite(){return this.capacidad}abrir(t,n){for(this.purgar();this.entradas.size>=
555
- this.capacidad;){let r=this.entradas.keys().next().value;if(r===void 0)break;this.quitar(r);}this.entradas.set(t,{informe:{schema:Nd,requestId:t,responseId:null,path:n,status:"pending",reason:null,report:null},
556
- abiertaMs:this.now()}),this.avisar();}anotarRespuesta(t,n){let r=this.entradas.get(t);!r||r.informe.responseId!==null||!n||!mr.test(n)||(r.informe.responseId=n,this.porRespuestaId.set(n,t),this.avisar());}medido(t,n){
587
+ this.capacidad;){let r=this.entradas.keys().next().value;if(r===void 0)break;this.quitar(r);}this.entradas.set(t,{informe:{schema:wp,requestId:t,responseId:null,path:n,status:"pending",reason:null,report:null},
588
+ abiertaMs:this.now()}),this.avisar();}anotarRespuesta(t,n){let r=this.entradas.get(t);!r||r.informe.responseId!==null||!n||!vr.test(n)||(r.informe.responseId=n,this.porRespuestaId.set(n,t),this.avisar());}medido(t,n){
557
589
  this.cerrar(t,"metered",null,n);}noMedido(t,n){this.cerrar(t,"not_metered",n,null);}porPeticion(t){return this.purgar(),this.entradas.get(t)?.informe}porRespuesta(t){this.purgar();let n=this.porRespuestaId.
558
590
  get(t);return n===void 0?void 0:this.entradas.get(n)?.informe}esperar(t,n,r){let o=s=>s!==void 0&&s.status!=="pending",i=t();return o(i)||n<=0||r?.aborted?Promise.resolve(i):new Promise(s=>{let a=false,c=()=>{
559
591
  a||(a=true,clearTimeout(d),this.oyentes.delete(l),r?.removeEventListener("abort",c),s(t()));},l=()=>{o(t())&&c();},d=setTimeout(c,Math.min(n,3e4));this.oyentes.add(l),r?.addEventListener("abort",c);})}cerrar(t,n,r,o){
560
592
  let i=this.entradas.get(t);!i||i.informe.status!=="pending"||(i.informe.status=n,i.informe.reason=r,i.informe.report=o===null?null:structuredClone(o),this.avisar());}quitar(t){let n=this.entradas.get(t);
561
593
  this.entradas.delete(t);let r=n?.informe.responseId;r&&this.porRespuestaId.get(r)===t&&this.porRespuestaId.delete(r);}purgar(){let t=this.now()-36e5;for(let[n,r]of this.entradas){if(r.abiertaMs>=t)break;
562
- this.quitar(n);}}avisar(){for(let t of [...this.oyentes])t();}};function Ca(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e;for(let n of [t.message?.id,t.response?.id,t.id])if(typeof n==
563
- "string"&&mr.test(n))return n;return null}function No(e){try{return Ca(JSON.parse(e.toString("utf8")))}catch{return null}}var gr=class{resto="";leidos=0;id=null;observar(t){if(this.id!==null||this.leidos>
594
+ this.quitar(n);}}avisar(){for(let t of [...this.oyentes])t();}};function ja(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e;for(let n of [t.message?.id,t.response?.id,t.id])if(typeof n==
595
+ "string"&&vr.test(n))return n;return null}function qo(e){try{return ja(JSON.parse(e.toString("utf8")))}catch{return null}}var kr=class{resto="";leidos=0;id=null;observar(t){if(this.id!==null||this.leidos>
564
596
  262144)return;let n=typeof t=="string"?t:t.toString("utf8");this.leidos+=n.length,this.resto+=n;let r;for(;(r=this.resto.indexOf(`
565
- `))>=0;){let o=this.resto.slice(0,r).replace(/\r$/,"");if(this.resto=this.resto.slice(r+1),!o.startsWith("data:"))continue;let i=o.slice(5).trim();if(!(i===""||i==="[DONE]"))try{let s=Ca(JSON.parse(i));
566
- if(s!==null){this.id=s,this.resto="";return}}catch{}}this.leidos>262144&&(this.resto="");}valor(){return this.id}};function Aa(e){try{return new URL(e).origin}catch{return "unknown"}}function Ra(e){let t;
567
- try{t=new URL(e??"/","http://127.0.0.1");}catch{return null}return t.pathname.startsWith($d)?t:null}var jd=new Set(["127.0.0.1","localhost","[::1]"]);function Bd(e){if(e===void 0||e==="")return true;let t;
568
- try{t=new URL(`http://${e}`).hostname.toLowerCase();}catch{return false}return jd.has(t)}function Mo(e,t,n){e.writeHead(t,{"content-type":"application/json","cache-control":"no-store"}),e.end(JSON.stringify(
569
- n));}function bt(e,t,n,r){Mo(e,t,{type:"error",error:{type:n,message:r}});}async function Ia(e,t,n,r){if(e.resume(),!Bd(e.headers.host)){bt(t,403,"forbidden","bvsala gateway: local routes answer only to\
570
- 127.0.0.1 or localhost");return}if(e.method!=="GET"){t.setHeader("allow","GET"),bt(t,405,"method_not_allowed","bvsala gateway: local routes only answer GET");return}if(n.pathname==="/_bvsala/v1/statu\
571
- s"){Mo(t,200,r.estado());return}let o=Number(n.searchParams.get("wait_ms")??"0");if(!Number.isFinite(o)||o<0){bt(t,400,"invalid_request","bvsala gateway: wait_ms must be a non-negative number of milli\
597
+ `))>=0;){let o=this.resto.slice(0,r).replace(/\r$/,"");if(this.resto=this.resto.slice(r+1),!o.startsWith("data:"))continue;let i=o.slice(5).trim();if(!(i===""||i==="[DONE]"))try{let s=ja(JSON.parse(i));
598
+ if(s!==null){this.id=s,this.resto="";return}}catch{}}this.leidos>262144&&(this.resto="");}valor(){return this.id}};function Ba(e){try{return new URL(e).origin}catch{return "unknown"}}function Ua(e){let t;
599
+ try{t=new URL(e??"/","http://127.0.0.1");}catch{return null}return t.pathname.startsWith(xp)?t:null}var Sp=new Set(["127.0.0.1","localhost","[::1]"]);function Ep(e){if(e===void 0||e==="")return true;let t;
600
+ try{t=new URL(`http://${e}`).hostname.toLowerCase();}catch{return false}return Sp.has(t)}function Vo(e,t,n){e.writeHead(t,{"content-type":"application/json","cache-control":"no-store"}),e.end(JSON.stringify(
601
+ n));}function kt(e,t,n,r){Vo(e,t,{type:"error",error:{type:n,message:r}});}async function Va(e,t,n,r){if(e.resume(),!Ep(e.headers.host)){kt(t,403,"forbidden","bvsala gateway: local routes answer only to\
602
+ 127.0.0.1 or localhost");return}if(e.method!=="GET"){t.setHeader("allow","GET"),kt(t,405,"method_not_allowed","bvsala gateway: local routes only answer GET");return}if(n.pathname==="/_bvsala/v1/statu\
603
+ s"){Vo(t,200,r.estado());return}let o=Number(n.searchParams.get("wait_ms")??"0");if(!Number.isFinite(o)||o<0){kt(t,400,"invalid_request","bvsala gateway: wait_ms must be a non-negative number of milli\
572
604
  seconds");return}let i=Math.min(Math.floor(o),3e4),s=new AbortController;t.on("close",()=>s.abort());let a=null,c="",l=/^\/_bvsala\/v1\/reports\/([^/]+)$/.exec(n.pathname);if(l){let u="";try{u=decodeURIComponent(
573
- l[1]);}catch{u="";}if(!mr.test(u)){bt(t,400,"invalid_request","bvsala gateway: malformed request id");return}a=()=>r.buzon.porPeticion(u),c=`request id ${u}`;}else if(n.pathname==="/_bvsala/v1/reports"){
574
- let u=n.searchParams.get("response_id")??"";if(!mr.test(u)){bt(t,400,"invalid_request","bvsala gateway: pass ?response_id=<the id of the provider's response>");return}a=()=>r.buzon.porRespuesta(u),c=`\
575
- response id ${u}`;}if(a===null){bt(t,404,"not_found",`bvsala gateway: no local route ${n.pathname}`);return}let d=await r.buzon.esperar(a,i,s.signal);if(!t.destroyed){if(d===void 0){bt(t,404,"not_found",
576
- `bvsala gateway: no report for ${c}. Reports exist only for requests sent with the header "${fn}: 1", while this gateway process keeps them (the last ${r.buzon.limite}, one hour at most).`);return}Mo(
577
- t,200,d);}}var Pa=4096;function Da(e){let t={marcas:0,de1h:0,deOtroTtl:0,enLaCola:false,herramientaDeServidor:false};return Nr(e,(n,r)=>{t.marcas++,n.ttl==="1h"?t.de1h++:t.deOtroTtl++,(r==="raiz"||r==="ultimoMensaje")&&
578
- (t.enLaCola=true);}),t.herramientaDeServidor=$r(e),t}function Oa(e){let t=e["x-claude-code-session-id"];if(typeof t=="string"?t!=="":Array.isArray(t)&&t.length>0)return true;let n=e["user-agent"];return typeof n==
579
- "string"&&n.startsWith("claude-cli/")}var La=e=>e.cache_creation_input_tokens??(e.cache_creation?.ephemeral_5m_input_tokens??0)+(e.cache_creation?.ephemeral_1h_input_tokens??0);function Ma(e){if((e.cache_read_input_tokens??
580
- 0)===0&&La(e)===0&&(e.input_tokens??0)>=Pa)return true;let n=e.cache_creation;return n!==void 0&&(n.ephemeral_5m_input_tokens??0)>0&&(n.ephemeral_1h_input_tokens??0)===0}function $a(e){let{vista:t,uso:n,
581
- ttlReescritoPorLaCapa:r}=e;if(t.marcas===0)return null;if((n.cache_read_input_tokens??0)===0&&La(n)===0&&t.enLaCola&&(n.input_tokens??0)>=Pa)return "cacheIgnorada";let i=n.cache_creation;return !r&&t.de1h>
582
- 0&&t.deOtroTtl===0&&!t.herramientaDeServidor&&i!==void 0&&(i.ephemeral_1h_input_tokens??0)===0&&(i.ephemeral_5m_input_tokens??0)>0?"ttlAcortado":null}function jo(e,t){let n=`[gateway] degraded traffic${t.
605
+ l[1]);}catch{u="";}if(!vr.test(u)){kt(t,400,"invalid_request","bvsala gateway: malformed request id");return}a=()=>r.buzon.porPeticion(u),c=`request id ${u}`;}else if(n.pathname==="/_bvsala/v1/reports"){
606
+ let u=n.searchParams.get("response_id")??"";if(!vr.test(u)){kt(t,400,"invalid_request","bvsala gateway: pass ?response_id=<the id of the provider's response>");return}a=()=>r.buzon.porRespuesta(u),c=`\
607
+ response id ${u}`;}if(a===null){kt(t,404,"not_found",`bvsala gateway: no local route ${n.pathname}`);return}let d=await r.buzon.esperar(a,i,s.signal);if(!t.destroyed){if(d===void 0){kt(t,404,"not_found",
608
+ `bvsala gateway: no report for ${c}. Reports exist only for requests sent with the header "${bn}: 1", while this gateway process keeps them (the last ${r.buzon.limite}, one hour at most).`);return}Vo(
609
+ t,200,d);}}var Fa=4096;function qa(e){let t={marcas:0,de1h:0,deOtroTtl:0,enLaCola:false,herramientaDeServidor:false};return Vr(e,(n,r)=>{t.marcas++,n.ttl==="1h"?t.de1h++:t.deOtroTtl++,(r==="raiz"||r==="ultimoMensaje")&&
610
+ (t.enLaCola=true);}),t.herramientaDeServidor=Ur(e),t}function za(e){let t=e["x-claude-code-session-id"];if(typeof t=="string"?t!=="":Array.isArray(t)&&t.length>0)return true;let n=e["user-agent"];return typeof n==
611
+ "string"&&n.startsWith("claude-cli/")}var Ha=e=>e.cache_creation_input_tokens??(e.cache_creation?.ephemeral_5m_input_tokens??0)+(e.cache_creation?.ephemeral_1h_input_tokens??0);function Wa(e){if((e.cache_read_input_tokens??
612
+ 0)===0&&Ha(e)===0&&(e.input_tokens??0)>=Fa)return true;let n=e.cache_creation;return n!==void 0&&(n.ephemeral_5m_input_tokens??0)>0&&(n.ephemeral_1h_input_tokens??0)===0}function Ka(e){let{vista:t,uso:n,
613
+ ttlReescritoPorLaCapa:r}=e;if(t.marcas===0)return null;if((n.cache_read_input_tokens??0)===0&&Ha(n)===0&&t.enLaCola&&(n.input_tokens??0)>=Fa)return "cacheIgnorada";let i=n.cache_creation;return !r&&t.de1h>
614
+ 0&&t.deOtroTtl===0&&!t.herramientaDeServidor&&i!==void 0&&(i.ephemeral_1h_input_tokens??0)===0&&(i.ephemeral_5m_input_tokens??0)>0?"ttlAcortado":null}function zo(e,t){let n=`[gateway] degraded traffic${t.
583
615
  sesion?` (session ${t.sesion})`:""} \xB7 `,r=" Logged once per session; further cases are counted, not logged.";return e==="cacheIgnorada"?n+`prompt caching: the request carried cache_control and the \
584
616
  provider counted ${t.entrada??0} input tokens, but reported no cache read and no cache write. The gateway forwards cache_control as the client sent it (the TTL lever only changes ttl), so look upstrea\
585
617
  m: another proxy in the chain, or an endpoint that ignores prompt caching.`+r:e==="ttlAcortado"?n+`cache TTL: every cache_control in the request asked for ttl "1h" and the provider wrote the cache at \
586
618
  the 5-minute TTL only (${t.escrita5m??0} tokens at 5m, none at 1h). The gateway did not change this request's ttl, so something upstream did (another proxy in the chain, or the endpoint). A 5-minute e\
587
619
  ntry expires between turns more than 5 minutes apart.`+r:n+`tool search: the client sent ${t.definiciones??0} full tool definitions, none deferred and no tool_reference, so tool search is off and the \
588
620
  whole catalog is billed in every request. Behind a proxy, Claude Code turns it off by default: \`bvsala claude\` turns it back on in a NEW WINDOW, or export ENABLE_TOOL_SEARCH=true before launching it b\
589
- y hand.`+r}var br=class{constructor(t=4096){this.maxSesiones=t;}maxSesiones;cuentas={cacheIgnorada:0,ttlAcortado:0,busquedaApagada:0};dichas=new Set;anotar(t,n){this.cuentas[t]++;let r=`${t}|${n??""}`;
621
+ y hand.`+r}var xr=class{constructor(t=4096){this.maxSesiones=t;}maxSesiones;cuentas={cacheIgnorada:0,ttlAcortado:0,busquedaApagada:0};dichas=new Set;anotar(t,n){this.cuentas[t]++;let r=`${t}|${n??""}`;
590
622
  if(this.dichas.has(r))return false;if(this.dichas.add(r),this.dichas.size>this.maxSesiones){let o=this.dichas.values().next();o.done!==true&&this.dichas.delete(o.value);}return true}contadores(){return {...this.
591
- cuentas}}};function Na(e){let t=[];return e.cacheIgnorada>0&&t.push(`${e.cacheIgnorada} request(s) with cache_control but no cache read or write`),e.ttlAcortado>0&&t.push(`${e.ttlAcortado} request(s) \
623
+ cuentas}}};function Ga(e){let t=[];return e.cacheIgnorada>0&&t.push(`${e.cacheIgnorada} request(s) with cache_control but no cache read or write`),e.ttlAcortado>0&&t.push(`${e.ttlAcortado} request(s) \
592
624
  whose 1-hour cache TTL was written at 5 minutes upstream`),e.busquedaApagada>0&&t.push(`${e.busquedaApagada} request(s) with tool search off`),t.length===0?null:`[bvsala gateway] degraded traffic in t\
593
- his run: ${t.join(" \xB7 ")}. What each one means and what to do: "What the gateway guarantees" in docs/terminales/README.md of the package.`}var Ua='[bvsala gateway] streamed /v1/chat/completions requests without stream_options.include_usage carry no usage, so they are forwarded but NOT metered. Add stream_options={"include_usage": True} t\
594
- o the call (Node: stream_options: { include_usage: true }); its last chunk then has an empty choices list.',Fd=Ua+" Or start the gateway with BVSALA_GATEWAY_USAGE_INJECT=1 to add it for clients you ca\
595
- nnot change.",zd=Ua+" BVSALA_GATEWAY_USAGE_INJECT=1 is on, but it only adds the option to an uncompressed request body that sends no stream_options of its own.",qd=e=>`[bvsala gateway] POST ${e} answe\
596
- red without the provider's final usage, so it was forwarded but NOT metered. Nothing is estimated in its place.`,Hd=e=>`[bvsala gateway] POST ${e} is forwarded but NOT metered: the gateway reads usage\
597
- from /v1/messages, \u2026/chat/completions and \u2026/responses only.`,ja=/\/(count_tokens|input_tokens)$/,Wd=["content-encoding","content-length","transfer-encoding"],Kd=new Set(["connection","keep-\
598
- alive","proxy-connection","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","expect"]);function jt(e){let t=e?.cause;if(t==null)return String(e);let n=t instanceof
599
- AggregateError&&t.errors.length>0?t.errors.map(r=>String(r)).join("; "):String(t);return `${String(e)} \xB7 cause: ${n}`}var Bo=class extends Error{code;puerto;constructor(t,n,r){super(t==="EADDRINUSE"?
625
+ his run: ${t.join(" \xB7 ")}. What each one means and what to do: "What the gateway guarantees" in docs/terminales/README.md of the package.`}var Za='[bvsala gateway] streamed /v1/chat/completions requests without stream_options.include_usage carry no usage, so they are forwarded but NOT metered. Add stream_options={"include_usage": True} t\
626
+ o the call (Node: stream_options: { include_usage: true }); its last chunk then has an empty choices list.',Cp=Za+" Or start the gateway with BVSALA_GATEWAY_USAGE_INJECT=1 to add it for clients you ca\
627
+ nnot change.",Ap=Za+" BVSALA_GATEWAY_USAGE_INJECT=1 is on, but it only adds the option to an uncompressed request body that sends no stream_options of its own.",Rp=e=>`[bvsala gateway] POST ${e} answe\
628
+ red without the provider's final usage, so it was forwarded but NOT metered. Nothing is estimated in its place.`,Ip=e=>`[bvsala gateway] POST ${e} is forwarded but NOT metered: the gateway reads usage\
629
+ from /v1/messages, \u2026/chat/completions and \u2026/responses only.`,Ja=/\/(count_tokens|input_tokens)$/,Pp=["content-encoding","content-length","transfer-encoding"],Dp=new Set(["connection","keep-\
630
+ alive","proxy-connection","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","expect"]);function Ft(e){let t=e?.cause;if(t==null)return String(e);let n=t instanceof
631
+ AggregateError&&t.errors.length>0?t.errors.map(r=>String(r)).join("; "):String(t);return `${String(e)} \xB7 cause: ${n}`}var Ho=class extends Error{code;puerto;constructor(t,n,r){super(t==="EADDRINUSE"?
600
632
  `port ${n} is already in use: the gateway could not start`:t==="EACCES"?`port ${n} cannot be opened: permission denied`:`could not listen on 127.0.0.1:${n} (${t})`,{cause:r}),this.name="ErrorDeEscucha",
601
- this.code=t,this.puerto=n;}};function Ba(e,t){if(e===t)return true;let n=Object.keys(e);return n.length!==Object.keys(t).length?false:n.every(r=>Object.hasOwn(t,r)&&e[r]===t[r])}function Gd(e){return e.writableFinished?
602
- Promise.resolve(true):e.destroyed?Promise.resolve(false):new Promise(t=>{let n=()=>o(true),r=()=>o(e.writableFinished),o=i=>{e.off("finish",n),e.off("close",r),t(i);};e.once("finish",n),e.once("close",r);})}async function Va(e){
603
- if(!e?.license)throw new Error("arrancarGateway: a verified BiVelio license is required (LICENSE section 2)");let t=Po(e.license.publicKey),n=dr(e.license.token,t);if(!n.ok)throw new Error(`arrancarGa\
604
- teway: the license token does not verify (${n.reason})`);let r=(e.upstream??"https://api.anthropic.com").replace(/\/+$/,""),o=xa(r),i=e.fetchImpl??fetch,s=e.log??(m=>console.log(m)),a=e.warn??(m=>console.
605
- error(m)),c=e.license.now??Date.now,l=e.license.licenseServerUrl?.replace(/\/+$/,""),d=new It,u=Oo(n.license,t,d,c),p;if(e.serviceAccountKey){p=new Tt({url:e.meteringUrl??"https://savings.bivelio.com/\
606
- api/metering/usage",serviceAccountKey:e.serviceAccountKey,surface:"gateway",...e.fetchImpl?{fetchImpl:e.fetchImpl}:{},onAuthError:_=>G("gateway-ingest-auth",`[bvsala gateway] the usage ingest is rejec\
633
+ this.code=t,this.puerto=n;}};function Ya(e,t){if(e===t)return true;let n=Object.keys(e);return n.length!==Object.keys(t).length?false:n.every(r=>Object.hasOwn(t,r)&&e[r]===t[r])}function Op(e){return e.writableFinished?
634
+ Promise.resolve(true):e.destroyed?Promise.resolve(false):new Promise(t=>{let n=()=>o(true),r=()=>o(e.writableFinished),o=i=>{e.off("finish",n),e.off("close",r),t(i);};e.once("finish",n),e.once("close",r);})}async function Xa(e){
635
+ if(!e?.license)throw new Error("arrancarGateway: a verified BiVelio license is required (LICENSE section 2)");let t=No(e.license.publicKey),n=hr(e.license.token,t);if(!n.ok)throw new Error(`arrancarGa\
636
+ teway: the license token does not verify (${n.reason})`);let r=(e.upstream??"https://api.anthropic.com").replace(/\/+$/,""),o=Da(r),i=e.fetchImpl??fetch,s=e.log??(m=>console.log(m)),a=e.warn??(m=>console.
637
+ error(m)),c=e.license.now??Date.now,l=e.license.licenseServerUrl?.replace(/\/+$/,""),d=new Ot,u=Bo(n.license,t,d,c),p;if(e.serviceAccountKey){p=new Rt({url:e.meteringUrl??"https://savings.bivelio.com/\
638
+ api/metering/usage",serviceAccountKey:e.serviceAccountKey,surface:"gateway",...e.fetchImpl?{fetchImpl:e.fetchImpl}:{},onAuthError:_=>Y("gateway-ingest-auth",`[bvsala gateway] the usage ingest is rejec\
607
639
  ting the credential (${_}). Traffic keeps flowing (warn, never break), but this usage is not reaching your dashboard. Check BIVELIO_SERVICE_KEY and your subscription status at savings.bivelio.com.`)});
608
- let m=Mn();e.seatId?p.setSeat(e.seatId,m):$n(e.serviceAccountKey).then(_=>p?.setSeat(_,m)).catch(()=>{}),p.start();}else G("gateway-sin-clave","[bvsala gateway] no BIVELIO_SERVICE_KEY: this in-process \
609
- gateway forwards traffic but does not meter it (the bvsala CLI refuses to start without the key).");let f=e.coalescer?new pr:null,g=e.sombra&&p?new ar:null,b=new hr,h=new In,v=new br,k=new fr,x=e.serviceAccountKey?
610
- new cr({url:l?`${l}/api/org/entitlements`:new URL("/api/org/entitlements",e.meteringUrl??"https://savings.bivelio.com/api/metering/usage").toString(),serviceAccountKey:e.serviceAccountKey,...e.fetchImpl?
611
- {fetchImpl:e.fetchImpl}:{},...e.entitlementsTtlMs!==void 0?{ttlMs:e.entitlementsTtlMs}:{},log:s}):null,y=x!==null&&e.elision!==false,A=()=>Do(u.gate,x?.blockReason()??null,u.license.payload),R=null;{let m=Do(
612
- u.gate,null,u.license.payload);m.serve&&(R=m.state);}let I=m=>{let _=ha(R,m,u.license.payload);R=m.state,_&&a(_);},D,N,H=Number.NEGATIVE_INFINITY,Y=new Set,E=(m,_)=>{Y.has(m)||(Y.add(m),s(_));},C=false,O=m=>m===
613
- "/v1/messages"?new Le:m.endsWith("/responses")?new Ot:m.endsWith("/chat/completions")?new an:null,$=(m,_,L,B,W,ee,V)=>{b.noMedido(m,ee),s(`[gateway] ${_} ${L} \u2192 ${B}${W?" (stream)":""} \xB7 not mete\
614
- red: ${ee}`),(ht(L)||L.startsWith("/v1/"))&&k.noMedida(ee),e.avisosDeNoMedido!==false&&(V==="chat"&&G("gateway-chat-sin-include-usage",Fd),V==="chat-con-inyeccion"&&G("gateway-chat-sin-include-usage-con-\
615
- inyeccion",zd),V==="uso"&&G(`gateway-sin-usage:${L}`,qd(L)),V==="dialecto"&&G(`gateway-sin-dialecto:${L}`,Hd(L)));},Q=(m,_,L,B)=>{let W=m instanceof Ot?m.estadoFinal():null;if(W!==null&&W!=="completed")
616
- return {motivo:`the response ended as response.${W} without usage`,aviso:"uso"};if(!(m instanceof an&&B!=="inyectado"&&Zs(_,L)!==true))return {motivo:"the stream ended without the provider's final usage e\
617
- vent",aviso:"uso"};let V="the request did not ask for usage (stream_options.include_usage)";return B==="rechazada-por-el-upstream"?{motivo:`${V}, and the upstream rejects that option`,aviso:null}:B===
618
- "comprimido"?{motivo:`${V}; usage injection skips compressed request bodies`,aviso:"chat-con-inyeccion"}:B!==null?{motivo:V,aviso:"chat-con-inyeccion"}:{motivo:V,aviso:"chat"}},Z=(m,_,L,B,W,ee,V,z,Ie,ot,ye,xe,S,U,Ye)=>{
619
- if(!p||!L){b.noMedido(m,p?"the provider reported no usage":"metering is off: the gateway has no BIVELIO_SERVICE_KEY");return}let Ft=p,kn=L,K=qs(_,ee),_e=`[gateway] POST ${W}${B?" \xB7 COALESCED (call avo\
620
- ided)":""}`;if(!K){let pe=`could not read the model from the request body${ee?` (content-encoding: ${ee})`:""}`;s(`${_e} \xB7 not metered: ${pe}`),k.noMedida(pe),b.noMedido(m,"could not read the model\
621
- from the request body"),G(`gateway-sin-modelo:${W}`,`[bvsala gateway] could not read the model from the ${W} request body (content-encoding: ${ee??"none"}); its usage is forwarded but not metered.`);
622
- return}let de=!B&&ye?ye.servido:K,ie=zs(de,L,ot);if(ie){let pe=B?Qs(K,ie,S,Lt(_,ee),{suscripcion:xe===true,entregada:U?.entregada===true,tierServido:U?.tierServido}):null,it=B?ea(m,K,ie,V,pe?.ok?pe.credit:
623
- null,Ye===true):Xs(m,de,ie,V,z,Ie,ye,xe===true,!o,Ye===true);p.record(it),B?k.replica():k.medida(),b.medido(m,it);let te=it.cost.eliminatedInputFloorCost;s(`[gateway] POST ${W} ${B?"\xB7 COALESCED (call avoide\
624
- d)":""} \xB7 ${de!==K?`${K}\u2192${de} (sibling model)`:K} \xB7 $${(Ye?0:ie.costeUsd).toFixed(6)} (in ${ie.tokens.entrada}, cache\u2191${ie.tokens.cacheEscrita}${ie.tokens.cacheEscrita1h?` (1h ${ie.tokens.
625
- cacheEscrita1h})`:""} cache\u2193${ie.tokens.cacheLeida}, out ${ie.tokens.salida})`+(z?` \xB7 elision: ${z.borrados} clear(s), ${z.tokensLimpiados} tok cleared by the provider`+(te!==void 0?` \xB7 floor \
626
- $${te.toFixed(6)} (cache read price)`:z.tokensLimpiadosToolUses>0?z.atribuible?" \xB7 no cache read price in the catalog: no floor":" \xB7 your own context_management settings: counted, not credited":
627
- z.tokensLimpiados>0?" \xB7 thinking only (your config): counted, not credited":""):"")+(Ye?" \xB7 refusal the provider does not bill: measured at $0, no saving credited":"")+(xe&&!B&&(Ie||ye)?" \xB7 subs\
628
- cription traffic: lever applied, saving not credited (no per-token invoice)":"")+(!o&&!xe&&!B&&(Ie||ye||z?.atribuible)?" \xB7 unofficial upstream: lever applied, saving not credited (list prices only hol\
629
- d at the provider's own API)":"")+(pe?pe.ok?` \xB7 by reference: floor $${To(pe.credit).toFixed(6)} (cache read price${pe.credit.creditedOutputTokens>0?`, ${pe.credit.creditedOutputTokens} output tok \
630
- at temperature 0`:", no output credited"})`:` \xB7 estimated, not by reference: ${pe.reason}`:""));let xn=z?.atribuible===true&&z.tokensLimpiadosToolUses>0;g&&!B&&W==="/v1/messages"&&setImmediate(()=>{try{
631
- let we=Lt(_,ee);if(!we||typeof we!="object")return;let Be=g.observar({cuerpo:we,uso:kn,model:K,at:ot??Date.now(),...V?.sessionId!==void 0?{sessionId:V.sessionId}:{},...V?.agentId!==void 0?{agentId:V.agentId}:
632
- {}});if(!Be)return;if(xn){s(`[gateway] shadow estimate \xB7 ${K} \xB7 the provider already cleared context via our settings: chain advances, nothing emitted`);return}Ft.record(ta(`${m}:shadow`,K,Be.baselineUsd,
633
- Be.politicaUsd,V)),s(`[gateway] shadow estimate \xB7 ${K} \xB7 baseline $${Be.baselineUsd.toFixed(6)} \u2192 with elision $${Be.politicaUsd.toFixed(6)}`);}catch{}});}else b.noMedido(m,`model "${de}" has\
634
- no list price in the catalog`),s(`${_e} \xB7 not metered: model "${de}" has no list price in the catalog`),k.noMedida(`model "${de}" has no list price in the catalog`),G(`gateway-sin-precio:${de}`,`[\
635
- bvsala gateway] model "${de}" is not in the price catalog; its usage is forwarded but not metered.`);},be=(m,_,L,B,W,ee)=>{if(!(m!=="/v1/messages"||B===null||!Ma(B)||(L===void 0||L===""||L==="identity")&&
636
- !_.includes('"cache_control"')))try{let z=Lt(_,L);if(z===null||typeof z!="object"||Array.isArray(z))return;let Ie=$a({vista:Da(z),uso:B,ttlReescritoPorLaCapa:W});Ie!==null&&v.anotar(Ie,ee)&&s(jo(Ie,{sesion:ee,
637
- entrada:B.input_tokens??0,escrita5m:B.cache_creation?.ephemeral_5m_input_tokens??0}));}catch{}},ve=createServer(async(m,_)=>{let L=randomUUID(),B=Date.now(),W=A();if(I(W),!W.serve){let F=c();N&&F-H>=da&&(H=F,N.check({force:true})),
638
- m.resume(),_.writeHead(402,{"content-type":"application/json","cache-control":"no-store","x-bvsala-license-status":W.state}),_.end(m.method==="HEAD"?void 0:ma(W.state));let M="/";try{M=new URL(m.url??
639
- "/","http://x").pathname;}catch{}s(`[gateway] ${m.method} ${M} \u2192 402 (license ${W.state})`);return}let ee=Ra(m.url);if(ee!==null){await Ia(m,_,ee,{buzon:b,estado:()=>({schema:_a,gateway:"bvsala",version:me,
640
- upstream:Aa(r),license:{state:W.state,plan:u.license.payload.plan??null,expiresAt:Re(u.license.payload.expires_at)},metering:p!==void 0,reports:{requestHeader:fn,responseHeader:$o,capacity:b.limite}})});
641
- return}let V=Ta(m.headers[fn]),z=V?new gr:null;if(V){let F="/";try{F=new URL(m.url??"/","http://x").pathname;}catch{}b.abrir(L,F);}let Ie=F=>V?{...F,[$o]:L}:F,ot=null,ye=new AbortController;_.on("close",
642
- ()=>{_.writableEnded||ye.abort();});let xe=null,S=new URL(m.url??"/",r),U=null,Ye=Buffer.alloc(0),Ft=false,kn=false,K=null,_e=null,de=false,ie=false,pe=(F,M)=>{if(F===null||K===null||!K.nuestros)return F;let st=M?.
643
- cache_creation,qt=M?.cache_creation_input_tokens??(st?.ephemeral_5m_input_tokens??0)+(st?.ephemeral_1h_input_tokens??0),Ht=(M?.input_tokens??0)+(M?.cache_read_input_tokens??0)+qt+F.tokensLimpiados,Wt=K.
644
- triggerDelCliente!==null&&Ht>=K.triggerDelCliente;return {...F,atribuible:!Wt}},it=m.headers["content-encoding"],te=Array.isArray(it)?it[0]:it,xn=F=>{let M=Array.isArray(F)?F[0]:F;return M!==void 0&&/^[A-Za-z0-9._:/-]{1,128}$/.
645
- test(M)?M:void 0},we=xn(m.headers["x-claude-code-session-id"]),Be=xn(m.headers["x-claude-code-agent-id"]),zt=we!==void 0||Be!==void 0?{...we!==void 0?{sessionId:we}:{},...Be!==void 0?{agentId:Be}:{}}:
646
- void 0;try{let F=[];for await(let w of m)F.push(w);let M=Buffer.concat(F);Ye=M,S=new URL(m.url??"/",r);let st=f!==null&&m.method==="POST"&&M.length>0,qt=ya(w=>{let T=m.headers[w];return Array.isArray(
647
- T)?T.join(", "):T}),Ht=st?va("POST",S.pathname+S.search,M,qt):"";if(st)if(f.tieneEnVuelo(Ht)){let w=await f.esperar(Ht);if(w){let T=ye.signal.aborted||_.destroyed;T||_.writeHead(w.status,Ie(w.headers)),
648
- ot=w.status;let ne=O(S.pathname)??new Le;for(let Et of w.chunks)T||_.write(Et),ne.observar(Et),z?.observar(Et);z&&b.anotarRespuesta(L,z.valor()??No(Buffer.concat(w.chunks))),T||_.end();let St=T?!1:await Gd(
649
- _),Ze=ne.usageFinal()??sr(S.pathname,Buffer.concat(w.chunks));if(Ze===null){if(p&&!ja.test(S.pathname)){let Et=String(w.headers["content-type"]??"").includes("text/event-stream");$(L,m.method??"POST",
650
- S.pathname,w.status,Et,ht(S.pathname)?Et?Q(ne,M,te,null).motivo:"the response carried no usage":"no usage dialect for this route",null);}return}let Gt=m.headers["anthropic-beta"],at=_o(S.pathname,Array.
651
- isArray(Gt)?Gt.join(", "):Gt,r);Z(L,M,Ze,!0,S.pathname,te,zt,null,null,B,null,at,w.primaria??null,{entregada:St,tierServido:Js(S.pathname,Buffer.concat(w.chunks))},S.pathname==="/v1/messages"&&(ne instanceof
652
- Le&&ne.negativaNoCobrada()||Eo(S.pathname,Buffer.concat(w.chunks))));return}}else xe=f.registrar(Ht);let Wt=m.headers.connection,Jc=new Set((Array.isArray(Wt)?Wt.join(","):Wt??"").split(",").map(w=>w.
653
- trim().toLowerCase()).filter(w=>w!=="")),Ue={};for(let[w,T]of Object.entries(m.headers))w==="host"||w==="content-length"||T===void 0||Kd.has(w)||Jc.has(w)||w!==fn&&(Ue[w]=Array.isArray(T)?T.join(", "):
654
- T);let Kt={...Ue};de=_o(S.pathname,Kt["anthropic-beta"],r);let ke=M;if(y&&e.dialesElision===!0&&m.method==="POST"&&S.pathname==="/v1/messages"&&x.tiene("context_elision"))try{let w=mi(M,te);w!==null&&
655
- (ke=w.cuerpo,K={nuestros:w.nuestros,triggerDelCliente:w.triggerDelCliente},Ue["anthropic-beta"]=gi(Ue["anthropic-beta"]));}catch{}if(m.method==="POST"&&S.pathname==="/v1/messages"&&(te??"")==="")try{let w=ga(
656
- M.toString("utf8")),T=ba(w);T&&(G("gateway-busqueda-herramientas",T),Oa(m.headers)&&v.anotar("busquedaApagada",we)&&s(jo("busquedaApagada",{sesion:we,definiciones:w.definiciones})));}catch{}let li=y&&e.
657
- modeloHermano===!0&&m.method==="POST"&&(S.pathname==="/v1/messages"||S.pathname==="/v1/messages/count_tokens");if(li&&!x.tiene("sibling_model_routing")&&G("gateway-hermano-sin-feature","[bvsala gatewa\
658
- y] sibling model routing: the flag is set but your org's license does not include sibling_model_routing; the request is forwarded unchanged (fail-closed)."),li&&x.tiene("sibling_model_routing"))try{let T=Di(
659
- ke,ke===M?te:"identity",{betas:Ue["anthropic-beta"]});T!==null&&(ke=T.cuerpo,_e=T.cambio);}catch{}let wn=!1;if(y&&Br(e.esfuerzo)&&m.method==="POST"&&S.pathname==="/v1/messages"&&x.tiene("per_turn_effor\
660
- t"))try{let w=ke===M?te:"identity",T=_i(ke,e.esfuerzo,w);T!==null&&(ke=T.cuerpo,Ue["anthropic-beta"]=Ti(Ue["anthropic-beta"]),wn=!0);}catch{}let xt=null;if(y&&m.method==="POST"&&S.pathname==="/v1/messa\
661
- ges"&&x.tiene("cache_ttl_tuning"))try{let T=ct(ke,ke===M?te:"identity");if(T!==null){let ne=vi(T),St=`${zt?.sessionId??"sin-sesion"}:${ne.system}`,Ze=Date.now(),Gt=h.ultima(St,Ze);if(h.anotar(St,ne,Ze),
662
- ki({fraccionNueva:yi(Gt,ne)})){let at=xi(T);at!==null&&(ke=at.cuerpo,xt={rebajadas:at.rebajadas,yaEran5m:at.yaEran5m,herramientaDeServidor:at.herramientaDeServidor},ie=!0);}}}catch{}let wt=!1,Sn=null;if(m.
663
- method==="POST"&&S.pathname.endsWith("/chat/completions")&&p&&e.usageInject===!0)if(C)Sn="rechazada-por-el-upstream";else try{let w=Ys(M,te);Sn=w.motivo,w.cuerpo&&(ke=w.cuerpo,wt=!0);}catch{}let j,Cr=ke,
664
- Ar=Ue;try{j=await i(S,{method:m.method,headers:Ue,body:["GET","HEAD"].includes(m.method??"")?void 0:ke,redirect:"manual",signal:ye.signal});}catch(w){xe?.abortar(),_.headersSent||(_.writeHead(502,{"con\
665
- tent-type":"application/json"}),_.end(JSON.stringify({error:"bvsala gateway: upstream unreachable",detail:jt(w)}))),s(`[gateway] ${m.method} ${S.pathname} \u2192 upstream unreachable: ${jt(w)}`);return}
666
- if(((Cr!==M||!Ba(Ar,Kt))&&j.status===400||wt&&(j.status===400||j.status===422))&&!ye.signal.aborted){let w="";try{w=(await j.text()).slice(0,300).replace(/\s+/g," ");}catch{}let T=wt;s(T?`[gateway] the\
667
- upstream rejected (${j.status}) the request with stream_options.include_usage added; forwarding it unchanged \xB7 ${w}`:`[gateway] the upstream rejected (400) the rewritten request${_e?` to ${_e.servido}`:
668
- ""}${wn?" (per-turn effort)":""}${xt?" (cache TTL)":""}${K?" (context editing dials)":""}; forwarding it unchanged \xB7 ${w}`),_e=null,wn=!1,xt=null,ie=!1,K=null,wt=!1,T&&(Sn="rechazada-por-el-upstrea\
669
- m"),Cr=M,Ar=Kt;try{j=await i(S,{method:m.method,headers:Kt,body:M,redirect:"manual",signal:ye.signal});}catch(ne){xe?.abortar(),_.headersSent||(_.writeHead(502,{"content-type":"application/json"}),_.end(
670
- JSON.stringify({error:"bvsala gateway: upstream unreachable",detail:jt(ne)}))),s(`[gateway] ${m.method} ${S.pathname} \u2192 upstream unreachable on retry: ${jt(ne)}`);return}T&&j.ok&&(C=!0,G("gateway\
640
+ let m=Bn();e.seatId?p.setSeat(e.seatId,m):Un(e.serviceAccountKey).then(_=>p?.setSeat(_,m)).catch(()=>{}),p.start();}else Y("gateway-sin-clave","[bvsala gateway] no BIVELIO_SERVICE_KEY: this in-process \
641
+ gateway forwards traffic but does not meter it (the bvsala CLI refuses to start without the key).");let f=e.coalescer?new gr:null,g=e.sombra&&p?new dr:null,b=new yr,h=new Ln,v=new xr,k=new br,x=e.serviceAccountKey?
642
+ new pr({url:l?`${l}/api/org/entitlements`:new URL("/api/org/entitlements",e.meteringUrl??"https://savings.bivelio.com/api/metering/usage").toString(),serviceAccountKey:e.serviceAccountKey,...e.fetchImpl?
643
+ {fetchImpl:e.fetchImpl}:{},...e.entitlementsTtlMs!==void 0?{ttlMs:e.entitlementsTtlMs}:{},log:s}):null,y=x!==null&&e.elision!==false,R=()=>jo(u.gate,x?.blockReason()??null,u.license.payload),P=null;{let m=jo(
644
+ u.gate,null,u.license.payload);m.serve&&(P=m.state);}let D=m=>{let _=Ta(P,m,u.license.payload);P=m.state,_&&a(_);},L,B,K=Number.NEGATIVE_INFINITY,X=new Set,E=(m,_)=>{X.has(m)||(X.add(m),s(_));},A=false,M=m=>m===
645
+ "/v1/messages"?new $e:m.endsWith("/responses")?new Nt:m.endsWith("/chat/completions")?new un:null,j=(m,_,$,V,G,ne,q)=>{b.noMedido(m,ne),s(`[gateway] ${_} ${$} \u2192 ${V}${G?" (stream)":""} \xB7 not mete\
646
+ red: ${ne}`),(vt($)||$.startsWith("/v1/"))&&k.noMedida(ne),e.avisosDeNoMedido!==false&&(q==="chat"&&Y("gateway-chat-sin-include-usage",Cp),q==="chat-con-inyeccion"&&Y("gateway-chat-sin-include-usage-con-\
647
+ inyeccion",Ap),q==="uso"&&Y(`gateway-sin-usage:${$}`,Rp($)),q==="dialecto"&&Y(`gateway-sin-dialecto:${$}`,Ip($)));},te=(m,_,$,V)=>{let G=m instanceof Nt?m.estadoFinal():null;if(G!==null&&G!=="completed")
648
+ return {motivo:`the response ended as response.${G} without usage`,aviso:"uso"};if(!(m instanceof un&&V!=="inyectado"&&ca(_,$)!==true))return {motivo:"the stream ended without the provider's final usage e\
649
+ vent",aviso:"uso"};let q="the request did not ask for usage (stream_options.include_usage)";return V==="rechazada-por-el-upstream"?{motivo:`${q}, and the upstream rejects that option`,aviso:null}:V===
650
+ "comprimido"?{motivo:`${q}; usage injection skips compressed request bodies`,aviso:"chat-con-inyeccion"}:V!==null?{motivo:q,aviso:"chat-con-inyeccion"}:{motivo:q,aviso:"chat"}},Q=(m,_,$,V,G,ne,q,H,De,st,xe,Se,S,F,Qe)=>{
651
+ if(!p||!$){b.noMedido(m,p?"the provider reported no usage":"metering is off: the gateway has no BIVELIO_SERVICE_KEY");return}let Wt=p,En=$,J=Qs(_,ne),Ce=`[gateway] POST ${G}${V?" \xB7 COALESCED (call avo\
652
+ ided)":""}`;if(!J){let me=`could not read the model from the request body${ne?` (content-encoding: ${ne})`:""}`;s(`${Ce} \xB7 not metered: ${me}`),k.noMedida(me),b.noMedido(m,"could not read the model\
653
+ from the request body"),Y(`gateway-sin-modelo:${G}`,`[bvsala gateway] could not read the model from the ${G} request body (content-encoding: ${ne??"none"}); its usage is forwarded but not metered.`);
654
+ return}let fe=!V&&xe?xe.servido:J,ae=Xs(fe,$,st);if(ae){let me=V?ua(J,ae,S,jt(_,ne),{suscripcion:Se===true,entregada:F?.entregada===true,tierServido:F?.tierServido}):null,at=V?da(m,J,ae,q,me?.ok?me.credit:
655
+ null,Qe===true):la(m,fe,ae,q,H,De,xe,Se===true,!o,Qe===true);p.record(at),V?k.replica():k.medida(),b.medido(m,at);let re=at.cost.eliminatedInputFloorCost;s(`[gateway] POST ${G} ${V?"\xB7 COALESCED (call avoide\
656
+ d)":""} \xB7 ${fe!==J?`${J}\u2192${fe} (sibling model)`:J} \xB7 $${(Qe?0:ae.costeUsd).toFixed(6)} (in ${ae.tokens.entrada}, cache\u2191${ae.tokens.cacheEscrita}${ae.tokens.cacheEscrita1h?` (1h ${ae.tokens.
657
+ cacheEscrita1h})`:""} cache\u2193${ae.tokens.cacheLeida}, out ${ae.tokens.salida})`+(H?` \xB7 elision: ${H.borrados} clear(s), ${H.tokensLimpiados} tok cleared by the provider`+(re!==void 0?` \xB7 floor \
658
+ $${re.toFixed(6)} (cache read price)`:H.tokensLimpiadosToolUses>0?H.atribuible?" \xB7 no cache read price in the catalog: no floor":" \xB7 your own context_management settings: counted, not credited":
659
+ H.tokensLimpiados>0?" \xB7 thinking only (your config): counted, not credited":""):"")+(Qe?" \xB7 refusal the provider does not bill: measured at $0, no saving credited":"")+(Se&&!V&&(De||xe)?" \xB7 subs\
660
+ cription traffic: lever applied, saving not credited (no per-token invoice)":"")+(!o&&!Se&&!V&&(De||xe||H?.atribuible)?" \xB7 unofficial upstream: lever applied, saving not credited (list prices only hol\
661
+ d at the provider's own API)":"")+(me?me.ok?` \xB7 by reference: floor $${Do(me.credit).toFixed(6)} (cache read price${me.credit.creditedOutputTokens>0?`, ${me.credit.creditedOutputTokens} output tok \
662
+ at temperature 0`:", no output credited"})`:` \xB7 estimated, not by reference: ${me.reason}`:""));let _n=H?.atribuible===true&&H.tokensLimpiadosToolUses>0;g&&!V&&G==="/v1/messages"&&setImmediate(()=>{try{
663
+ let Ee=jt(_,ne);if(!Ee||typeof Ee!="object")return;let Ve=g.observar({cuerpo:Ee,uso:En,model:J,at:st??Date.now(),...q?.sessionId!==void 0?{sessionId:q.sessionId}:{},...q?.agentId!==void 0?{agentId:q.agentId}:
664
+ {}});if(!Ve)return;if(_n){s(`[gateway] shadow estimate \xB7 ${J} \xB7 the provider already cleared context via our settings: chain advances, nothing emitted`);return}Wt.record(pa(`${m}:shadow`,J,Ve.baselineUsd,
665
+ Ve.politicaUsd,q)),s(`[gateway] shadow estimate \xB7 ${J} \xB7 baseline $${Ve.baselineUsd.toFixed(6)} \u2192 with elision $${Ve.politicaUsd.toFixed(6)}`);}catch{}});}else b.noMedido(m,`model "${fe}" has\
666
+ no list price in the catalog`),s(`${Ce} \xB7 not metered: model "${fe}" has no list price in the catalog`),k.noMedida(`model "${fe}" has no list price in the catalog`),Y(`gateway-sin-precio:${fe}`,`[\
667
+ bvsala gateway] model "${fe}" is not in the price catalog; its usage is forwarded but not metered.`);},ye=(m,_,$,V,G,ne)=>{if(!(m!=="/v1/messages"||V===null||!Wa(V)||($===void 0||$===""||$==="identity")&&
668
+ !_.includes('"cache_control"')))try{let H=jt(_,$);if(H===null||typeof H!="object"||Array.isArray(H))return;let De=Ka({vista:qa(H),uso:V,ttlReescritoPorLaCapa:G});De!==null&&v.anotar(De,ne)&&s(zo(De,{sesion:ne,
669
+ entrada:V.input_tokens??0,escrita5m:V.cache_creation?.ephemeral_5m_input_tokens??0}));}catch{}},ke=createServer(async(m,_)=>{let $=randomUUID(),V=Date.now(),G=R();if(D(G),!G.serve){let z=c();B&&z-K>=wa&&(K=z,B.check({force:true})),
670
+ m.resume(),_.writeHead(402,{"content-type":"application/json","cache-control":"no-store","x-bvsala-license-status":G.state}),_.end(m.method==="HEAD"?void 0:_a(G.state));let N="/";try{N=new URL(m.url??
671
+ "/","http://x").pathname;}catch{}s(`[gateway] ${m.method} ${N} \u2192 402 (license ${G.state})`);return}let ne=Ua(m.url);if(ne!==null){await Va(m,_,ne,{buzon:b,estado:()=>({schema:$a,gateway:"bvsala",version:ge,
672
+ upstream:Ba(r),license:{state:G.state,plan:u.license.payload.plan??null,expiresAt:Pe(u.license.payload.expires_at)},metering:p!==void 0,reports:{requestHeader:bn,responseHeader:Fo,capacity:b.limite}})});
673
+ return}let q=Na(m.headers[bn]),H=q?new kr:null;if(q){let z="/";try{z=new URL(m.url??"/","http://x").pathname;}catch{}b.abrir($,z);}let De=z=>q?{...z,[Fo]:$}:z,st=null,xe=new AbortController;_.on("close",
674
+ ()=>{_.writableEnded||xe.abort();});let Se=null,S=new URL(m.url??"/",r),F=null,Qe=Buffer.alloc(0),Wt=false,En=false,J=null,Ce=null,fe=false,ae=false,me=(z,N)=>{if(z===null||J===null||!J.nuestros)return z;let ct=N?.
675
+ cache_creation,Gt=N?.cache_creation_input_tokens??(ct?.ephemeral_5m_input_tokens??0)+(ct?.ephemeral_1h_input_tokens??0),Jt=(N?.input_tokens??0)+(N?.cache_read_input_tokens??0)+Gt+z.tokensLimpiados,Yt=J.
676
+ triggerDelCliente!==null&&Jt>=J.triggerDelCliente;return {...z,atribuible:!Yt}},at=m.headers["content-encoding"],re=Array.isArray(at)?at[0]:at,_n=z=>{let N=Array.isArray(z)?z[0]:z;return N!==void 0&&/^[A-Za-z0-9._:/-]{1,128}$/.
677
+ test(N)?N:void 0},Ee=_n(m.headers["x-claude-code-session-id"]),Ve=_n(m.headers["x-claude-code-agent-id"]),Kt=Ee!==void 0||Ve!==void 0?{...Ee!==void 0?{sessionId:Ee}:{},...Ve!==void 0?{agentId:Ve}:{}}:
678
+ void 0;try{let z=[];for await(let w of m)z.push(w);let N=Buffer.concat(z);Qe=N,S=new URL(m.url??"/",r);let ct=f!==null&&m.method==="POST"&&N.length>0,Gt=Ia(w=>{let T=m.headers[w];return Array.isArray(
679
+ T)?T.join(", "):T}),Jt=ct?Ra("POST",S.pathname+S.search,N,Gt):"";if(ct)if(f.tieneEnVuelo(Jt)){let w=await f.esperar(Jt);if(w){let T=xe.signal.aborted||_.destroyed;T||_.writeHead(w.status,De(w.headers)),
680
+ st=w.status;let oe=M(S.pathname)??new $e;for(let Ct of w.chunks)T||_.write(Ct),oe.observar(Ct),H?.observar(Ct);H&&b.anotarRespuesta($,H.valor()??qo(Buffer.concat(w.chunks))),T||_.end();let Tt=T?!1:await Op(
681
+ _),ze=oe.usageFinal()??ur(S.pathname,Buffer.concat(w.chunks));if(ze===null){if(p&&!Ja.test(S.pathname)){let Ct=String(w.headers["content-type"]??"").includes("text/event-stream");j($,m.method??"POST",
682
+ S.pathname,w.status,Ct,vt(S.pathname)?Ct?te(oe,N,re,null).motivo:"the response carried no usage":"no usage dialect for this route",null);}return}let lt=m.headers["anthropic-beta"],ut=Po(S.pathname,Array.
683
+ isArray(lt)?lt.join(", "):lt,r);Q($,N,ze,!0,S.pathname,re,Kt,null,null,V,null,ut,w.primaria??null,{entregada:Tt,tierServido:sa(S.pathname,Buffer.concat(w.chunks))},S.pathname==="/v1/messages"&&(oe instanceof
684
+ $e&&oe.negativaNoCobrada()||Io(S.pathname,Buffer.concat(w.chunks))));return}}else Se=f.registrar(Jt);let Yt=m.headers.connection,sl=new Set((Array.isArray(Yt)?Yt.join(","):Yt??"").split(",").map(w=>w.
685
+ trim().toLowerCase()).filter(w=>w!=="")),Fe={};for(let[w,T]of Object.entries(m.headers))w==="host"||w==="content-length"||T===void 0||Dp.has(w)||sl.has(w)||w!==bn&&(Fe[w]=Array.isArray(T)?T.join(", "):
686
+ T);let Zt={...Fe};fe=Po(S.pathname,Zt["anthropic-beta"],r);let we=N;if(y&&e.dialesElision===!0&&m.method==="POST"&&S.pathname==="/v1/messages"&&x.tiene("context_elision"))try{let w=xi(N,re);w!==null&&
687
+ (we=w.cuerpo,J={nuestros:w.nuestros,triggerDelCliente:w.triggerDelCliente},Fe["anthropic-beta"]=Si(Fe["anthropic-beta"]));}catch{}if(m.method==="POST"&&S.pathname==="/v1/messages"&&(re??"")==="")try{let w=Ca(
688
+ N.toString("utf8")),T=Aa(w);T&&(Y("gateway-busqueda-herramientas",T),za(m.headers)&&v.anotar("busquedaApagada",Ee)&&s(zo("busquedaApagada",{sesion:Ee,definiciones:w.definiciones})));}catch{}let gi=y&&e.
689
+ modeloHermano===!0&&m.method==="POST"&&(S.pathname==="/v1/messages"||S.pathname==="/v1/messages/count_tokens");if(gi&&!x.tiene("sibling_model_routing")&&Y("gateway-hermano-sin-feature","[bvsala gatewa\
690
+ y] sibling model routing: the flag is set but your org's license does not include sibling_model_routing; the request is forwarded unchanged (fail-closed)."),gi&&x.tiene("sibling_model_routing"))try{let T=Bi(
691
+ we,we===N?re:"identity",{betas:Fe["anthropic-beta"]});T!==null&&(we=T.cuerpo,Ce=T.cambio);}catch{}let Tn=!1;if(y&&qr(e.esfuerzo)&&m.method==="POST"&&S.pathname==="/v1/messages"&&x.tiene("per_turn_effor\
692
+ t"))try{let w=we===N?re:"identity",T=Di(we,e.esfuerzo,w);T!==null&&(we=T.cuerpo,Fe["anthropic-beta"]=Oi(Fe["anthropic-beta"]),Tn=!0);}catch{}let Et=null;if(y&&m.method==="POST"&&S.pathname==="/v1/messa\
693
+ ges"&&x.tiene("cache_ttl_tuning"))try{let T=dt(we,we===N?re:"identity");if(T!==null){let oe=_i(T),Tt=`${Kt?.sessionId??"sin-sesion"}:${oe.system}`,ze=Date.now(),lt=h.ultima(Tt,ze);if(h.anotar(Tt,oe,ze),
694
+ Ci({fraccionNueva:Ti(lt,oe)})){let ut=Ai(T);ut!==null&&(we=ut.cuerpo,Et={rebajadas:ut.rebajadas,yaEran5m:ut.yaEran5m,herramientaDeServidor:ut.herramientaDeServidor},ae=!0);}}}catch{}let _t=!1,Cn=null;if(m.
695
+ method==="POST"&&S.pathname.endsWith("/chat/completions")&&p&&e.usageInject===!0)if(A)Cn="rechazada-por-el-upstream";else try{let w=aa(N,re);Cn=w.motivo,w.cuerpo&&(we=w.cuerpo,_t=!0);}catch{}let U,Pr=we,
696
+ Dr=Fe;try{U=await i(S,{method:m.method,headers:Fe,body:["GET","HEAD"].includes(m.method??"")?void 0:we,redirect:"manual",signal:xe.signal});}catch(w){Se?.abortar(),_.headersSent||(_.writeHead(502,{"con\
697
+ tent-type":"application/json"}),_.end(JSON.stringify({error:"bvsala gateway: upstream unreachable",detail:Ft(w)}))),s(`[gateway] ${m.method} ${S.pathname} \u2192 upstream unreachable: ${Ft(w)}`);return}
698
+ if(((Pr!==N||!Ya(Dr,Zt))&&U.status===400||_t&&(U.status===400||U.status===422))&&!xe.signal.aborted){let w="";try{w=(await U.text()).slice(0,300).replace(/\s+/g," ");}catch{}let T=_t;s(T?`[gateway] the\
699
+ upstream rejected (${U.status}) the request with stream_options.include_usage added; forwarding it unchanged \xB7 ${w}`:`[gateway] the upstream rejected (400) the rewritten request${Ce?` to ${Ce.servido}`:
700
+ ""}${Tn?" (per-turn effort)":""}${Et?" (cache TTL)":""}${J?" (context editing dials)":""}; forwarding it unchanged \xB7 ${w}`),Ce=null,Tn=!1,Et=null,ae=!1,J=null,_t=!1,T&&(Cn="rechazada-por-el-upstrea\
701
+ m"),Pr=N,Dr=Zt;try{U=await i(S,{method:m.method,headers:Zt,body:N,redirect:"manual",signal:xe.signal});}catch(oe){Se?.abortar(),_.headersSent||(_.writeHead(502,{"content-type":"application/json"}),_.end(
702
+ JSON.stringify({error:"bvsala gateway: upstream unreachable",detail:Ft(oe)}))),s(`[gateway] ${m.method} ${S.pathname} \u2192 upstream unreachable on retry: ${Ft(oe)}`);return}T&&U.ok&&(A=!0,Y("gateway\
671
703
  -sin-stream-options","[bvsala gateway] the upstream rejects stream_options, so usage injection is off for the rest of this process: streamed /v1/chat/completions answers from it are forwarded but NOT \
672
- metered (stream=false answers still are)."));}let Rr=Object.fromEntries(j.headers.entries());for(let w of Wd)delete Rr[w];_.writeHead(j.status,Ie(Rr)),ot=j.status;let En=j.headers.get("content-type")??
673
- "",_n=En.includes("text/event-stream")||En===""&&j.ok&&O(S.pathname)!==null&&!S.pathname.endsWith("/chat/completions");U=_n?O(S.pathname):null,kn=j.ok;let Ve=!_n&&j.ok&&p!==void 0&&m.method==="POST"&&
674
- ht(S.pathname)&&(j.headers.get("content-type")??"").includes("application/json")?[]:null,ui=0,di=!1;if(j.body)for await(let w of j.body){let T=Buffer.from(w);_.write(T),U?.observar(T),z?.observar(T),Ve&&
675
- (ui+=T.length,ui>Lo?(Ve=null,di=!0):Ve.push(T)),xe?.capturar(T);}if(_.end(),z&&b.anotarRespuesta(L,z.valor()??(Ve?No(Buffer.concat(Ve)):null)),xe){let w=_e===null&&!wn&&K===null&&!wt&&xt===null&&Cr===M&&
676
- Ba(Ar,Kt),T=Ve?Buffer.concat(Ve):null,ne=j.ok&&(U?U.usageFinal()!==null:T!==null&&sr(S.pathname,T)!==null),St=U instanceof Ot&&U.estadoFinal()==="failed"||T!==null&&Ws(S.pathname,T),Ze=U!==null&&U.negativa()||
677
- T!==null&&Gs(S.pathname,T);xe.terminar(j.status,Rr,{requestId:L,at:Date.now(),intacta:w,proveedorOficial:o,conContador:ne,suscripcion:de,fallida:St,...Ze?{negativa:Ze}:{}});}if(U&&j.ok){Ft=!0;let w=U.usageFinal();
678
- if(w===null&&p){let T=Q(U,M,te,wt?"inyectado":Sn);$(L,m.method??"POST",S.pathname,j.status,!0,T.motivo,T.aviso);}else {let T=pe(U instanceof Le?U.elision():null,w),ne=S.pathname==="/v1/messages"&&U instanceof
679
- Le&&U.negativaNoCobrada();Z(L,M,w,!1,S.pathname,te,zt,T,xt,B,_e,de,void 0,void 0,ne),be(S.pathname,M,te,w,ie,we);}p||s(`[gateway] ${m.method} ${S.pathname} \u2192 ${j.status} (stream) \xB7 not metered: no\
680
- BIVELIO_SERVICE_KEY`);}else if(Ve){let w=Buffer.concat(Ve),T=sr(S.pathname,w);if(T===null)$(L,m.method??"POST",S.pathname,j.status,!1,"the response carried no usage","uso");else {let ne=S.pathname==="/\
681
- v1/messages"?Bs(w):null;Z(L,M,T,!1,S.pathname,te,zt,pe(ne,T),xt,B,_e,de,void 0,void 0,Eo(S.pathname,w)),be(S.pathname,M,te,T,ie,we);}}else di?$(L,m.method??"POST",S.pathname,j.status,!1,"the response w\
682
- as too large to read its usage",null):p&&m.method==="POST"&&j.ok&&ht(S.pathname)?$(L,m.method,S.pathname,j.status,!1,`the response is neither JSON nor an event stream (content-type: ${En===""?"none":En.
683
- slice(0,80)})`,null):p&&m.method==="POST"&&j.ok&&!ht(S.pathname)&&!ja.test(S.pathname)?$(L,m.method,S.pathname,j.status,_n,"no usage dialect for this route",S.pathname.startsWith("/v1/")?"dialecto":null):
684
- s(`[gateway] ${m.method} ${S.pathname} \u2192 ${j.status}${_n?" (stream)":""}`);}catch(F){if(xe?.abortar(),ye.signal.aborted){let M=!Ft&&U?U.usageFinal():null;if(M){s(`[gateway] ${m.method} ${S.pathname}\
685
- \u2192 client closed after the final usage; metered anyway`);let st=pe(U instanceof Le?U.elision():null,M),qt=S.pathname==="/v1/messages"&&U instanceof Le&&U.negativaNoCobrada();Z(L,Ye,M,false,S.pathname,
686
- te,zt,st,void 0,B,_e,de,void 0,void 0,qt),be(S.pathname,Ye,te,M,ie,we);}else s(`[gateway] ${m.method} ${S.pathname} \u2192 client aborted; upstream cancelled`),U&&kn&&!Ft&&k.noMedida("the client closed\
687
- the stream before the provider's final usage");}else if(s(`[gateway] ${m.method} ${S.pathname} \u2192 error while serving: ${jt(F)}`),!_.headersSent){_.writeHead(502,{"content-type":"application/json"}),
688
- _.end(JSON.stringify({error:"bvsala gateway: stream interrupted",detail:jt(F)}));return}_.writableEnded||_.end();}finally{V&&b.noMedido(L,ye.signal.aborted?"the client closed the connection before the \
689
- provider's final usage":ot===null?"the request did not get an answer from the provider":`no usage was read from the provider's answer (HTTP ${ot})`);}});ve.on("upgrade",(m,_)=>{s(`[gateway] ${m.method}\
690
- ${new URL(m.url??"/","http://x").pathname} \u2192 426 (WebSocket not supported; the client falls back to HTTP)`),_.once("error",()=>{}),_.once("finish",()=>_.destroy()),_.end(`HTTP/1.1 426 Upgrade Re\
691
- quired\r
704
+ metered (stream=false answers still are)."));}let Or=Object.fromEntries(U.headers.entries());for(let w of Pp)delete Or[w];_.writeHead(U.status,De(Or)),st=U.status;let An=U.headers.get("content-type")??
705
+ "",Rn=An.includes("text/event-stream")||An===""&&U.ok&&M(S.pathname)!==null&&!S.pathname.endsWith("/chat/completions");F=Rn?M(S.pathname):null,En=U.ok;let qe=!Rn&&U.ok&&p!==void 0&&m.method==="POST"&&
706
+ vt(S.pathname)&&(U.headers.get("content-type")??"").includes("application/json")?[]:null,bi=0,vi=!1;if(U.body)for await(let w of U.body){let T=Buffer.from(w);_.write(T),F?.observar(T),H?.observar(T),qe&&
707
+ (bi+=T.length,bi>Uo?(qe=null,vi=!0):qe.push(T)),Se?.capturar(T);}if(_.end(),H&&b.anotarRespuesta($,H.valor()??(qe?qo(Buffer.concat(qe)):null)),Se){let w=Ce===null&&!Tn&&J===null&&!_t&&Et===null&&Pr===N&&
708
+ Ya(Dr,Zt),T=qe?Buffer.concat(qe):null,oe=U.ok&&(F?F.usageFinal()!==null:T!==null&&ur(S.pathname,T)!==null),Tt=F instanceof Nt&&F.estadoFinal()==="failed"||T!==null&&ta(S.pathname,T),ze=F!==null&&F.negativa()||
709
+ T!==null&&ra(S.pathname,T),lt=!ze&&ia(F!==null?F.textoInicial():T!==null?oa(S.pathname,T):"");Se.terminar(U.status,Or,{requestId:$,at:Date.now(),intacta:w,proveedorOficial:o,conContador:oe,suscripcion:fe,
710
+ fallida:Tt,...ze?{negativa:ze}:{},...lt?{negativaEnTexto:!0}:{}});}if(F&&U.ok){Wt=!0;let w=F.usageFinal();if(w===null&&p){let T=te(F,N,re,_t?"inyectado":Cn);j($,m.method??"POST",S.pathname,U.status,!0,
711
+ T.motivo,T.aviso);}else {let T=me(F instanceof $e?F.elision():null,w),oe=S.pathname==="/v1/messages"&&F instanceof $e&&F.negativaNoCobrada();Q($,N,w,!1,S.pathname,re,Kt,T,Et,V,Ce,fe,void 0,void 0,oe),ye(
712
+ S.pathname,N,re,w,ae,Ee);}p||s(`[gateway] ${m.method} ${S.pathname} \u2192 ${U.status} (stream) \xB7 not metered: no BIVELIO_SERVICE_KEY`);}else if(qe){let w=Buffer.concat(qe),T=ur(S.pathname,w);if(T===
713
+ null)j($,m.method??"POST",S.pathname,U.status,!1,"the response carried no usage","uso");else {let oe=S.pathname==="/v1/messages"?Gs(w):null;Q($,N,T,!1,S.pathname,re,Kt,me(oe,T),Et,V,Ce,fe,void 0,void 0,
714
+ Io(S.pathname,w)),ye(S.pathname,N,re,T,ae,Ee);}}else vi?j($,m.method??"POST",S.pathname,U.status,!1,"the response was too large to read its usage",null):p&&m.method==="POST"&&U.ok&&vt(S.pathname)?j($,m.
715
+ method,S.pathname,U.status,!1,`the response is neither JSON nor an event stream (content-type: ${An===""?"none":An.slice(0,80)})`,null):p&&m.method==="POST"&&U.ok&&!vt(S.pathname)&&!Ja.test(S.pathname)?
716
+ j($,m.method,S.pathname,U.status,Rn,"no usage dialect for this route",S.pathname.startsWith("/v1/")?"dialecto":null):s(`[gateway] ${m.method} ${S.pathname} \u2192 ${U.status}${Rn?" (stream)":""}`);}catch(z){
717
+ if(Se?.abortar(),xe.signal.aborted){let N=!Wt&&F?F.usageFinal():null;if(N){s(`[gateway] ${m.method} ${S.pathname} \u2192 client closed after the final usage; metered anyway`);let ct=me(F instanceof $e?
718
+ F.elision():null,N),Gt=S.pathname==="/v1/messages"&&F instanceof $e&&F.negativaNoCobrada();Q($,Qe,N,false,S.pathname,re,Kt,ct,void 0,V,Ce,fe,void 0,void 0,Gt),ye(S.pathname,Qe,re,N,ae,Ee);}else s(`[gatewa\
719
+ y] ${m.method} ${S.pathname} \u2192 client aborted; upstream cancelled`),F&&En&&!Wt&&k.noMedida("the client closed the stream before the provider's final usage");}else if(s(`[gateway] ${m.method} ${S.pathname}\
720
+ \u2192 error while serving: ${Ft(z)}`),!_.headersSent){_.writeHead(502,{"content-type":"application/json"}),_.end(JSON.stringify({error:"bvsala gateway: stream interrupted",detail:Ft(z)}));return}_.writableEnded||
721
+ _.end();}finally{q&&b.noMedido($,xe.signal.aborted?"the client closed the connection before the provider's final usage":st===null?"the request did not get an answer from the provider":`no usage was rea\
722
+ d from the provider's answer (HTTP ${st})`);}});ke.on("upgrade",(m,_)=>{s(`[gateway] ${m.method} ${new URL(m.url??"/","http://x").pathname} \u2192 426 (WebSocket not supported; the client falls back to HTTP\
723
+ )`),_.once("error",()=>{}),_.once("finish",()=>_.destroy()),_.end(`HTTP/1.1 426 Upgrade Required\r
692
724
  connection: close\r
693
725
  content-length: 0\r
694
726
  \r
695
- `);});let je=e.puerto??8402;try{await new Promise((m,_)=>{ve.once("error",_),ve.listen(je,"127.0.0.1",()=>m());});}catch(m){p?.stop();let _=m?.code;throw new Bo(typeof _=="string"?_:"EUNKNOWN",je,m)}let Je=ve.
696
- address().port;return l&&(D=new sn({url:`${l}/licenses/revocations`,publicKeyPem:t,snapshot:d,getRefreshAfter:()=>u.gate.refreshAfter?.(),nowSeconds:()=>Math.floor(c()/1e3),...e.fetchImpl?{fetchImpl:e.
727
+ `);});let Ue=e.puerto??8402;try{await new Promise((m,_)=>{ke.once("error",_),ke.listen(Ue,"127.0.0.1",()=>m());});}catch(m){p?.stop();let _=m?.code;throw new Ho(typeof _=="string"?_:"EUNKNOWN",Ue,m)}let Xe=ke.
728
+ address().port;return l&&(L=new ln({url:`${l}/licenses/revocations`,publicKeyPem:t,snapshot:d,getRefreshAfter:()=>u.gate.refreshAfter?.(),nowSeconds:()=>Math.floor(c()/1e3),...e.fetchImpl?{fetchImpl:e.
697
729
  fetchImpl}:{},silenceWarnings:true,onEvent:m=>{m.type==="rejected"&&E(`poller:${m.reason}`,`[gateway] revocation list rejected (${m.reason}); known revocations still apply`);},...e.license.revocations??{}}),
698
- D.start(),e.serviceAccountKey&&(N=new ur({licenseServerUrl:l,serviceAccountKey:e.serviceAccountKey,publicKey:t,revocation:d,current:()=>u.license,onAdopt:m=>{u=Oo(m,t,d,c),s(`[gateway] renewed license\
699
- adopted (expires ${Re(m.payload.expires_at)})`),I(A());},onWarning:a,...e.fetchImpl?{fetchImpl:e.fetchImpl}:{},now:c,...e.license.renewal??{}}),N.start({checkNow:e.license.checkOnStart===true}))),{puerto:Je,
700
- cerrar:async()=>{N?.stop(),D?.stop(),await p?.stopAndDrain(),await new Promise(m=>ve.close(()=>m()));},licenseStatus:()=>A().state,degradaciones:()=>v.contadores(),medicion:()=>k.estado()}}var Uo=["claude","codex","goose","qwen","opencode","kilo","copilot","aider"];function mn(e){return Uo.includes(e??"")}function Vo(e,t={}){
730
+ L.start(),e.serviceAccountKey&&(B=new mr({licenseServerUrl:l,serviceAccountKey:e.serviceAccountKey,publicKey:t,revocation:d,current:()=>u.license,onAdopt:m=>{u=Bo(m,t,d,c),s(`[gateway] renewed license\
731
+ adopted (expires ${Pe(m.payload.expires_at)})`),D(R());},onWarning:a,...e.fetchImpl?{fetchImpl:e.fetchImpl}:{},now:c,...e.license.renewal??{}}),B.start({checkNow:e.license.checkOnStart===true}))),{puerto:Xe,
732
+ cerrar:async()=>{B?.stop(),L?.stop(),await p?.stopAndDrain(),await new Promise(m=>ke.close(()=>m()));},licenseStatus:()=>R().state,degradaciones:()=>v.contadores(),medicion:()=>k.estado()}}var Wo=["claude","codex","goose","qwen","opencode","kilo","copilot","aider"];function vn(e){return Wo.includes(e??"")}function Ko(e,t={}){
701
733
  let n=t.path??process.env.PATH??"",r=t.existe??existsSync,o=null;for(let i of n.split(";").filter(s=>s.length>0)){for(let s of [".exe",".com"]){let a=join(i,e+s);if(r(a))return {tipo:"exe",ruta:a}}if(o===null)for(let s of [
702
- ".cmd",".bat"]){let a=join(i,e+s);if(r(a)){o=a;break}}}return o!==null?{tipo:"solo-shim",ruta:o}:{tipo:"no-encontrado"}}function Ha(e={}){let n=(e.env??process.env).BVSALA_CODEX_AUTH?.toLowerCase();if(n===
734
+ ".cmd",".bat"]){let a=join(i,e+s);if(r(a)){o=a;break}}}return o!==null?{tipo:"solo-shim",ruta:o}:{tipo:"no-encontrado"}}function nc(e={}){let n=(e.env??process.env).BVSALA_CODEX_AUTH?.toLowerCase();if(n===
703
735
  "api-key"||n==="apikey")return "api-key";if(n==="chatgpt")return "chatgpt";let r=null;try{r=e.leerAuth?e.leerAuth():null;}catch{r=null;}if(r===null)return "api-key";try{let o=JSON.parse(r);return typeof o.
704
- auth_mode=="string"?o.auth_mode.toLowerCase().replace(/[^a-z]/g,"")==="apikey"?"api-key":"chatgpt":o.tokens!==void 0&&o.tokens!==null?"chatgpt":"api-key"}catch{return "api-key"}}var Yd={"api-key":{upstream:"\
705
- https://api.openai.com",prefijo:"/v1"},chatgpt:{upstream:"https://chatgpt.com",prefijo:"/backend-api/codex"}},za="https://api.anthropic.com",qa="https://api.openai.com",Wa={opencode:"OPENCODE_CONFIG_C\
706
- ONTENT",kilo:"KILO_CONFIG_CONTENT"};function Ka(e,t){let n={};if(e!==void 0&&e.trim()!==""){let a;try{a=JSON.parse(e);}catch{return null}if(typeof a!="object"||a===null||Array.isArray(a))return null;n=
736
+ auth_mode=="string"?o.auth_mode.toLowerCase().replace(/[^a-z]/g,"")==="apikey"?"api-key":"chatgpt":o.tokens!==void 0&&o.tokens!==null?"chatgpt":"api-key"}catch{return "api-key"}}var Mp={"api-key":{upstream:"\
737
+ https://api.openai.com",prefijo:"/v1"},chatgpt:{upstream:"https://chatgpt.com",prefijo:"/backend-api/codex"}},ec="https://api.anthropic.com",tc="https://api.openai.com",rc={opencode:"OPENCODE_CONFIG_C\
738
+ ONTENT",kilo:"KILO_CONFIG_CONTENT"};function oc(e,t){let n={};if(e!==void 0&&e.trim()!==""){let a;try{a=JSON.parse(e);}catch{return null}if(typeof a!="object"||a===null||Array.isArray(a))return null;n=
707
739
  a;}let r=(a,c)=>{let l=a[c];return l===void 0?{}:typeof l=="object"&&l!==null&&!Array.isArray(l)?l:null},o=r(n,"provider"),i=o&&r(o,"anthropic"),s=i&&r(i,"options");return !o||!i||!s?null:JSON.stringify(
708
- {...n,provider:{...o,anthropic:{...i,options:{...s,baseURL:t}}}})}function Ga(e){let t=e.COPILOT_PROVIDER_BASE_URL?.trim()??"";if(t==="")return {ok:false,error:"Copilot CLI goes through a base URL only wi\
740
+ {...n,provider:{...o,anthropic:{...i,options:{...s,baseURL:t}}}})}function ic(e){let t=e.COPILOT_PROVIDER_BASE_URL?.trim()??"";if(t==="")return {ok:false,error:"Copilot CLI goes through a base URL only wi\
709
741
  th your own provider key (BYOK). Without COPILOT_PROVIDER_BASE_URL it uses GitHub-hosted models, which never pass through the gateway: there is nothing to meter (its /usage shows those AI credits). To\
710
742
  meter BYOK with Anthropic, export COPILOT_PROVIDER_TYPE=anthropic, COPILOT_PROVIDER_BASE_URL=https://api.anthropic.com, COPILOT_PROVIDER_API_KEY and COPILOT_MODEL, and run `bvsala copilot` again."};let n=e.
711
743
  COPILOT_PROVIDER_TYPE?.trim().toLowerCase()||"openai";if(n==="openai")return {ok:false,error:"`bvsala copilot` wraps the anthropic provider type only for now. With the openai type (the default) Copilot CL\
712
744
  I can call the Responses API over WebSocket, which the gateway answers with 426, and its fallback to HTTP is not validated yet. To meter it by hand and check the log, see `bvsala doctor`."};if(n!=="an\
713
745
  thropic")return {ok:false,error:"COPILOT_PROVIDER_TYPE is neither anthropic nor openai: the gateway prices only the provider's own API at its list price (Azure, a local model or a reseller bills different\
714
746
  ly, or not at all), so `bvsala copilot` wraps the anthropic type only."};let r;try{r=new URL(t);}catch{return {ok:false,error:"COPILOT_PROVIDER_BASE_URL is not a URL: fix it so Copilot CLI works directly f\
715
- irst."}}return r.origin!==za?{ok:false,error:`COPILOT_PROVIDER_BASE_URL does not point at ${za}: the gateway prices only the provider's own API at its list price (a local model or a reseller bills differ\
716
- ently, or not at all), so it does not wrap it.`}:{ok:true,ruta:r.pathname.replace(/\/+$/,"")}}function Ja(e,t=process.env){if(e==="opencode"||e==="kilo"){let n=Wa[e];return Ka(t[n],"http://127.0.0.1:1/v\
747
+ irst."}}return r.origin!==ec?{ok:false,error:`COPILOT_PROVIDER_BASE_URL does not point at ${ec}: the gateway prices only the provider's own API at its list price (a local model or a reseller bills differ\
748
+ ently, or not at all), so it does not wrap it.`}:{ok:true,ruta:r.pathname.replace(/\/+$/,"")}}function sc(e,t=process.env){if(e==="opencode"||e==="kilo"){let n=rc[e];return oc(t[n],"http://127.0.0.1:1/v\
717
749
  1")===null?`${n} is set but is not a JSON object with an object at provider.anthropic.options, so the wrapper cannot add the gateway's baseURL without guessing (its value is not shown). Unset it, or u\
718
- se the manual recipe in \`bvsala doctor\`.`:null}if(e==="copilot"){let n=Ga(t);return n.ok?null:n.error}return null}function vr(e,t,n,r={},o=process.env){let i=`http://127.0.0.1:${t}`;switch(e){case "c\
750
+ se the manual recipe in \`bvsala doctor\`.`:null}if(e==="copilot"){let n=ic(t);return n.ok?null:n.error}return null}function wr(e,t,n,r={},o=process.env){let i=`http://127.0.0.1:${t}`;switch(e){case "c\
719
751
  laude":return {bin:"claude",args:n,env:{ANTHROPIC_BASE_URL:i,ENABLE_TOOL_SEARCH:o.ENABLE_TOOL_SEARCH??"true"}};case "goose":return {bin:"goose",args:n,env:{ANTHROPIC_HOST:i}};case "qwen":return {bin:"qwen",
720
- args:n,env:{ANTHROPIC_BASE_URL:i},nota:'Qwen Code only routes through here with `security.auth.selectedType: "anthropic"` in ~/.qwen/settings.json (see `bvsala doctor`).'};case "opencode":case "kilo":{let s=Wa[e],
721
- a=Ka(o[s],`${i}/v1`),c=e==="opencode"?"opencode":"Kilo";return {bin:e,args:n,env:a===null?{}:{[s]:a},nota:`routes ${c}'s \`anthropic\` provider (your Anthropic API key) through the gateway, with ${s}: \
722
- nothing is written to disk. Other providers`+(e==="kilo"?", the Kilo Gateway included,":"")+" go straight to their API and are not metered."}}case "copilot":{let s=Ga(o);return s.ok?{bin:"copilot",args:n,
752
+ args:n,env:{ANTHROPIC_BASE_URL:i},nota:'Qwen Code only routes through here with `security.auth.selectedType: "anthropic"` in ~/.qwen/settings.json (see `bvsala doctor`).'};case "opencode":case "kilo":{let s=rc[e],
753
+ a=oc(o[s],`${i}/v1`),c=e==="opencode"?"opencode":"Kilo";return {bin:e,args:n,env:a===null?{}:{[s]:a},nota:`routes ${c}'s \`anthropic\` provider (your Anthropic API key) through the gateway, with ${s}: \
754
+ nothing is written to disk. Other providers`+(e==="kilo"?", the Kilo Gateway included,":"")+" go straight to their API and are not metered."}}case "copilot":{let s=ic(o);return s.ok?{bin:"copilot",args:n,
723
755
  env:{COPILOT_PROVIDER_BASE_URL:`${i}${s.ruta}`},nota:"BYOK with Anthropic: the gateway routes to api.anthropic.com. Your key and model stay as you exported them."}:{bin:"copilot",args:n,env:{}}}case "a\
724
- ider":{if(r.upstreamElegido===qa){let s=o.BVSALA_GATEWAY_USAGE_INJECT==="1";return {bin:"aider",args:n,env:{OPENAI_BASE_URL:`${i}/v1`,OPENAI_API_BASE:`${i}/v1`},upstream:qa,nota:"OpenAI models through \
756
+ ider":{if(r.upstreamElegido===tc){let s=o.BVSALA_GATEWAY_USAGE_INJECT==="1";return {bin:"aider",args:n,env:{OPENAI_BASE_URL:`${i}/v1`,OPENAI_API_BASE:`${i}/v1`},upstream:tc,nota:"OpenAI models through \
725
757
  the gateway (Anthropic ones go direct in this run). "+(s?"Usage injection is on: streamed replies ask for their usage.":"litellm asks for streamed usage only when it talks to api.openai.com itself: st\
726
758
  reamed replies are forwarded but NOT metered unless you relaunch with BVSALA_GATEWAY_USAGE_INJECT=1 (or use --no-stream).")}}return {bin:"aider",args:n,env:{ANTHROPIC_API_BASE:i},nota:"Anthropic models\
727
- through the gateway; OpenAI and other providers go direct and are not metered (for OpenAI models: BVSALA_GATEWAY_UPSTREAM=openai bvsala aider)."}}case "codex":{let s=r.modoCodex??"api-key",a=Yd[s];return {
759
+ through the gateway; OpenAI and other providers go direct and are not metered (for OpenAI models: BVSALA_GATEWAY_UPSTREAM=openai bvsala aider)."}}case "codex":{let s=r.modoCodex??"api-key",a=Mp[s];return {
728
760
  bin:"codex",args:["-c",`openai_base_url="${i}${a.prefijo}"`,...n],env:{},upstream:a.upstream,nota:s==="chatgpt"?"ChatGPT auth detected: the gateway routes to chatgpt.com/backend-api/codex. Subscriptio\
729
761
  n traffic is metered at list-price equivalent with no commission (there is no per-token invoice); the per-seat license applies as for any other use.":"API key auth: the gateway routes to api.openai.co\
730
- m/v1."}}}}var Zd=["gateway","doctor","skill","init"],Ya=new Set(["help","--help","-h"]),Za=new Set(["version","--version","-v"]);function Xa(e){let[t,...n]=e;return t===void 0||Ya.has(t)?{tipo:"ayuda",salida:0}:
731
- Za.has(t)?{tipo:"version"}:mn(t)?{tipo:"arrancar",comando:t,resto:n}:Zd.includes(t)?n.some(r=>Ya.has(r))?{tipo:"ayuda",salida:0}:n.some(r=>Za.has(r))?{tipo:"version"}:{tipo:"arrancar",comando:t,resto:n}:
732
- {tipo:"ayuda",salida:1}}function Qa(e){return e.length===1&&(e[0]==="--help"||e[0]==="-h"||e[0]==="--version")}function ec(e,t,n){let r=e??{},o=typeof r.puerto=="number"?r.puerto:n;if(r.code==="EADDRI\
762
+ m/v1."}}}}var $p=["gateway","doctor","skill","init"],ac=new Set(["help","--help","-h"]),cc=new Set(["version","--version","-v"]);function lc(e){let[t,...n]=e;return t===void 0||ac.has(t)?{tipo:"ayuda",salida:0}:
763
+ cc.has(t)?{tipo:"version"}:vn(t)?{tipo:"arrancar",comando:t,resto:n}:$p.includes(t)?n.some(r=>ac.has(r))?{tipo:"ayuda",salida:0}:n.some(r=>cc.has(r))?{tipo:"version"}:{tipo:"arrancar",comando:t,resto:n}:
764
+ {tipo:"ayuda",salida:1}}function uc(e){return e.length===1&&(e[0]==="--help"||e[0]==="-h"||e[0]==="--version")}function dc(e,t,n){let r=e??{},o=typeof r.puerto=="number"?r.puerto:n;if(r.code==="EADDRI\
733
765
  NUSE")return `port ${o} is already in use (another gateway, or a terminal launched earlier?): use --port ${o+1} or stop the other process`;if(r.code==="EACCES")return `port ${o} cannot be opened: permis\
734
- sion denied (EACCES; ports below 1024 need privileges): use --port ${Math.max(1024,o)} or higher`;let i=e instanceof Error?e.message:String(e);return `could not start the gateway for \`bvsala ${t}\`: ${i}`}function Xd(e){let t=Number.parseInt(e.slice(8,10),10);return Number.isFinite(t)&&t%2===0?"palanca":"control"}function tc(e){let t;try{t=JSON.parse(e());}catch{return null}if(typeof t!="object"||t===null)return null;let n=t,r=n.espia;return typeof r!="number"||!Number.isInteger(r)||r<1||r>65535?null:{activo:n.
735
- activo!==false,espia:r}}function nc(e){let{enrolamiento:t,espiaVivo:n,upstreamEnv:r,elisionEnv:o,hoyUtcIso:i}=e;if(!t)return {linea:"",aviso:false};if(!t.activo)return {linea:"A/B plan: enrolment paused (acti\
766
+ sion denied (EACCES; ports below 1024 need privileges): use --port ${Math.max(1024,o)} or higher`;let i=e instanceof Error?e.message:String(e);return `could not start the gateway for \`bvsala ${t}\`: ${i}`}function Np(e){let t=Number.parseInt(e.slice(8,10),10);return Number.isFinite(t)&&t%2===0?"palanca":"control"}function pc(e){let t;try{t=JSON.parse(e());}catch{return null}if(typeof t!="object"||t===null)return null;let n=t,r=n.espia;return typeof r!="number"||!Number.isInteger(r)||r<1||r>65535?null:{activo:n.
767
+ activo!==false,espia:r}}function fc(e){let{enrolamiento:t,espiaVivo:n,upstreamEnv:r,elisionEnv:o,hoyUtcIso:i}=e;if(!t)return {linea:"",aviso:false};if(!t.activo)return {linea:"A/B plan: enrolment paused (acti\
736
768
  vo:false)",aviso:false};if(!n)return {linea:`A/B plan: enrolled but the capture proxy is NOT listening on :${t.espia} \u2014 NOT chaining (today's traffic will not enter the corpus). Start it with \`pnpm anillo\
737
- 2:espia\`.`,aviso:true};let s=Xd(i),a=`http://127.0.0.1:${t.espia}`,c=r!==void 0&&r!=="",l=o!==void 0&&o!=="",d=[];d.push(`A/B plan: ${i} UTC \u2192 arm ${s.toUpperCase()}`);let u=e.upstreamOrigen==="fl\
769
+ 2:espia\`.`,aviso:true};let s=Np(i),a=`http://127.0.0.1:${t.espia}`,c=r!==void 0&&r!=="",l=o!==void 0&&o!=="",d=[];d.push(`A/B plan: ${i} UTC \u2192 arm ${s.toUpperCase()}`);let u=e.upstreamOrigen==="fl\
738
770
  ag"?"--upstream":"the environment";return d.push(c?`upstream kept from ${u} (${r})`:`chained to :${t.espia}`),l&&d.push(`elision flag kept from the environment (=${o})`),d.push("context elision dials \
739
- OFF (2026-09-09): the arm no longer turns them on"),d.push("assignment PER SESSION since 2026-09-10 (brazoDeSesion), not by day parity"),{...c?{}:{upstream:a},brazo:s,linea:d.join(", "),aviso:false}}var np="check: the gateway log must show `[gateway] POST /v1/messages \u2026`; if you see `/v1/v1\
740
- /messages`, there is one /v1 too many; if you see a bare `POST /messages`, one is missing.",rp=[{id:"claude",nombre:"Claude Code",binario:"claude",configs:[],detectable:true,receta:({base:e})=>["use `bv\
771
+ OFF (2026-09-09): the arm no longer turns them on"),d.push("assignment PER SESSION since 2026-09-10 (brazoDeSesion), not by day parity"),{...c?{}:{upstream:a},brazo:s,linea:d.join(", "),aviso:false}}var Vp="check: the gateway log must show `[gateway] POST /v1/messages \u2026`; if you see `/v1/v1\
772
+ /messages`, there is one /v1 too many; if you see a bare `POST /messages`, one is missing.",Fp=[{id:"claude",nombre:"Claude Code",binario:"claude",configs:[],detectable:true,receta:({base:e})=>["use `bv\
741
773
  sala claude` \u2014 starts the gateway on an ephemeral port, launches `claude` pointed at it and shuts it down on exit.",`by hand: ANTHROPIC_BASE_URL=${e} claude (no /v1: the client appends /v1/mess\
742
774
  ages)`]},{id:"codex",nombre:"Codex CLI",binario:"codex",configs:[join(".codex","config.toml"),join(".codex","auth.json")],detectable:true,comprobar:"check: the gateway log must show `[gateway] POST /v1/resp\
743
775
  onses \u2026` (API key) or `POST /backend-api/codex/responses \u2026` (ChatGPT); `/v1/v1/responses` means one /v1 too many.",receta:({base:e,rutas:t})=>["use `bvsala codex` \u2014 the base URL prefix depen\
@@ -784,109 +816,109 @@ he stream is forwarded but NOT metered; the last chunk then has an empty choices
784
816
  o is client.responses.create. Cost is priced at the model's list price;","a model without one is forwarded but not metered, and the gateway log says so on every such request."]},{id:"python-anthropic",
785
817
  nombre:"Python, or any Anthropic SDK (Messages)",configs:[],detectable:false,estadoSinDeteccion:"no detection: any language, through the SDK's base URL",receta:({base:e,puerto:t})=>[`start: bvsala gatewa\
786
818
  y --port ${t} (Anthropic is the default upstream)`,`python: client = Anthropic(base_url="${e}") (NO /v1: the SDK appends /v1/messages)`,`node: const client = new Anthropic({ baseURL: "${e}" })`,
787
- "streamed and stream=False requests are both metered."]}];function op(e,t){let n=e.split(delimiter).filter(o=>o.length>0),r=process.platform==="win32"?["",".exe",".cmd",".bat"]:[""];return o=>n.some(i=>r.some(
788
- s=>t(join(i,o+s))))}async function rc(e,t={}){if(!Number.isInteger(e)||e<1||e>65535)throw new RangeError(`[bvsala doctor] invalid port: ${String(e)}`);let n=t.home??homedir(),r=t.existe??existsSync,o=t.enPath??op(t.
819
+ "streamed and stream=False requests are both metered."]}];function qp(e,t){let n=e.split(delimiter).filter(o=>o.length>0),r=process.platform==="win32"?["",".exe",".cmd",".bat"]:[""];return o=>n.some(i=>r.some(
820
+ s=>t(join(i,o+s))))}async function mc(e,t={}){if(!Number.isInteger(e)||e<1||e>65535)throw new RangeError(`[bvsala doctor] invalid port: ${String(e)}`);let n=t.home??homedir(),r=t.existe??existsSync,o=t.enPath??qp(t.
789
821
  path??process.env.PATH??"",r),i=`http://127.0.0.1:${e}`,s=`${i}/v1`,a=[],c=[`bvsala doctor \u2014 local gateway at ${i}`,"Print only: it writes no configuration. Detection by existence (binaries on th\
790
822
  e PATH and","user configuration files); the contents of a file are never read.","The gateway needs BIVELIO_SERVICE_KEY and an active BiVelio license in every mode: it collects the license with that ke\
791
- y and does not start without one.",""];for(let l of rp){let d=l.configs.map(b=>join(n,b)),u=l.binario!==void 0&&o(l.binario),p=d.filter(b=>r(b)),f=u||p.length>0;f&&a.push(l.id);let g;l.detectable?f?g=`d\
823
+ y and does not start without one.",""];for(let l of Fp){let d=l.configs.map(b=>join(n,b)),u=l.binario!==void 0&&o(l.binario),p=d.filter(b=>r(b)),f=u||p.length>0;f&&a.push(l.id);let g;l.detectable?f?g=`d\
792
824
  etected \u2014 ${[...u?[`binary \`${l.binario}\` on PATH`]:[],...p.map(h=>`config present: ${h}`)].join("; ")}`:g="not detected":g=l.estadoSinDeteccion??"no automatic detection (editor extension)",c.push(
793
- `\xBB ${l.id}: ${g}`),c.push(` ${l.nombre}`);for(let b of l.receta({base:i,baseV1:s,puerto:e,rutas:d}))c.push(` ${b}`);l.comprobar!==null&&c.push(` ${l.comprobar??np}`),c.push("");}return c.push("BY\
825
+ `\xBB ${l.id}: ${g}`),c.push(` ${l.nombre}`);for(let b of l.receta({base:i,baseV1:s,puerto:e,rutas:d}))c.push(` ${b}`);l.comprobar!==null&&c.push(` ${l.comprobar??Vp}`),c.push("");}return c.push("BY\
794
826
  OK rule: the recipes for the third-party terminals (opencode, Kilo, Copilot, Aider, Goose, Crush, Qwen Code, Droid,","Cline, Continue) are for API keys. Never route the OAuth of a Claude Pro/Max subsc\
795
827
  ription through the gateway from a","third-party harness - Anthropic forbids it. Claude Code and Codex on a subscription are routed and metered at","list-price equivalent, with no commission (there is\
796
828
  no per-token invoice); the per-seat license applies.","Any language through the gateway: it measures every request whose usage it can read (Anthropic Messages, OpenAI Chat","Completions and Responses\
797
829
  ) for models with a list price, and its log line says when one is not metered. The saving","levers of the SDK (npm) are TypeScript; the gateway's own levers apply to Anthropic /v1/messages with a PRO \
798
830
  license.","Per-terminal detail: docs/terminales/<terminal>.md"),{texto:c.join(`
799
- `),detectados:a}}var Fo=["ai-sdk","mastra","langchain","anthropic-sdk","sdk"],gn={"ai-sdk":["openai","anthropic"],mastra:["openai","anthropic"],langchain:["openai","anthropic"],"anthropic-sdk":["anthropic"],sdk:["open\
800
- ai","anthropic"]},bn={"ai-sdk":"Vercel AI SDK",mastra:"Mastra",langchain:"LangChain.js","anthropic-sdk":"Anthropic TypeScript SDK",sdk:"the SDK directly (no framework)"},zo={"ai-sdk":"@bivelio/savings\
801
- -layer/ai-sdk",mastra:"@bivelio/savings-layer/mastra",langchain:"@bivelio/savings-layer/langchain","anthropic-sdk":"@bivelio/savings-layer/anthropic-sdk",sdk:"@bivelio/savings-layer"},ip={openai:"gpt-\
802
- 4o-mini",anthropic:"claude-haiku-4-5"},oc="What is 2 + 2 * 3?",hn=["licenseKey: process.env.BIVELIO_LICENSE_KEY,",'licenseServerUrl: "https://savings.bivelio.com",',"serviceAccountKey: process.env.BIV\
803
- ELIO_SERVICE_KEY,"],sp=["onReport: (report) => {"," seen.calls += 1;"," seen.avoidedLlm = report.calls.avoidedLlm;"," seen.basis = report.cost.basis;","},"];function ic(e,t){switch(e){case "ai-sdk":
831
+ `),detectados:a}}var Go=["ai-sdk","mastra","langchain","anthropic-sdk","sdk"],kn={"ai-sdk":["openai","anthropic"],mastra:["openai","anthropic"],langchain:["openai","anthropic"],"anthropic-sdk":["anthropic"],sdk:["open\
832
+ ai","anthropic"]},xn={"ai-sdk":"Vercel AI SDK",mastra:"Mastra",langchain:"LangChain.js","anthropic-sdk":"Anthropic TypeScript SDK",sdk:"the SDK directly (no framework)"},Jo={"ai-sdk":"@bivelio/savings\
833
+ -layer/ai-sdk",mastra:"@bivelio/savings-layer/mastra",langchain:"@bivelio/savings-layer/langchain","anthropic-sdk":"@bivelio/savings-layer/anthropic-sdk",sdk:"@bivelio/savings-layer"},zp={openai:"gpt-\
834
+ 4o-mini",anthropic:"claude-haiku-4-5"},hc="What is 2 + 2 * 3?",yn=["licenseKey: process.env.BIVELIO_LICENSE_KEY,",'licenseServerUrl: "https://savings.bivelio.com",',"serviceAccountKey: process.env.BIV\
835
+ ELIO_SERVICE_KEY,"],Hp=["onReport: (report) => {"," seen.calls += 1;"," seen.avoidedLlm = report.calls.avoidedLlm;"," seen.basis = report.cost.basis;","},"];function gc(e,t){switch(e){case "ai-sdk":
804
836
  return ["ai",t==="openai"?"@ai-sdk/openai":"@ai-sdk/anthropic"];case "mastra":return ["@mastra/core"];case "langchain":return ["langchain","@langchain/core",t==="openai"?"@langchain/openai":"@langchain/ant\
805
- hropic"];case "anthropic-sdk":return ["@anthropic-ai/sdk"];case "sdk":return []}}function $e(e,t){let n=" ".repeat(t);return e.map(r=>r===""?"":n+r)}function Ge(e){return e?"export ":""}function Bt(e,t){let n=ip[t];
837
+ hropic"];case "anthropic-sdk":return ["@anthropic-ai/sdk"];case "sdk":return []}}function je(e,t){let n=" ".repeat(t);return e.map(r=>r===""?"":n+r)}function Ze(e){return e?"export ":""}function qt(e,t){let n=zp[t];
806
838
  switch(e){case "ai-sdk":{let r=t==="openai"?"openai":"anthropic";return {imports:['import { wrapLanguageModel } from "ai";',`import { ${r} } from "@ai-sdk/${r}";`,'import { savingsMiddleware } from "@bi\
807
- velio/savings-layer/ai-sdk";'],adaptador:"savings",construir:(o,i)=>[`${Ge(i)}const savings = savingsMiddleware({`,...$e([...hn,...o],2),"});",...i?["","// Pass `model` wherever you pass a model today\
808
- (generateText, streamText\u2026).","// `savings` goes LAST in the middleware list: nothing between it and the model."]:[],`${Ge(i)}const model = wrapLanguageModel({ model: ${r}("${n}"), middleware: s\
839
+ velio/savings-layer/ai-sdk";'],adaptador:"savings",construir:(o,i)=>[`${Ze(i)}const savings = savingsMiddleware({`,...je([...yn,...o],2),"});",...i?["","// Pass `model` wherever you pass a model today\
840
+ (generateText, streamText\u2026).","// `savings` goes LAST in the middleware list: nothing between it and the model."]:[],`${Ze(i)}const model = wrapLanguageModel({ model: ${r}("${n}"), middleware: s\
809
841
  avings });`],exporta:["model"],importsDeUso:['import { generateText } from "ai";','import { getSavingsReport } from "@bivelio/savings-layer/ai-sdk";'],llamar:o=>[`const result = await generateText({ m\
810
842
  odel, ${o==="prompt"?"prompt":`prompt: ${o}`} });`,"const text = result.text;","const basis = getSavingsReport(result)?.cost.basis;"],daBasis:true,importsDeComprobacion:['import { generateText } from "a\
811
843
  i";'],preguntar:o=>[`const { text } = await generateText({ model, prompt: ${o} });`]}}case "mastra":return {imports:['import { Agent } from "@mastra/core/agent";','import { savingsProcessor } from "@biv\
812
- elio/savings-layer/mastra";'],adaptador:"bivelio",construir:(r,o)=>[`${Ge(o)}const bivelio = savingsProcessor({`,...$e([...hn,...r],2),"});",...o?["","// Add `bivelio` LAST to the inputProcessors of e\
813
- ach agent you already have;","// this one shows where. Its reports go to `onReport` if you pass one above."]:[],`${Ge(o)}const agent = new Agent({`,' id: "assistant",',' name: "Assistant",',' instr\
844
+ elio/savings-layer/mastra";'],adaptador:"bivelio",construir:(r,o)=>[`${Ze(o)}const bivelio = savingsProcessor({`,...je([...yn,...r],2),"});",...o?["","// Add `bivelio` LAST to the inputProcessors of e\
845
+ ach agent you already have;","// this one shows where. Its reports go to `onReport` if you pass one above."]:[],`${Ze(o)}const agent = new Agent({`,' id: "assistant",',' name: "Assistant",',' instr\
814
846
  uctions: "Answer briefly.",',` model: "${t}/${n}",`," inputProcessors: [bivelio],","});"],exporta:["agent"],importsDeUso:[],llamar:r=>[`const result = await agent.generate(${r});`,"const text = resu\
815
847
  lt.text;"],daBasis:false,importsDeComprobacion:[],preguntar:r=>[`const { text } = await agent.generate(${r});`]};case "langchain":return {imports:['import { createAgent } from "langchain";','import { savin\
816
- gsAgentMiddleware } from "@bivelio/savings-layer/langchain";'],adaptador:"savings",construir:(r,o)=>[`${Ge(o)}const savings = savingsAgentMiddleware({`,...$e([...hn,...r],2),"});",...o?["","// Add `sa\
817
- vings` LAST to the middleware of each agent you already have; this one shows where."]:[],`${Ge(o)}const agent = createAgent({ model: "${t}:${n}", tools: [], middleware: [savings] });`],exporta:["agent"],
848
+ gsAgentMiddleware } from "@bivelio/savings-layer/langchain";'],adaptador:"savings",construir:(r,o)=>[`${Ze(o)}const savings = savingsAgentMiddleware({`,...je([...yn,...r],2),"});",...o?["","// Add `sa\
849
+ vings` LAST to the middleware of each agent you already have; this one shows where."]:[],`${Ze(o)}const agent = createAgent({ model: "${t}:${n}", tools: [], middleware: [savings] });`],exporta:["agent"],
818
850
  importsDeUso:['import { getSavingsReportFromMessage } from "@bivelio/savings-layer/langchain";'],llamar:r=>[`const state = await agent.invoke({ messages: [{ role: "user", content: ${r} }] });`,"const \
819
851
  last = state.messages.at(-1);",'const text = last?.text ?? "";',"const basis = getSavingsReportFromMessage(last)?.cost.basis;"],daBasis:true,importsDeComprobacion:[],preguntar:r=>[`const state = await a\
820
852
  gent.invoke({ messages: [{ role: "user", content: ${r} }] });`,'const text = state.messages.at(-1)?.text ?? "";']};case "anthropic-sdk":{let r=i=>`const message = await client.messages.create({ model: \
821
853
  "${n}", max_tokens: 1024, messages: [{ role: "user", content: ${i} }] });`,o='const text = message.content.map((block) => (block.type === "text" ? block.text : "")).join("");';return {imports:['import \
822
- Anthropic from "@anthropic-ai/sdk";','import { anthropicSavings } from "@bivelio/savings-layer/anthropic-sdk";'],adaptador:"claudeSavings",construir:(i,s)=>[`${Ge(s)}const claudeSavings = anthropicSav\
823
- ings({`,...$e([...hn,...i],2),"});",...s?["","// Use `client` for messages.create(); `claudeSavings.middleware` goes LAST in the list."]:[],`${Ge(s)}const client = new Anthropic({ middleware: [claudeS\
854
+ Anthropic from "@anthropic-ai/sdk";','import { anthropicSavings } from "@bivelio/savings-layer/anthropic-sdk";'],adaptador:"claudeSavings",construir:(i,s)=>[`${Ze(s)}const claudeSavings = anthropicSav\
855
+ ings({`,...je([...yn,...i],2),"});",...s?["","// Use `client` for messages.create(); `claudeSavings.middleware` goes LAST in the list."]:[],`${Ze(s)}const client = new Anthropic({ middleware: [claudeS\
824
856
  avings.middleware] });`],exporta:["client","claudeSavings"],importsDeUso:[],llamar:i=>[r(i),o,"const basis = claudeSavings.reportFor(message)?.cost.basis;"],daBasis:true,importsDeComprobacion:[],preguntar:i=>[
825
857
  r(i),o]}}case "sdk":{let r=`${t}/${n}`,o=t==="openai"?'provider: new OpenAICompatibleProvider({ baseUrl: "https://api.openai.com/v1", apiKey: process.env.OPENAI_API_KEY }),':"provider: new AnthropicPro\
826
858
  vider({ apiKey: process.env.ANTHROPIC_API_KEY }),",i=t==="openai"?"OpenAICompatibleProvider":"AnthropicProvider";return {imports:[t==="openai"?`import { createSavingsLayer, ${i} } from "@bivelio/saving\
827
859
  s-layer";`:`import { ${i}, createSavingsLayer } from "@bivelio/savings-layer";`],adaptador:"layer",construir:(a,c)=>[...c?["// Your provider. LLM traffic goes straight to it: the layer is not a proxy."]:
828
- [],`${Ge(c)}const layer = createSavingsLayer({`,...$e([o,...hn,...a],2),"});"],exporta:["layer"],importsDeUso:[],llamar:a=>[`const { text, report } = await layer.generate({ model: "${r}", messages: [{\
860
+ [],`${Ze(c)}const layer = createSavingsLayer({`,...je([o,...yn,...a],2),"});"],exporta:["layer"],importsDeUso:[],llamar:a=>[`const { text, report } = await layer.generate({ model: "${r}", messages: [{\
829
861
  role: "user", content: ${a} }] });`,"const basis = report.cost.basis;"],daBasis:true,importsDeComprobacion:[],preguntar:a=>[`const { text, report } = await layer.generate({ model: "${r}", messages: [{ \
830
- role: "user", content: ${a} }] });`]}}}}function qo(e,t){let n=Bt(e,t);return ["// BiVelio Savings Layer: created once, when this module loads, and reused by every","// request. The exact cache lives i\
862
+ role: "user", content: ${a} }] });`]}}}}function Yo(e,t){let n=qt(e,t);return ["// BiVelio Savings Layer: created once, when this module loads, and reused by every","// request. The exact cache lives i\
831
863
  n this instance, so do not create one per request.",...n.imports,"",...n.construir([],true),""].join(`
832
- `)}var sc=["// BiVelio Savings Layer: a free wiring check, generated by `bvsala init`.","// It asks a question the layer answers on this machine (2 + 2 * 3), so with the","// layer in place the model \
864
+ `)}var bc=["// BiVelio Savings Layer: a free wiring check, generated by `bvsala init`.","// It asks a question the layer answers on this machine (2 + 2 * 3), so with the","// layer in place the model \
833
865
  is not called and your provider bills nothing for it.","// The saving is `estimated`, and estimated savings are never billed. It needs","// BIVELIO_LICENSE_KEY: the layer is fail-closed. Delete this f\
834
- ile once it says ok."];function ac(e){return e==="sdk"?['const ok = text.trim() === "8" && report.calls.avoidedLlm === 1;',"const line = ok",' ? `ok: the layer answered "8" on this machine without ca\
866
+ ile once it says ok."];function vc(e){return e==="sdk"?['const ok = text.trim() === "8" && report.calls.avoidedLlm === 1;',"const line = ok",' ? `ok: the layer answered "8" on this machine without ca\
835
867
  lling the model (basis: ${report.cost.basis}).`'," : `not ok: the layer did not answer it (got ${JSON.stringify(text)}). Send this output to support@bivelio.com.`;"]:['const ok = text.trim() === "8" \
836
868
  && seen.avoidedLlm === 1;',"const line = ok",' ? `ok: the layer answered "8" on this machine without calling the model (basis: ${seen.basis}).`'," : seen.calls === 0",' ? "not ok: the layer did n\
837
869
  ot see the call. It has to go LAST in the list, next to the model."'," : `not ok: the layer saw the call but did not answer it (got ${JSON.stringify(text)}). Send this output to support@bivelio.com\
838
- .`;"]}function cc(e,t){let n=Bt(e,t),r=Ho([...n.importsDeComprobacion,...n.imports]),o=e==="sdk"?n.construir([],false):['const seen = { calls: 0, avoidedLlm: 0, basis: "" };',...n.construir(sp,false)];return {
839
- imports:r,cuerpo:o}}function Ho(e){let t=new Map,n=[];for(let r of e){let o=/^import \{ ([^}]+) \} from "([^"]+)";$/.exec(r);if(!o){n.includes(r)||n.push(r);continue}let[,i="",s=""]=o,a=t.get(s);a||(a=
840
- new Set,t.set(s,a),n.push({modulo:s}));for(let c of i.split(", "))a.add(c);}return n.map(r=>typeof r=="string"?r:`import { ${[...t.get(r.modulo)??[]].sort().join(", ")} } from "${r.modulo}";`)}function lc(e,t){
841
- let n=Bt(e,t),{imports:r,cuerpo:o}=cc(e,t);return [...sc,...r,"",...o,"","try {",...$e([...n.preguntar(JSON.stringify(oc)),...ac(e),"console.log(line);","if (!ok) process.exitCode = 1;"],2),"} catch (e\
870
+ .`;"]}function yc(e,t){let n=qt(e,t),r=Zo([...n.importsDeComprobacion,...n.imports]),o=e==="sdk"?n.construir([],false):['const seen = { calls: 0, avoidedLlm: 0, basis: "" };',...n.construir(Hp,false)];return {
871
+ imports:r,cuerpo:o}}function Zo(e){let t=new Map,n=[];for(let r of e){let o=/^import \{ ([^}]+) \} from "([^"]+)";$/.exec(r);if(!o){n.includes(r)||n.push(r);continue}let[,i="",s=""]=o,a=t.get(s);a||(a=
872
+ new Set,t.set(s,a),n.push({modulo:s}));for(let c of i.split(", "))a.add(c);}return n.map(r=>typeof r=="string"?r:`import { ${[...t.get(r.modulo)??[]].sort().join(", ")} } from "${r.modulo}";`)}function kc(e,t){
873
+ let n=qt(e,t),{imports:r,cuerpo:o}=yc(e,t);return [...bc,...r,"",...o,"","try {",...je([...n.preguntar(JSON.stringify(hc)),...vc(e),"console.log(line);","if (!ok) process.exitCode = 1;"],2),"} catch (e\
842
874
  rr) {"," console.log(`not ok: ${err instanceof Error ? err.message : String(err)}`);"," process.exitCode = 1;","} finally {",` ${n.adaptador}.close();`,"}",""].join(`
843
- `)}function uc(e,t){let n=Bt(e,t),{imports:r,cuerpo:o}=cc(e,t);return [...sc,"// It answers only in development: in production it is a 404.",...r,"","// Run on each request, never at build time.",'expo\
844
- rt const dynamic = "force-dynamic";',"","export async function GET() {",' if (process.env.NODE_ENV === "production") {',' return new Response("Not found", { status: 404 });'," }",...$e(o,2)," tr\
845
- y {",...$e([...n.preguntar(JSON.stringify(oc)),...ac(e),"return Response.json({ ok, message: line }, { status: ok ? 200 : 500 });"],4)," } catch (err) {"," return Response.json({ ok: false, messag\
875
+ `)}function xc(e,t){let n=qt(e,t),{imports:r,cuerpo:o}=yc(e,t);return [...bc,"// It answers only in development: in production it is a 404.",...r,"","// Run on each request, never at build time.",'expo\
876
+ rt const dynamic = "force-dynamic";',"","export async function GET() {",' if (process.env.NODE_ENV === "production") {',' return new Response("Not found", { status: 404 });'," }",...je(o,2)," tr\
877
+ y {",...je([...n.preguntar(JSON.stringify(hc)),...vc(e),"return Response.json({ ok, message: line }, { status: ok ? 200 : 500 });"],4)," } catch (err) {"," return Response.json({ ok: false, messag\
846
878
  e: `not ok: ${err instanceof Error ? err.message : String(err)}` }, { status: 500 });"," } finally {",` ${n.adaptador}.close();`," }","}",""].join(`
847
- `)}function dc(e,t,n){let r=Bt(e,t),o=r.daBasis?"{ text, basis }":"{ text }";return [...Ho(r.importsDeUso),`import { ${r.exporta.slice().sort().join(", ")} } from "${n.importeDelCableado}";`,"",`export\
848
- async function POST(req${n.ts?": Request":""}) {`,` const { prompt } = ${n.ts?"(await req.json()) as { prompt: string }":"await req.json()"};`,...$e(r.llamar("prompt"),2),` return Response.json(${o}\
879
+ `)}function wc(e,t,n){let r=qt(e,t),o=r.daBasis?"{ text, basis }":"{ text }";return [...Zo(r.importsDeUso),`import { ${r.exporta.slice().sort().join(", ")} } from "${n.importeDelCableado}";`,"",`export\
880
+ async function POST(req${n.ts?": Request":""}) {`,` const { prompt } = ${n.ts?"(await req.json()) as { prompt: string }":"await req.json()"};`,...je(r.llamar("prompt"),2),` return Response.json(${o}\
849
881
  );`,"}",""].join(`
850
- `)}function pc(e,t){let n=Bt(e,t),r=n.daBasis?"{ text, basis }":"{ text }";return ['import express from "express";',...Ho([...n.imports,...n.importsDeUso]),"","// Created once, at startup, not inside t\
851
- he handler: the exact cache lives in this instance.",...n.construir([],false),"","const app = express();","app.use(express.json());","",'app.post("/api/chat", async (req, res, next) => {'," try {",...$e(
882
+ `)}function Sc(e,t){let n=qt(e,t),r=n.daBasis?"{ text, basis }":"{ text }";return ['import express from "express";',...Zo([...n.imports,...n.importsDeUso]),"","// Created once, at startup, not inside t\
883
+ he handler: the exact cache lives in this instance.",...n.construir([],false),"","const app = express();","app.use(express.json());","",'app.post("/api/chat", async (req, res, next) => {'," try {",...je(
852
884
  n.llamar('String(req.body?.prompt ?? "")'),4),` res.json(${r});`," } catch (err) {"," next(err);"," }","});","","app.listen(Number(process.env.PORT ?? 3000));",""].join(`
853
- `)}var yr="usage: bvsala init [--write [--yes]] [--json] [--stack ai-sdk|mastra|langchain|anthropic-sdk|sdk] [--provider openai|anthropic] [--cwd <dir>]";function bc(e,t){let n={cwd:t,escribir:false,si:false,json:false};
885
+ `)}var Sr="usage: bvsala init [--write [--yes]] [--json] [--stack ai-sdk|mastra|langchain|anthropic-sdk|sdk] [--provider openai|anthropic] [--cwd <dir>]";function Ac(e,t){let n={cwd:t,escribir:false,si:false,json:false};
854
886
  for(let r=0;r<e.length;r++){let o=e[r],i=()=>{let s=e[r+1];if(!(s===void 0||s.startsWith("-")))return r++,s};if(o==="--write")n.escribir=true;else if(o==="--yes"||o==="-y")n.si=true;else if(o==="--json")n.
855
- json=true;else if(o==="--stack"){let s=i();if(!s||!Fo.includes(s))return {ok:false,mensaje:`--stack needs one of: ${Fo.join(", ")}.
856
- ${yr}`};n.capa=s;}else if(o==="--provider"){let s=i();if(s!=="openai"&&s!=="anthropic")return {ok:false,mensaje:`--provider needs openai or anthropic.
857
- ${yr}`};n.proveedor=s;}else if(o==="--cwd"){let s=i();if(!s)return {ok:false,mensaje:`--cwd needs a directory.
858
- ${yr}`};n.cwd=s.startsWith("/")||/^[A-Za-z]:[\\/]/.test(s)?s:join(t,s);}else return {ok:false,mensaje:`unknown option: ${o}
859
- ${yr}`}}return n.json&&n.escribir?{ok:false,mensaje:"--json prints the plan and --write applies it: use one of them."}:n.si&&!n.escribir?{ok:false,mensaje:"--yes only confirms --write: add --write, or drop \
860
- --yes."}:n.capa&&n.proveedor&&!gn[n.capa].includes(n.proveedor)?{ok:false,mensaje:`--stack ${n.capa} only works with --provider ${gn[n.capa].join(" or ")}.`}:{ok:true,valor:n}}var ap=[["pnpm-lock.yaml","pn\
861
- pm"],["yarn.lock","yarn"],["bun.lock","bun"],["bun.lockb","bun"],["package-lock.json","npm"]];function cp(e,t,n){if(typeof e.packageManager=="string"){let r=e.packageManager.split("@")[0];if(r==="pnpm"||
862
- r==="yarn"||r==="bun"||r==="npm")return r}for(let r=t,o=0;o<20;o++){for(let[s,a]of ap)if(n.existe(join(r,s)))return a;let i=dirname(r);if(i===r)break;r=i;}return "npm"}function lp(e){let t={};for(let n of [e.devDependencies,
863
- e.dependencies])if(n&&typeof n=="object")for(let[r,o]of Object.entries(n))typeof o=="string"&&(t[r]=o);return t}function up(e,t,n,r){let o=r.leer(join(n,"node_modules",...e.split("/"),"package.json"));if(o)
887
+ json=true;else if(o==="--stack"){let s=i();if(!s||!Go.includes(s))return {ok:false,mensaje:`--stack needs one of: ${Go.join(", ")}.
888
+ ${Sr}`};n.capa=s;}else if(o==="--provider"){let s=i();if(s!=="openai"&&s!=="anthropic")return {ok:false,mensaje:`--provider needs openai or anthropic.
889
+ ${Sr}`};n.proveedor=s;}else if(o==="--cwd"){let s=i();if(!s)return {ok:false,mensaje:`--cwd needs a directory.
890
+ ${Sr}`};n.cwd=s.startsWith("/")||/^[A-Za-z]:[\\/]/.test(s)?s:join(t,s);}else return {ok:false,mensaje:`unknown option: ${o}
891
+ ${Sr}`}}return n.json&&n.escribir?{ok:false,mensaje:"--json prints the plan and --write applies it: use one of them."}:n.si&&!n.escribir?{ok:false,mensaje:"--yes only confirms --write: add --write, or drop \
892
+ --yes."}:n.capa&&n.proveedor&&!kn[n.capa].includes(n.proveedor)?{ok:false,mensaje:`--stack ${n.capa} only works with --provider ${kn[n.capa].join(" or ")}.`}:{ok:true,valor:n}}var Wp=[["pnpm-lock.yaml","pn\
893
+ pm"],["yarn.lock","yarn"],["bun.lock","bun"],["bun.lockb","bun"],["package-lock.json","npm"]];function Kp(e,t,n){if(typeof e.packageManager=="string"){let r=e.packageManager.split("@")[0];if(r==="pnpm"||
894
+ r==="yarn"||r==="bun"||r==="npm")return r}for(let r=t,o=0;o<20;o++){for(let[s,a]of Wp)if(n.existe(join(r,s)))return a;let i=dirname(r);if(i===r)break;r=i;}return "npm"}function Gp(e){let t={};for(let n of [e.devDependencies,
895
+ e.dependencies])if(n&&typeof n=="object")for(let[r,o]of Object.entries(n))typeof o=="string"&&(t[r]=o);return t}function Jp(e,t,n,r){let o=r.leer(join(n,"node_modules",...e.split("/"),"package.json"));if(o)
864
896
  try{let s=JSON.parse(o).version;if(typeof s=="string")return s}catch{}let i=/(\d+)(?:\.(\d+))?(?:\.(\d+))?/.exec(t.replace(/^npm:[^@]+@/,""));if(!(!i||/^(workspace|catalog|link|file|git|github):/.test(
865
- t)))return `${i[1]}.${i[2]??0}.${i[3]??0}`}function Go(e){let[t=0,n=0,r=0]=e.split(/[.+-]/).map(o=>Number.parseInt(o,10)||0);return [t,n,r]}function Jo(e,t){let n=Go(e),r=Go(t);for(let o=0;o<3;o++)if(n[o]!==
866
- r[o])return n[o]>r[o];return true}var vc=[{paquete:"ai",capa:"ai-sdk",desde:"6.0.0",hasta:"8.0.0",texto:"ai 6 or 7"},{paquete:"@mastra/core",capa:"mastra",desde:"1.68.0",hasta:"2.0.0",texto:"@mastra/core\
897
+ t)))return `${i[1]}.${i[2]??0}.${i[3]??0}`}function ei(e){let[t=0,n=0,r=0]=e.split(/[.+-]/).map(o=>Number.parseInt(o,10)||0);return [t,n,r]}function ti(e,t){let n=ei(e),r=ei(t);for(let o=0;o<3;o++)if(n[o]!==
898
+ r[o])return n[o]>r[o];return true}var Rc=[{paquete:"ai",capa:"ai-sdk",desde:"6.0.0",hasta:"8.0.0",texto:"ai 6 or 7"},{paquete:"@mastra/core",capa:"mastra",desde:"1.68.0",hasta:"2.0.0",texto:"@mastra/core\
867
899
  \u2265 1.68 < 2"},{paquete:"langchain",capa:"langchain",desde:"1.1.0",hasta:"2.0.0",texto:"langchain \u2265 1.1 < 2"},{paquete:"@langchain/core",capa:"langchain",desde:"1.1.0",hasta:"2.0.0",texto:"@l\
868
- angchain/core \u2265 1.1 < 2"},{paquete:"@anthropic-ai/sdk",capa:"anthropic-sdk",desde:"0.103.0",hasta:"1.0.0",texto:"@anthropic-ai/sdk \u2265 0.103 < 1"}],yc=[["@mastra/core","mastra"],["langchain","\
869
- langchain"],["ai","ai-sdk"],["@anthropic-ai/sdk","anthropic-sdk"],["openai","sdk"]];function kc(e,t){let n=t.leer(join(e,"package.json"));if(n===void 0){let u=["pyproject.toml","requirements.txt","setup\
900
+ angchain/core \u2265 1.1 < 2"},{paquete:"@anthropic-ai/sdk",capa:"anthropic-sdk",desde:"0.103.0",hasta:"1.0.0",texto:"@anthropic-ai/sdk \u2265 0.103 < 1"}],Ic=[["@mastra/core","mastra"],["langchain","\
901
+ langchain"],["ai","ai-sdk"],["@anthropic-ai/sdk","anthropic-sdk"],["openai","sdk"]];function Pc(e,t){let n=t.leer(join(e,"package.json"));if(n===void 0){let u=["pyproject.toml","requirements.txt","setup\
870
902
  .py","Pipfile"].find(p=>t.existe(join(e,p)));return u?{ok:false,mensaje:`no package.json in ${e}, and ${u} says this is Python. The SDK is TypeScript; for Python (or any language), run the local gateway an\
871
903
  d point your client's base URL at it: \`bvsala gateway --upstream openai --port 8403\`, then OpenAI(base_url="http://127.0.0.1:8403/v1"). It measures; the saving levers are TypeScript. \`bvsala doctor\` p\
872
904
  rints the recipe for each SDK.`}:{ok:false,mensaje:`no package.json in ${e}. Run this from your project's root, or pass --cwd <dir>.`}}let r;try{r=JSON.parse(n);}catch(u){return {ok:false,mensaje:`${join(e,"pac\
873
905
  kage.json")} is not valid JSON (${u instanceof Error?u.message:String(u)}). Fix it and run init again.`}}if(!r||typeof r!="object"||Array.isArray(r))return {ok:false,mensaje:`${join(e,"package.json")} is no\
874
- t a JSON object. Fix it and run init again.`};let o=lp(r),i={};for(let[u,p]of Object.entries(o))i[u]=up(u,p,e,t);let s=["app","src/app"].find(u=>t.existe(join(e,...u.split("/")))),a="next"in i?"next":"e\
875
- xpress"in i?"express":"node",c=yc.filter(([u])=>u in i).map(([,u])=>u),l={dir:e,gestor:cp(r,e,t),ts:"typescript"in i||t.existe(join(e,"tsconfig.json")),esm:r.type==="module",anfitrion:a,src:t.existe(join(
906
+ t a JSON object. Fix it and run init again.`};let o=Gp(r),i={};for(let[u,p]of Object.entries(o))i[u]=Jp(u,p,e,t);let s=["app","src/app"].find(u=>t.existe(join(e,...u.split("/")))),a="next"in i?"next":"e\
907
+ xpress"in i?"express":"node",c=Ic.filter(([u])=>u in i).map(([,u])=>u),l={dir:e,gestor:Kp(r,e,t),ts:"typescript"in i||t.existe(join(e,"tsconfig.json")),esm:r.type==="module",anfitrion:a,src:t.existe(join(
876
908
  e,"src")),capas:c,deps:i,monorepo:r.workspaces!==void 0||t.existe(join(e,"pnpm-workspace.yaml")),ficherosEnv:[".env",".env.local"].filter(u=>t.existe(join(e,u))),scriptDev:typeof r.scripts?.dev=="string"},
877
909
  d=a==="node"?void 0:i[a];return d&&(l.versionDelAnfitrion=d),a==="next"&&s&&(l.appDir=s),"@bivelio/savings-layer"in o&&(l.yaInstalado=i["@bivelio/savings-layer"]??o["@bivelio/savings-layer"]),{ok:true,valor:l}}
878
- var mc=(e,t)=>t.some(n=>n in e.deps),dp=["openai","@ai-sdk/openai","@langchain/openai"],pp=["@anthropic-ai/sdk","@ai-sdk/anthropic","@langchain/anthropic"];function fp(e,t){if(e==="anthropic-sdk")return "\
910
+ var _c=(e,t)=>t.some(n=>n in e.deps),Yp=["openai","@ai-sdk/openai","@langchain/openai"],Zp=["@anthropic-ai/sdk","@ai-sdk/anthropic","@langchain/anthropic"];function Xp(e,t){if(e==="anthropic-sdk")return "\
879
911
  anthropic";if(e==="ai-sdk"){if("@ai-sdk/openai"in t.deps)return "openai";if("@ai-sdk/anthropic"in t.deps)return "anthropic"}if(e==="langchain"){if("@langchain/openai"in t.deps)return "openai";if("@langch\
880
- ain/anthropic"in t.deps)return "anthropic"}return mc(t,pp)&&!mc(t,dp)?"anthropic":"openai"}function hc(e,t){for(let n of vc){if(n.capa!==e)continue;let r=t.deps[n.paquete];if(r!==void 0&&(!Jo(r,n.desde)||
881
- Jo(r,n.hasta)))return `${n.paquete} ${r} is outside what the adapter supports (${n.texto})`}}var Wo={npm:"npm i",pnpm:"pnpm add",yarn:"yarn add",bun:"bun add"};function mp(e){let t=e.ficherosEnv[0];return t?
882
- `node --env-file=${t} bivelio-check.mjs`:"node bivelio-check.mjs"}function xc(e,t,n){let[r=0]=Go(n.node);if(r<20)return {ok:false,mensaje:`Node ${n.node} is too old: @bivelio/savings-layer needs Node \u2265 20\
883
- . Upgrade Node and run init again.`};let o=[],i=t.capa,s=[];if(i){let f=hc(i,e);f&&o.push(`${f}: the snippets below will not work until you upgrade it.`);}else for(let f of e.capas){let g=hc(f,e);if(!g){
912
+ ain/anthropic"in t.deps)return "anthropic"}return _c(t,Zp)&&!_c(t,Yp)?"anthropic":"openai"}function Tc(e,t){for(let n of Rc){if(n.capa!==e)continue;let r=t.deps[n.paquete];if(r!==void 0&&(!ti(r,n.desde)||
913
+ ti(r,n.hasta)))return `${n.paquete} ${r} is outside what the adapter supports (${n.texto})`}}var Xo={npm:"npm i",pnpm:"pnpm add",yarn:"yarn add",bun:"bun add"};function Qp(e){let t=e.ficherosEnv[0];return t?
914
+ `node --env-file=${t} bivelio-check.mjs`:"node bivelio-check.mjs"}function Dc(e,t,n){let[r=0]=ei(n.node);if(r<20)return {ok:false,mensaje:`Node ${n.node} is too old: @bivelio/savings-layer needs Node \u2265 20\
915
+ . Upgrade Node and run init again.`};let o=[],i=t.capa,s=[];if(i){let f=Tc(i,e);f&&o.push(`${f}: the snippets below will not work until you upgrade it.`);}else for(let f of e.capas){let g=Tc(f,e);if(!g){
884
916
  i=f;break}s.push({capa:f,motivo:g});}i||(i="sdk",e.capas.length===0&&o.push(e.monorepo?"No LLM library in this package.json, and it looks like a monorepo root: run init inside the package that calls th\
885
917
  e LLM (--cwd <path>).":"No LLM library found (ai, @mastra/core, langchain, @anthropic-ai/sdk or openai): showing the SDK on its own. If you call the LLM from another language, see `bvsala doctor`."));
886
- for(let f of s){let g=vc.find(b=>b.capa===f.capa&&f.motivo.startsWith(`${b.paquete} `))?.paquete??"";o.push(`${f.motivo}: showing ${bn[i]} instead. To use the ${bn[f.capa]} adapter, upgrade it: ${Wo[e.
887
- gestor]} ${g}@latest`);}let a=t.proveedor??fp(i,e);if(!gn[i].includes(a))return {ok:false,mensaje:`--stack ${i} only works with --provider ${gn[i].join(" or ")}.`};let c=[];e.yaInstalado||c.push("@bivelio/\
888
- savings-layer");for(let f of ic(i,a))f in e.deps||c.push(f);a==="openai"&&!("gpt-tokenizer"in e.deps)&&c.push("gpt-tokenizer");let l=e.deps["@bivelio/savings-layer"];e.yaInstalado&&i!=="sdk"&&l&&!Jo(l,
889
- "0.4.25")&&o.push(`@bivelio/savings-layer ${l} has no framework adapters (they arrived in 0.4.25): ${Wo[e.gestor]} @bivelio/savings-layer@latest`),r<22&&(i==="mastra"||i==="ai-sdk"&&(e.deps.ai??"7").startsWith(
918
+ for(let f of s){let g=Rc.find(b=>b.capa===f.capa&&f.motivo.startsWith(`${b.paquete} `))?.paquete??"";o.push(`${f.motivo}: showing ${xn[i]} instead. To use the ${xn[f.capa]} adapter, upgrade it: ${Xo[e.
919
+ gestor]} ${g}@latest`);}let a=t.proveedor??Xp(i,e);if(!kn[i].includes(a))return {ok:false,mensaje:`--stack ${i} only works with --provider ${kn[i].join(" or ")}.`};let c=[];e.yaInstalado||c.push("@bivelio/\
920
+ savings-layer");for(let f of gc(i,a))f in e.deps||c.push(f);a==="openai"&&!("gpt-tokenizer"in e.deps)&&c.push("gpt-tokenizer");let l=e.deps["@bivelio/savings-layer"];e.yaInstalado&&i!=="sdk"&&l&&!ti(l,
921
+ "0.4.25")&&o.push(`@bivelio/savings-layer ${l} has no framework adapters (they arrived in 0.4.25): ${Xo[e.gestor]} @bivelio/savings-layer@latest`),r<22&&(i==="mastra"||i==="ai-sdk"&&(e.deps.ai??"7").startsWith(
890
922
  "7"))&&o.push(`Node ${n.node}: ${i==="mastra"?"@mastra/core":"ai 7"} declares Node \u2265 22 in its own engines.`),!e.ts&&!e.esm&&e.anfitrion!=="next"&&o.push('Your package.json has no "type": "module\
891
923
  " and the package is ESM-only. The check is a .mjs file and runs as is; from your own CommonJS files, load it with `await import(\u2026)`, or with require() on Node \u2265 22.');let d=[{nombre:"BIVELI\
892
924
  O_LICENSE_KEY",puesta:n.env("BIVELIO_LICENSE_KEY"),para:"required: the layer is fail-closed"},{nombre:"BIVELIO_SERVICE_KEY",puesta:n.env("BIVELIO_SERVICE_KEY"),para:"seat metering and license auto-ren\
@@ -895,68 +927,89 @@ est without credentials"});else {let f=a==="openai"?"OPENAI_API_KEY":"ANTHROPIC_
895
927
  "your provider key; the free check does not need it";d.push({nombre:f,puesta:n.env(f),para:g});}let u=e.anfitrion==="next"?"Put them in .env.local (Next.js loads it) or in your host's environment setti\
896
928
  ngs.":e.ficherosEnv.length>0?`Export them, or keep them in ${e.ficherosEnv[0]} and pass it to node with --env-file (Node \u2265 20.6).`:"Export them in your shell, or keep them in a .env file and pass\
897
929
  it to node with --env-file (Node \u2265 20.6).",p={deteccion:e,capa:i,proveedor:a,alternativas:e.capas.filter(f=>f!==i),instalar:c,claves:d,dondeVanLasClaves:u,ficheros:[],usos:[],comoComprobar:[],avisos:o};
898
- return c.length>0&&(p.comandoDeInstalacion=`${Wo[e.gestor]} ${c.join(" ")}`),{ok:true,valor:p}}function wc(e,t){let n=e.deteccion,{capa:r,proveedor:o}=e,i=n.ts?"ts":n.esm||n.anfitrion==="next"?"js":"mjs",
930
+ return c.length>0&&(p.comandoDeInstalacion=`${Xo[e.gestor]} ${c.join(" ")}`),{ok:true,valor:p}}function Oc(e,t){let n=e.deteccion,{capa:r,proveedor:o}=e,i=n.ts?"ts":n.esm||n.anfitrion==="next"?"js":"mjs",
899
931
  s=p=>t.existe(join(n.dir,...p.split("/"))),a=[],c=[],l=[],d=n.anfitrion==="next"?`${n.appDir?.startsWith("src/")?"src/":""}lib/savings.${i}`:`${n.src?"src/":""}savings.${i}`;if(n.anfitrion==="next"&&n.appDir){
900
- a.push({ruta:d,proposito:"wiring",contenido:qo(r,o),existe:s(d)});let p=`${n.appDir}/api/chat/route.${i}`,f=posix.relative(posix.dirname(p),d.replace(/\.[^.]+$/,""));c.push({titulo:`Use it in a route handle\
901
- r (example: ${p})`,ruta:p,contenido:dc(r,o,{ts:n.ts,importeDelCableado:f.startsWith(".")?f:`./${f}`})});let g=`${n.appDir}/api/bivelio-check/route.${i}`;a.push({ruta:g,proposito:"check",contenido:uc(r,
932
+ a.push({ruta:d,proposito:"wiring",contenido:Yo(r,o),existe:s(d)});let p=`${n.appDir}/api/chat/route.${i}`,f=posix.relative(posix.dirname(p),d.replace(/\.[^.]+$/,""));c.push({titulo:`Use it in a route handle\
933
+ r (example: ${p})`,ruta:p,contenido:wc(r,o,{ts:n.ts,importeDelCableado:f.startsWith(".")?f:`./${f}`})});let g=`${n.appDir}/api/bivelio-check/route.${i}`;a.push({ruta:g,proposito:"check",contenido:xc(r,
902
934
  o),existe:s(g)});let b=n.scriptDev?n.gestor==="npm"?"npm run dev":`${n.gestor} dev`:"next dev";l.push(`Start your dev server (${b}) and open http://localhost:3000/api/bivelio-check (or your dev port).`,
903
935
  'It answers {"ok":true,\u2026} when the layer is in place, and a message that says what to fix when it is not.');}else n.anfitrion==="express"?c.push({titulo:"In your Express server: the layer is creat\
904
- ed once at startup, then used by the route",ruta:`server.${i}`,contenido:pc(r,o)}):a.push({ruta:d,proposito:"wiring",contenido:qo(r,o),existe:s(d)}),a.push({ruta:"bivelio-check.mjs",proposito:"check",
905
- contenido:lc(r,o),existe:s("bivelio-check.mjs")}),l.push(`Run it: ${mp(n)}`,'It prints "ok: \u2026" and exits 0 when the layer is in place, or "not ok: \u2026" with what to fix and exits 1.');let u=[...e.
936
+ ed once at startup, then used by the route",ruta:`server.${i}`,contenido:Sc(r,o)}):a.push({ruta:d,proposito:"wiring",contenido:Yo(r,o),existe:s(d)}),a.push({ruta:"bivelio-check.mjs",proposito:"check",
937
+ contenido:kc(r,o),existe:s("bivelio-check.mjs")}),l.push(`Run it: ${Qp(n)}`,'It prints "ok: \u2026" and exits 0 when the layer is in place, or "not ok: \u2026" with what to fix and exits 1.');let u=[...e.
906
938
  avisos];return n.anfitrion==="next"&&!n.appDir&&u.push("No app/ directory (Pages Router?): the check is a script instead of a route. The wiring works the same from an API route."),l.push("The question\
907
939
  (2 + 2 * 3) is answered on your machine: with the layer in place the model is not called, so your provider bills nothing for it,","and the saving is `estimated`, which is never billed. Delete the che\
908
- ck once it says ok."),{...e,ficheros:a,usos:c,comoComprobar:l,avisos:u}}function Ko(e,t){let n="-".repeat(Math.max(8,Math.min(72,e.length+12)));return `----- ${e} -----
940
+ ck once it says ok."),{...e,ficheros:a,usos:c,comoComprobar:l,avisos:u}}function Qo(e,t){let n="-".repeat(Math.max(8,Math.min(72,e.length+12)));return `----- ${e} -----
909
941
  ${t.replace(/\n$/,"")}
910
- ${n}`}function hp(e){let t=[];return e.anfitrion==="next"?t.push(`Next.js${e.versionDelAnfitrion?` ${e.versionDelAnfitrion}`:""}${e.appDir?`, App Router in ${e.appDir}`:""}`):e.anfitrion==="express"?t.
911
- push(`Express${e.versionDelAnfitrion?` ${e.versionDelAnfitrion}`:""}`):t.push("Node.js"),t.push(e.ts?"TypeScript":e.esm?"JavaScript (ESM)":"JavaScript (CommonJS)"),t.push(e.gestor),t.join(", ")}function gp(e){
912
- let t=e.deteccion,n=yc.find(([,s])=>s===e.capa)?.[0],r=n?t.deps[n]:void 0,o=t.capas.includes(e.capa);return `${`${bn[e.capa]}${o&&r&&e.capa!=="sdk"?` ${r}`:""}`}${o||e.capa==="sdk"?"":" (not installed \
913
- yet)"} with ${e.proveedor==="openai"?"OpenAI":"Anthropic"} models \u2192 ${zo[e.capa]}`}function Sc(e,t,n,r={}){let o=e.deteccion,i=[t,"",`Detected in ${o.dir}`,` app: ${hp(o)}`,` LLM calls: \
914
- ${gp(e)}`];if(e.alternativas.length>0&&i.push(` also found: ${e.alternativas.map(u=>`${bn[u]} (${n} --stack ${u})`).join(", ")}`),o.yaInstalado){let u=o.deps["@bivelio/savings-layer"];i.push(` inst\
942
+ ${n}`}function ef(e){let t=[];return e.anfitrion==="next"?t.push(`Next.js${e.versionDelAnfitrion?` ${e.versionDelAnfitrion}`:""}${e.appDir?`, App Router in ${e.appDir}`:""}`):e.anfitrion==="express"?t.
943
+ push(`Express${e.versionDelAnfitrion?` ${e.versionDelAnfitrion}`:""}`):t.push("Node.js"),t.push(e.ts?"TypeScript":e.esm?"JavaScript (ESM)":"JavaScript (CommonJS)"),t.push(e.gestor),t.join(", ")}function tf(e){
944
+ let t=e.deteccion,n=Ic.find(([,s])=>s===e.capa)?.[0],r=n?t.deps[n]:void 0,o=t.capas.includes(e.capa);return `${`${xn[e.capa]}${o&&r&&e.capa!=="sdk"?` ${r}`:""}`}${o||e.capa==="sdk"?"":" (not installed \
945
+ yet)"} with ${e.proveedor==="openai"?"OpenAI":"Anthropic"} models \u2192 ${Jo[e.capa]}`}function Lc(e,t,n,r={}){let o=e.deteccion,i=[t,"",`Detected in ${o.dir}`,` app: ${ef(o)}`,` LLM calls: \
946
+ ${tf(e)}`];if(e.alternativas.length>0&&i.push(` also found: ${e.alternativas.map(u=>`${xn[u]} (${n} --stack ${u})`).join(", ")}`),o.yaInstalado){let u=o.deps["@bivelio/savings-layer"];i.push(` inst\
915
947
  alled: @bivelio/savings-layer ${u??`(declared as "${o.yaInstalado}")`}`);}for(let u of e.avisos)i.push("",`note: ${u}`);let s=1;i.push("",`${s++} \xB7 Install`),i.push(e.comandoDeInstalacion?` ${e.comandoDeInstalacion}`:
916
948
  " nothing to install: every package the snippets import is already a dependency."),i.push("",`${s++} \xB7 Keys (checked by name in this shell; values are never read or shown)`);let a=Math.max(...e.claves.
917
949
  map(u=>u.nombre.length));for(let u of e.claves)i.push(` ${u.nombre.padEnd(a)} ${u.puesta?"set ":"not set"} ${u.para}`);i.push(" Copy the BiVelio keys from https://savings.bivelio.com/dashboard/\
918
950
  install. Running needs an active license:"," without one, every call fails with LicenseError and the model is not called.",` ${e.dondeVanLasClaves}`);let c=e.ficheros.find(u=>u.proposito==="wiring");
919
- i.push("",`${s++} \xB7 Wire it`),c&&i.push(Ko(`${c.ruta} (new file${c.existe?"; it already exists, compare it":""})`,c.contenido));for(let u of e.usos)i.push(Ko(u.titulo,u.contenido));let l=e.ficheros.
920
- find(u=>u.proposito==="check");i.push("",`${s++} \xB7 Check it, for free`),l&&i.push(Ko(`${l.ruta} (new file${l.existe?"; it already exists, compare it":""})`,l.contenido));for(let u of e.comoComprobar)
951
+ i.push("",`${s++} \xB7 Wire it`),c&&i.push(Qo(`${c.ruta} (new file${c.existe?"; it already exists, compare it":""})`,c.contenido));for(let u of e.usos)i.push(Qo(u.titulo,u.contenido));let l=e.ficheros.
952
+ find(u=>u.proposito==="check");i.push("",`${s++} \xB7 Check it, for free`),l&&i.push(Qo(`${l.ruta} (new file${l.existe?"; it already exists, compare it":""})`,l.contenido));for(let u of e.comoComprobar)
921
953
  i.push(` ${u}`);let d=e.ficheros.filter(u=>!u.existe);return r.escribira||(i.push(""),d.length>0?i.push(`Nothing was written. To create ${d.length===1?"the new file":`the ${d.length} new files`} abov\
922
954
  e (${d.map(u=>u.ruta).join(", ")}): ${n} --write. It asks first and never overwrites; nothing else is touched.`):i.push("Nothing was written: the files above already exist in your project.")),i.join(`\
923
955
 
924
- `)}function Ec(e,t){let n=e.deteccion;return JSON.stringify({version:t,dir:n.dir,detected:{host:n.anfitrion,hostVersion:n.versionDelAnfitrion??null,appDir:n.appDir??null,typescript:n.ts,esm:n.esm,packageManager:n.
925
- gestor,stacks:n.capas,installed:n.yaInstalado?n.deps["@bivelio/savings-layer"]??n.yaInstalado:null},stack:e.capa,provider:e.proveedor,adapter:zo[e.capa],install:e.comandoDeInstalacion??null,keys:e.claves.
956
+ `)}function Mc(e,t){let n=e.deteccion;return JSON.stringify({version:t,dir:n.dir,detected:{host:n.anfitrion,hostVersion:n.versionDelAnfitrion??null,appDir:n.appDir??null,typescript:n.ts,esm:n.esm,packageManager:n.
957
+ gestor,stacks:n.capas,installed:n.yaInstalado?n.deps["@bivelio/savings-layer"]??n.yaInstalado:null},stack:e.capa,provider:e.proveedor,adapter:Jo[e.capa],install:e.comandoDeInstalacion??null,keys:e.claves.
926
958
  map(r=>({name:r.nombre,set:r.puesta,purpose:r.para})),files:e.ficheros.map(r=>({path:r.ruta,purpose:r.proposito,exists:r.existe,content:r.contenido})),snippets:e.usos.map(r=>({title:r.titulo,content:r.
927
- contenido})),check:e.comoComprobar,notes:e.avisos},null,2)}async function _c(e,t){let n=[],r=[],o=e.ficheros.filter(a=>!a.existe);for(let a of e.ficheros.filter(c=>c.existe))n.push(`left as is: ${a.ruta}\
959
+ contenido})),check:e.comoComprobar,notes:e.avisos},null,2)}async function $c(e,t){let n=[],r=[],o=e.ficheros.filter(a=>!a.existe);for(let a of e.ficheros.filter(c=>c.existe))n.push(`left as is: ${a.ruta}\
928
960
  already exists (compare it with the code above).`);if(o.length===0)return n.push("Nothing to write."),{salida:0,lineas:n,creados:r};n.push(`About to create ${o.length===1?"1 new file":`${o.length} ne\
929
961
  w files`} in ${e.deteccion.dir}:`);for(let a of o)n.push(` ${a.ruta}`);n.push("No existing file is changed, nothing is installed and nothing is run.");let i=t.si;if(!i){if(!t.esTerminal)return n.push(
930
962
  "Not writing: this is not an interactive terminal and --yes was not given. Re-run with --write --yes, or copy the code above by hand."),{salida:1,lineas:n,creados:r};let a=await t.preguntar("Create th\
931
963
  em? [y/N] ");if(i=/^(y|yes)$/i.test(a.trim()),!i)return n.push("Nothing written."),{salida:0,lineas:n,creados:r}}let s=0;for(let a of o){let c=join(e.deteccion.dir,...a.ruta.split("/"));try{t.crearDir(dirname(
932
964
  c)),t.crearExclusivo(c,a.contenido),r.push(a.ruta),n.push(`created ${a.ruta}`);}catch(l){l.code==="EEXIST"?n.push(`left as is: ${a.ruta} appeared while we asked; it was not overwritten.`):(s=1,n.push(`\
933
- could not create ${a.ruta}: ${l instanceof Error?l.message:String(l)}`));}}return {salida:s,lineas:n,creados:r}}var Tc="savings-mode";function Cc(e,t){for(let n of e){let r=join(n,"skills",Tc,"SKILL.md");if(t.existe(r))return r}return null}var Ac="<!-- bvsala:savings-mode:inicio -->",
934
- kr="<!-- bvsala:savings-mode:fin -->";function bp(e){let t=e.replace(/^---\n[\s\S]*?\n---\n*/,"").trim();return `${Ac}
965
+ could not create ${a.ruta}: ${l instanceof Error?l.message:String(l)}`));}}return {salida:s,lineas:n,creados:r}}var Nc="savings-mode";function jc(e,t){for(let n of e){let r=join(n,"skills",Nc,"SKILL.md");if(t.existe(r))return r}return null}var Bc="<!-- bvsala:savings-mode:inicio -->",
966
+ Er="<!-- bvsala:savings-mode:fin -->";function nf(e){let t=e.replace(/^---\n[\s\S]*?\n---\n*/,"").trim();return `${Bc}
935
967
  ${t}
936
968
 
937
969
  _Always on (AGENTS.md has no activation step). Delete this block to turn it off; \`bvsala skill --codex --force\` restores it._
938
- ${kr}`}function Rc(e){let t=Cc(e.origenes,e.fs);if(!t)return {ok:false,destino:"",mensaje:`[bvsala skill] cannot find the bundled SKILL.md (roots tried: ${e.origenes.join(", ")})`};let n=bp(e.fs.leer(t)),
970
+ ${Er}`}function Uc(e){let t=jc(e.origenes,e.fs);if(!t)return {ok:false,destino:"",mensaje:`[bvsala skill] cannot find the bundled SKILL.md (roots tried: ${e.origenes.join(", ")})`};let n=nf(e.fs.leer(t)),
939
971
  r=e.proyecto?e.cwd:join(e.home,".codex"),o=join(r,"AGENTS.md");if(!e.fs.existe(o))return e.fs.crearDir(r),e.fs.escribir(o,n+`
940
- `),{ok:true,destino:o,mensaje:Yo(o,"installed")};let i=e.fs.leer(o),s=i.indexOf(Ac),a=i.indexOf(kr);return s===-1||a===-1||a<s?(e.fs.escribir(o,i.trimEnd()+`
972
+ `),{ok:true,destino:o,mensaje:ni(o,"installed")};let i=e.fs.leer(o),s=i.indexOf(Bc),a=i.indexOf(Er);return s===-1||a===-1||a<s?(e.fs.escribir(o,i.trimEnd()+`
941
973
 
942
974
  `+n+`
943
- `),{ok:true,destino:o,mensaje:Yo(o,"appended to the existing AGENTS.md")}):i.slice(s,a+kr.length)===n?{ok:true,destino:o,mensaje:`[bvsala skill] already installed and up to date: ${o}`}:e.forzar?(e.fs.escribir(
944
- o,i.slice(0,s)+n+i.slice(a+kr.length)),{ok:true,destino:o,mensaje:Yo(o,"block updated")}):{ok:false,destino:o,mensaje:`[bvsala skill] the savings-mode block in ${o} has DIFFERENT content \u2014 not overwriting \
945
- it; use --force to update it`}}function Yo(e,t){return `[bvsala skill] ${t}: ${e}
975
+ `),{ok:true,destino:o,mensaje:ni(o,"appended to the existing AGENTS.md")}):i.slice(s,a+Er.length)===n?{ok:true,destino:o,mensaje:`[bvsala skill] already installed and up to date: ${o}`}:e.forzar?(e.fs.escribir(
976
+ o,i.slice(0,s)+n+i.slice(a+Er.length)),{ok:true,destino:o,mensaje:ni(o,"block updated")}):{ok:false,destino:o,mensaje:`[bvsala skill] the savings-mode block in ${o} has DIFFERENT content \u2014 not overwriting \
977
+ it; use --force to update it`}}function ni(e,t){return `[bvsala skill] ${t}: ${e}
946
978
  [bvsala skill] AGENTS.md is ALWAYS active in Codex (there is no activation step); delete the block to turn it off.
947
- [bvsala skill] to measure its effect: work a few days with it and a few without, under \`bvsala codex\`, and compare in the dashboard.`}function Ic(e){let t=Cc(e.origenes,e.fs);if(!t)return {ok:false,destino:"",
948
- mensaje:`[bvsala skill] cannot find the bundled SKILL.md (roots tried: ${e.origenes.join(", ")})`};let n=e.proyecto?join(e.cwd,".claude","skills"):join(e.home,".claude","skills"),r=join(n,Tc),o=join(r,"SKILL.\
979
+ [bvsala skill] to measure its effect: work a few days with it and a few without, under \`bvsala codex\`, and compare in the dashboard.`}function Vc(e){let t=jc(e.origenes,e.fs);if(!t)return {ok:false,destino:"",
980
+ mensaje:`[bvsala skill] cannot find the bundled SKILL.md (roots tried: ${e.origenes.join(", ")})`};let n=e.proyecto?join(e.cwd,".claude","skills"):join(e.home,".claude","skills"),r=join(n,Nc),o=join(r,"SKILL.\
949
981
  md"),i=e.fs.leer(t);if(e.fs.existe(o)&&!e.forzar){let s=e.fs.leer(o)===i;return {ok:s,destino:o,mensaje:s?`[bvsala skill] already installed and up to date: ${o}`:`[bvsala skill] ${o} already exists wit\
950
982
  h DIFFERENT content \u2014 not overwriting it; use --force to overwrite`}}return e.fs.crearDir(r),e.fs.escribir(o,i),{ok:true,destino:o,mensaje:`[bvsala skill] installed: ${o}
951
983
  [bvsala skill] start (or restart) Claude Code and ask for "savings mode" \u2014 or let it activate on its own when you mention limits.
952
- [bvsala skill] to measure its real effect: work a few days with it and a few without, under \`bvsala claude\`, and compare in the dashboard.`}}var Zo=class{id;exact=false;constructor(t="heuristic"){this.id=t;}count(t){if(t.length===0)return 0;let n=t.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.
984
+ [bvsala skill] to measure its real effect: work a few days with it and a few without, under \`bvsala claude\`, and compare in the dashboard.`}}var ri=class{id;exact=false;constructor(t="heuristic"){this.id=t;}count(t){if(t.length===0)return 0;let n=t.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.
953
985
  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,
954
- Math.ceil(t.length/4))}},Xo=new Zo;var Qo=class{estimators=new Map;modelToTokenizer=new Map;fallbackId;constructor(t=Xo){this.fallbackId=t.id,this.estimators.set(t.id,t);}register(t){return this.estimators.set(t.id,t),this}mapModel(t,n){
986
+ Math.ceil(t.length/4))}},oi=new ri;var ii=class{estimators=new Map;modelToTokenizer=new Map;fallbackId;constructor(t=oi){this.fallbackId=t.id,this.estimators.set(t.id,t);}register(t){return this.estimators.set(t.id,t),this}mapModel(t,n){
955
987
  return this.modelToTokenizer.set(t,n),this}resolve(t){let n=t.tokenizer?this.estimators.get(t.tokenizer):void 0;if(n)return n;if(t.model){let r=this.modelToTokenizer.get(t.model);if(r){let o=this.estimators.
956
- get(r);if(o)return o}}return this.estimators.get(this.fallbackId)}count(t,n){return this.resolve(n).count(t)}};new Qo;var Dc={o200k_base:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","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",
957
- "text-embedding-3-large"]};var Kp={"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 enums)",pares:8}};
958
- Vr(Kp);new Set(Object.values(Dc).flatMap(e=>e.flatMap(t=>[t,`openai/${t}`])));function ff(e,t=300){return new Promise(n=>{let r=connect({port:e,host:"127.0.0.1"}),o=i=>{r.destroy(),n(i);};r.setTimeout(t,()=>o(false)),r.once("connect",()=>o(true)),r.once("error",()=>o(false));})}var _r=Xa(process.
959
- argv.slice(2));function mf(){console.log(`bvsala ${me} \u2014 BiVelio Savings Layer
988
+ get(r);if(o)return o}}return this.estimators.get(this.fallbackId)}count(t,n){return this.resolve(n).count(t)}};new ii;var qc={o200k_base:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","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",
989
+ "text-embedding-3-large"]};var lf=new Map;function C(e,t){for(let n of e.split(/\s+/).filter(Boolean))lf.set(n,t);}var uf=["zero","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen",
990
+ "fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"];uf.forEach((e,t)=>C(e,{k:"unidad",v:t}));["twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"].forEach((e,t)=>C(e,{k:"\
991
+ decena",v:20+10*t}));C("hundred hundreds",{k:"cien"});C("thousand thousands",{k:"escala",v:1e3});C("million millions",{k:"escala",v:1e6});C("billion billions",{k:"escala",v:1e9});var df=["","first","s\
992
+ econd","third","fourth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelfth","thirteenth","fourteenth","fifteenth","sixteenth","seventeenth","eighteenth","nineteenth"];df.forEach((e,t)=>{
993
+ e&&(C(e,{k:"ordinal",v:t}),t>=3&&C(`${e}s`,{k:"ordinal",v:t}));});["twentieth","thirtieth","fortieth","fiftieth","sixtieth","seventieth","eightieth","ninetieth"].forEach((e,t)=>{C(e,{k:"ordinal",v:20+10*
994
+ t}),C(`${e}s`,{k:"ordinal",v:20+10*t});});C("hundredth hundredths",{k:"ordinal",v:100});C("thousandth thousandths",{k:"ordinal",v:1e3});C("millionth millionths",{k:"ordinal",v:1e6});C("half halves",{k:"\
995
+ token",t:"f:1/2"});C("quarter quarters",{k:"token",t:"f:1/4"});C("once single",{k:"token",t:"m:1"});C("twice double doubled doubles doubling",{k:"token",t:"m:2"});C("thrice triple tripled triples trip\
996
+ ling",{k:"token",t:"m:3"});C("quadruple quadrupled quadruples quadrupling",{k:"token",t:"m:4"});C("dozen dozens",{k:"token",t:"c:12"});C("pair pairs",{k:"token",t:"c:2"});C("times time",{k:"veces"});C(
997
+ "and",{k:"conector"});var pf=["cero","uno","dos","tres","cuatro","cinco","seis","siete","ocho","nueve","diez","","doce","trece","catorce","quince","dieciseis","diecisiete","dieciocho","diecinueve"];pf.
998
+ forEach((e,t)=>e&&C(e,{k:"unidad",v:t}));C("veinte",{k:"decena",v:20});["veintiuno","veintidos","veintitres","veinticuatro","veinticinco","veintiseis","veintisiete","veintiocho","veintinueve"].forEach(
999
+ (e,t)=>C(e,{k:"unidad",v:21+t}));["treinta","cuarenta","cincuenta","sesenta","setenta","ochenta","noventa"].forEach((e,t)=>C(e,{k:"decena",v:30+10*t}));C("cien ciento",{k:"centena",v:100});[["doscient\
1000
+ os doscientas",200],["trescientos trescientas",300],["cuatrocientos cuatrocientas",400],["quinientos quinientas",500],["seiscientos seiscientas",600],["setecientos setecientas",700],["ochocientos ocho\
1001
+ cientas",800],["novecientos novecientas",900]].forEach(([e,t])=>C(e,{k:"centena",v:t}));C("mil miles",{k:"escala",v:1e3});C("millon millones",{k:"escala",v:1e6});C("billon billones",{k:"escala",v:1e12});
1002
+ [["primero primera primer primeros primeras",1],["segundo segunda segundos segundas",2],["tercero tercera tercer terceros terceras tercio tercios",3],["cuarto cuarta cuartos cuartas",4],["quinto quint\
1003
+ a quintos quintas",5],["sexto sexta sextos sextas",6],["septimo septima septimos septimas",7],["octavo octava octavos octavas",8],["noveno novena novenos novenas",9],["decimo decima decimos decimas",10]].
1004
+ forEach(([e,t])=>C(e,{k:"ordinal",v:t}));C("mitad mitades medio media medios medias",{k:"token",t:"f:1/2"});C("doble dobles",{k:"token",t:"m:2"});C("cuadruple",{k:"token",t:"m:4"});C("docena docenas",
1005
+ {k:"token",t:"c:12"});C("par pares",{k:"token",t:"c:2"});C("veces vez",{k:"veces"});C("y",{k:"conector"});[["zero",0],["dues",2],["quatre",4],["cinc",5],["sis",6],["set",7],["vuit",8],["nou",9],["deu",
1006
+ 10],["onze",11],["dotze",12],["tretze",13],["catorze",14],["quinze",15],["setze",16],["disset",17],["divuit",18],["dinou",19]].forEach(([e,t])=>C(e,{k:"unidad",v:t}));["vint","trenta","quaranta","cinq\
1007
+ uanta","seixanta","setanta","vuitanta","noranta"].forEach((e,t)=>C(e,{k:"decena",v:20+10*t}));C("cent",{k:"centena",v:100});C("cents centes",{k:"cien"});C("milio milions",{k:"escala",v:1e6});[["segon \
1008
+ 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(
1009
+ ([e,t])=>C(e,{k:"ordinal",v:t}));C("meitat meitats mig mitja",{k:"token",t:"f:1/2"});C("dotzena dotzenes",{k:"token",t:"c:12"});C("parell parells",{k:"token",t:"c:2"});C("vegades vegada",{k:"veces"});
1010
+ C("i",{k:"conector"});var $f={"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 enums)",pares:8}};
1011
+ Hr($f);new Set(Object.values(qc).flatMap(e=>e.flatMap(t=>[t,`openai/${t}`])));function tm(e,t=300){return new Promise(n=>{let r=connect({port:e,host:"127.0.0.1"}),o=i=>{r.destroy(),n(i);};r.setTimeout(t,()=>o(false)),r.once("connect",()=>o(true)),r.once("error",()=>o(false));})}var Rr=lc(process.
1012
+ argv.slice(2));function nm(){console.log(`bvsala ${ge} \u2014 BiVelio Savings Layer
960
1013
 
961
1014
  Commands:
962
1015
  gateway [--port N] [--upstream U]
@@ -1076,49 +1129,49 @@ forwards and warns. On a Claude or ChatGPT subscription there is no per-token in
1076
1129
  traffic is metered at list-price equivalent and never carries commission.
1077
1130
  Your prompts, completions and provider keys never reach BiVelio: what it receives is per-request
1078
1131
  usage (token counts, cost, the model id and opaque ids); LICENSE \xA75 lists every field.
1079
- More: savings.bivelio.com`);}_r.tipo==="ayuda"&&(mf(),process.exit(_r.salida));_r.tipo==="version"&&(console.log(me),process.exit(0));var{comando:q,resto:le}=_r,Vt=mn(q);if(q==="init"){let e=bc(le,process.
1080
- cwd());e.ok||(console.error(`[bvsala init] ${e.mensaje}`),process.exit(1));let t=e.valor,n={leer:c=>{try{return readFileSync(c,"utf8")}catch{return}},existe:existsSync},r=kc(t.cwd,n);r.ok||(console.error(`[bvsala init]\
1081
- ${r.mensaje}`),process.exit(1));let o=xc(r.valor,t,{node:process.versions.node,env:c=>!!process.env[c]?.trim()});o.ok||(console.error(`[bvsala init] ${o.mensaje}`),process.exit(1));let i=wc(o.valor,n);
1082
- t.json&&(console.log(Ec(i,me)),process.exit(0)),console.log(Sc(i,`bvsala init \xB7 BiVelio Savings Layer ${me}`,"npx @bivelio/savings-layer@latest init",{escribira:t.escribir})),t.escribir||process.exit(
1083
- 0),console.log("");let{createInterface:s}=await import('readline/promises'),a=await _c(i,{si:t.si,esTerminal:!!process.stdin.isTTY,preguntar:async c=>{let l=s({input:process.stdin,output:process.stdout});
1132
+ More: savings.bivelio.com`);}Rr.tipo==="ayuda"&&(nm(),process.exit(Rr.salida));Rr.tipo==="version"&&(console.log(ge),process.exit(0));var{comando:W,resto:de}=Rr,Ht=vn(W);if(W==="init"){let e=Ac(de,process.
1133
+ cwd());e.ok||(console.error(`[bvsala init] ${e.mensaje}`),process.exit(1));let t=e.valor,n={leer:c=>{try{return readFileSync(c,"utf8")}catch{return}},existe:existsSync},r=Pc(t.cwd,n);r.ok||(console.error(`[bvsala init]\
1134
+ ${r.mensaje}`),process.exit(1));let o=Dc(r.valor,t,{node:process.versions.node,env:c=>!!process.env[c]?.trim()});o.ok||(console.error(`[bvsala init] ${o.mensaje}`),process.exit(1));let i=Oc(o.valor,n);
1135
+ t.json&&(console.log(Mc(i,ge)),process.exit(0)),console.log(Lc(i,`bvsala init \xB7 BiVelio Savings Layer ${ge}`,"npx @bivelio/savings-layer@latest init",{escribira:t.escribir})),t.escribir||process.exit(
1136
+ 0),console.log("");let{createInterface:s}=await import('readline/promises'),a=await $c(i,{si:t.si,esTerminal:!!process.stdin.isTTY,preguntar:async c=>{let l=s({input:process.stdin,output:process.stdout});
1084
1137
  try{return await l.question(c)}finally{l.close();}},crearDir:c=>mkdirSync(c,{recursive:true}),crearExclusivo:(c,l)=>writeFileSync(c,l,{flag:"wx"})});for(let c of a.lineas)(a.salida===0?console.log:console.error)(c);process.
1085
- exit(a.salida);}if(q==="skill"){let e=dirname(fileURLToPath(import.meta.url)),t={origenes:[join(e,"..",".."),join(e,"..")],home:homedir(),cwd:process.cwd(),proyecto:le.includes("--project")||le.includes("--proyecto"),forzar:le.
1086
- includes("--force")||le.includes("--forzar"),fs:{existe:existsSync,leer:r=>readFileSync(r,"utf8"),escribir:(r,o)=>writeFileSync(r,o),crearDir:r=>mkdirSync(r,{recursive:true})}},n=le.includes("--codex")?Rc(t):Ic(t);console.log(n.mensaje),process.
1087
- exit(n.ok?0:1);}var si=le.indexOf("--port")>=0?le.indexOf("--port"):le.indexOf("--puerto"),yt=Vt?0:si>=0?Number(le[si+1]):8402;(!Number.isInteger(yt)||(q==="doctor"?yt<1:yt<0)||yt>65535)&&(console.error(
1088
- `[bvsala ${q}] invalid port: ${le[si+1]}`),process.exit(1));if(q==="doctor"){le.includes("--write")&&(console.error("[bvsala doctor] --write does not exist yet: the doctor only prints; copy the block \
1089
- by hand."),process.exit(1));let e=await rc(yt);console.log(e.texto),process.exit(0);}function hf(e,t){mn(e)||process.exit(1);let n=vr(e,0,[],{}).bin;if(process.platform==="win32"){let o=Vo(n);o.tipo===
1138
+ exit(a.salida);}if(W==="skill"){let e=dirname(fileURLToPath(import.meta.url)),t={origenes:[join(e,"..",".."),join(e,"..")],home:homedir(),cwd:process.cwd(),proyecto:de.includes("--project")||de.includes("--proyecto"),forzar:de.
1139
+ includes("--force")||de.includes("--forzar"),fs:{existe:existsSync,leer:r=>readFileSync(r,"utf8"),escribir:(r,o)=>writeFileSync(r,o),crearDir:r=>mkdirSync(r,{recursive:true})}},n=de.includes("--codex")?Uc(t):Vc(t);console.log(n.mensaje),process.
1140
+ exit(n.ok?0:1);}var fi=de.indexOf("--port")>=0?de.indexOf("--port"):de.indexOf("--puerto"),wt=Ht?0:fi>=0?Number(de[fi+1]):8402;(!Number.isInteger(wt)||(W==="doctor"?wt<1:wt<0)||wt>65535)&&(console.error(
1141
+ `[bvsala ${W}] invalid port: ${de[fi+1]}`),process.exit(1));if(W==="doctor"){de.includes("--write")&&(console.error("[bvsala doctor] --write does not exist yet: the doctor only prints; copy the block \
1142
+ by hand."),process.exit(1));let e=await mc(wt);console.log(e.texto),process.exit(0);}function rm(e,t){vn(e)||process.exit(1);let n=wr(e,0,[],{}).bin;if(process.platform==="win32"){let o=Ko(n);o.tipo===
1090
1143
  "exe"?n=o.ruta:o.tipo==="solo-shim"&&(console.error(`[bvsala ${e}] \`${n}\` is installed as an npm shim (${o.ruta}) and Windows cannot launch it safely with arguments (CVE-2024-27980). Install it with\
1091
1144
  its native installer (which leaves a ${n}.exe on the PATH) or use the manual recipe in docs/terminales/.`),process.exit(127));}let r=spawn(n,t,{stdio:"inherit"});return r.on("error",o=>{console.error(`[b\
1092
- vsala ${e}] could not launch \`${n}\`: ${String(o)}. Is it installed and on the PATH?`),process.exit(127);}),r.on("exit",(o,i)=>process.exit(o??(i?1:0))),new Promise(()=>{})}Vt&&Qa(le)&&await hf(q,le);
1093
- if(Vt){let e=Ja(q);e&&(console.error(`[bvsala ${q}] ${e}`),process.exit(1));}var gf=q==="gateway"?wa(le):void 0,ue=Sa({flag:gf,env:process.env.BVSALA_GATEWAY_UPSTREAM});ue.ok||(console.error(ue.error),
1094
- process.exit(1));var Hc=process.env.BIVELIO_SERVICE_KEY?.trim()||void 0,kt=await fa({serviceAccountKey:Hc,licenseKey:process.env.BIVELIO_LICENSE_KEY,licenseServerUrl:Io});kt.ok||(console.
1095
- error(`[bvsala ${q}] ${kt.message}`),process.exit(1));var Ne=Vt?vr(q,0,le,{modoCodex:q==="codex"?Ha({leerAuth:()=>readFileSync(join(homedir(),".codex","auth.json"),"utf8")}):void 0,...ue.upstream?{upstreamElegido:ue.upstream}:
1096
- {}}):null,bf=Vt&&process.env.BVSALA_GATEWAY_LOG!=="1",ii=Ne?.upstream?null:tc(()=>readFileSync(process.env.BVSALA_ANILLO2_FICHERO??join(homedir(),".bvsala","anillo2.json"),"utf8")),yn=nc({enrolamiento:ii,espiaVivo:ii!==
1097
- null&&await ff(ii.espia),upstreamEnv:ue.upstream,...ue.origen!=="none"?{upstreamOrigen:ue.origen}:{},elisionEnv:process.env.BVSALA_GATEWAY_ELISION,hoyUtcIso:new Date().toISOString().slice(0,10)}),ai=ue.
1098
- upstream??yn.upstream,Sr=process.env.BVSALA_GATEWAY_ELISION??yn.elision,Ee;try{Ee=await Va({puerto:yt,...bf?{log:()=>{},avisosDeNoMedido:!1}:{},license:{token:kt.license.token,publicKey:mt,licenseServerUrl:Io,
1099
- checkOnStart:kt.source==="offline"},warn:e=>console.error(e),serviceAccountKey:Hc,...process.env.BVSALA_SEAT_ID?{seatId:process.env.BVSALA_SEAT_ID}:{},...ai?{upstream:ai}:Ne?.upstream?{upstream:Ne.upstream}:
1100
- {},...process.env.BVSALA_GATEWAY_COALESCE==="1"?{coalescer:!0}:{},...process.env.BVSALA_GATEWAY_USAGE_INJECT==="1"?{usageInject:!0}:{},...process.env.BVSALA_GATEWAY_SHADOW==="1"?{sombra:!0}:{},elision:Sr!==
1145
+ vsala ${e}] could not launch \`${n}\`: ${String(o)}. Is it installed and on the PATH?`),process.exit(127);}),r.on("exit",(o,i)=>process.exit(o??(i?1:0))),new Promise(()=>{})}Ht&&uc(de)&&await rm(W,de);
1146
+ if(Ht){let e=sc(W);e&&(console.error(`[bvsala ${W}] ${e}`),process.exit(1));}var om=W==="gateway"?Oa(de):void 0,pe=La({flag:om,env:process.env.BVSALA_GATEWAY_UPSTREAM});pe.ok||(console.error(pe.error),
1147
+ process.exit(1));var nl=process.env.BIVELIO_SERVICE_KEY?.trim()||void 0,St=await Ea({serviceAccountKey:nl,licenseKey:process.env.BIVELIO_LICENSE_KEY,licenseServerUrl:$o});St.ok||(console.
1148
+ error(`[bvsala ${W}] ${St.message}`),process.exit(1));var Be=Ht?wr(W,0,de,{modoCodex:W==="codex"?nc({leerAuth:()=>readFileSync(join(homedir(),".codex","auth.json"),"utf8")}):void 0,...pe.upstream?{upstreamElegido:pe.upstream}:
1149
+ {}}):null,im=Ht&&process.env.BVSALA_GATEWAY_LOG!=="1",pi=Be?.upstream?null:pc(()=>readFileSync(process.env.BVSALA_ANILLO2_FICHERO??join(homedir(),".bvsala","anillo2.json"),"utf8")),Sn=fc({enrolamiento:pi,espiaVivo:pi!==
1150
+ null&&await tm(pi.espia),upstreamEnv:pe.upstream,...pe.origen!=="none"?{upstreamOrigen:pe.origen}:{},elisionEnv:process.env.BVSALA_GATEWAY_ELISION,hoyUtcIso:new Date().toISOString().slice(0,10)}),mi=pe.
1151
+ upstream??Sn.upstream,Cr=process.env.BVSALA_GATEWAY_ELISION??Sn.elision,Te;try{Te=await Xa({puerto:wt,...im?{log:()=>{},avisosDeNoMedido:!1}:{},license:{token:St.license.token,publicKey:bt,licenseServerUrl:$o,
1152
+ checkOnStart:St.source==="offline"},warn:e=>console.error(e),serviceAccountKey:nl,...process.env.BVSALA_SEAT_ID?{seatId:process.env.BVSALA_SEAT_ID}:{},...mi?{upstream:mi}:Be?.upstream?{upstream:Be.upstream}:
1153
+ {},...process.env.BVSALA_GATEWAY_COALESCE==="1"?{coalescer:!0}:{},...process.env.BVSALA_GATEWAY_USAGE_INJECT==="1"?{usageInject:!0}:{},...process.env.BVSALA_GATEWAY_SHADOW==="1"?{sombra:!0}:{},elision:Cr!==
1101
1154
  "0",...process.env.BVSALA_GATEWAY_DIALES_ELISION==="1"?{dialesElision:!0}:{},...process.env.BVSALA_GATEWAY_MODELO_HERMANO==="1"?{modeloHermano:!0}:{},...process.env.BVSALA_GATEWAY_ESFUERZO?{esfuerzo:process.
1102
- env.BVSALA_GATEWAY_ESFUERZO}:{},...process.env.BVSALA_METERING_URL?{meteringUrl:process.env.BVSALA_METERING_URL}:{}});}catch(e){console.error(`[bvsala ${q}] ${ec(e,q,yt)}`),process.exit(1);}var Wc=ai??Ne?.
1103
- upstream??"https://api.anthropic.com";console.log(`[bvsala gateway] v${me} listening on http://127.0.0.1:${Ee.puerto} \u2192 ${Wc}`);(kt.lineIsWarning?console.error:console.log)(`[bvsala gateway] ${kt.
1104
- line}`);for(let e of kt.warnings)console.error(`[bvsala gateway] ${e}`);console.log("[bvsala gateway] metering: ON (service key present)");process.env.BVSALA_METERING_URL&&console.error(`[bvsala gatew\
1155
+ env.BVSALA_GATEWAY_ESFUERZO}:{},...process.env.BVSALA_METERING_URL?{meteringUrl:process.env.BVSALA_METERING_URL}:{}});}catch(e){console.error(`[bvsala ${W}] ${dc(e,W,wt)}`),process.exit(1);}var rl=mi??Be?.
1156
+ upstream??"https://api.anthropic.com";console.log(`[bvsala gateway] v${ge} listening on http://127.0.0.1:${Te.puerto} \u2192 ${rl}`);(St.lineIsWarning?console.error:console.log)(`[bvsala gateway] ${St.
1157
+ line}`);for(let e of St.warnings)console.error(`[bvsala gateway] ${e}`);console.log("[bvsala gateway] metering: ON (service key present)");process.env.BVSALA_METERING_URL&&console.error(`[bvsala gatew\
1105
1158
  ay] WARNING: BVSALA_METERING_URL=${process.env.BVSALA_METERING_URL} redirects usage reporting away from savings.bivelio.com (development only): your dashboard will not see this usage. The license and \
1106
- the entitlements channel still use savings.bivelio.com.`);ue.aviso&&console.error(ue.aviso);process.env.BVSALA_GATEWAY_USAGE_INJECT==="1"&&console.log("[bvsala gateway] usage injection: ON (BVSALA_GAT\
1107
- EWAY_USAGE_INJECT=1) \u2014 streamed chat completions without stream_options get include_usage; their last chunk has an empty choices list.");{let e=hi(Sr,true,process.env.BVSALA_GATEWAY_DIALES_ELISION===
1108
- "1");(e.aviso?console.error:console.log)(`[bvsala gateway] ${e.linea}`);let t=Oi(process.env.BVSALA_GATEWAY_MODELO_HERMANO,true,Sr!=="0");(t.aviso?console.error:console.log)(`[bvsala gateway] ${t.linea}`);
1109
- let n=Ci(process.env.BVSALA_GATEWAY_ESFUERZO,true,Sr!=="0");(n.aviso?console.error:console.log)(`[bvsala gateway] ${n.linea}`),yn.linea&&(yn.aviso?console.error:console.log)(`[bvsala gateway] ${yn.linea}`);}
1110
- ue.upstream&&Ne?.upstream&&ue.upstream!==Ne.upstream&&console.error(`[bvsala ${q}] WARNING: BVSALA_GATEWAY_UPSTREAM=${ue.upstream} overrides this terminal's upstream (${Ne.upstream}). If that is not w\
1111
- hat you want, unset the variable.`);q==="codex"&&!Hs()&&console.error(`[bvsala codex] WARNING: this Node (${process.version}) cannot decompress zstd and Codex sends its body in zstd: traffic passes th\
1112
- rough but is NOT metered. Use Node >= 22.15.`);var Uc=false;function Kc(){if(Uc)return;Uc=true;let e=Na(Ee.degradaciones());e&&console.error(e),console.error(Ea(Ee.medicion(),q));}if(Ne&&Vt){let e=vr(q,Ee.puerto,
1113
- le,{...Ne.upstream?{modoCodex:Ne.upstream.includes("chatgpt.com")?"chatgpt":"api-key"}:{},...ue.upstream?{upstreamElegido:ue.upstream}:{}});e.nota&&console.log(`[bvsala ${q}] ${e.nota}`);let t=e.bin;if(process.
1114
- platform==="win32"){let r=Vo(e.bin);r.tipo==="exe"?t=r.ruta:r.tipo==="solo-shim"&&(console.error(`[bvsala ${q}] \`${e.bin}\` is installed as an npm shim (${r.ruta}) and Windows cannot launch it safely\
1115
- with arguments (CVE-2024-27980). Install it with its native installer (which leaves a ${e.bin}.exe on the PATH) or use the manual recipe in docs/terminales/.`),await Ee.cerrar(),process.exit(127));}let n=spawn(
1116
- t,e.args,{stdio:"inherit",env:{...process.env,...e.env}});n.on("error",r=>{console.error(`[bvsala ${q}] could not launch \`${e.bin}\`: ${String(r)}. Is it installed and on the PATH?`),Ee.cerrar().then(
1117
- ()=>process.exit(127));}),n.on("exit",(r,o)=>{Kc(),Ee.cerrar().then(()=>process.exit(r??(o?1:0)));});}else {let e=new URL(Wc).hostname;e==="api.openai.com"?console.log(`[bvsala gateway] point your SDK at \
1118
- it: base_url=http://127.0.0.1:${Ee.puerto}/v1 (OpenAI SDKs) \xB7 streamed chat completions are metered when the request sets stream_options.include_usage \xB7 bvsala doctor for recipes`):e==="api.anth\
1119
- ropic.com"||ue.upstream===void 0?console.log(`[bvsala gateway] point your terminal at it (or use \`bvsala ${Uo.join("|")}\`): ANTHROPIC_BASE_URL=http://127.0.0.1:${Ee.puerto} claude \xB7 bvsala doct\
1120
- or for the others`):console.log(`[bvsala gateway] point your client at http://127.0.0.1:${Ee.puerto} plus the path prefix it already uses (for example /v1) \xB7 bvsala doctor for recipes`);}var Gc=async()=>{
1121
- Kc(),await Ee.cerrar(),process.exit(0);};process.on("SIGINT",()=>{Gc();});process.on("SIGTERM",()=>{Gc();});
1159
+ the entitlements channel still use savings.bivelio.com.`);pe.aviso&&console.error(pe.aviso);process.env.BVSALA_GATEWAY_USAGE_INJECT==="1"&&console.log("[bvsala gateway] usage injection: ON (BVSALA_GAT\
1160
+ EWAY_USAGE_INJECT=1) \u2014 streamed chat completions without stream_options get include_usage; their last chunk has an empty choices list.");{let e=wi(Cr,true,process.env.BVSALA_GATEWAY_DIALES_ELISION===
1161
+ "1");(e.aviso?console.error:console.log)(`[bvsala gateway] ${e.linea}`);let t=Ui(process.env.BVSALA_GATEWAY_MODELO_HERMANO,true,Cr!=="0");(t.aviso?console.error:console.log)(`[bvsala gateway] ${t.linea}`);
1162
+ let n=Li(process.env.BVSALA_GATEWAY_ESFUERZO,true,Cr!=="0");(n.aviso?console.error:console.log)(`[bvsala gateway] ${n.linea}`),Sn.linea&&(Sn.aviso?console.error:console.log)(`[bvsala gateway] ${Sn.linea}`);}
1163
+ pe.upstream&&Be?.upstream&&pe.upstream!==Be.upstream&&console.error(`[bvsala ${W}] WARNING: BVSALA_GATEWAY_UPSTREAM=${pe.upstream} overrides this terminal's upstream (${Be.upstream}). If that is not w\
1164
+ hat you want, unset the variable.`);W==="codex"&&!ea()&&console.error(`[bvsala codex] WARNING: this Node (${process.version}) cannot decompress zstd and Codex sends its body in zstd: traffic passes th\
1165
+ rough but is NOT metered. Use Node >= 22.15.`);var Zc=false;function ol(){if(Zc)return;Zc=true;let e=Ga(Te.degradaciones());e&&console.error(e),console.error(Ma(Te.medicion(),W));}if(Be&&Ht){let e=wr(W,Te.puerto,
1166
+ de,{...Be.upstream?{modoCodex:Be.upstream.includes("chatgpt.com")?"chatgpt":"api-key"}:{},...pe.upstream?{upstreamElegido:pe.upstream}:{}});e.nota&&console.log(`[bvsala ${W}] ${e.nota}`);let t=e.bin;if(process.
1167
+ platform==="win32"){let r=Ko(e.bin);r.tipo==="exe"?t=r.ruta:r.tipo==="solo-shim"&&(console.error(`[bvsala ${W}] \`${e.bin}\` is installed as an npm shim (${r.ruta}) and Windows cannot launch it safely\
1168
+ with arguments (CVE-2024-27980). Install it with its native installer (which leaves a ${e.bin}.exe on the PATH) or use the manual recipe in docs/terminales/.`),await Te.cerrar(),process.exit(127));}let n=spawn(
1169
+ t,e.args,{stdio:"inherit",env:{...process.env,...e.env}});n.on("error",r=>{console.error(`[bvsala ${W}] could not launch \`${e.bin}\`: ${String(r)}. Is it installed and on the PATH?`),Te.cerrar().then(
1170
+ ()=>process.exit(127));}),n.on("exit",(r,o)=>{ol(),Te.cerrar().then(()=>process.exit(r??(o?1:0)));});}else {let e=new URL(rl).hostname;e==="api.openai.com"?console.log(`[bvsala gateway] point your SDK at \
1171
+ it: base_url=http://127.0.0.1:${Te.puerto}/v1 (OpenAI SDKs) \xB7 streamed chat completions are metered when the request sets stream_options.include_usage \xB7 bvsala doctor for recipes`):e==="api.anth\
1172
+ ropic.com"||pe.upstream===void 0?console.log(`[bvsala gateway] point your terminal at it (or use \`bvsala ${Wo.join("|")}\`): ANTHROPIC_BASE_URL=http://127.0.0.1:${Te.puerto} claude \xB7 bvsala doct\
1173
+ or for the others`):console.log(`[bvsala gateway] point your client at http://127.0.0.1:${Te.puerto} plus the path prefix it already uses (for example /v1) \xB7 bvsala doctor for recipes`);}var il=async()=>{
1174
+ ol(),await Te.cerrar(),process.exit(0);};process.on("SIGINT",()=>{il();});process.on("SIGTERM",()=>{il();});
1122
1175
  /*! Bundled license information:
1123
1176
 
1124
1177
  @noble/curves/utils.js: