@bivelio/savings-layer 0.4.25 → 0.4.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,43 +1,47 @@
1
1
  #!/usr/bin/env node
2
- import {spawn}from'child_process';import {existsSync,readFileSync,mkdirSync,writeFileSync}from'fs';import {homedir}from'os';import {join,dirname,delimiter}from'path';import {fileURLToPath}from'url';import {randomUUID,createHash}from'crypto';import {createServer}from'http';import*as Ne from'zlib';import {connect}from'net';var cn="context-management-2025-06-27";function nr(){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 ka=new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});function xa(e){try{return ka.decode(e)}catch{return null}}function wa(e){return /^(?:0|[1-9]\d{0,9})$/.test(e)&&Number(e)<4294967295}function Sa(e){
3
- return e===32||e===10||e===13||e===9}function Ea(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 s=r,i=false;for(r++;;){if(r>=t)return false;let u=e.charCodeAt(r);if(u===92){i=true,r+=2;continue}if(u===34)break;r++;}r++;let a=r;for(;a<t&&Sa(e.charCodeAt(a));)a++;if(a<
5
- t&&e.charCodeAt(a)===58){let u=e.slice(s+1,r-1);if(i)try{u=JSON.parse(e.slice(s,r));}catch{return false}if(wa(u))return false;let c=n.at(-1);if(c){if(c.has(u))return false;c.add(u);}}continue}if(o===45||o>=48&&o<=57){
6
- let s=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 i=e.slice(s,r);if(String(Number(i))!==i)return false;continue}r++;}return true}function un(e,t){
7
- if(t!==void 0&&t!==""&&t!=="identity")return null;let n=xa(e);if(n===null)return null;let r;try{r=JSON.parse(n);}catch{return null}return Ea(n)?r:null}function Ao(e,t){try{let n=un(e,t);if(n===null||typeof n!="object"||Array.isArray(n)||typeof n.model!="string"||!Array.isArray(n.messages))return null;let r=Ta(n.context_management),o=Ra(n.context_management);
8
- return n.context_management=Ia(n.context_management),{cuerpo:Buffer.from(JSON.stringify(n),"utf8"),nuestros:r,triggerDelCliente:o}}catch{return null}}function Ta(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===rr);return Ro(n)!==Ro([nr().edits[0]])}function Ra(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===rr);if(n.length===0)return null;let r=Number.POSITIVE_INFINITY;
11
- for(let o of n){let s=o.trigger,i=s!==null&&typeof s=="object"&&s.type==="input_tokens"&&typeof s.value=="number"&&Number.isFinite(s.value)&&s.value>0?s.value:1e5;i<r&&(r=i);}return r}function Ro(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 rr="clear_tool_uses_20250919",Io="clear_thinking_20251015";function Ia(e){
13
- let t=nr().edits[0],n=e!==null&&typeof e=="object"&&!Array.isArray(e)?{...e}:{},r=(Array.isArray(n.edits)?n.edits:[]).filter(i=>i!==null&&typeof i=="object"&&!Array.isArray(i)&&i.type!==rr),o=r.filter(
14
- i=>i.type===Io),s=r.filter(i=>i.type!==Io);return {...n,edits:[...o,...s,t]}}function Co(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 He from'zlib';import {connect}from'net';var En="context-management-2025-06-27";function Rr(){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 qc=new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});function Hc(e){try{return qc.decode(e)}catch{return null}}function Wc(e){return /^(?:0|[1-9]\d{0,9})$/.test(e)&&Number(e)<4294967295}function Kc(e){
3
+ return e===32||e===10||e===13||e===9}function Gc(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&&Kc(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(Wc(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 _n(e,t){
7
+ if(t!==void 0&&t!==""&&t!=="identity")return null;let n=Hc(e);if(n===null)return null;let r;try{r=JSON.parse(n);}catch{return null}return Gc(n)?r:null}function di(e,t){try{let n=_n(e,t);if(n===null||typeof n!="object"||Array.isArray(n)||typeof n.model!="string"||!Array.isArray(n.messages))return null;let r=Yc(n.context_management),o=Zc(n.context_management);
8
+ return n.context_management=Xc(n.context_management),{cuerpo:Buffer.from(JSON.stringify(n),"utf8"),nuestros:r,triggerDelCliente:o}}catch{return null}}function Yc(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===Ir);return li(n)!==li([Rr().edits[0]])}function Zc(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===Ir);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 li(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 Ir="clear_tool_uses_20250919",ui="clear_thinking_20251015";function Xc(e){
13
+ let t=Rr().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!==Ir),o=r.filter(
14
+ s=>s.type===ui),i=r.filter(s=>s.type!==ui);return {...n,edits:[...o,...i,t]}}function pi(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 Do(e){return e===void 0||e.trim()===""?cn:e.split(",").map(n=>n.trim()).filter(
18
- n=>n.length>0).includes(cn)?e:`${e},${cn}`}function Po(e){let t=e.toLowerCase(),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Aa(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 fe(e){let t=Po(e);return t.startsWith("gpt-")||t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4")?Aa(t)?1.25:1:t.startsWith("gemini")?1:1.25}function or(e){let t=e.toLowerCase();return t.startsWith("claude")||t.startsWith("anthropic/")||Po(t).startsWith("claude")?2:fe(e)}var Da=.3,Pa=/^(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"&&!Pa.test(n)}):false}var Oa=4096,La=(e,t)=>e==="cache_control"?void 0:t;function sr(e){return e===void 0?"":JSON.stringify(e,La)??""}function Ma(e){
21
- return Array.isArray(e)?e.filter(t=>!(t!==null&&typeof t=="object"&&t.defer_loading===true)):e}function ir(e){return createHash("sha1").update(e).digest("base64url").slice(0,16)}function Ye(e,t){let n=un(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 Oo(e){let t=sr(e.system),n=sr(Ma(e.tools)),r=Array.isArray(e.
23
- messages)?e.messages.slice(0,Oa):[],o=[],s=[];for(let i of r){let a=sr(i);o.push(ir(a)),s.push(Buffer.byteLength(a,"utf8"));}return {system:ir(t),tools:ir(n),mensajes:o,bytes:s,bytesFijos:Buffer.byteLength(
24
- t,"utf8")+Buffer.byteLength(n,"utf8")}}function Lo(e,t){if(e===void 0||e.system!==t.system||e.tools!==t.tools)return 1;let n=t.bytesFijos;for(let s of t.bytes)n+=s;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 s=r;s<t.bytes.length;s++)o+=t.bytes[s]??0;return o/n}function Mo(e){let{fraccionNueva:t,umbral:n=Da}=e;return t>=n}function Na(e,t){
26
- e.ttl==="1h"?(e.ttl="5m",t.rebajadas++):(e.ttl==="5m"||e.ttl===void 0)&&t.yaEran5m++;}var Nt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),ar=e=>Nt(e)&&Nt(e.cache_control)?e.cache_control:null,$a=8;
27
- function ln(e,t,n,r){if(!(!Array.isArray(e)||r>$a))for(let o of e){let s=ar(o);if(s&&n(s,t),!Nt(o))continue;Array.isArray(o.content)&&ln(o.content,t,n,r+1);let i=o.source;Nt(i)&&i.type==="content"&&Array.
28
- isArray(i.content)&&ln(i.content,t,n,r+1);}}function lr(e,t){let n=ar(e);if(n&&t(n,"raiz"),ln(e.system,"system",t,0),Array.isArray(e.tools))for(let r of e.tools){let o=ar(r);o&&t(o,"tools");}if(Array.isArray(
29
- e.messages)){let r=e.messages.length-1;e.messages.forEach((o,s)=>{Nt(o)&&ln(o.content,s===r?"ultimoMensaje":"mensaje",t,0);});}}function No(e,t){let n=Buffer.isBuffer(e)?Ye(e,t):e;if(n===null)return null;
30
- try{let r={rebajadas:0,yaEran5m:0};return lr(n,o=>Na(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 dn=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 fi(e){return e===void 0||e.trim()===""?En:e.split(",").map(n=>n.trim()).filter(
18
+ n=>n.length>0).includes(En)?e:`${e},${En}`}function mi(e){let t=e.toLowerCase(),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Qc(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 we(e){let t=mi(e);return t.startsWith("gpt-")||t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4")?Qc(t)?1.25:1:t.startsWith("gemini")?1:1.25}function Tn(e){let t=e.toLowerCase();return t.startsWith("claude")||t.startsWith("anthropic/")||mi(t).startsWith("claude")?2:we(e)}var tl=.3,nl=/^(custom|bash_|text_editor_|computer_|browser_|memory_)/;function Mr(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"&&!nl.test(n)}):false}var rl=4096,ol=(e,t)=>e==="cache_control"?void 0:t;function Pr(e){return e===void 0?"":JSON.stringify(e,ol)??""}function il(e){
21
+ return Array.isArray(e)?e.filter(t=>!(t!==null&&typeof t=="object"&&t.defer_loading===true)):e}function Dr(e){return createHash("sha1").update(e).digest("base64url").slice(0,16)}function ot(e,t){let n=_n(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 hi(e){let t=Pr(e.system),n=Pr(il(e.tools)),r=Array.isArray(e.
23
+ messages)?e.messages.slice(0,rl):[],o=[],i=[];for(let s of r){let a=Pr(s);o.push(Dr(a)),i.push(Buffer.byteLength(a,"utf8"));}return {system:Dr(t),tools:Dr(n),mensajes:o,bytes:i,bytesFijos:Buffer.byteLength(
24
+ t,"utf8")+Buffer.byteLength(n,"utf8")}}function gi(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 bi(e){let{fraccionNueva:t,umbral:n=tl}=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 Jt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Or=e=>Jt(e)&&Jt(e.cache_control)?e.cache_control:null,al=8;
27
+ function Cn(e,t,n,r){if(!(!Array.isArray(e)||r>al))for(let o of e){let i=Or(o);if(i&&n(i,t),!Jt(o))continue;Array.isArray(o.content)&&Cn(o.content,t,n,r+1);let s=o.source;Jt(s)&&s.type==="content"&&Array.
28
+ isArray(s.content)&&Cn(s.content,t,n,r+1);}}function $r(e,t){let n=Or(e);if(n&&t(n,"raiz"),Cn(e.system,"system",t,0),Array.isArray(e.tools))for(let r of e.tools){let o=Or(r);o&&t(o,"tools");}if(Array.isArray(
29
+ e.messages)){let r=e.messages.length-1;e.messages.forEach((o,i)=>{Jt(o)&&Cn(o.content,i===r?"ultimoMensaje":"mensaje",t,0);});}}function vi(e,t){let n=Buffer.isBuffer(e)?ot(e,t):e;if(n===null)return null;
30
+ try{let r={rebajadas:0,yaEran5m:0};return $r(n,o=>sl(o,r)),r.rebajadas===0?null:{cuerpo:Buffer.from(JSON.stringify(n),"utf8"),rebajadas:r.rebajadas,yaEran5m:r.yaEran5m,herramientaDeServidor:Mr(n)}}catch{
31
+ return null}}var An=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 dr="mid-conversation-output-config-2026-07-01",pr=["low","medium","high","xhigh","max"],ja=new Set(["claude-fable-5-1","claude-mythos-5-1","claude-opus-5"]);function Ba(e){return ja.has(e)}function fr(e){
34
- return e!==void 0&&pr.includes(e)}function Ua(e){return {role:"system",content:[],output_config:{effort:e}}}function Fa(e){if(e.output_config!==void 0&&e.output_config!==null)return true;let t=e.messages;
35
- return Array.isArray(t)?t.some(n=>typeof n=="object"&&n!==null&&n.output_config!==void 0):false}function $o(e,t,n){let r=Ye(e,n);if(r===null||typeof r.model!="string"||!Ba(r.model)||Fa(r))return null;let o=r.
36
- messages;return Array.isArray(o)?(r.messages=[...o,Ua(t)],{cuerpo:Buffer.from(JSON.stringify(r),"utf8"),nivel:t}):null}function jo(e){return e===void 0||e.trim()===""?dr:e.split(",").map(n=>n.trim()).
37
- includes(dr)?e:`${e},${dr}`}function Bo(e,t,n){return e===void 0||e===""?{linea:`per-turn effort: OFF (BVSALA_GATEWAY_ESFUERZO=${pr.join("|")} turns it on)`,aviso:false}:fr(e)?n?{linea:`per-turn effort\
38
- : ARMED at "${e}" (ON if your licence includes per_turn_effort; fail-closed). Only fable-5-1, mythos-5-1 and opus-5; every other model passes through unchanged. Does NOT reset the prefix cache: the di\
39
- al is appended at the end and nothing earlier is rewritten`,aviso:false}:{linea:"per-turn effort: NOT ARMED - BVSALA_GATEWAY_ELISION=0 turns off the levers",aviso:true}:{linea:`per-turn effort: NOT ARMED \u2014 "${e}" is n\
40
- ot a level. Use one of: ${pr.join(", ")}`,aviso:true}}var $t={"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},
33
+ this.visto.delete(o.value);}}get tamano(){return this.visto.size}};var Nr="mid-conversation-output-config-2026-07-01",Pn=["low","medium","high","xhigh","max"],cl=new Set(["claude-fable-5-1","claude-mythos-5-1","claude-opus-5-5","claude-opus-5"]),yi={"claude-fable-5-1":"\
34
+ high","claude-mythos-5-1":"high","claude-opus-5-5":"medium","claude-opus-5":"high"};function ll(e){return xi(e)?yi[e]:void 0}function ki(e,t){let n=ll(e);return n!==void 0&&Pn.indexOf(t)<Pn.indexOf(n)}
35
+ var In=Pn.filter(e=>Object.keys(yi).some(t=>ki(t,e)));function xi(e){return cl.has(e)}function jr(e){return e!==void 0&&Pn.includes(e)}function ul(e){return {role:"system",content:[],output_config:{effort:e}}}
36
+ function dl(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 wi(e,t,n){
37
+ let r=ot(e,n);if(r===null||typeof r.model!="string"||!xi(r.model)||!ki(r.model,t)||dl(r))return null;let o=r.messages;return Array.isArray(o)?(r.messages=[...o,ul(t)],{cuerpo:Buffer.from(JSON.stringify(
38
+ r),"utf8"),nivel:t}):null}function Si(e){return e===void 0||e.trim()===""?Nr:e.split(",").map(n=>n.trim()).includes(Nr)?e:`${e},${Nr}`}function Ei(e,t,n){return e===void 0||e===""?{linea:`per-turn eff\
39
+ ort: OFF (BVSALA_GATEWAY_ESFUERZO=${In.join("|")} turns it on)`,aviso:false}:jr(e)?In.includes(e)?n?{linea:`per-turn effort: ARMED at "${e}" (ON if your licence includes per_turn_effort; fail-closed). \
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
+ 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
+ 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 ${In.join(" or ")}`,aviso:true}:{linea:`per-turn effort: NOT ARMED \u2014 "${e}" is not a level. Use one of: ${In.
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},
41
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,
42
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},
43
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},
@@ -59,30 +63,30 @@ cachedInputPer1k:3e-5},"gemini-3.8-flash":{inputPer1k:75e-5,outputPer1k:.00375,c
59
63
  inputPer1k:75e-5,outputPer1k:.00375,cachedInputPer1k:75e-6},"gemini-3.1-flash-lite":{inputPer1k:25e-5,outputPer1k:.0015,cachedInputPer1k:25e-6},"gemini-3-flash-preview":{inputPer1k:5e-4,outputPer1k:.003,
60
64
  cachedInputPer1k:5e-5},"gemini-3.5-flash":{inputPer1k:.0015,outputPer1k:.009,cachedInputPer1k:15e-5},"gemini-3.5-flash-lite":{inputPer1k:3e-4,outputPer1k:.0025,cachedInputPer1k:3e-5},"gemini-3.1-pro-p\
61
65
  review":{inputPer1k:.002,outputPer1k:.012,cachedInputPer1k:2e-4},"gemini-2.5-pro":{inputPer1k:.00125,outputPer1k:.01,cachedInputPer1k:125e-6},"gemini-2.5-flash":{inputPer1k:3e-4,outputPer1k:.0025,cachedInputPer1k:3e-5}},
62
- Va={"gemini-3.8-flash":{vigenteHasta:"2027-01-01"},"gemini-3.7-flash":{vigenteHasta:"2027-01-01"},"gemini-3.6-flash":{vigenteHasta:"2027-01-01"}},za={"gemini-3.8-flash":[{vigenteDesde:"2027-01-01",precio:{
66
+ pl={"gemini-3.8-flash":{vigenteHasta:"2027-01-01"},"gemini-3.7-flash":{vigenteHasta:"2027-01-01"},"gemini-3.6-flash":{vigenteHasta:"2027-01-01"}},fl={"gemini-3.8-flash":[{vigenteDesde:"2027-01-01",precio:{
63
67
  inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}],"gemini-3.7-flash":[{vigenteDesde:"2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}],"gemini-3.6-flash":[{vigenteDesde:"\
64
- 2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}]},qa=Object.fromEntries(Object.keys($t).map(e=>[e,[{...Va[e],precio:$t[e]},...za[e]??[]]]));var Ha=864e13;function Uo(e){let t=e instanceof Date?e.getTime():e,n=typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<=Ha?t:Date.now();return new Date(n).toISOString().slice(0,10)}function Fo(e,t){
65
- for(let n of qa[e]??[])if(!(n.vigenteDesde!==void 0&&t<n.vigenteDesde)&&!(n.vigenteHasta!==void 0&&t>=n.vigenteHasta))return n.precio}function Vo(e,t,n){if(!n)return;let r=e[n];if(r)return r;let o=n.lastIndexOf("/"),s=o>=0?n.slice(o+1):n,i=e[s];if(i)return i;for(let a of t){if(!s.startsWith(a))continue;let u=s.charAt(a.length);if(u!==
66
- ""&&u!=="-"&&u!=="."&&u!=="_")continue;let c=s.slice(a.length+1);if(!(/^\d/.test(c)&&!/^\d{4}/.test(c)))return e[a]}}function hr(e){return Object.keys(e).sort((t,n)=>n.length-t.length)}var Wa=["o3-dee\
67
- 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"],mr={...$t,...Object.
68
- fromEntries(Wa.map(e=>[e,null]))},Ka=hr(mr);function be(e,t){let n=Ze(e);return n===void 0?void 0:Fo(n,Uo(t))}var Ga=Object.fromEntries(Object.keys(mr).map(e=>[e,mr[e]===null?null:e]));function Ze(e){
69
- return Vo(Ga,Ka,e)??void 0}var Ja=/^\d{4}-?\d{2}-?\d{2}$/;function pt(e,t){let n=Ze(e);if(n===void 0)return;let r=e.lastIndexOf("/"),o=r>=0?e.slice(r+1):e;if(!(n!==e&&n!==o&&!Ja.test(o.slice(n.length+
70
- 1))))return Fo(n,Uo(t))}var zo={"claude-fable-5":"claude-fable-5-1"};function Ya(e,t){let n=be(e),r=be(t);if(n===void 0||r===void 0||n.inputPer1k!==r.inputPer1k||n.outputPer1k!==r.outputPer1k||fe(e)!==fe(t))return false;let o=n.
71
- cachedInputPer1k??n.inputPer1k;return (r.cachedInputPer1k??r.inputPer1k)<o}function Za(e){let t=Ze(e);if(t===void 0||t!==e)return null;let n=zo[t];return n===void 0||n===t||!Ya(t,n)?null:{solicitado:e,
72
- servido:n}}var Xa=/(^|,)\s*context-1m/i;function Qa(e){let t=e.tool_choice;if(t===null||typeof t!="object")return false;let n=t.type;return n==="any"||n==="tool"}function qo(e,t,n={}){if(n.betas!==void 0&&
73
- Xa.test(n.betas))return null;let r=Ye(e,t);if(r===null||Qa(r))return null;let o=Za(r.model);return o===null?null:(r.model=o.servido,{cuerpo:Buffer.from(JSON.stringify(r),"utf8"),cambio:o})}function Ho(e,t,n){
74
- let r=Object.entries(zo).map(([o,s])=>`${o}\u2192${s}`).join(", ");return e!=="1"?{linea:"sibling model routing: OFF (BVSALA_GATEWAY_MODELO_HERMANO=1 turns it on)",aviso:false}:n?{linea:`sibling model \
68
+ 2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}]},ml=Object.fromEntries(Object.keys(Yt).map(e=>[e,[{...pl[e],precio:Yt[e]},...fl[e]??[]]]));var hl=864e13;function _i(e){let t=e instanceof Date?e.getTime():e,n=typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<=hl?t:Date.now();return new Date(n).toISOString().slice(0,10)}function Ti(e,t){
69
+ for(let n of ml[e]??[])if(!(n.vigenteDesde!==void 0&&t<n.vigenteDesde)&&!(n.vigenteHasta!==void 0&&t>=n.vigenteHasta))return n.precio}function Ci(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 Ur(e){return Object.keys(e).sort((t,n)=>n.length-t.length)}var gl=["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"],Br={...Yt,...Object.
72
+ fromEntries(gl.map(e=>[e,null]))},bl=Ur(Br);function Te(e,t){let n=it(e);return n===void 0?void 0:Ti(n,_i(t))}var vl=Object.fromEntries(Object.keys(Br).map(e=>[e,Br[e]===null?null:e]));function it(e){
73
+ return Ci(vl,bl,e)??void 0}var yl=/^\d{4}-?\d{2}-?\d{2}$/;function Et(e,t){let n=it(e);if(n===void 0)return;let r=e.lastIndexOf("/"),o=r>=0?e.slice(r+1):e;if(!(n!==e&&n!==o&&!yl.test(o.slice(n.length+
74
+ 1))))return Ti(n,_i(t))}var Ai={"claude-fable-5":"claude-fable-5-1"};function kl(e,t){let n=Te(e),r=Te(t);if(n===void 0||r===void 0||n.inputPer1k!==r.inputPer1k||n.outputPer1k!==r.outputPer1k||we(e)!==we(t))return false;let o=n.
75
+ cachedInputPer1k??n.inputPer1k;return (r.cachedInputPer1k??r.inputPer1k)<o}function xl(e){let t=it(e);if(t===void 0||t!==e)return null;let n=Ai[t];return n===void 0||n===t||!kl(t,n)?null:{solicitado:e,
76
+ servido:n}}var wl=/(^|,)\s*context-1m/i;function Sl(e){let t=e.tool_choice;if(t===null||typeof t!="object")return false;let n=t.type;return n==="any"||n==="tool"}function Ri(e,t,n={}){if(n.betas!==void 0&&
77
+ wl.test(n.betas))return null;let r=ot(e,t);if(r===null||Sl(r))return null;let o=xl(r.model);return o===null?null:(r.model=o.servido,{cuerpo:Buffer.from(JSON.stringify(r),"utf8"),cambio:o})}function Ii(e,t,n){
78
+ let r=Object.entries(Ai).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 \
75
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\
76
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_\
77
- ELISION=0 turns off the levers",aviso:true}}var Wo=new Set;function z(e,t){Wo.has(e)||(Wo.add(e),console.warn(t));}var we="0.4.25",gr="x-bvsala-version";var ft=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 Pi=new Set;function W(e,t){Pi.has(e)||(Pi.add(e),console.warn(t));}var he="0.4.26",Vr="x-bvsala-version";var _t=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=
78
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.
79
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.
80
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??
81
- Math.ceil(this.maxBuffer/this.maxBatch)+4,r=0;for(let o=0;o<n&&this.buffer.length>0;o++){let s=this.buffer.length;if(await this.flush(),r=this.buffer.length>=s?r+1:0,r>=2)break}}async flush(){if(this.
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.
82
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.
83
- fetch;if(!t)return;let n=this.buffer.splice(0,this.maxBatch);try{let r=n.map(s=>this.toWire(s)),o=await t(this.options.url,{method:"POST",headers:{"content-type":"application/json",authorization:`Bear\
84
- er ${this.options.serviceAccountKey}`,[gr]:`${this.options.surface??"sdk"}/${we}`},body:JSON.stringify(r)});o.ok?this.fallosSeguidos=0:o.status>=500?(this.fallosSeguidos++,this.requeue(n),this.avisarDeFallo(
85
- `the server responded ${o.status}`)):o.status===401||o.status===403?(z(`metering-auth-${o.status}`,`[bv-sala] usage reporting is being rejected with HTTP ${o.status} at ${this.options.url}. Check 'ser\
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}`,[Vr]:`${this.options.surface??"sdk"}/${he}`},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?(W(`metering-auth-${o.status}`,`[bv-sala] usage reporting is being rejected with HTTP ${o.status} at ${this.options.url}. Check 'ser\
86
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?.(
87
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.
88
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||
@@ -94,34 +98,34 @@ tokens.compressedInput,baselineOutputTokens:n.tokens.baselineOutput,actualOutput
94
98
  eliminatedInputFloorCost!==void 0&&Number.isFinite(n.cost.eliminatedInputFloorCost)&&n.cost.eliminatedInputFloorCost>0&&n.tokens.eliminatedInput>0?{eliminatedInputFloorCost:n.cost.eliminatedInputFloorCost}:
95
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}$/.
96
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.
97
- attribution.sessionId}:{},...n.attribution?.agentId?{agentId:n.attribution.agentId}:{}}}};function fn(){return globalThis.process}function ec(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\
98
- ]";return new RegExp(`-${t}{8,10}-${t}{5}$`).test(e)}function tc(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??
99
- e.NETLIFY)}async function nc(){if(fn()?.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 rc(e,t=nc){
100
- if(e.KUBERNETES_SERVICE_HOST||tc(e))return;let n=e.HOSTNAME??e.COMPUTERNAME??await t();if(!(!n||ec(n)))return n}async function oc(){let e=fn();if(!e||!e.env)return;let t=e.env,n=await rc(t),r=[e.platform,
101
- 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 sc=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTI\
102
- 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=fn()?.env;if(!e)
103
- return false;for(let t of sc){let n=e[t];if(n&&n!=="false"&&n!=="0")return true}return false}async function ic(e,t){let n=globalThis.crypto,r=new TextEncoder;if(n?.subtle)try{let i=await n.subtle.importKey("raw",
104
- r.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await n.subtle.sign("HMAC",i,r.encode(t));return [...new Uint8Array(a)].map(u=>u.toString(16).padStart(2,"0")).join("")}catch{}let o=2166136261,s=`${e}\
105
- |${t}`;for(let i=0;i<s.length;i++)o^=s.charCodeAt(i),o=Math.imul(o,16777619);return (o>>>0).toString(16).padStart(8,"0")}async function hn(e){let n=fn()?.env?.BVSALA_SEAT_ID;if(n&&ac.test(n))return n;let r=await oc();
106
- if(!r)return;let o=await ic(e,r);if(o)return `m-${o.slice(0,32)}`}var ac=/^[A-Za-z0-9._:/-]{1,128}$/;function br(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function gn(e,t=""){if(typeof e!="number"){let n=t&&
107
- `"${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 ve(e,t,n=""){
108
- let r=br(e),o=e?.length,s=t!==void 0;if(!r||s&&o!==t){let i=n&&`"${n}" `,a=s?` of length ${t}`:"",u=r?`length=${o}`:`type=${typeof e}`,c=i+"expected Uint8Array"+a+", got "+u;throw r?new RangeError(c):
109
- new TypeError(c)}return e}function vr(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 Go(e,t){ve(e,void 0,"digestInt\
110
- o() output");let n=t.outputLen;if(e.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function jt(...e){for(let t=0;t<e.length;t++)e[t].fill(0);}function bn(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var Jo=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",cc=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function vn(e){if(ve(e),Jo)return e.toHex();
111
- let t="";for(let n=0;n<e.length;n++)t+=cc[e[n]];return t}var De={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ko(e){if(e>=De._0&&e<=De._9)return e-De._0;if(e>=De.A&&e<=De.F)return e-(De.A-10);if(e>=De.a&&
112
- e<=De.f)return e-(De.a-10)}function Bt(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);if(Jo)try{return Uint8Array.fromHex(e)}catch(o){throw o instanceof SyntaxError?
113
- 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,s=0;o<n;o++,s+=2){let i=Ko(e.charCodeAt(
114
- s)),a=Ko(e.charCodeAt(s+1));if(i===void 0||a===void 0){let u=e[s]+e[s+1];throw new RangeError('hex string expected, got non-hex character "'+u+'" at index '+s)}r[o]=i*16+a;}return r}function yr(...e){let t=0;for(let r=0;r<e.length;r++){let o=e[r];ve(o),t+=o.length;}let n=new Uint8Array(t);for(let r=0,o=0;r<e.length;r++){let s=e[r];n.set(s,o),o+=s.length;}return n}function Yo(e,t={}){let n=(o,s)=>e(s).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 Zo(e=32){
115
- gn(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(
116
- `"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}var Xo=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});var yn=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=
117
- new Uint8Array(t),this.view=bn(this.buffer);}update(t){vr(this),ve(t);let{view:n,buffer:r,blockLen:o}=this,s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let u=bn(t);for(;o<=s-i;i+=
118
- o)this.process(u,i);continue}r.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(n,0),this.pos=0);}return this.length+=t.length,this.roundClean(),this}digestInto(t){vr(this),
119
- Go(t,this),this.finished=true;let{buffer:n,view:r,blockLen:o,isLE:s}=this,{pos:i}=this;n[i++]=128,jt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(r,0),i=0);for(let l=i;l<o;l++)n[l]=0;r.setBigUint64(
120
- o-8,BigInt(this.length*8),s),this.process(r,0);let a=bn(t),u=this.outputLen;if(u%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let c=u/4,d=this.get();if(c>d.length)throw new Error("_s\
121
- ha2: outputLen bigger than state");for(let l=0;l<c;l++)a.setUint32(4*l,d[l],s);}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.
122
- constructor,t.set(...this.get());let{blockLen:n,buffer:r,length:o,finished:s,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=s,t.length=o,t.pos=a,o%n&&t.buffer.set(r),t}clone(){return this._cloneInto()}};var ne=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var kn=BigInt(4294967295),Qo=BigInt(32);function uc(e,t=false){return t?{h:Number(e&kn),l:Number(e>>Qo&kn)}:{h:Number(e>>Qo&kn)|0,l:Number(e&kn)|0}}function es(e,t=false){let n=e.length,r=new Uint32Array(n),
123
- o=new Uint32Array(n);for(let s=0;s<n;s++){let{h:i,l:a}=uc(e[s],t);[r[s],o[s]]=[i,a];}return [r,o]}var kr=(e,t,n)=>e>>>n,xr=(e,t,n)=>e<<32-n|t>>>n,Xe=(e,t,n)=>e>>>n|t<<32-n,Qe=(e,t,n)=>e<<32-n|t>>>n,Ut=(e,t,n)=>e<<64-n|t>>>n-32,Ft=(e,t,n)=>e>>>n-32|t<<64-n;function Se(e,t,n,r){let o=(t>>>0)+(r>>>0);return {h:e+n+(o/2**32|0)|0,l:o|0}}var ts=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),ns=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,rs=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),os=(e,t,n,r,o)=>t+
124
- n+r+o+(e/2**32|0)|0,ss=(e,t,n,r,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(o>>>0),is=(e,t,n,r,o,s)=>t+n+r+o+s+(e/2**32|0)|0;var as=es(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242",
101
+ attribution.sessionId}:{},...n.attribution?.agentId?{agentId:n.attribution.agentId}:{}}}};function Dn(){return globalThis.process}function El(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 _l(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 Tl(){if(Dn()?.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 Cl(e,t=Tl){
104
+ if(e.KUBERNETES_SERVICE_HOST||_l(e))return;let n=e.HOSTNAME??e.COMPUTERNAME??await t();if(!(!n||El(n)))return n}async function Al(){let e=Dn();if(!e||!e.env)return;let t=e.env,n=await Cl(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 Rl=["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 On(){let e=Dn()?.env;if(!e)
107
+ return false;for(let t of Rl){let n=e[t];if(n&&n!=="false"&&n!=="0")return true}return false}async function Il(e,t){let n=globalThis.crypto,r=new TextEncoder;if(n?.subtle)try{let s=await n.subtle.importKey("raw",
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 Ln(e){let n=Dn()?.env?.BVSALA_SEAT_ID;if(n&&Pl.test(n))return n;let r=await Al();
110
+ if(!r)return;let o=await Il(e,r);if(o)return `m-${o.slice(0,32)}`}var Pl=/^[A-Za-z0-9._:/-]{1,128}$/;function Fr(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Mn(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=Fr(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 zr(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 Oi(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 $n(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var Li=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Dl=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Nn(e){if(Ce(e),Li)return e.toHex();
115
+ let t="";for(let n=0;n<e.length;n++)t+=Dl[e[n]];return t}var Ue={_0:48,_9:57,A:65,F:70,a:97,f:102};function Di(e){if(e>=Ue._0&&e<=Ue._9)return e-Ue._0;if(e>=Ue.A&&e<=Ue.F)return e-(Ue.A-10);if(e>=Ue.a&&
116
+ e<=Ue.f)return e-(Ue.a-10)}function Xt(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);if(Li)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=Di(e.charCodeAt(
118
+ i)),a=Di(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 qr(...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 Mi(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 $i(e=32){
119
+ Mn(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 Ni=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});var jn=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=$n(this.buffer);}update(t){zr(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=$n(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){zr(this),
123
+ Oi(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=$n(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
+ 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 Bn=BigInt(4294967295),ji=BigInt(32);function Ol(e,t=false){return t?{h:Number(e&Bn),l:Number(e>>ji&Bn)}:{h:Number(e>>ji&Bn)|0,l:Number(e&Bn)|0}}function Bi(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}=Ol(e[i],t);[r[i],o[i]]=[s,a];}return [r,o]}var Hr=(e,t,n)=>e>>>n,Wr=(e,t,n)=>e<<32-n|t>>>n,st=(e,t,n)=>e>>>n|t<<32-n,at=(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 Ie(e,t,n,r){let o=(t>>>0)+(r>>>0);return {h:e+n+(o/2**32|0)|0,l:o|0}}var Ui=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Vi=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Fi=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),zi=(e,t,n,r,o)=>t+
128
+ n+r+o+(e/2**32|0)|0,qi=(e,t,n,r,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(o>>>0),Hi=(e,t,n,r,o,i)=>t+n+r+o+i+(e/2**32|0)|0;var Wi=Bi(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242",
125
129
  "0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc6\
126
130
  8b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","\
127
131
  0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3\
@@ -129,571 +133,813 @@ c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a6
129
133
  x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5d\
130
134
  efb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0x\
131
135
  eada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c1\
132
- 00d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),dc=as[0],pc=as[1],Ue=new Uint32Array(80),Fe=new Uint32Array(80),wr=class extends yn{constructor(t){
133
- super(128,t,16,false);}get(){let{Ah:t,Al:n,Bh:r,Bl:o,Ch:s,Cl:i,Dh:a,Dl:u,Eh:c,El:d,Fh:l,Fl:p,Gh:f,Gl:g,Hh:y,Hl:h}=this;return [t,n,r,o,s,i,a,u,c,d,l,p,f,g,y,h]}set(t,n,r,o,s,i,a,u,c,d,l,p,f,g,y,h){this.Ah=
134
- t|0,this.Al=n|0,this.Bh=r|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=u|0,this.Eh=c|0,this.El=d|0,this.Fh=l|0,this.Fl=p|0,this.Gh=f|0,this.Gl=g|0,this.Hh=y|0,this.Hl=h|0;}process(t,n){for(let _=0;_<
135
- 16;_++,n+=4)Ue[_]=t.getUint32(n),Fe[_]=t.getUint32(n+=4);for(let _=16;_<80;_++){let v=Ue[_-15]|0,I=Fe[_-15]|0,A=Xe(v,I,1)^Xe(v,I,8)^kr(v,I,7),C=Qe(v,I,1)^Qe(v,I,8)^xr(v,I,7),P=Ue[_-2]|0,M=Fe[_-2]|0,q=Xe(
136
- P,M,19)^Ut(P,M,61)^kr(P,M,6),J=Qe(P,M,19)^Ft(P,M,61)^xr(P,M,6),S=rs(C,J,Fe[_-7],Fe[_-16]),T=os(S,A,q,Ue[_-7],Ue[_-16]);Ue[_]=T|0,Fe[_]=S|0;}let{Ah:r,Al:o,Bh:s,Bl:i,Ch:a,Cl:u,Dh:c,Dl:d,Eh:l,El:p,Fh:f,Fl:g,
137
- Gh:y,Gl:h,Hh:b,Hl:w}=this;for(let _=0;_<80;_++){let v=Xe(l,p,14)^Xe(l,p,18)^Ut(l,p,41),I=Qe(l,p,14)^Qe(l,p,18)^Ft(l,p,41),A=l&f^~l&y,C=p&g^~p&h,P=ss(w,I,C,pc[_],Fe[_]),M=is(P,b,v,A,dc[_],Ue[_]),q=P|0,
138
- J=Xe(r,o,28)^Ut(r,o,34)^Ut(r,o,39),S=Qe(r,o,28)^Ft(r,o,34)^Ft(r,o,39),T=r&s^r&a^s&a,O=o&i^o&u^i&u;b=y|0,w=h|0,y=f|0,h=g|0,f=l|0,g=p|0,{h:l,l:p}=Se(c|0,d|0,M|0,q|0),c=a|0,d=u|0,a=s|0,u=i|0,s=r|0,i=o|0;
139
- let L=ts(q,S,O);r=ns(L,M,J,T),o=L|0;}(({h:r,l:o}=Se(this.Ah|0,this.Al|0,r|0,o|0))),{h:s,l:i}=Se(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:u}=Se(this.Ch|0,this.Cl|0,a|0,u|0),{h:c,l:d}=Se(this.Dh|0,this.Dl|0,c|0,
140
- d|0),{h:l,l:p}=Se(this.Eh|0,this.El|0,l|0,p|0),{h:f,l:g}=Se(this.Fh|0,this.Fl|0,f|0,g|0),{h:y,l:h}=Se(this.Gh|0,this.Gl|0,y|0,h|0),{h:b,l:w}=Se(this.Hh|0,this.Hl|0,b|0,w|0),this.set(r,o,s,i,a,u,c,d,l,
141
- p,f,g,y,h,b,w);}roundClean(){jt(Ue,Fe);}destroy(){this.destroyed=true,jt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}},Sr=class extends wr{Ah=ne[0]|0;Al=ne[1]|0;Bh=ne[2]|0;Bl=ne[3]|0;Ch=ne[4]|0;Cl=ne[5]|
142
- 0;Dh=ne[6]|0;Dl=ne[7]|0;Eh=ne[8]|0;El=ne[9]|0;Fh=ne[10]|0;Fl=ne[11]|0;Gh=ne[12]|0;Gl=ne[13]|0;Hh=ne[14]|0;Hl=ne[15]|0;constructor(){super(64);}};var xn=Yo(()=>new Sr,Xo(3));var Z=(e,t,n)=>ve(e,t,n),_r=gn,Tr=vn,Ee=(...e)=>yr(...e),cs=e=>Bt(e),En=br,us=e=>Zo(e),Sn=BigInt(0),Er=BigInt(1);function mt(e,t=""){if(typeof e!="boolean"){let n=t&&`"${t}" `;throw new TypeError(n+"e\
143
- xpected boolean, got type="+typeof e)}return e}function fc(e){if(typeof e=="bigint"){if(!wn(e))throw new RangeError("positive bigint expected, got "+e)}else _r(e);return e}function Pe(e,t=""){if(typeof e!=
144
- "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 ls(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);return e===""?Sn:BigInt("0x"+e)}function Rr(e){return ls(vn(e))}function Oe(e){return ls(vn(Vt(ve(e)).reverse()))}
145
- function Ir(e,t){if(gn(t),t===0)throw new RangeError("zero length");e=fc(e);let n=e.toString(16);if(n.length>t*2)throw new RangeError("number too large");return Bt(n.padStart(t*2,"0"))}function ds(e,t){
146
- return Ir(e,t).reverse()}function ps(e,t){if(e=Z(e),t=Z(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 Vt(e){return Uint8Array.from(Z(e))}var wn=e=>typeof e=="bigint"&&Sn<=e;function mc(e,t,n){return wn(e)&&wn(t)&&wn(n)&&t<=e&&e<n}function Ar(e,t,n,r){if(!mc(t,n,r))throw new RangeError(
147
- "expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function Cr(e){if(e<Sn)throw new Error("expected non-negative bigint, got "+e);let t;for(t=0;e>Sn;e>>=Er,t+=1);return t}var fs=e=>(Er<<BigInt(e))-Er;function et(e,t={},n={}){if(Object.prototype.toString.call(e)!=="[object Object]")throw new TypeError("expected valid options object");function r(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(e,s))throw new TypeError(
148
- `param "${s}" is invalid: expected own property`);let u=e[s];if(a&&u===void 0)return;let c=typeof u;if(c!==i||u===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${c}`)}let o=(s,i)=>Object.
149
- entries(s).forEach(([a,u])=>r(a,u,i));o(t,false),o(n,true);}var Dr=()=>{throw new Error("not implemented")};var re=BigInt(0),Q=BigInt(1),tt=BigInt(2),bs=BigInt(3),vs=BigInt(4),ys=BigInt(5),hc=BigInt(7),ks=BigInt(8),gc=BigInt(9),xs=BigInt(16);function G(e,t){if(t<=re)throw new Error("mod: expected positive m\
150
- odulus, got "+t);let n=e%t;return n>=re?n:t+n}function ye(e,t,n){if(t<re)throw new Error("pow2: expected non-negative exponent, got "+t);let r=e;for(;t-- >re;)r*=r,r%=n;return r}function ms(e,t){if(e===re)throw new Error("invert: expected non-zer\
151
- o number");if(t<=re)throw new Error("invert: expected positive modulus, got "+t);let n=G(e,t),r=t,o=re,i=Q;for(;n!==re;){let c=r/n,d=r-n*c,l=o-i*c;r=n,n=d,o=i,i=l;}if(r!==Q)throw new Error(
152
- "invert: does not exist");return G(o,t)}function Pr(e,t,n){let r=e;if(!r.eql(r.sqr(t),n))throw new Error("Cannot find square root")}function ws(e,t){let n=e,r=(n.ORDER+Q)/vs,o=n.pow(t,r);return Pr(n,o,
153
- t),o}function bc(e,t){let n=e,r=(n.ORDER-ys)/ks,o=n.mul(t,tt),s=n.pow(o,r),i=n.mul(t,s),a=n.mul(n.mul(i,tt),s),u=n.mul(i,n.sub(a,n.ONE));return Pr(n,u,t),u}function vc(e){let t=In(e),n=Ss(e),r=n(t,t.neg(
154
- t.ONE)),o=n(t,r),s=n(t,t.neg(r)),i=(e+hc)/xs;return((a,u)=>{let c=a,d=c.pow(u,i),l=c.mul(d,r),p=c.mul(d,o),f=c.mul(d,s),g=c.eql(c.sqr(l),u),y=c.eql(c.sqr(p),u);d=c.cmov(d,l,g),l=c.cmov(f,p,y);let h=c.
155
- eql(c.sqr(l),u),b=c.cmov(d,l,h);return Pr(c,b,u),b})}function Ss(e){if(e<bs)throw new Error("sqrt is not defined for small field");let t=e-Q,n=0;for(;t%tt===re;)t/=tt,n++;let r=tt,o=In(e);for(;hs(o,r)===
156
- 1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return ws;let s=o.pow(r,t),i=(t+Q)/tt;return function(u,c){let d=u;if(d.is0(c))return c;if(hs(d,c)!==1)throw new Error(
157
- "Cannot find square root");let l=n,p=d.mul(d.ONE,s),f=d.pow(c,t),g=d.pow(c,i);for(;!d.eql(f,d.ONE);){if(d.is0(f))return d.ZERO;let y=1,h=d.sqr(f);for(;!d.eql(h,d.ONE);)if(y++,h=d.sqr(h),y===l)throw new Error(
158
- "Cannot find square root");let b=Q<<BigInt(l-y-1),w=d.pow(p,b);l=y,p=d.sqr(w),f=d.mul(f,p),g=d.mul(g,w);}return g}}function yc(e){return e%vs===bs?ws:e%ks===ys?bc:e%xs===gc?vc(e):Ss(e)}var Le=(e,t)=>(G(
159
- e,t)&Q)===Q,kc=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Es(e){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},n=kc.
160
- reduce((r,o)=>(r[o]="function",r),t);if(et(e,n),Pe(e.BYTES,"BYTES"),Pe(e.BITS,"BITS"),e.BYTES<1||e.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(e.ORDER<=Q)throw new Error("inval\
161
- id field: expected ORDER > 1, got "+e.ORDER);return e}function xc(e,t,n){let r=e;if(n<re)throw new Error("invalid exponent, negatives unsupported");if(n===re)return r.ONE;if(n===Q)return t;let o=r.ONE,
162
- s=t;for(;n>re;)n&Q&&(o=r.mul(o,s)),s=r.sqr(s),n>>=Q;return o}function Rn(e,t,n=false){let r=e,o=new Array(t.length).fill(n?r.ZERO:void 0),s=t.reduce((a,u,c)=>r.is0(u)?a:(o[c]=a,r.mul(a,u)),r.ONE),i=r.inv(
163
- s);return t.reduceRight((a,u,c)=>r.is0(u)?a:(o[c]=r.mul(a,o[c]),r.mul(a,u)),i),o}function hs(e,t){let n=e,r=(n.ORDER-Q)/tt,o=n.pow(t,r),s=n.eql(o,n.ONE),i=n.eql(o,n.ZERO),a=n.eql(o,n.neg(n.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function wc(e,t){if(t!==void 0&&_r(t),e<=re)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);
164
- let n=Cr(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 gs=new WeakMap,
165
- Tn=class{ORDER;BITS;BYTES;isLE;ZERO=re;ONE=Q;_lengths;_mod;constructor(t,n={}){if(t<=Q)throw new Error("invalid field: expected ORDER > 1, got "+t);let r;this.isLE=false,n!=null&&typeof n=="object"&&(typeof n.
136
+ 00d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),Ml=Wi[0],$l=Wi[1],Ge=new Uint32Array(80),Je=new Uint32Array(80),Kr=class extends jn{constructor(t){
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
+ 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)Ge[x]=t.getUint32(n),Je[x]=t.getUint32(n+=4);for(let x=16;x<80;x++){let v=Ge[x-15]|0,A=Je[x-15]|0,R=st(v,A,1)^st(v,A,8)^Hr(v,A,7),I=at(v,A,1)^at(v,A,8)^Wr(v,A,7),D=Ge[x-2]|0,N=Je[x-2]|0,z=st(
140
+ D,N,19)^Qt(D,N,61)^Hr(D,N,6),G=at(D,N,19)^en(D,N,61)^Wr(D,N,6),S=Fi(I,G,Je[x-7],Je[x-16]),C=zi(S,R,z,Ge[x-7],Ge[x-16]);Ge[x]=C|0,Je[x]=S|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:y,Hl:k}=this;for(let x=0;x<80;x++){let v=st(u,p,14)^st(u,p,18)^Qt(u,p,41),A=at(u,p,14)^at(u,p,18)^en(u,p,41),R=u&f^~u&b,I=p&g^~p&h,D=qi(k,A,I,$l[x],Je[x]),N=Hi(D,y,v,R,Ml[x],Ge[x]),z=D|0,
142
+ G=st(r,o,28)^Qt(r,o,34)^Qt(r,o,39),S=at(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;y=b|0,k=h|0,b=f|0,h=g|0,f=u|0,g=p|0,{h:u,l:p}=Ie(l|0,d|0,N|0,z|0),l=a|0,d=c|0,a=i|0,c=s|0,i=r|0,s=o|0;
143
+ let $=Ui(z,S,O);r=Vi($,N,G,C),o=$|0;}(({h:r,l:o}=Ie(this.Ah|0,this.Al|0,r|0,o|0))),{h:i,l:s}=Ie(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Ie(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:d}=Ie(this.Dh|0,this.Dl|0,l|0,
144
+ d|0),{h:u,l:p}=Ie(this.Eh|0,this.El|0,u|0,p|0),{h:f,l:g}=Ie(this.Fh|0,this.Fl|0,f|0,g|0),{h:b,l:h}=Ie(this.Gh|0,this.Gl|0,b|0,h|0),{h:y,l:k}=Ie(this.Hh|0,this.Hl|0,y|0,k|0),this.set(r,o,i,s,a,c,l,d,u,
145
+ p,f,g,b,h,y,k);}roundClean(){Zt(Ge,Je);}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);}},Gr=class extends Kr{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 Un=Mi(()=>new Gr,Ni(3));var Z=(e,t,n)=>Ce(e,t,n),Yr=Mn,Zr=Nn,Pe=(...e)=>qr(...e),Ki=e=>Xt(e),zn=Fr,Gi=e=>$i(e),Fn=BigInt(0),Jr=BigInt(1);function Tt(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 Nl(e){if(typeof e=="bigint"){if(!Vn(e))throw new RangeError("positive bigint expected, got "+e)}else Yr(e);return e}function Ve(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 Ji(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);return e===""?Fn:BigInt("0x"+e)}function Xr(e){return Ji(Nn(e))}function Fe(e){return Ji(Nn(tn(Ce(e)).reverse()))}
149
+ function Qr(e,t){if(Mn(t),t===0)throw new RangeError("zero length");e=Nl(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 Yi(e,t){
150
+ return Qr(e,t).reverse()}function Zi(e,t){if(e=Z(e),t=Z(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(Z(e))}var Vn=e=>typeof e=="bigint"&&Fn<=e;function jl(e,t,n){return Vn(e)&&Vn(t)&&Vn(n)&&t<=e&&e<n}function eo(e,t,n,r){if(!jl(t,n,r))throw new RangeError(
151
+ "expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function to(e){if(e<Fn)throw new Error("expected non-negative bigint, got "+e);let t;for(t=0;e>Fn;e>>=Jr,t+=1);return t}var Xi=e=>(Jr<<BigInt(e))-Jr;function ct(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
+ `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 no=()=>{throw new Error("not implemented")};var ae=BigInt(0),te=BigInt(1),lt=BigInt(2),ns=BigInt(3),rs=BigInt(4),os=BigInt(5),Bl=BigInt(7),is=BigInt(8),Ul=BigInt(9),ss=BigInt(16);function K(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 Qi(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=K(e,t),r=t,o=ae,s=te;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!==te)
156
+ throw new Error("invert: does not exist");return K(o,t)}function ro(e,t,n){let r=e;if(!r.eql(r.sqr(t),n))throw new Error("Cannot find square root")}function as(e,t){let n=e,r=(n.ORDER+te)/rs,o=n.pow(t,
157
+ r);return ro(n,o,t),o}function Vl(e,t){let n=e,r=(n.ORDER-os)/is,o=n.mul(t,lt),i=n.pow(o,r),s=n.mul(t,i),a=n.mul(n.mul(s,lt),i),c=n.mul(s,n.sub(a,n.ONE));return ro(n,c,t),c}function Fl(e){let t=Kn(e),
158
+ n=cs(e),r=n(t,t.neg(t.ONE)),o=n(t,r),i=n(t,t.neg(r)),s=(e+Bl)/ss;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),y=l.cmov(d,u,h);return ro(l,y,c),y})}function cs(e){if(e<ns)throw new Error("sqrt is not defined for small field");let t=e-te,n=0;for(;t%lt===ae;)t/=lt,n++;let r=lt,
160
+ o=Kn(e);for(;es(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return as;let i=o.pow(r,t),s=(t+te)/lt;return function(c,l){let d=c;if(d.is0(l))return l;
161
+ if(es(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 y=te<<BigInt(u-b-1),k=d.pow(p,y);u=b,p=d.sqr(k),f=d.mul(f,p),g=d.mul(g,k);}return g}}function zl(e){return e%rs===ns?as:e%is===os?Vl:e%ss===
163
+ Ul?Fl(e):cs(e)}var ze=(e,t)=>(K(e,t)&te)===te,ql=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ls(e){let t={ORDER:"bigint",
164
+ BYTES:"number",BITS:"number"},n=ql.reduce((r,o)=>(r[o]="function",r),t);if(ct(e,n),Ve(e.BYTES,"BYTES"),Ve(e.BITS,"BITS"),e.BYTES<1||e.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(e.
165
+ ORDER<=te)throw new Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function Hl(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===te)return t;let o=r.ONE,i=t;for(;n>ae;)n&te&&(o=r.mul(o,i)),i=r.sqr(i),n>>=te;return o}function Wn(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 es(e,t){let n=e,r=(n.ORDER-te)/lt,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 Wl(e,t){if(t!==void 0&&Yr(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=to(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 ts=new WeakMap,
169
+ Hn=class{ORDER;BITS;BYTES;isLE;ZERO=ae;ONE=te;_lengths;_mod;constructor(t,n={}){if(t<=te)throw new Error("invalid field: expected ORDER > 1, got "+t);let r;this.isLE=false,n!=null&&typeof n=="object"&&(typeof n.
166
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.
167
- freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:s}=wc(t,r);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2\
168
- 048 bytes");this.ORDER=t,this.BITS=o,this.BYTES=s,Object.freeze(this);}create(t){return G(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new TypeError("invalid field element: expected bigint, got\
169
- "+typeof t);return re<=t&&t<this.ORDER}is0(t){return t===re}isValidNot0(t){return !this.is0(t)&&this.isValid(t)}isOdd(t){return (t&Q)===Q}neg(t){return G(-t,this.ORDER)}eql(t,n){return t===n}sqr(t){return G(
170
- t*t,this.ORDER)}add(t,n){return G(t+n,this.ORDER)}sub(t,n){return G(t-n,this.ORDER)}mul(t,n){return G(t*n,this.ORDER)}pow(t,n){return xc(this,t,n)}div(t,n){return G(t*ms(n,this.ORDER),this.ORDER)}sqrN(t){
171
- return t*t}addN(t,n){return t+n}subN(t,n){return t-n}mulN(t,n){return t*n}inv(t){return ms(t,this.ORDER)}sqrt(t){let n=gs.get(this);return n||gs.set(this,n=yc(this.ORDER)),n(this,t)}toBytes(t){return this.
172
- isLE?ds(t,this.BYTES):Ir(t,this.BYTES)}fromBytes(t,n=false){Z(t);let{_lengths:r,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(r){if(t.length<1||!r.includes(t.length)||t.length>o)throw new Error("Field.fromBytes\
173
- : expected "+r+" bytes, got "+t.length);let c=new Uint8Array(o);c.set(t,s?0:c.length-t.length),t=c;}if(t.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);let u=s?Oe(t):
174
- Rr(t);if(a&&(u=G(u,i)),!n&&!this.isValid(u))throw new Error("invalid field element: outside of range 0..ORDER");return u}invertBatch(t){return Rn(this,t)}cmov(t,n,r){return mt(r,"condition"),r?n:t}};Object.
175
- freeze(Tn.prototype);function In(e,t={}){return new Tn(e,t)}var An=BigInt(0),Nr=BigInt(1);function _s(e,t){let n=t.negate();return e?n:t}function Dn(e,t){let n=Rn(e.Fp,t.map(r=>r.Z));return t.map((r,o)=>e.fromAffine(r.toAffine(n[o])))}function As(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)
176
- throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Or(e,t){As(e,t);let n=Math.ceil(t/e)+1,r=2**(e-1),o=2**e,s=fs(e),i=BigInt(e);return {windows:n,windowSize:r,mask:s,maxNumber:o,
177
- shiftBy:i}}function Ts(e,t,n){let{windowSize:r,mask:o,maxNumber:s,shiftBy:i}=n,a=Number(e&o),u=e>>i;a>r&&(a-=s,u+=Nr);let c=t*r,d=c+Math.abs(a)-1,l=a===0,p=a<0,f=t%2!==0;return {nextN:u,offset:d,isZero:l,
178
- isNeg:p,isNegF:f,offsetF:c}}var Lr=new WeakMap,Cs=new WeakMap;function Mr(e){return Cs.get(e)||1}function Rs(e){if(e!==An)throw new Error("invalid wNAF")}var Cn=class{BASE;ZERO;Fn;bits;constructor(t,n){this.BASE=t.BASE,this.ZERO=
179
- t.ZERO,this.Fn=t.Fn,this.bits=n;}_unsafeLadder(t,n,r=this.ZERO){let o=t;for(;n>An;)n&Nr&&(r=r.add(o)),o=o.double(),n>>=Nr;return r}precomputeWindow(t,n){let{windows:r,windowSize:o}=Or(n,this.bits),s=[],
180
- i=t,a=i;for(let u=0;u<r;u++){a=i,s.push(a);for(let c=1;c<o;c++)a=a.add(i),s.push(a);i=a.double();}return s}wNAF(t,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,
181
- i=Or(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:u,offset:c,isZero:d,isNeg:l,isNegF:p,offsetF:f}=Ts(r,a,i);r=u,d?s=s.add(_s(p,n[f])):o=o.add(_s(l,n[c]));}return Rs(r),{p:o,f:s}}wNAFUnsafe(t,n,r,o=this.
182
- ZERO){let s=Or(t,this.bits);for(let i=0;i<s.windows&&r!==An;i++){let{nextN:a,offset:u,isZero:c,isNeg:d}=Ts(r,i,s);if(r=a,!c){let l=n[u];o=o.add(d?l.negate():l);}}return Rs(r),o}getPrecomputes(t,n,r){let o=Lr.
183
- get(n);return o||(o=this.precomputeWindow(n,t),t!==1&&(typeof r=="function"&&(o=r(o)),Lr.set(n,o))),o}cached(t,n,r){let o=Mr(t);return this.wNAF(o,this.getPrecomputes(o,t,r),n)}unsafe(t,n,r,o){let s=Mr(
184
- t);return s===1?this._unsafeLadder(t,n,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,r),n,o)}createCache(t,n){As(n,this.bits),Cs.set(t,n),Lr.delete(t);}hasCache(t){return Mr(t)!==1}};function Is(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Es(t),t}else return In(e,{isLE:n})}function Ds(e,t,n={},r){if(r===void 0&&(r=e==="edwar\
185
- ds"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(let u of ["p","n","h"]){let c=t[u];if(!(typeof c=="bigint"&&c>An))throw new Error(`CURVE.${u} must be positive bigint`)}
186
- let o=Is(t.p,n.Fp,r),s=Is(t.n,n.Fn,r),a=["Gx","Gy","a","d"];for(let u of a)if(!o.isValid(t[u]))throw new Error(`CURVE.${u} must be valid field element of CURVE.Fp`);return t=Object.
187
- freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:s}}function Ps(e,t){return function(r){let o=e(r);return {secretKey:o,publicKey:t(o)}}}var Ve=BigInt(0),ee=BigInt(1),$r=BigInt(2),Sc=BigInt(8);function Ec(e,t,n,r){let o=e.sqr(n),s=e.sqr(r),i=e.add(e.mul(t.a,o),s),a=e.add(e.ONE,e.mul(t.d,e.mul(o,s)));return e.eql(i,a)}function Os(e,t={}){
188
- let n=t,r=Ds("edwards",e,n,n.FpFnLE),{Fp:o,Fn:s}=r,i=r.CURVE,{h:a}=i;et(n,{},{uvRatio:"function"});let u=$r<<BigInt(s.BYTES*8)-ee,c=y=>o.create(y),d=n.uvRatio===void 0?(y,h)=>{try{return {isValid:!0,value:o.
189
- sqrt(o.div(y,h))}}catch{return {isValid:false,value:Ve}}}:n.uvRatio;if(!Ec(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function l(y,h,b=false){let w=b?ee:Ve;return Ar("coordinate "+y,
190
- h,w,u),h}function p(y){if(!(y instanceof f))throw new Error("EdwardsPoint expected")}class f{static BASE=new f(i.Gx,i.Gy,ee,c(i.Gx*i.Gy));static ZERO=new f(Ve,ee,ee,Ve);static Fp=o;static Fn=s;X;Y;Z;T;constructor(h,b,w,_){
191
- this.X=l("x",h),this.Y=l("y",b),this.Z=l("z",w,true),this.T=l("t",_),Object.freeze(this);}static CURVE(){return i}static fromAffine(h){if(h instanceof f)throw new Error("extended point not allowed");let{
192
- x:b,y:w}=h||{};return l("x",b),l("y",w),new f(b,w,ee,c(b*w))}static fromBytes(h,b=false){let w=o.BYTES,{a:_,d:v}=i;h=Vt(Z(h,w,"point")),mt(b,"zip215");let I=Vt(h),A=h[w-1];I[w-1]=A&-129;let C=Oe(I),P=b?u:
193
- o.ORDER;Ar("point.y",C,Ve,P);let M=c(C*C),q=c(M-ee),J=c(v*M-_),{isValid:S,value:T}=d(q,J);if(!S)throw new Error("bad point: invalid y coordinate");let O=(T&ee)===ee,L=(A&128)!==0;if(!b&&T===Ve&&L)throw new Error(
194
- "bad point: x=0 and x_0=1");return L!==O&&(T=c(-T)),f.fromAffine({x:T,y:C})}static fromHex(h,b=false){return f.fromBytes(cs(h),b)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(h=8,b=true){
195
- return g.createCache(this,h),b||this.multiply($r),this}assertValidity(){let h=this,{a:b,d:w}=i;if(h.is0())throw new Error("bad point: ZERO");let{X:_,Y:v,Z:I,T:A}=h,C=c(_*_),P=c(v*v),M=c(I*I),q=c(M*M),
196
- J=c(C*b),S=c(M*c(J+P)),T=c(q+c(w*c(C*P)));if(S!==T)throw new Error("bad point: equation left != right (1)");let O=c(_*v),L=c(I*A);if(O!==L)throw new Error("bad point: equation left != right (2)")}equals(h){
197
- p(h);let{X:b,Y:w,Z:_}=this,{X:v,Y:I,Z:A}=h,C=c(b*A),P=c(v*_),M=c(w*A),q=c(I*_);return C===P&&M===q}is0(){return this.equals(f.ZERO)}negate(){return new f(c(-this.X),this.Y,this.Z,c(-this.T))}double(){
198
- let{a:h}=i,{X:b,Y:w,Z:_}=this,v=c(b*b),I=c(w*w),A=c($r*c(_*_)),C=c(h*v),P=b+w,M=c(c(P*P)-v-I),q=C+I,J=q-A,S=C-I,T=c(M*J),O=c(q*S),L=c(M*S),Y=c(J*q);return new f(T,O,Y,L)}add(h){p(h);let{a:b,d:w}=i,{X:_,
199
- Y:v,Z:I,T:A}=this,{X:C,Y:P,Z:M,T:q}=h,J=c(_*C),S=c(v*P),T=c(A*w*q),O=c(I*M),L=c((_+v)*(C+P)-J-S),Y=O-T,H=O+T,le=c(S-b*J),Ie=c(L*Y),m=c(H*le),x=c(L*le),j=c(Y*H);return new f(Ie,m,j,x)}subtract(h){return p(
200
- h),this.add(h.negate())}multiply(h){if(!s.isValidNot0(h))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:b,f:w}=g.cached(this,h,_=>Dn(f,_));return Dn(f,[b,w])[0]}multiplyUnsafe(h){
201
- if(!s.isValid(h))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return h===Ve?f.ZERO:this.is0()||h===ee?this:g.unsafe(this,h,b=>Dn(f,b))}isSmallOrder(){return this.clearCofactor().
202
- is0()}isTorsionFree(){return g.unsafe(this,i.n).is0()}toAffine(h){let b=this,w=h,{X:_,Y:v,Z:I}=b,A=b.is0();w==null&&(w=A?Sc:o.inv(I));let C=c(_*w),P=c(v*w),M=o.mul(I,w);if(A)return {x:Ve,y:ee};if(M!==ee)
203
- throw new Error("invZ was invalid");return {x:C,y:P}}clearCofactor(){return a===ee?this:this.multiplyUnsafe(a)}toBytes(){let{x:h,y:b}=this.toAffine(),w=o.toBytes(b);return w[w.length-1]|=h&ee?128:0,w}toHex(){
204
- return Tr(this.toBytes())}toString(){return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let g=new Cn(f,s.BITS);return s.BITS>=8&&f.BASE.precompute(8),Object.freeze(f.prototype),Object.freeze(f),f}var Pn=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(t){
205
- this.ep=t;}static fromBytes(t){Dr();}static fromHex(t){Dr();}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity();}toAffine(t){
206
- return this.ep.toAffine(t)}toHex(){return Tr(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){
171
+ freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:i}=Wl(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 K(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&te)===te}neg(t){return K(-t,this.ORDER)}eql(t,n){return t===n}sqr(t){return K(
174
+ t*t,this.ORDER)}add(t,n){return K(t+n,this.ORDER)}sub(t,n){return K(t-n,this.ORDER)}mul(t,n){return K(t*n,this.ORDER)}pow(t,n){return Hl(this,t,n)}div(t,n){return K(t*Qi(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 Qi(t,this.ORDER)}sqrt(t){let n=ts.get(this);return n||ts.set(this,n=zl(this.ORDER)),n(this,t)}toBytes(t){return this.
176
+ isLE?Yi(t,this.BYTES):Qr(t,this.BYTES)}fromBytes(t,n=false){Z(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?Fe(t):
178
+ Xr(t);if(a&&(c=K(c,s)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return Wn(this,t)}cmov(t,n,r){return Tt(r,"condition"),r?n:t}};Object.
179
+ freeze(Hn.prototype);function Kn(e,t={}){return new Hn(e,t)}var Gn=BigInt(0),ao=BigInt(1);function us(e,t){let n=t.negate();return e?n:t}function Yn(e,t){let n=Wn(e.Fp,t.map(r=>r.Z));return t.map((r,o)=>e.fromAffine(r.toAffine(n[o])))}function ms(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)
180
+ throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function oo(e,t){ms(e,t);let n=Math.ceil(t/e)+1,r=2**(e-1),o=2**e,i=Xi(e),s=BigInt(e);return {windows:n,windowSize:r,mask:i,maxNumber:o,
181
+ shiftBy:s}}function ds(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+=ao);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 io=new WeakMap,hs=new WeakMap;function so(e){return hs.get(e)||1}function ps(e){if(e!==Gn)throw new Error("invalid wNAF")}var Jn=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>Gn;)n&ao&&(r=r.add(o)),o=o.double(),n>>=ao;return r}precomputeWindow(t,n){let{windows:r,windowSize:o}=oo(n,this.bits),i=[],
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=oo(t,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:l,isZero:d,isNeg:u,isNegF:p,offsetF:f}=ds(r,a,s);r=c,d?i=i.add(us(p,n[f])):o=o.add(us(u,n[l]));}return ps(r),{p:o,f:i}}wNAFUnsafe(t,n,r,o=this.
186
+ ZERO){let i=oo(t,this.bits);for(let s=0;s<i.windows&&r!==Gn;s++){let{nextN:a,offset:c,isZero:l,isNeg:d}=ds(r,s,i);if(r=a,!l){let u=n[c];o=o.add(d?u.negate():u);}}return ps(r),o}getPrecomputes(t,n,r){let o=io.
187
+ get(n);return o||(o=this.precomputeWindow(n,t),t!==1&&(typeof r=="function"&&(o=r(o)),io.set(n,o))),o}cached(t,n,r){let o=so(t);return this.wNAF(o,this.getPrecomputes(o,t,r),n)}unsafe(t,n,r,o){let i=so(
188
+ t);return i===1?this._unsafeLadder(t,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,t,r),n,o)}createCache(t,n){ms(n,this.bits),hs.set(t,n),io.delete(t);}hasCache(t){return so(t)!==1}};function fs(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return ls(t),t}else return Kn(e,{isLE:n})}function gs(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>Gn))throw new Error(`CURVE.${c} must be positive bigint`)}
190
+ let o=fs(t.p,n.Fp,r),i=fs(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 bs(e,t){return function(r){let o=e(r);return {secretKey:o,publicKey:t(o)}}}var Ye=BigInt(0),ne=BigInt(1),co=BigInt(2),Kl=BigInt(8);function Gl(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 vs(e,t={}){
192
+ let n=t,r=gs("edwards",e,n,n.FpFnLE),{Fp:o,Fn:i}=r,s=r.CURVE,{h:a}=s;ct(n,{},{uvRatio:"function"});let c=co<<BigInt(i.BYTES*8)-ne,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:Ye}}}:n.uvRatio;if(!Gl(o,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function u(b,h,y=false){let k=y?ne:Ye;return eo("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,ne,l(s.Gx*s.Gy));static ZERO=new f(Ye,ne,ne,Ye);static Fp=o;static Fn=i;X;Y;Z;T;constructor(h,y,k,x){
195
+ this.X=u("x",h),this.Y=u("y",y),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:y,y:k}=h||{};return u("x",y),u("y",k),new f(y,k,ne,l(y*k))}static fromBytes(h,y=false){let k=o.BYTES,{a:x,d:v}=s;h=tn(Z(h,k,"point")),Tt(y,"zip215");let A=tn(h),R=h[k-1];A[k-1]=R&-129;let I=Fe(A),D=y?c:
197
+ o.ORDER;eo("point.y",I,Ye,D);let N=l(I*I),z=l(N-ne),G=l(v*N-x),{isValid:S,value:C}=d(z,G);if(!S)throw new Error("bad point: invalid y coordinate");let O=(C&ne)===ne,$=(R&128)!==0;if(!y&&C===Ye&&$)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,y=false){return f.fromBytes(Ki(h),y)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(h=8,y=true){
199
+ return g.createCache(this,h),y||this.multiply(co),this}assertValidity(){let h=this,{a:y,d:k}=s;if(h.is0())throw new Error("bad point: ZERO");let{X:x,Y:v,Z:A,T:R}=h,I=l(x*x),D=l(v*v),N=l(A*A),z=l(N*N),
200
+ G=l(I*y),S=l(N*l(G+D)),C=l(z+l(k*l(I*D)));if(S!==C)throw new Error("bad point: equation left != right (1)");let O=l(x*v),$=l(A*R);if(O!==$)throw new Error("bad point: equation left != right (2)")}equals(h){
201
+ p(h);let{X:y,Y:k,Z:x}=this,{X:v,Y:A,Z:R}=h,I=l(y*R),D=l(v*x),N=l(k*R),z=l(A*x);return I===D&&N===z}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:y,Y:k,Z:x}=this,v=l(y*y),A=l(k*k),R=l(co*l(x*x)),I=l(h*v),D=y+k,N=l(l(D*D)-v-A),z=I+A,G=z-R,S=I-A,C=l(N*G),O=l(z*S),$=l(N*S),X=l(G*z);return new f(C,O,X,$)}add(h){p(h);let{a:y,d:k}=s,{X:x,
203
+ Y:v,Z:A,T:R}=this,{X:I,Y:D,Z:N,T:z}=h,G=l(x*I),S=l(v*D),C=l(R*k*z),O=l(A*N),$=l((x+v)*(I+D)-G-S),X=O-C,J=O+C,ve=l(S-y*G),ye=l($*X),$e=l(J*ve),Ke=l($*ve),m=l(X*J);return new f(ye,$e,m,Ke)}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:y,f:k}=g.cached(this,h,x=>Yn(f,x));return Yn(f,[y,k])[0]}multiplyUnsafe(h){
205
+ if(!i.isValid(h))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return h===Ye?f.ZERO:this.is0()||h===ne?this:g.unsafe(this,h,y=>Yn(f,y))}isSmallOrder(){return this.clearCofactor().
206
+ is0()}isTorsionFree(){return g.unsafe(this,s.n).is0()}toAffine(h){let y=this,k=h,{X:x,Y:v,Z:A}=y,R=y.is0();k==null&&(k=R?Kl:o.inv(A));let I=l(x*k),D=l(v*k),N=o.mul(A,k);if(R)return {x:Ye,y:ne};if(N!==ne)
207
+ throw new Error("invZ was invalid");return {x:I,y:D}}clearCofactor(){return a===ne?this:this.multiplyUnsafe(a)}toBytes(){let{x:h,y}=this.toAffine(),k=o.toBytes(y);return k[k.length-1]|=h&ne?128:0,k}toHex(){
208
+ return Zr(this.toBytes())}toString(){return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let g=new Jn(f,i.BITS);return i.BITS>=8&&f.BASE.precompute(8),Object.freeze(f.prototype),Object.freeze(f),f}var Zn=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(t){
209
+ this.ep=t;}static fromBytes(t){no();}static fromHex(t){no();}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 Zr(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){
207
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.
208
- ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,n){return this.ep.precompute(t,n),this}};function Ls(e,t,n={}){if(typeof t!="function")throw new Error('"hash" function param is r\
209
- equired');let r=t,o=n;et(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:u}=e,c=r.
210
- outputLen,d=2*a.BYTES;if(c!==void 0&&(Pe(c,"hash.outputLen"),c!==d))throw new Error(`hash.outputLen must be ${d}, got ${c}`);let l=o.randomBytes===void 0?us:o.randomBytes,p=o.adjustScalarBytes===void 0?
211
- S=>S:o.adjustScalarBytes,f=o.domain===void 0?(S,T,O)=>{if(mt(O,"phflag"),T.length||O)throw new Error("Contexts/pre-hash are not supported");return S}:o.domain;function g(S){return u.create(Oe(S))}function y(S){
212
- let T=C.secretKey;Z(S,C.secretKey,"secretKey");let O=Z(r(S),2*T,"hashedSecretKey"),L=p(O.slice(0,T)),Y=O.slice(T,2*T),H=g(L);return {head:L,prefix:Y,scalar:H}}function h(S){let{head:T,prefix:O,scalar:L}=y(
213
- S),Y=i.multiply(L),H=Y.toBytes();return {head:T,prefix:O,scalar:L,point:Y,pointBytes:H}}function b(S){return h(S).pointBytes}function w(S=Uint8Array.of(),...T){let O=Ee(...T);return g(r(f(O,Z(S,void 0,
214
- "context"),!!s)))}function _(S,T,O={}){S=Z(S,void 0,"message"),s&&(S=s(S));let{prefix:L,scalar:Y,pointBytes:H}=h(T),le=w(O.context,L,S),Ie=i.multiply(le).toBytes(),m=w(O.context,Ie,H,S),x=u.create(le+
215
- m*Y);if(!u.isValid(x))throw new Error("sign failed: invalid s");let j=Ee(Ie,u.toBytes(x));return Z(j,C.signature,"result")}let v={zip215:o.zip215};function I(S,T,O,L=v){let{context:Y}=L,H=L.zip215===void 0?
216
- !!v.zip215:L.zip215,le=C.signature;S=Z(S,le,"signature"),T=Z(T,void 0,"message"),O=Z(O,C.publicKey,"publicKey"),H!==void 0&&mt(H,"zip215"),s&&(T=s(T));let Ie=le/2,m=S.subarray(0,Ie),x=Oe(S.subarray(Ie,
217
- le)),j,N,U;try{j=e.fromBytes(O,H),N=e.fromBytes(m,H),U=i.multiplyUnsafe(x);}catch{return false}if(!H&&j.isSmallOrder())return false;let B=w(Y,m,O,T);return N.add(j.multiplyUnsafe(B)).subtract(U).clearCofactor().
218
- is0()}let A=a.BYTES,C={secretKey:A,publicKey:A,signature:2*A,seed:A};function P(S){return S=S===void 0?l(C.seed):S,Z(S,C.seed,"seed")}function M(S){return En(S)&&S.length===C.secretKey}function q(S,T){
219
- try{return !!e.fromBytes(S,T===void 0?v.zip215:T)}catch{return false}}let J={getExtendedPublicKey:h,randomSecretKey:P,isValidSecretKey:M,isValidPublicKey:q,toMontgomery(S){let{y:T}=e.fromBytes(S),O=C.publicKey,
220
- L=O===32;if(!L&&O!==57)throw new Error("only defined for 25519 and 448");let Y=L?a.div(ee+T,ee-T):a.div(T-ee,T+ee);return a.toBytes(Y)},toMontgomerySecret(S){let T=C.secretKey;Z(S,T);let O=r(S.subarray(
221
- 0,T));return p(O).subarray(0,T)}};return Object.freeze(C),Object.freeze(J),Object.freeze({keygen:Ps(P,b),getPublicKey:b,sign:_,verify:I,utils:J,Point:e,lengths:C})}var Rc=BigInt(0),Me=BigInt(1),Ns=BigInt(2);var Ic=BigInt(5),Ac=BigInt(8),ht=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Vr={p:ht,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Ac,
212
+ ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,n){return this.ep.precompute(t,n),this}};function ys(e,t,n={}){if(typeof t!="function")throw new Error('"hash" function param is r\
213
+ equired');let r=t,o=n;ct(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&&(Ve(l,"hash.outputLen"),l!==d))throw new Error(`hash.outputLen must be ${d}, got ${l}`);let u=o.randomBytes===void 0?Gi:o.randomBytes,p=o.adjustScalarBytes===void 0?
215
+ S=>S:o.adjustScalarBytes,f=o.domain===void 0?(S,C,O)=>{if(Tt(O,"phflag"),C.length||O)throw new Error("Contexts/pre-hash are not supported");return S}:o.domain;function g(S){return c.create(Fe(S))}function b(S){
216
+ let C=I.secretKey;Z(S,I.secretKey,"secretKey");let O=Z(r(S),2*C,"hashedSecretKey"),$=p(O.slice(0,C)),X=O.slice(C,2*C),J=g($);return {head:$,prefix:X,scalar:J}}function h(S){let{head:C,prefix:O,scalar:$}=b(
217
+ S),X=s.multiply($),J=X.toBytes();return {head:C,prefix:O,scalar:$,point:X,pointBytes:J}}function y(S){return h(S).pointBytes}function k(S=Uint8Array.of(),...C){let O=Pe(...C);return g(r(f(O,Z(S,void 0,
218
+ "context"),!!i)))}function x(S,C,O={}){S=Z(S,void 0,"message"),i&&(S=i(S));let{prefix:$,scalar:X,pointBytes:J}=h(C),ve=k(O.context,$,S),ye=s.multiply(ve).toBytes(),$e=k(O.context,ye,J,S),Ke=c.create(ve+
219
+ $e*X);if(!c.isValid(Ke))throw new Error("sign failed: invalid s");let m=Pe(ye,c.toBytes(Ke));return Z(m,I.signature,"result")}let v={zip215:o.zip215};function A(S,C,O,$=v){let{context:X}=$,J=$.zip215===
220
+ void 0?!!v.zip215:$.zip215,ve=I.signature;S=Z(S,ve,"signature"),C=Z(C,void 0,"message"),O=Z(O,I.publicKey,"publicKey"),J!==void 0&&Tt(J,"zip215"),i&&(C=i(C));let ye=ve/2,$e=S.subarray(0,ye),Ke=Fe(S.subarray(
221
+ ye,ve)),m,E,L;try{m=e.fromBytes(O,J),E=e.fromBytes($e,J),L=s.multiplyUnsafe(Ke);}catch{return false}if(!J&&m.isSmallOrder())return false;let B=k(X,$e,O,C);return E.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(S){return S=S===void 0?u(I.seed):S,Z(S,I.seed,"seed")}function N(S){return zn(S)&&S.length===I.secretKey}function z(S,C){
223
+ try{return !!e.fromBytes(S,C===void 0?v.zip215:C)}catch{return false}}let G={getExtendedPublicKey:h,randomSecretKey:D,isValidSecretKey:N,isValidPublicKey:z,toMontgomery(S){let{y:C}=e.fromBytes(S),O=I.publicKey,
224
+ $=O===32;if(!$&&O!==57)throw new Error("only defined for 25519 and 448");let X=$?a.div(ne+C,ne-C):a.div(C-ne,C+ne);return a.toBytes(X)},toMontgomerySecret(S){let C=I.secretKey;Z(S,C);let O=r(S.subarray(
225
+ 0,C));return p(O).subarray(0,C)}};return Object.freeze(I),Object.freeze(G),Object.freeze({keygen:bs(D,y),getPublicKey:y,sign:x,verify:A,utils:G,Point:e,lengths:I})}var Zl=BigInt(0),qe=BigInt(1),xs=BigInt(2);var Xl=BigInt(5),Ql=BigInt(8),Ct=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),mo={p:Ct,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Ql,
222
226
  a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6d\
223
- c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Cc(e){let t=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),s=ht,a=e*e%
224
- s*e%s,u=ye(a,Ns,s)*a%s,c=ye(u,Me,s)*e%s,d=ye(c,Ic,s)*c%s,l=ye(d,t,s)*d%s,p=ye(l,n,s)*l%s,f=ye(p,r,s)*p%s,g=ye(f,o,s)*f%s,y=ye(g,o,s)*f%s,h=ye(y,t,s)*d%s;return {pow_p_5_8:ye(h,Ns,s)*e%s,b2:a}}function Dc(e){
225
- return e[0]&=248,e[31]&=127,e[31]|=64,e}var Br=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function zr(e,t){let n=ht,r=G(t*t*t,n),o=G(r*r*t,n),s=Cc(e*o).pow_p_5_8,
226
- i=G(e*r*s,n),a=G(t*i*i,n),u=i,c=G(i*Br,n),d=a===e,l=a===G(-e,n),p=a===G(-e*Br,n);return d&&(i=u),(l||p)&&(i=c),Le(i,n)&&(i=G(-i,n)),{isValid:d||l,value:i}}var qe=Os(Vr,{uvRatio:zr}),ze=qe.Fp,Bs=qe.Fn;function Pc(e){return Ls(qe,xn,Object.assign({adjustScalarBytes:Dc,zip215:true},e))}var Us=Pc({});var Ur=Br;BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");var Lc=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt(
227
- "1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var $s=e=>zr(Me,e),$c=BigInt("0x7\
228
- fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Fr=e=>ze.create(Oe(e)&$c);var He=class e extends Pn{static BASE=new e(
229
- qe.BASE);static ZERO=new e(qe.ZERO);static Fp=ze;static Fn=Bs;constructor(t){super(t);}static fromAffine(t){return new e(qe.fromAffine(t))}assertSame(t){if(!(t instanceof e))throw new Error("RistrettoP\
230
- oint expected")}init(t){return new e(t)}static fromBytes(t){ve(t,32);let{a:n,d:r}=Vr,o=ht,s=v=>ze.create(v),i=Fr(t);if(!ps(ze.toBytes(i),t)||Le(i,o))throw new Error("invalid ristretto255 encoding 1");
231
- let a=s(i*i),u=s(Me+n*a),c=s(Me-n*a),d=s(u*u),l=s(c*c),p=s(n*r*d-l),{isValid:f,value:g}=$s(s(p*l)),y=s(g*c),h=s(g*y*p),b=s((i+i)*y);Le(b,o)&&(b=s(-b));let w=s(u*h),_=s(b*w);if(!f||Le(_,o)||w===Rc)throw new Error(
232
- "invalid ristretto255 encoding 2");return new e(new qe(b,w,Me,_))}static fromHex(t){return e.fromBytes(Bt(t))}toBytes(){let{X:t,Y:n,Z:r,T:o}=this.ep,s=ht,i=h=>ze.create(h),a=i(i(r+n)*i(r-n)),u=i(t*n),
233
- c=i(u*u),{value:d}=$s(i(a*c)),l=i(d*a),p=i(d*u),f=i(l*p*o),g;if(Le(o*f,s)){let h=i(n*Ur),b=i(t*Ur);t=h,n=b,g=i(l*Lc);}else g=p;Le(t*f,s)&&(n=i(-n));let y=i((r-n)*g);return Le(y,s)&&(y=i(-y)),ze.toBytes(
234
- y)}equals(t){this.assertSame(t);let{X:n,Y:r}=this.ep,{X:o,Y:s}=t.ep,i=c=>ze.create(c),a=i(n*s)===i(r*o),u=i(r*s)===i(n*o);return a||u}is0(){return this.equals(e.ZERO)}};Object.freeze(He.BASE);Object.freeze(
235
- He.ZERO);Object.freeze(He.prototype);Object.freeze(He);var nt=`-----BEGIN PUBLIC KEY-----
227
+ c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function eu(e){let t=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),i=Ct,a=e*e%
228
+ i*e%i,c=Ae(a,xs,i)*a%i,l=Ae(c,qe,i)*e%i,d=Ae(l,Xl,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,xs,i)*e%i,b2:a}}function tu(e){
229
+ return e[0]&=248,e[31]&=127,e[31]|=64,e}var uo=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function ho(e,t){let n=Ct,r=K(t*t*t,n),o=K(r*r*t,n),i=eu(e*o).pow_p_5_8,
230
+ s=K(e*r*i,n),a=K(t*s*s,n),c=s,l=K(s*uo,n),d=a===e,u=a===K(-e,n),p=a===K(-e*uo,n);return d&&(s=c),(u||p)&&(s=l),ze(s,n)&&(s=K(-s,n)),{isValid:d||u,value:s}}var Xe=vs(mo,{uvRatio:ho}),Ze=Xe.Fp,Es=Xe.Fn;function nu(e){return ys(Xe,Un,Object.assign({adjustScalarBytes:tu,zip215:true},e))}var _s=nu({});var po=uo;BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");var ou=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt(
231
+ "1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var ws=e=>ho(qe,e),au=BigInt("0x7\
232
+ fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),fo=e=>Ze.create(Fe(e)&au);var Qe=class e extends Zn{static BASE=new e(
233
+ Xe.BASE);static ZERO=new e(Xe.ZERO);static Fp=Ze;static Fn=Es;constructor(t){super(t);}static fromAffine(t){return new e(Xe.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}=mo,o=Ct,i=v=>Ze.create(v),s=fo(t);if(!Zi(Ze.toBytes(s),t)||ze(s,o))throw new Error("invalid ristretto255 encoding 1");
235
+ let a=i(s*s),c=i(qe+n*a),l=i(qe-n*a),d=i(c*c),u=i(l*l),p=i(n*r*d-u),{isValid:f,value:g}=ws(i(p*u)),b=i(g*l),h=i(g*b*p),y=i((s+s)*b);ze(y,o)&&(y=i(-y));let k=i(c*h),x=i(y*k);if(!f||ze(x,o)||k===Zl)throw new Error(
236
+ "invalid ristretto255 encoding 2");return new e(new Xe(y,k,qe,x))}static fromHex(t){return e.fromBytes(Xt(t))}toBytes(){let{X:t,Y:n,Z:r,T:o}=this.ep,i=Ct,s=h=>Ze.create(h),a=s(s(r+n)*s(r-n)),c=s(t*n),
237
+ l=s(c*c),{value:d}=ws(s(a*l)),u=s(d*a),p=s(d*c),f=s(u*p*o),g;if(ze(o*f,i)){let h=s(n*po),y=s(t*po);t=h,n=y,g=s(u*ou);}else g=p;ze(t*f,i)&&(n=s(-n));let b=s((r-n)*g);return ze(b,i)&&(b=s(-b)),Ze.toBytes(
238
+ b)}equals(t){this.assertSame(t);let{X:n,Y:r}=this.ep,{X:o,Y:i}=t.ep,s=l=>Ze.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(Qe.BASE);Object.freeze(
239
+ Qe.ZERO);Object.freeze(Qe.prototype);Object.freeze(Qe);var ut=`-----BEGIN PUBLIC KEY-----
236
240
  MCowBQYDK2VwAyEAWBiklf0kmDIVmM7nMiCxwiEAkwQIiqWGuRiRDJonsFY=
237
- -----END PUBLIC KEY-----`;function Fs(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 qr(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.
238
- length%4?"=".repeat(4-t.length%4):"";return Fs(t+n)}function Bc(e){let t=e.replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=Fs(t);return n.subarray(n.length-32)}var Uc=new TextEncoder,Vs=new TextDecoder;
239
- function Hr(e){return typeof e=="object"&&e!==null&&"keys"in e}function gt(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 Fc=/^[A-Za-z0-9_-]+$/;
240
- function zs(e){let t=e.split(".");return t.length===3&&t.every(n=>Fc.test(n))}function qt(e){return e===""?"empty":zs(e)?"token":"malformed"}function Ht(e,t){if(!zs(e))return {ok:false,reason:"malformed t\
241
- oken"};let n=e.split("."),r=n[0],o=n[1],s=n[2],i;try{i=JSON.parse(Vs.decode(qr(r)));}catch{return {ok:false,reason:"header is not valid JSON"}}let a;if(Hr(t)){let d=typeof i.kid=="string"?i.kid:t.defaultKid,
242
- l=t.keys[d];if(!l)return {ok:false,reason:`unknown key id "${d}"`};a=l;}else {if(!t)return {ok:false,reason:"no verification key"};a=t;}let u;try{if(u=Bc(a),u.length!==32)return {ok:!1,reason:"invalid public key"}}catch{
243
- return {ok:false,reason:"invalid public key"}}let c=false;try{c=Us.verify(qr(s),Uc.encode(`${r}.${o}`),u);}catch{return {ok:false,reason:"signature verification error"}}return c?{ok:true,header:i,payloadBytes:qr(o)}:
244
- {ok:false,reason:"bad signature"}}function Wr(e,t){let n=Ht(e,t);if(!n.ok||!n.payloadBytes)return {signatureValid:false,...n.reason?{reason:n.reason}:{}};try{return {signatureValid:!0,payload:JSON.parse(Vs.decode(
245
- n.payloadBytes))}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function On(e,t,n){if(n?.has(e.jti))return "revoked";let r=e.expires_at+e.grace_days*86400;return t<=e.expires_at?"\
246
- active":t<=r?"grace":"expired"}var qs="BVSALA-REVOC",Vc=300,zc=new TextDecoder;function Hs(e,t,n={}){let r=c=>({ok:false,seq:-1,asOf:0,revoked:new Set,reason:c}),o=Ht(e,t);if(!o.ok||!o.payloadBytes)return r(o.reason??"bad signature");
247
- if(o.header?.typ!==qs)return r(`unexpected token type "${String(o.header?.typ??"")}" (want ${qs})`);let s;try{s=JSON.parse(zc.decode(o.payloadBytes));}catch{return r("payload is not valid JSON")}if(typeof s.
248
- seq!="number"||typeof s.asOf!="number"||!Array.isArray(s.revoked))return r("malformed revocation payload");let i=n.minSeq??0;if(s.seq<i)return r(`stale/rolled-back list (seq ${s.seq} < ${i})`);let a=n.
249
- nowSeconds??Math.floor(Date.now()/1e3),u=n.maxSkewSeconds??Vc;return s.asOf>a+u?r(`asOf too far in the future (${s.asOf} > ${a+u})`):{ok:true,seq:s.seq,asOf:s.asOf,revoked:new Set(s.revoked)}}var bt=class{_seq=-1;_asOf=0;_lastContactAt=0;set=new Set;get seq(){
241
+ -----END PUBLIC KEY-----`;function Ts(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 go(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.
242
+ length%4?"=".repeat(4-t.length%4):"";return Ts(t+n)}function lu(e){let t=e.replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=Ts(t);return n.subarray(n.length-32)}var uu=new TextEncoder,Cs=new TextDecoder;
243
+ function bo(e){return typeof e=="object"&&e!==null&&"keys"in e}function At(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 du=/^[A-Za-z0-9_-]+$/;
244
+ function As(e){let t=e.split(".");return t.length===3&&t.every(n=>du.test(n))}function rn(e){return e===""?"empty":As(e)?"token":"malformed"}function on(e,t){if(!As(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(Cs.decode(go(r)));}catch{return {ok:false,reason:"header is not valid JSON"}}let a;if(bo(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=lu(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=_s.verify(go(i),uu.encode(`${r}.${o}`),c);}catch{return {ok:false,reason:"signature verification error"}}return l?{ok:true,header:s,payloadBytes:go(o)}:
248
+ {ok:false,reason:"bad signature"}}function vo(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(Cs.decode(
249
+ n.payloadBytes))}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function Xn(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 Rs="BVSALA-REVOC",pu=300,fu=new TextDecoder;function Is(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!==Rs)return r(`unexpected token type "${String(o.header?.typ??"")}" (want ${Rs})`);let i;try{i=JSON.parse(fu.decode(o.payloadBytes));}catch{return r("payload is not valid JSON")}if(typeof i.
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??pu;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 Rt=class{_seq=-1;_asOf=0;_lastContactAt=0;set=new Set;get seq(){
250
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.
251
- set}apply(t){if(t.seq<this._seq)return false;let n=this.set.size;for(let s of t.revoked)this.set.add(s);let r=this.set.size>n,o=t.seq>this._seq;return t.seq>this._seq&&(this._seq=t.seq),t.asOf>this._asOf&&
252
- (this._asOf=t.asOf),r||o}};function Ln(e,t,n){let r=()=>Math.floor((n.now?n.now():Date.now())/1e3),o=n.startedAt??r(),s=gt(e),i=qt(s),a=i==="token"?Wr(s,t):{signatureValid:false,reason:i},u=a.signatureValid?a.payload:void 0,c=new Set(
253
- u?.features??[]),d=()=>{if(i==="empty")return "none";if(!u)return "invalid";let p=On(u,r(),n.revocation.snapshot());if(n.maxStalenessSeconds!=null&&(p==="active"||p==="grace")){let f=u.expires_at+u.grace_days*
254
- 86400,g=Math.min(o,f),y=Math.max(n.revocation.lastContactAt,g);if(r()-y>n.maxStalenessSeconds)return "stale"}return p},l=()=>{let p=d();return p==="active"||p==="grace"};return {isEntitled:p=>l()&&c.has(
255
- p),isActive:()=>l(),status:d,reason:()=>u?void 0:a.reason,refreshAfter:()=>{if(u)return Math.min(u.expires_at,r()+86400)}}}var vt={pollIntervalSeconds:900,floorSeconds:300,maxIntervalSeconds:3600,jitterRatio:.1,maxSkewSeconds:300,requestTimeoutMs:3e4},Ws=3,qc=12;function Hc(e){let t=e.random??Math.random,n;if(e.consecutiveFailures>
256
- 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,s=o<0?e.pollIntervalSeconds:
257
- o;n=Math.min(e.pollIntervalSeconds,Math.max(e.floorSeconds,s));}let r=1+(t()*2-1)*e.jitterRatio;return Math.max(e.floorSeconds,n*r)}var Wc=10,Wt=class{constructor(t){this.opts=t;}opts;timer=null;controller=null;consecutiveFailures=0;stopped=false;started=false;warnedNoFetch=false;lastEtag=null;consecutive304=0;now(){
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 Qn(e,t,n){let r=()=>Math.floor((n.now?n.now():Date.now())/1e3),o=n.startedAt??r(),i=At(e),s=rn(i),a=s==="token"?vo(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=Xn(c,r(),n.revocation.snapshot());if(n.maxStalenessSeconds!=null&&(p==="active"||p==="grace")){let f=c.expires_at+c.grace_days*
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 It={pollIntervalSeconds:900,floorSeconds:300,maxIntervalSeconds:3600,jitterRatio:.1,maxSkewSeconds:300,requestTimeoutMs:3e4},Ps=3,mu=12;function hu(e){let t=e.random??Math.random,n;if(e.consecutiveFailures>
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 gu=10,sn=class{constructor(t){this.opts=t;}opts;timer=null;controller=null;consecutiveFailures=0;stopped=false;started=false;warnedNoFetch=false;lastEtag=null;consecutive304=0;now(){
258
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();
259
263
  if(!t){this.warnedNoFetch||(this.warnedNoFetch=true,console.warn("[bv-sala] no global fetch available; revocation call-home disabled (offline). License expiry is still enforced from the token.")),this.opts.
260
- onEvent?.({type:"no-fetch"});return}let n=new AbortController;this.controller=n;let r=this.opts.requestTimeoutMs??vt.requestTimeoutMs,o=setTimeout(()=>n.abort(),r);o.unref?.();let s={accept:"applicati\
261
- on/json"};this.lastEtag&&(s["if-none-match"]=this.lastEtag);try{let i=await t(this.opts.url,{signal:n.signal,headers:s});if(i.status===304){this.consecutiveFailures=0,this.opts.snapshot.markContact(this.
262
- now()),this.opts.onEvent?.({type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=Wc&&(this.consecutive304=0,this.lastEtag=null);return}if(this.consecutive304=0,!i.
263
- ok)throw new Error(`revocations HTTP ${i.status}`);let a=i.headers.get("etag"),u=await i.json();if(!u.list)throw new Error("response missing `list`");this.consecutiveFailures=0;let c=Hs(u.list,this.opts.
264
- publicKeyPem,{minSeq:this.opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??vt.maxSkewSeconds});if(!c.ok){let l=c.reason??"rejected";this.opts.onEvent?.({type:"rejected",
265
- reason:l}),this.avisar(`rechazada:${l}`,`[bv-sala] the revocation list does NOT verify (${l}). The last known-good list is kept, so revocations ALREADY known still apply, but new ones are not arriving\
266
- . Check ${this.opts.url}.`);return}a&&(this.lastEtag=a),this.opts.snapshot.markContact(this.now());let d=this.opts.snapshot.apply(c);this.opts.onEvent?.(d?{type:"applied",seq:c.seq,size:this.opts.snapshot.
267
- snapshot().size}:{type:"unchanged",seq:c.seq});}catch(i){this.consecutiveFailures++,this.opts.onEvent?.({type:"error",error:i}),this.avisarFalloDeRed(i);}finally{clearTimeout(o),this.controller=null;}}callado(){
268
- return !!(this.opts.silenceWarnings??this.opts.silenciarAvisos)}avisar(t,n){this.callado()||z(`poller:${this.opts.url}:${t}`,n);}avisarFalloDeRed(t){if(this.callado())return;let n=this.consecutiveFailures;
269
- if(n<Ws||(n-Ws)%qc!==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\
264
+ onEvent?.({type:"no-fetch"});return}let n=new AbortController;this.controller=n;let r=this.opts.requestTimeoutMs??It.requestTimeoutMs,o=setTimeout(()=>n.abort(),r);o.unref?.();let i={accept:"applicati\
265
+ on/json"};this.lastEtag&&(i["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.
266
+ now()),this.opts.onEvent?.({type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=gu&&(this.consecutive304=0,this.lastEtag=null);return}if(this.consecutive304=0,!s.
267
+ ok)throw new Error(`revocations HTTP ${s.status}`);let a=s.headers.get("etag"),c=await s.json();if(!c.list)throw new Error("response missing `list`");this.consecutiveFailures=0;let l=Is(c.list,this.opts.
268
+ publicKeyPem,{minSeq:this.opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??It.maxSkewSeconds});if(!l.ok){let u=l.reason??"rejected";this.opts.onEvent?.({type:"rejected",
269
+ reason:u}),this.avisar(`rechazada:${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\
270
+ . Check ${this.opts.url}.`);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.
271
+ snapshot().size}:{type:"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(){
272
+ return !!(this.opts.silenceWarnings??this.opts.silenciarAvisos)}avisar(t,n){this.callado()||W(`poller:${this.opts.url}:${t}`,n);}avisarFalloDeRed(t){if(this.callado())return;let n=this.consecutiveFailures;
273
+ if(n<Ps||(n-Ps)%mu!==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\
270
274
  revocations still apply, but NEW ones are not arriving. Check egress to ${this.opts.url}.`);}start(){this.started||this.stopped||(this.started=true,this.pollOnce().finally(()=>this.schedule()));}schedule(){
271
- if(this.stopped)return;let t=Hc({refreshAfter:this.opts.getRefreshAfter?.(),nowSeconds:this.now(),consecutiveFailures:this.consecutiveFailures,floorSeconds:this.opts.floorSeconds??vt.floorSeconds,pollIntervalSeconds:this.
272
- opts.pollIntervalSeconds??vt.pollIntervalSeconds,maxIntervalSeconds:this.opts.maxIntervalSeconds??vt.maxIntervalSeconds,jitterRatio:this.opts.jitterRatio??vt.jitterRatio,...this.opts.random?{random:this.
275
+ if(this.stopped)return;let t=hu({refreshAfter:this.opts.getRefreshAfter?.(),nowSeconds:this.now(),consecutiveFailures:this.consecutiveFailures,floorSeconds:this.opts.floorSeconds??It.floorSeconds,pollIntervalSeconds:this.
276
+ opts.pollIntervalSeconds??It.pollIntervalSeconds,maxIntervalSeconds:this.opts.maxIntervalSeconds??It.maxIntervalSeconds,jitterRatio:this.opts.jitterRatio??It.jitterRatio,...this.opts.random?{random:this.
273
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.
274
- controller?.abort();}};var Kc="https://developers.openai.com/api/docs/pricing",Gc="https://ai.google.dev/gemini-api/docs/pricing",Ks="2026-09-27",ue=e=>({...e,fuente:Kc,consultado:Ks}),yt=e=>({...e,fuente:Gc,consultado:Ks});
275
- ({openai:{flex:{"gpt-5":ue({inputPer1k:625e-6,cachedInputPer1k:625e-7,outputPer1k:.005}),"gpt-5-mini":ue({inputPer1k:125e-6,cachedInputPer1k:125e-7,outputPer1k:.001}),"gpt-5-nano":ue({inputPer1k:25e-6,
276
- cachedInputPer1k:25e-7,outputPer1k:2e-4}),"gpt-5.2":ue({inputPer1k:875e-6,cachedInputPer1k:875e-7,outputPer1k:.007}),"gpt-5.4":ue({inputPer1k:.00125,cachedInputPer1k:13e-5,outputPer1k:.0075,largo:{estandar:{
277
- inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225},tier:{inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.01125}}}),"gpt-5.4-mini":ue({inputPer1k:375e-6,cachedInputPer1k:375e-7,outputPer1k:.00225}),
278
- "gpt-5.4-nano":ue({inputPer1k:1e-4,cachedInputPer1k:1e-5,outputPer1k:625e-6}),"gpt-5.5":ue({inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.015,largo:{estandar:{inputPer1k:.01,cachedInputPer1k:.001,
279
- outputPer1k:.045},tier:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225}}}),"gpt-5.6-luna":ue({inputPer1k:1e-4,cachedInputPer1k:1e-5,cacheWritePer1k:125e-6,outputPer1k:6e-4,largo:{estandar:{inputPer1k:4e-4,
280
- cachedInputPer1k:4e-5,cacheWritePer1k:5e-4,outputPer1k:.0018},tier:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,outputPer1k:9e-4}}}),"gpt-5.6-sol":ue({inputPer1k:.002,cachedInputPer1k:2e-4,
281
- cacheWritePer1k:.0025,outputPer1k:.01,largo:{estandar:{inputPer1k:.008,cachedInputPer1k:8e-4,cacheWritePer1k:.01,outputPer1k:.03},tier:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.015}},
282
- vigenteHasta:"2026-11-21"}),"gpt-5.6-terra":ue({inputPer1k:.001,cachedInputPer1k:1e-4,cacheWritePer1k:.00125,outputPer1k:.006,largo:{estandar:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,
283
- outputPer1k:.018},tier:{inputPer1k:.002,cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.009}}}),o3:ue({inputPer1k:.001,cachedInputPer1k:25e-5,outputPer1k:.004}),"o4-mini":ue({inputPer1k:55e-5,
284
- cachedInputPer1k:138e-6,outputPer1k:.0022})}},google:{flex:{"gemini-3.7-flash":yt({inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.5-flash":yt({inputPer1k:75e-5,
285
- outputPer1k:.0045,cachedInputPer1k:8e-5}),"gemini-3.5-flash-lite":yt({inputPer1k:15e-5,outputPer1k:.00125,cachedInputPer1k:2e-5}),"gemini-3.1-pro-preview":yt({inputPer1k:.001,outputPer1k:.006,cachedInputPer1k:2e-4,
286
- largo:{estandar:{inputPer1k:.004,outputPer1k:.018,cachedInputPer1k:4e-4},tier:{inputPer1k:.002,outputPer1k:.009,cachedInputPer1k:4e-4}}}),"gemini-2.5-pro":yt({inputPer1k:625e-6,outputPer1k:.005,cachedInputPer1k:125e-6,
287
- largo:{estandar:{inputPer1k:.0025,outputPer1k:.015,cachedInputPer1k:25e-5},tier:{inputPer1k:.00125,outputPer1k:.0075,cachedInputPer1k:25e-5}}}),"gemini-2.5-flash":yt({inputPer1k:15e-5,outputPer1k:.00125,
288
- cachedInputPer1k:3e-5})}}});var Gs={flex:.5,default:1,auto:1,priority:1,fast:1,scale:1,standard:1,batch:.5};Math.min(...Object.values(Gs).filter(e=>e<1));function Mn(e){if(e==null||e==="")return null;let t=Gs[e];return t==null?{servido:e,factor:null,conDescuento:false}:{servido:e,factor:t,conDescuento:t<1}}var eu={"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.\
278
+ controller?.abort();}};var bu="https://developers.openai.com/api/docs/pricing",vu="https://ai.google.dev/gemini-api/docs/pricing",yo="2026-09-27",P=e=>({...e,fuente:bu,consultado:yo}),De=e=>({...e,fuente:vu,consultado:yo}),
279
+ yu="https://platform.claude.com/docs/en/about-claude/pricing",ce=e=>({...e,fuente:yu,consultado:yo});({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,
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,
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,
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,
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":De({inputPer1k:375e-6,
316
+ outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.5-flash":De({inputPer1k:75e-5,outputPer1k:.0045,cachedInputPer1k:8e-5}),"gemini-3.5-flash-lite":De({inputPer1k:15e-5,outputPer1k:.00125,
317
+ cachedInputPer1k:2e-5}),"gemini-3.1-pro-preview":De({inputPer1k:.001,outputPer1k:.006,cachedInputPer1k:2e-4,largo:{estandar:{inputPer1k:.004,outputPer1k:.018,cachedInputPer1k:4e-4},tier:{inputPer1k:.002,
318
+ outputPer1k:.009,cachedInputPer1k:4e-4}}}),"gemini-2.5-pro":De({inputPer1k:625e-6,outputPer1k:.005,cachedInputPer1k:125e-6,largo:{estandar:{inputPer1k:.0025,outputPer1k:.015,cachedInputPer1k:25e-5},tier:{
319
+ inputPer1k:.00125,outputPer1k:.0075,cachedInputPer1k:25e-5}}}),"gemini-2.5-flash":De({inputPer1k:15e-5,outputPer1k:.00125,cachedInputPer1k:3e-5}),"gemini-3.8-flash":De({inputPer1k:375e-6,outputPer1k:.001875,
320
+ cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.6-flash":De({inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.1-flash-lite":De({inputPer1k:125e-6,
321
+ outputPer1k:75e-5,cachedInputPer1k:125e-7}),"gemini-3-flash-preview":De({inputPer1k:25e-5,outputPer1k:.0015,cachedInputPer1k:5e-5})}}});var Ds={flex:.5,default:1,auto:1,priority:1,fast:1,scale:1,standard:1,batch:.5};Math.min(...Object.values(Ds).filter(e=>e<1));function er(e){if(e==null||e==="")return null;let t=Ds[e];return t==null?{servido:e,factor:null,conDescuento:false}:{servido:e,factor:t,conDescuento:t<1}}var _u={"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.\
289
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\
290
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,
291
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\
292
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,"claude-3-haiku":false,"gemini-3.8-flash":true,"gemini-3.7-flash":true,
293
- "gemini-3.6-flash":true,"gemini-3.1-flash-lite":true,"gemini-3-flash-preview":true,"gemini-3.5-flash":true,"gemini-3.5-flash-lite":true,"gemini-3.1-pro-preview":true,"gemini-2.5-pro":true,"gemini-2.5-flash":true},tu=new Set(
294
- ["claude-opus-4-7","claude-opus-4-8"]),nu=[/^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($|[-_.])/,
295
- /^qwq/,/^qwen3/,/^glm-(4\.[5-9]|[5-9])/,/magistral/];function Kr(e){let t=e.lastIndexOf("/"),n=(t>=0?e.slice(t+1):e).toLowerCase();if(nu.some(s=>s.test(n)))return "reasoning-model";let r=Ze(e);if(r===void 0)
296
- return "unclassified-model";let o=eu[r];if(o===true)return "reasoning-model";if(o!==false)return "unclassified-model";if(tu.has(r))return "temperature-ignored"}var kt=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0;function Gr(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){
297
- if(n===null||typeof n!="object")continue;let r=n;if(r.type!=="compaction")continue;t.iteraciones++,t.input+=kt(r.input_tokens),t.output+=kt(r.output_tokens),t.cacheRead+=kt(r.cache_read_input_tokens);
298
- let o=r.cache_creation,s=kt(o?.ephemeral_5m_input_tokens),i=kt(o?.ephemeral_1h_input_tokens),a=typeof r.cache_creation_input_tokens=="number"?kt(r.cache_creation_input_tokens):s+i;t.cacheWrite+=a,t.cacheWrite1h+=
299
- Math.min(i,a);}return t.iteraciones>0?t:null}var Nn=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
+ "gemini-3.6-flash":true,"gemini-3.1-flash-lite":true,"gemini-3-flash-preview":true,"gemini-3.5-flash":true,"gemini-3.5-flash-lite":true,"gemini-3.1-pro-preview":true,"gemini-2.5-pro":true,"gemini-2.5-flash":true},Tu=new Set(
327
+ ["claude-opus-4-7","claude-opus-4-8"]),Cu=[/^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 ko(e){let t=e.lastIndexOf("/"),n=(t>=0?e.slice(t+1):e).toLowerCase();if(Cu.some(i=>i.test(n)))return "reasoning-model";let r=it(e);if(r===void 0)
329
+ return "unclassified-model";let o=_u[r];if(o===true)return "reasoning-model";if(o!==false)return "unclassified-model";if(Tu.has(r))return "temperature-ignored"}var Pt=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0;function xo(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+=Pt(r.input_tokens),t.output+=Pt(r.output_tokens),t.cacheRead+=Pt(r.cache_read_input_tokens);
331
+ let o=r.cache_creation,i=Pt(o?.ephemeral_5m_input_tokens),s=Pt(o?.ephemeral_1h_input_tokens),a=typeof r.cache_creation_input_tokens=="number"?Pt(r.cache_creation_input_tokens):i+s;t.cacheWrite+=a,t.cacheWrite1h+=
332
+ Math.min(s,a);}return t.iteraciones>0?t:null}var tr=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(
300
333
  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,
301
334
  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(
302
- 0)===10&&(o=1));let s=o;for(;o<r.length;){let i=r.charCodeAt(o);if(i!==10&&i!==13){o++;continue}this.linea(this.resto+r.slice(s,o),n),this.resto="",i===13&&(o+1<r.length?r.charCodeAt(o+1)===10&&o++:this.
303
- crPendiente=true),o++,s=o;}return this.resto+=r.slice(s),n}linea(t,n){if(t===""){this.despachar(n);return}if(t.charCodeAt(0)===58)return;let r=t.indexOf(":"),o,s;switch(r===-1?(o=t,s=""):(o=t.slice(0,r),
304
- s=t.slice(r+1),s.charCodeAt(0)===32&&(s=s.slice(1))),o){case "data":this.datos+=s+`
305
- `;break;case "event":this.evento=s;break;case "id":s.includes("\0")||(this.ultimoId=s);break;}}despachar(t){if(this.datos===""){this.evento="";return}t.push({event:this.evento===""?"message":
306
- this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};var rt=class{resto="";uso=null;elisionObservada=null;eventos={};observar(t){this.resto+=typeof t=="string"?t:t.toString("utf8");let n;for(;(n=this.resto.indexOf(`
335
+ 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.
336
+ 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),
337
+ i=t.slice(r+1),i.charCodeAt(0)===32&&(i=i.slice(1))),o){case "data":this.datos+=i+`
338
+ `;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":
339
+ this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};var dt=class{resto="";uso=null;elisionObservada=null;eventos={};observar(t){this.resto+=typeof t=="string"?t:t.toString("utf8");let n;for(;(n=this.resto.indexOf(`
307
340
 
308
341
  `))>=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;
309
- let s=/^data: (.+)$/m.exec(r)?.[1];if(s)try{let i=JSON.parse(s),a=Zs(i.context_management);a&&(this.elisionObservada=a);let u=i.usage??i.message?.usage;if(u){let c=u.cache_creation||this.uso?.cache_creation?
310
- {...this.uso?.cache_creation,...u.cache_creation}:void 0;this.uso={...this.uso,...u,...c?{cache_creation:c}:{}};}}catch{}}}usage(){return this.uso}usageFinal(){return (this.eventos.message_delta??0)>0?this.
311
- uso:null}elision(){return this.elisionObservada}};function ru(e,t){if(!t||t.atribuible!==true||!(t.tokensLimpiadosToolUses>0))return 0;let n=e.cachedInputPer1k;return typeof n!="number"||!Number.isFinite(
312
- n)||n<=0?0:t.tokensLimpiadosToolUses/1e3*n}function Zs(e){if(e===null||typeof e!="object")return null;let t=e.applied_edits;if(!Array.isArray(t)||t.length===0)return null;let n=0,r=0;for(let o of t){let s=o.
313
- cleared_input_tokens;typeof s=="number"&&Number.isFinite(s)&&s>0&&(n+=s,o.type==="clear_tool_uses_20250919"&&(r+=s));}return {borrados:t.length,tokensLimpiados:n,tokensLimpiadosToolUses:r}}function Xs(e){
314
- try{let t=JSON.parse(typeof e=="string"?e:e.toString("utf8"));return Zs(t.context_management)}catch{return null}}var xt=class{resto="";uso=null;final=null;eventos={};observar(t){this.resto+=typeof t==
342
+ let i=/^data: (.+)$/m.exec(r)?.[1];if(i)try{let s=JSON.parse(i),a=Ms(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?
343
+ {...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.
344
+ uso:null}elision(){return this.elisionObservada}};function Au(e,t){if(!t||t.atribuible!==true||!(t.tokensLimpiadosToolUses>0))return 0;let n=e.cachedInputPer1k;return typeof n!="number"||!Number.isFinite(
345
+ n)||n<=0?0:t.tokensLimpiadosToolUses/1e3*n}function Ms(e){if(e===null||typeof e!="object")return null;let t=e.applied_edits;if(!Array.isArray(t)||t.length===0)return null;let n=0,r=0;for(let o of t){let i=o.
346
+ cleared_input_tokens;typeof i=="number"&&Number.isFinite(i)&&i>0&&(n+=i,o.type==="clear_tool_uses_20250919"&&(r+=i));}return {borrados:t.length,tokensLimpiados:n,tokensLimpiadosToolUses:r}}function $s(e){
347
+ try{let t=JSON.parse(typeof e=="string"?e:e.toString("utf8"));return Ms(t.context_management)}catch{return null}}var Dt=class{resto="";uso=null;final=null;eventos={};observar(t){this.resto+=typeof t==
315
348
  "string"?t:t.toString("utf8");let n;for(;(n=this.resto.indexOf(`
316
349
 
317
- `))>=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 s=/^data: (.+)$/m.exec(r)?.[1];if(s)try{let i=JSON.
318
- parse(s),a=o??i.type,u=a!==void 0&&Object.hasOwn(Js,a)?Js[a]:void 0;if(u===void 0)continue;this.final=u;let c=i.response?.usage;if(!c)continue;u==="completed"?this.uso=$n(c):typeof c.input_tokens=="nu\
319
- mber"&&typeof c.output_tokens=="number"&&(this.uso=$n(c));}catch{}}}usage(){return this.uso}usageFinal(){return this.uso}estadoFinal(){return this.final}},Js={"response.completed":"completed","response\
320
- .incomplete":"incomplete","response.failed":"failed"};function $n(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.max(0,e.input_tokens_details?.
321
- 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 Qs(e){return !e||typeof e.prompt_tokens!=
322
- "number"||typeof e.completion_tokens!="number"?null:$n({input_tokens:e.prompt_tokens,output_tokens:e.completion_tokens,input_tokens_details:{...e.prompt_tokens_details?.cached_tokens!==void 0?{cached_tokens:e.
323
- prompt_tokens_details.cached_tokens}:{},...e.prompt_tokens_details?.cache_write_tokens!==void 0?{cache_write_tokens:e.prompt_tokens_details.cache_write_tokens}:{}}})}var Kt=class{parser=new Nn;ultimoUso=null;vioUsoFinal=false;vioDone=false;eventos={};observar(t){
350
+ `))>=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.
351
+ parse(i),a=o??s.type,c=a!==void 0&&Object.hasOwn(Os,a)?Os[a]:void 0;if(c===void 0)continue;this.final=c;let l=s.response?.usage;if(!l)continue;c==="completed"?this.uso=nr(l):typeof l.input_tokens=="nu\
352
+ mber"&&typeof l.output_tokens=="number"&&(this.uso=nr(l));}catch{}}}usage(){return this.uso}usageFinal(){return this.uso}estadoFinal(){return this.final}},Os={"response.completed":"completed","response\
353
+ .incomplete":"incomplete","response.failed":"failed"};function nr(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.max(0,e.input_tokens_details?.
354
+ 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 Ns(e){return !e||typeof e.prompt_tokens!=
355
+ "number"||typeof e.completion_tokens!="number"?null:nr({input_tokens:e.prompt_tokens,output_tokens:e.completion_tokens,input_tokens_details:{...e.prompt_tokens_details?.cached_tokens!==void 0?{cached_tokens:e.
356
+ prompt_tokens_details.cached_tokens}:{},...e.prompt_tokens_details?.cache_write_tokens!==void 0?{cache_write_tokens:e.prompt_tokens_details.cache_write_tokens}:{}}})}var an=class{parser=new tr;ultimoUso=null;vioUsoFinal=false;vioDone=false;eventos={};observar(t){
324
357
  for(let n of this.parser.push(t))this.mensaje(n);}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){
325
358
  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??
326
- 0)+1,n.usage===null||typeof n.usage!="object"))return;let r=Qs(n.usage);r!==null&&(this.ultimoUso=r,Array.isArray(n.choices)&&n.choices.length===0&&(this.vioUsoFinal=true));}};function ei(e,t,n){let r=e.
327
- cachedInputPer1k??e.inputPer1k;return t.entrada/1e3*e.inputPer1k+t.cacheLeida/1e3*r+(t.cacheEscrita-t.cacheEscrita1h)/1e3*e.inputPer1k*fe(n)+t.cacheEscrita1h/1e3*e.inputPer1k*2+t.salida/1e3*e.outputPer1k}
328
- function ti(e,t,n){let r=n??Date.now(),o=be(e,r);if(!o)return null;let s=Gr(t.iterations),i=(t.input_tokens??0)+(s?.input??0),a=(t.output_tokens??0)+(s?.output??0),u=(t.cache_read_input_tokens??0)+(s?.
329
- cacheRead??0),c=t.cache_creation,d=t.cache_creation_input_tokens??(c?.ephemeral_5m_input_tokens??0)+(c?.ephemeral_1h_input_tokens??0),l=d+(s?.cacheWrite??0),p=Math.min(Math.min(c?.ephemeral_1h_input_tokens??
330
- 0,d)+(s?.cacheWrite1h??0),l),f={entrada:i,salida:a,cacheLeida:u,cacheEscrita:l,cacheEscrita1h:p};return {costeUsd:ei(o,f,e),precio:o,tokens:f,instante:r}}function ni(e,t){let r=wt(e,t)?.model;return typeof r==
331
- "string"?r:""}function wt(e,t){try{let n=e,r={maxOutputLength:ou};switch((t??"").trim().toLowerCase()){case "gzip":case "x-gzip":n=Ne.gunzipSync(e,r);break;case "deflate":n=Ne.inflateSync(e,r);break;case "\
332
- br":n=Ne.brotliDecompressSync(e,r);break;case "zstd":{let o=Ne.zstdDecompressSync;if(typeof o!="function")return null;n=o(e,r);break}default:break}return JSON.parse(n.toString("utf8"))}catch{return null}}
333
- var ou=5*1024*1024;function ri(){return typeof Ne.zstdDecompressSync=="function"}function su(e){try{return JSON.parse(typeof e=="string"?e:e.toString("utf8")).usage??null}catch{return null}}function jn(e,t){
334
- if(e==="/v1/messages")return su(t);if(!St(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 Qs(
335
- n.usage);let r=n.usage;return r&&typeof r.input_tokens=="number"&&typeof r.output_tokens=="number"?$n(r):null}catch{return null}}function oi(e,t){if(!e.endsWith("/responses"))return false;try{let n=JSON.parse(
336
- typeof t=="string"?t:t.toString("utf8"));return n!==null&&typeof n=="object"&&n.status==="failed"}catch{return false}}function si(e,t){let n=typeof t=="string"?t:t.toString("utf8"),r=s=>{if(s===null||typeof s!=
337
- "object")return;let i=s,a=c=>c!==null&&typeof c=="object"?c.service_tier:void 0,u;return e==="/v1/messages"?(u=a(i.usage),u===void 0&&i.message!==null&&typeof i.message=="object"&&(u=a(i.message.usage))):
338
- e.endsWith("/chat/completions")?u=i.service_tier:e.endsWith("/responses")&&(u=i.service_tier,u===void 0&&i.response!==null&&typeof i.response=="object"&&(u=i.response.service_tier)),typeof u=="string"&&
339
- u!==""?u:void 0};try{return r(JSON.parse(n))}catch{}let o;for(let s of n.split(`
340
- `)){if(!s.startsWith("data:"))continue;let i=s.slice(5).trim();if(!(i===""||i==="[DONE]"))try{o=r(JSON.parse(i))??o;}catch{}}return o}function St(e){return e==="/v1/messages"||e.endsWith("/chat/complet\
341
- ions")||e.endsWith("/responses")}var iu=Buffer.from('"stream_options":{"include_usage":true},',"utf8");function ii(e,t){let n=(t??"").trim().toLowerCase();if(n!==""&&n!=="identity")return {cuerpo:null,
359
+ 0)+1,n.usage===null||typeof n.usage!="object"))return;let r=Ns(n.usage);r!==null&&(this.ultimoUso=r,Array.isArray(n.choices)&&n.choices.length===0&&(this.vioUsoFinal=true));}};function js(e,t,n){let r=e.
360
+ cachedInputPer1k??e.inputPer1k;return t.entrada/1e3*e.inputPer1k+t.cacheLeida/1e3*r+(t.cacheEscrita-t.cacheEscrita1h)/1e3*e.inputPer1k*we(n)+t.cacheEscrita1h/1e3*e.inputPer1k*2+t.salida/1e3*e.outputPer1k}
361
+ function Bs(e,t,n){let r=n??Date.now(),o=Te(e,r);if(!o)return null;let i=xo(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?.
362
+ 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??
363
+ 0,d)+(i?.cacheWrite1h??0),u),f={entrada:s,salida:a,cacheLeida:c,cacheEscrita:u,cacheEscrita1h:p};return {costeUsd:js(o,f,e),precio:o,tokens:f,instante:r}}function Us(e,t){let r=Ot(e,t)?.model;return typeof r==
364
+ "string"?r:""}function Ot(e,t){try{let n=e,r={maxOutputLength:Ru};switch((t??"").trim().toLowerCase()){case "gzip":case "x-gzip":n=He.gunzipSync(e,r);break;case "deflate":n=He.inflateSync(e,r);break;case "\
365
+ br":n=He.brotliDecompressSync(e,r);break;case "zstd":{let o=He.zstdDecompressSync;if(typeof o!="function")return null;n=o(e,r);break}default:break}return JSON.parse(n.toString("utf8"))}catch{return null}}
366
+ var Ru=5*1024*1024;function Vs(){return typeof He.zstdDecompressSync=="function"}function Iu(e){try{return JSON.parse(typeof e=="string"?e:e.toString("utf8")).usage??null}catch{return null}}function rr(e,t){
367
+ if(e==="/v1/messages")return Iu(t);if(!pt(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 Ns(
368
+ n.usage);let r=n.usage;return r&&typeof r.input_tokens=="number"&&typeof r.output_tokens=="number"?nr(r):null}catch{return null}}function Fs(e,t){if(!e.endsWith("/responses"))return false;try{let n=JSON.parse(
369
+ typeof t=="string"?t:t.toString("utf8"));return n!==null&&typeof n=="object"&&n.status==="failed"}catch{return false}}function zs(e,t){let n=typeof t=="string"?t:t.toString("utf8"),r=i=>{if(i===null||typeof i!=
370
+ "object")return;let s=i,a=l=>l!==null&&typeof l=="object"?l.service_tier: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))):
371
+ e.endsWith("/chat/completions")?c=s.service_tier:e.endsWith("/responses")&&(c=s.service_tier,c===void 0&&s.response!==null&&typeof s.response=="object"&&(c=s.response.service_tier)),typeof c=="string"&&
372
+ c!==""?c:void 0};try{return r(JSON.parse(n))}catch{}let o;for(let i of n.split(`
373
+ `)){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 pt(e){return e==="/v1/messages"||e.endsWith("/chat/complet\
374
+ ions")||e.endsWith("/responses")}var Pu=Buffer.from('"stream_options":{"include_usage":true},',"utf8");function qs(e,t){let n=(t??"").trim().toLowerCase();if(n!==""&&n!=="identity")return {cuerpo:null,
342
375
  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:"\
343
376
  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,
344
- motivo:"cliente-decide"};let s=0;for(;s<e.length;){let i=e[s];if(i===32||i===9||i===10||i===13){s++;continue}if(i===239&&e[s+1]===187&&e[s+2]===191){s+=3;continue}break}return e[s]!==123?{cuerpo:null,
345
- motivo:"ilegible"}:{cuerpo:Buffer.concat([e.subarray(0,s+1),iu,e.subarray(s+1)]),motivo:"inyectado"}}function ai(e,t){let n=wt(e,t);if(n===null||typeof n!="object")return null;let r=n;return r.stream!==
346
- true?null:r.stream_options?.include_usage===true}function Jr(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();
347
- return r==="chatgpt.com"||r.endsWith(".chatgpt.com")}catch{return false}}function ci(e,t,n,r,o,s,i,a){return pi(e,t,n,false,r,o,s,i,a)}var au=new Set(["auto","default","priority","standard_only"]);function cu(e){
348
- if(e==null)return 1;if(typeof e!="string")return null;if(au.has(e))return 1;let t=Mn(e);return t!==null&&t.conDescuento&&t.factor!==null?t.factor:null}function uu(e){if(e===void 0)return 1;if(e==="sca\
349
- le")return null;let t=Mn(e);return t!==null&&t.factor!==null?t.factor:null}function ui(e,t,n,r,o){if(!n||!n.conContador)return {ok:false,reason:"no-primary-record"};if(n.suscripcion||o.suscripcion)return {
377
+ 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,
378
+ motivo:"ilegible"}:{cuerpo:Buffer.concat([e.subarray(0,i+1),Pu,e.subarray(i+1)]),motivo:"inyectado"}}function Hs(e,t){let n=Ot(e,t);if(n===null||typeof n!="object")return null;let r=n;return r.stream!==
379
+ true?null:r.stream_options?.include_usage===true}function wo(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();
380
+ return r==="chatgpt.com"||r.endsWith(".chatgpt.com")}catch{return false}}function Ws(e,t,n,r,o,i,s,a){return Ys(e,t,n,false,r,o,i,s,a)}var Du=new Set(["auto","default","priority","standard_only"]);function Ou(e){
381
+ if(e==null)return 1;if(typeof e!="string")return null;if(Du.has(e))return 1;let t=er(e);return t!==null&&t.conDescuento&&t.factor!==null?t.factor:null}function Lu(e){if(e===void 0)return 1;if(e==="sca\
382
+ le")return null;let t=er(e);return t!==null&&t.factor!==null?t.factor:null}function Ks(e,t,n,r,o){if(!n||!n.conContador)return {ok:false,reason:"no-primary-record"};if(n.suscripcion||o.suscripcion)return {
350
383
  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:"primary-fail\
351
- ed"};if(!o.entregada)return {ok:false,reason:"client-disconnected"};let s=r!==null&&typeof r=="object"&&!Array.isArray(r)?r:{},i=cu(s.service_tier),a=uu(o.tierServido);if(i===null||a===null)return {ok:false,reason:"\
352
- service-tier"};let u=Math.min(i,a),c=pt(e,t.instante),d=c?.cachedInputPer1k;if(!c||typeof d!="number"||!Number.isFinite(d)||!(d>0)||!Number.isFinite(c.inputPer1k)||d>c.inputPer1k||!Number.isFinite(c.outputPer1k)||
353
- c.outputPer1k<0)return {ok:false,reason:"no-cached-price"};let l=t.tokens,p=l.entrada+l.cacheLeida+l.cacheEscrita,f=y=>Number.isInteger(y)&&y>=0;if(!f(l.entrada)||!f(l.cacheLeida)||!f(l.cacheEscrita)||!f(
354
- l.salida)||!(p>0))return {ok:false,reason:"no-credit"};let g=s.temperature===0&&Kr(e)===void 0;return {ok:true,credit:{requestId:n.requestId,at:n.at,inputTokens:p,outputTokens:l.salida,creditedInputTokens:p,
355
- creditedOutputTokens:g?Math.floor(.95*l.salida):0,cachedInputPer1k:d,outputPer1k:c.outputPer1k,tierFactor:u}}}function Yr(e){return e.tierFactor*(e.creditedInputTokens/1e3*e.cachedInputPer1k+e.creditedOutputTokens/
356
- 1e3*e.outputPer1k)}function li(e,t,n,r,o){let s=o?Yr(o):0;return !o||!(s>0)||!Number.isFinite(s)?pi(e,t,n,true,r):{requestId:e,model:t,...r&&(r.sessionId||r.agentId)?{attribution:r}:{},calls:{avoidedLlm:1,
384
+ ed"};if(!o.entregada)return {ok:false,reason:"client-disconnected"};let i=r!==null&&typeof r=="object"&&!Array.isArray(r)?r:{},s=Ou(i.service_tier),a=Lu(o.tierServido);if(s===null||a===null)return {ok:false,reason:"\
385
+ service-tier"};let c=Math.min(s,a),l=Et(e,t.instante),d=l?.cachedInputPer1k;if(!l||typeof d!="number"||!Number.isFinite(d)||!(d>0)||!Number.isFinite(l.inputPer1k)||d>l.inputPer1k||!Number.isFinite(l.outputPer1k)||
386
+ 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(b)&&b>=0;if(!f(u.entrada)||!f(u.cacheLeida)||!f(u.cacheEscrita)||!f(
387
+ u.salida)||!(p>0))return {ok:false,reason:"no-credit"};let g=i.temperature===0&&ko(e)===void 0;return {ok:true,credit:{requestId:n.requestId,at:n.at,inputTokens:p,outputTokens:u.salida,creditedInputTokens:p,
388
+ creditedOutputTokens:g?Math.floor(.95*u.salida):0,cachedInputPer1k:d,outputPer1k:l.outputPer1k,tierFactor:c}}}function So(e){return e.tierFactor*(e.creditedInputTokens/1e3*e.cachedInputPer1k+e.creditedOutputTokens/
389
+ 1e3*e.outputPer1k)}function Gs(e,t,n,r,o){let i=o?So(o):0;return !o||!(i>0)||!Number.isFinite(i)?Ys(e,t,n,true,r):{requestId:e,model:t,...r&&(r.sessionId||r.agentId)?{attribution:r}:{},calls:{avoidedLlm:1,
357
390
  actualLlm:0},tokens:{baselineInput:o.creditedInputTokens,actualInput:0,eliminatedInput:0,compressedInput:0,baselineOutput:o.creditedOutputTokens,actualOutput:0,providerCachedInput:0},cache:{result:"si\
358
- ngleflight",reference:o},cost:{baselineEstimate:s,actual:0,netSavings:1,basis:"reference"}}}function di(e,t,n,r,o){return {requestId:e,model:t,...o&&(o.sessionId||o.agentId)?{attribution:o}:{},calls:{avoidedLlm:0,
391
+ ngleflight",reference:o},cost:{baselineEstimate:i,actual:0,netSavings:1,basis:"reference"}}}function Js(e,t,n,r,o){return {requestId:e,model:t,...o&&(o.sessionId||o.agentId)?{attribution:o}:{},calls:{avoidedLlm:0,
359
392
  actualLlm:0},tokens:{baselineInput:0,actualInput:0,eliminatedInput:0,compressedInput:0,baselineOutput:0,actualOutput:0,providerCachedInput:0},cache:{result:"miss"},cost:{baselineEstimate:n,actual:r,netSavings:n>
360
- 0?Math.max(-100,Math.min(1,(n-r)/n)):0,basis:"shadow"}}}function lu(e,t){let n=be(e.solicitado,t.instante);return n===void 0?0:Math.max(0,ei(n,t.tokens,e.solicitado)-t.costeUsd)}function pi(e,t,n,r,o,s,i,a,u=false){
361
- let c=n.tokens.entrada+n.tokens.cacheLeida+n.tokens.cacheEscrita,d=!r&&!u,l=n.tokens.cacheEscrita-n.tokens.cacheEscrita1h,p=d&&i&&i.rebajadas>0&&i.yaEran5m===0&&!i.herramientaDeServidor&&l>0?l/1e3*n.precio.
362
- inputPer1k*(2-1.25):0,f=d&&a?lu(a,n):0,g=n.costeUsd+p+f,y=p+f,h=r?0:ru(n.precio,s);return {requestId:e,model:t,...o&&(o.sessionId||o.agentId)?{attribution:o}:{},calls:r?{avoidedLlm:1,actualLlm:0}:{avoidedLlm:0,
363
- actualLlm:1},tokens:{baselineInput:c,actualInput:r?0:c,eliminatedInput:r?0:s?.tokensLimpiados??0,compressedInput:0,baselineOutput:n.tokens.salida,actualOutput:r?0:n.tokens.salida,providerCachedInput:r?
393
+ 0?Math.max(-100,Math.min(1,(n-r)/n)):0,basis:"shadow"}}}function Mu(e,t){let n=Te(e.solicitado,t.instante);return n===void 0?0:Math.max(0,js(n,t.tokens,e.solicitado)-t.costeUsd)}function Ys(e,t,n,r,o,i,s,a,c=false){
394
+ let l=n.tokens.entrada+n.tokens.cacheLeida+n.tokens.cacheEscrita,d=!r&&!c,u=n.tokens.cacheEscrita-n.tokens.cacheEscrita1h,p=d&&s&&s.rebajadas>0&&s.yaEran5m===0&&!s.herramientaDeServidor&&u>0?u/1e3*n.precio.
395
+ inputPer1k*(2-1.25):0,f=d&&a?Mu(a,n):0,g=n.costeUsd+p+f,b=p+f,h=r?0:Au(n.precio,i);return {requestId:e,model:t,...o&&(o.sessionId||o.agentId)?{attribution:o}:{},calls:r?{avoidedLlm:1,actualLlm:0}:{avoidedLlm:0,
396
+ actualLlm:1},tokens:{baselineInput:l,actualInput:r?0:l,eliminatedInput:r?0:i?.tokensLimpiados??0,compressedInput:0,baselineOutput:n.tokens.salida,actualOutput:r?0:n.tokens.salida,providerCachedInput:r?
364
397
  0:n.tokens.cacheLeida},cache:{result:r?"singleflight":"miss"},cost:r?{baselineEstimate:n.costeUsd,actual:0,netSavings:1,basis:"estimated"}:{baselineEstimate:g,actual:n.costeUsd,netSavings:g>0?Math.max(
365
- -100,Math.min(1,y/g)):0,basis:"measured",...h>0?{eliminatedInputFloorCost:h}:{}}}}var du=1024,Gt=120,pu=8,fu=256*1024,mu=/error|exception|traceback|warn|fatal|fail|panic|assert|denied|refused|timeout|\bat\s+\S+:\d+/i,hi=/^\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)/;
366
- function hu(e){return Buffer.byteLength(typeof e=="string"?e:JSON.stringify(e??""))}function gu(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t&&typeof t=="object"&&typeof t.text=="string"?
398
+ -100,Math.min(1,b/g)):0,basis:"measured",...h>0?{eliminatedInputFloorCost:h}:{}}}}var $u=1024,cn=120,Nu=8,ju=256*1024,Bu=/error|exception|traceback|warn|fatal|fail|panic|assert|denied|refused|timeout|\bat\s+\S+:\d+/i,Qs=/^\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)/;
399
+ function Uu(e){return Buffer.byteLength(typeof e=="string"?e:JSON.stringify(e??""))}function Vu(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t&&typeof t=="object"&&typeof t.text=="string"?
367
400
  t.text:"").join(`
368
- `):""}var bu=/^\s*\d+[\t→]/;function gi(e){return e.replace(bu,"")}function vu(e){if(!e)return "otro";let t=e.split(`
369
- `),n=Math.max(1,t.length),r=0,o=0,s=0;for(let i of t){let a=gi(i);(/^[+-](?![+-])/.test(a)||a.startsWith("@@")||a.startsWith("diff --git"))&&(r+=1),hi.test(a)&&(o+=1),(/^\s*(\d{4}-\d{2}-\d{2}|\[\d|\d{2}:\d{2}:\d{2})/.
370
- test(a)||/\b(INFO|DEBUG|TRACE|WARN|ERROR)\b/.test(a))&&(s+=1);}return r/n>.25?"diff":s/n>.3?"log":o/n>.08?"codigo":"otro"}function yu(e,t){if(t==="diff"||t==="otro")return Buffer.byteLength(e);let n=e.
401
+ `):""}var Fu=/^\s*\d+[\t→]/;function ea(e){return e.replace(Fu,"")}function zu(e){if(!e)return "otro";let t=e.split(`
402
+ `),n=Math.max(1,t.length),r=0,o=0,i=0;for(let s of t){let a=ea(s);(/^[+-](?![+-])/.test(a)||a.startsWith("@@")||a.startsWith("diff --git"))&&(r+=1),Qs.test(a)&&(o+=1),(/^\s*(\d{4}-\d{2}-\d{2}|\[\d|\d{2}:\d{2}:\d{2})/.
403
+ 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 qu(e,t){if(t==="diff"||t==="otro")return Buffer.byteLength(e);let n=e.
371
404
  split(`
372
- `),r=new Set;for(let s=0;s<n.length;s++){let i=gi(n[s]);(t==="log"?mu.test(i):hi.test(i))&&(r.add(s),t==="log"&&(s>0&&r.add(s-1),s<n.length-1&&r.add(s+1)));}let o=Gt;for(let s of r)o+=Buffer.byteLength(
373
- n[s])+1;return Math.min(o,Buffer.byteLength(e))}var ku=(e,t)=>e==="cache_control"?void 0:t;function xu(e){if(typeof e=="string")return `text:${e}`;if(!e||typeof e!="object"||Array.isArray(e))return `jso\
374
- 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,ku)}`}
375
- function wu(e){return createHash("sha256").update(xu(e)).digest("hex").slice(0,16)}function Su(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.cache_control;return !t||typeof t!="object"?null:
376
- t.ttl==="1h"?"1h":"5m"}function bi(e){let t=[],n=(r,o)=>{let s=hu(o),i={clave:wu(o),tipo:r,marca:Su(o),bytes:s,bytesV1:s,clase:"otro",esError:false};if(r.endsWith(":tool_result")&&o&&typeof o=="object"){
377
- let a=o;i.esError=a.is_error===true;let u=gu(a.content);i.clase=vu(u);let c=s-Buffer.byteLength(u);i.bytesV1=Math.min(s,Math.max(0,c)+yu(u,i.clase));}t.push(i);};if(Array.isArray(e.tools))for(let r of e.tools)
405
+ `),r=new Set;for(let i=0;i<n.length;i++){let s=ea(n[i]);(t==="log"?Bu.test(s):Qs.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(
406
+ n[i])+1;return Math.min(o,Buffer.byteLength(e))}var Hu=(e,t)=>e==="cache_control"?void 0:t;function Wu(e){if(typeof e=="string")return `text:${e}`;if(!e||typeof e!="object"||Array.isArray(e))return `jso\
407
+ 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,Hu)}`}
408
+ function Ku(e){return createHash("sha256").update(Wu(e)).digest("hex").slice(0,16)}function Gu(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.cache_control;return !t||typeof t!="object"?null:
409
+ t.ttl==="1h"?"1h":"5m"}function ta(e){let t=[],n=(r,o)=>{let i=Uu(o),s={clave:Ku(o),tipo:r,marca:Gu(o),bytes:i,bytesV1:i,clase:"otro",esError:false};if(r.endsWith(":tool_result")&&o&&typeof o=="object"){
410
+ let a=o;s.esError=a.is_error===true;let c=Vu(a.content);s.clase=zu(c);let l=i-Buffer.byteLength(c);s.bytesV1=Math.min(i,Math.max(0,l)+qu(c,s.clase));}t.push(s);};if(Array.isArray(e.tools))for(let r of e.tools)
378
411
  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!=
379
- "object"){n("?:invalido",r);continue}let o=r,s=typeof o.role=="string"?o.role:"?";if(typeof o.content=="string")n(`${s}:text`,o.content);else if(Array.isArray(o.content))for(let i of o.content)n(`${s}\
380
- :${i?.type??"?"}`,i);}return t}function Eu(){return {nacimiento:new Map,turno:0,elididosV2m:new Set}}function _u(e,t){let n=e.turno++;for(let r of t)e.nacimiento.has(r.clave)||e.nacimiento.set(r.clave,n);
381
- return n}function vi(e,t,n,r,o=fu){let s=t.reduce((l,p,f)=>p.tipo.endsWith(":tool_result")?f:l,-1),i=(l,p)=>l.tipo.endsWith(":tool_result")&&l.bytes>=du&&p!==s;return t.map((l,p)=>{if(!i(l,
382
- p))return {clave:l.clave,bytes:l.bytes};let f=r-(n.nacimiento.get(l.clave)??r);return f>=2&&f*l.bytes/1024>=pu?{clave:`${l.clave}:e`,bytes:Gt}:{clave:l.clave,bytes:l.bytes}});}function Tu(e,t){let n=be(e,t);return n?{inputPer1k:n.inputPer1k,lecturaPer1k:n.cachedInputPer1k??n.inputPer1k,escrituraPer1k:n.inputPer1k*
383
- fe(e),escritura1hPer1k:n.inputPer1k*or(e)}:null}function fi(){return {lecturaUsd:0,escrituraUsd:0,entradaUsd:0,totalUsd:0,tokensLeidos:0,tokensEscritos:0,tokensEntrada:0,tokensInvalidados:0,invalidacionUsd:0}}
384
- var Xr={"1h":36e5,"5m":3e5},Ru=20,Iu=6e3,Au=2e4,Et=class{constructor(t=Au){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?
385
- r:null}escribir(t,n,r){this.entradas.delete(t),this.entradas.set(t,{expira:n+Xr[r],ttl:r}),this.entradas.size>this.tope&&this.podar(n);}refrescar(t,n){let r=this.entradas.get(t);r&&(this.entradas.delete(
386
- t),this.entradas.set(t,{expira:n+Xr[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().
387
- value;if(n===void 0)break;this.entradas.delete(n);}}};function Cu(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(
388
- "|").update(t[o]).digest("hex").slice(0,32),n[o]=r;return n}function Du(e){let t=new Array(e.length),n=-1,r="";for(let o=0;o<e.length;o++){let s=e[o],i=s.endsWith(":tool_use")||s.endsWith(":tool_resul\
389
- t");i&&s===r||(n+=1),r=i?s:"",t[o]=n;}return t}function mi(e,t){return e.endsWith(":image")?Math.min(t,Iu):t}var Jt=class{constructor(t,n){this.transformar=t;this.cache=n??new Et;}transformar;estado=Eu();cache;previo=[];previoUltimoBp=-1;previoTtl="\
390
- 5m";hayPrevio=false;atPrevio=0;acumulado=fi();paso(t){let n=fi(),r=_u(this.estado,t.bloques),o=Tu(t.model,t.at),s=this.transformar(t.bloques,this.estado,r);if(!o||t.entradaReal<=0||s.length===0)return this.
391
- previo=s,this.previoUltimoBp=-1,this.previoTtl="5m",this.hayPrevio=true,this.atPrevio=t.at,n;let i=s.map((v,I)=>t.bloques[I]?.tipo??""),a=s.map((v,I)=>t.bloques[I]?.marca??null),u=t.bloques.reduce((v,I)=>v+
392
- mi(I.tipo,I.bytes),0),c=u>0?t.entradaReal/u:0,d=s.map((v,I)=>mi(i[I],v.bytes)*c),l=Cu(t.model,s.map(v=>v.clave)),p=Du(i),f=a.map((v,I)=>v?I:-1).filter(v=>v>=0);if(f.length===0){for(let v=0;v<s.length;v++)
393
- n.tokensEntrada+=d[v],n.entradaUsd+=d[v]/1e3*o.inputPer1k;return n.totalUsd=n.entradaUsd,this.previo=s,this.previoUltimoBp=-1,this.previoTtl="5m",this.hayPrevio=true,this.atPrevio=t.at,this.acumulado.tokensEntrada+=
394
- n.tokensEntrada,this.acumulado.entradaUsd+=n.entradaUsd,this.acumulado.totalUsd+=n.totalUsd,n}let g=-1;for(let v of f){let I=p[v]-(Ru-1);for(let A=v;A>=0&&p[A]>=I;A--)if(this.cache.viva(l[A],t.at)){A>
395
- g&&(g=A);break}}for(let v=0;v<=g;v++)this.cache.refrescar(l[v],t.at);let y=f[f.length-1];for(let v of f)v>g&&this.cache.escribir(l[v],t.at,a[v]);let h=0,w=this.hayPrevio&&t.at-this.atPrevio>Xr[this.previoTtl]?
396
- []:this.previo.slice(g+1,this.previoUltimoBp+1),_=0;for(let v=0;v<s.length;v++){let I=s[v],A=d[v];if(v<=g){n.tokensLeidos+=A,n.lecturaUsd+=A/1e3*o.lecturaPer1k;continue}if(v>y){n.tokensEntrada+=A,n.entradaUsd+=
397
- A/1e3*o.inputPer1k;continue}for(;f[h]<v;)h+=1;let C=a[f[h]]==="1h"?o.escritura1hPer1k:o.escrituraPer1k;n.tokensEscritos+=A,n.escrituraUsd+=A/1e3*C;let P=_;for(;P<w.length&&w[P].clave!==I.clave;)P+=1;P<
398
- w.length&&(w[P].bytes===I.bytes&&(n.tokensInvalidados+=A,n.invalidacionUsd+=A/1e3*(C-o.lecturaPer1k)),_=P+1);}return this.previo=s,this.previoUltimoBp=y,this.previoTtl=a[y]??"5m",this.hayPrevio=true,this.
412
+ "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}\
413
+ :${s?.type??"?"}`,s);}return t}function Ju(){return {nacimiento:new Map,turno:0,elididosV2m:new Set}}function Yu(e,t){let n=e.turno++;for(let r of t)e.nacimiento.has(r.clave)||e.nacimiento.set(r.clave,n);
414
+ return n}function na(e,t,n,r,o=ju){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>=$u&&p!==i;return t.map((u,p)=>{if(!s(u,
415
+ p))return {clave:u.clave,bytes:u.bytes};let f=r-(n.nacimiento.get(u.clave)??r);return f>=2&&f*u.bytes/1024>=Nu?{clave:`${u.clave}:e`,bytes:cn}:{clave:u.clave,bytes:u.bytes}});}function Zu(e,t){let n=Te(e,t);return n?{inputPer1k:n.inputPer1k,lecturaPer1k:n.cachedInputPer1k??n.inputPer1k,escrituraPer1k:n.inputPer1k*
416
+ we(e),escritura1hPer1k:n.inputPer1k*Tn(e)}:null}function Zs(){return {lecturaUsd:0,escrituraUsd:0,entradaUsd:0,totalUsd:0,tokensLeidos:0,tokensEscritos:0,tokensEntrada:0,tokensInvalidados:0,invalidacionUsd:0}}
417
+ var _o={"1h":36e5,"5m":3e5},Xu=20,Qu=6e3,ed=2e4,Lt=class{constructor(t=ed){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?
418
+ r:null}escribir(t,n,r){this.entradas.delete(t),this.entradas.set(t,{expira:n+_o[r],ttl:r}),this.entradas.size>this.tope&&this.podar(n);}refrescar(t,n){let r=this.entradas.get(t);r&&(this.entradas.delete(
419
+ t),this.entradas.set(t,{expira:n+_o[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().
420
+ value;if(n===void 0)break;this.entradas.delete(n);}}};function td(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(
421
+ "|").update(t[o]).digest("hex").slice(0,32),n[o]=r;return n}function nd(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\
422
+ t");s&&i===r||(n+=1),r=s?i:"",t[o]=n;}return t}function Xs(e,t){return e.endsWith(":image")?Math.min(t,Qu):t}var ln=class{constructor(t,n){this.transformar=t;this.cache=n??new Lt;}transformar;estado=Ju();cache;previo=[];previoUltimoBp=-1;previoTtl="\
423
+ 5m";hayPrevio=false;atPrevio=0;acumulado=Zs();paso(t){let n=Zs(),r=Yu(this.estado,t.bloques),o=Zu(t.model,t.at),i=this.transformar(t.bloques,this.estado,r);if(!o||t.entradaReal<=0||i.length===0)return this.
424
+ previo=i,this.previoUltimoBp=-1,this.previoTtl="5m",this.hayPrevio=true,this.atPrevio=t.at,n;let s=i.map((v,A)=>t.bloques[A]?.tipo??""),a=i.map((v,A)=>t.bloques[A]?.marca??null),c=t.bloques.reduce((v,A)=>v+
425
+ Xs(A.tipo,A.bytes),0),l=c>0?t.entradaReal/c:0,d=i.map((v,A)=>Xs(s[A],v.bytes)*l),u=td(t.model,i.map(v=>v.clave)),p=nd(s),f=a.map((v,A)=>v?A:-1).filter(v=>v>=0);if(f.length===0){for(let v=0;v<i.length;v++)
426
+ n.tokensEntrada+=d[v],n.entradaUsd+=d[v]/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+=
427
+ n.tokensEntrada,this.acumulado.entradaUsd+=n.entradaUsd,this.acumulado.totalUsd+=n.totalUsd,n}let g=-1;for(let v of f){let A=p[v]-(Xu-1);for(let R=v;R>=0&&p[R]>=A;R--)if(this.cache.viva(u[R],t.at)){R>
428
+ g&&(g=R);break}}for(let v=0;v<=g;v++)this.cache.refrescar(u[v],t.at);let b=f[f.length-1];for(let v of f)v>g&&this.cache.escribir(u[v],t.at,a[v]);let h=0,k=this.hayPrevio&&t.at-this.atPrevio>_o[this.previoTtl]?
429
+ []:this.previo.slice(g+1,this.previoUltimoBp+1),x=0;for(let v=0;v<i.length;v++){let A=i[v],R=d[v];if(v<=g){n.tokensLeidos+=R,n.lecturaUsd+=R/1e3*o.lecturaPer1k;continue}if(v>b){n.tokensEntrada+=R,n.entradaUsd+=
430
+ R/1e3*o.inputPer1k;continue}for(;f[h]<v;)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<
431
+ 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.
399
432
  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.
400
433
  totalUsd+=n.totalUsd,this.acumulado.tokensLeidos+=n.tokensLeidos,this.acumulado.tokensEscritos+=n.tokensEscritos,this.acumulado.tokensEntrada+=n.tokensEntrada,this.acumulado.tokensInvalidados+=n.tokensInvalidados,
401
- this.acumulado.invalidacionUsd+=n.invalidacionUsd,n}};function yi(e){return e.map(t=>({clave:t.clave,bytes:t.bytes}))}var Ou=64,Bn=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??
402
- 0),r=(t.uso.input_tokens??0)+(t.uso.cache_read_input_tokens??0)+n;if(r<=0)return null;let o={bloques:bi(t.cuerpo),at:t.at,model:t.model,entradaReal:r,escritura1h:(t.uso.cache_creation?.ephemeral_1h_input_tokens??
403
- 0)>0};if(o.bloques.length===0)return null;let s=this.cadenaPara(this.clave(t),t.model),i=s.base.paso(o),a=s.v0.paso(o);return i.totalUsd<=0&&a.totalUsd<=0?null:{baselineUsd:i.totalUsd,politicaUsd:a.totalUsd}}clave(t){
434
+ this.acumulado.invalidacionUsd+=n.invalidacionUsd,n}};function ra(e){return e.map(t=>({clave:t.clave,bytes:t.bytes}))}var od=64,or=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??
435
+ 0),r=(t.uso.input_tokens??0)+(t.uso.cache_read_input_tokens??0)+n;if(r<=0)return null;let o={bloques:ta(t.cuerpo),at:t.at,model:t.model,entradaReal:r,escritura1h:(t.uso.cache_creation?.ephemeral_1h_input_tokens??
436
+ 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){
404
437
  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(
405
- "hex").slice(0,16)}\xB7${t.model}`}cachesDe(t){let n=this.cachesPorModelo.get(t);return n||(n={base:new Et,v0:new Et},this.cachesPorModelo.set(t,n)),n}cadenaPara(t,n){let r=this.cadenas.get(t);if(!r){
406
- let o=this.cachesDe(n);if(r={base:new Jt(s=>yi(s),o.base),v0:new Jt((s,i,a)=>vi("v0",s,i,a),o.v0),ultimoUso:0},this.cadenas.set(t,r),this.cadenas.size>Ou){let s=null,i=1/0;for(let[a,u]of this.cadenas)
407
- u.ultimoUso<i&&(i=u.ultimoUso,s=a);s!==null&&this.cadenas.delete(s);}}return r.ultimoUso=Date.now(),r}};var Lu="[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\
408
- oard/install and relaunch",Un=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,
438
+ "hex").slice(0,16)}\xB7${t.model}`}cachesDe(t){let n=this.cachesPorModelo.get(t);return n||(n={base:new Lt,v0:new Lt},this.cachesPorModelo.set(t,n)),n}cadenaPara(t,n){let r=this.cadenas.get(t);if(!r){
439
+ let o=this.cachesDe(n);if(r={base:new ln(i=>ra(i),o.base),v0:new ln((i,s,a)=>na("v0",i,s,a),o.v0),ultimoUso:0},this.cadenas.set(t,r),this.cadenas.size>od){let i=null,s=1/0;for(let[a,c]of this.cadenas)
440
+ c.ultimoUso<s&&(s=c.ultimoUso,i=a);i!==null&&this.cadenas.delete(i);}}return r.ultimoUso=Date.now(),r}};var id="[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\
441
+ oard/install and relaunch",ir=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,
409
442
  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(),
410
443
  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===
411
444
  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(
412
- "entitlements HTTP 401",Lu);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(
445
+ "entitlements HTTP 401",id);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(
413
446
  "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==
414
447
  "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,
415
448
  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\
416
- ing`));}};var eo="https://savings.bivelio.com",ie="https://savings.bivelio.com/dashboard/account",ot="https://savings.bivelio.com/dashboard/install",Mu=1e4,Nu=3e3,xi=6e4,$u=36e5,ju=7*86400,Bu=3e4,Uu=86400,Fu="B\
417
- VL";function to(e){return nt}function Vu(e){return Hr(e)?Object.keys(e.keys??{}).length===0:e.trim()===""}var Qr=e=>typeof e=="string"&&e.trim()!=="",Fn=e=>typeof e=="number"&&Number.
418
- isFinite(e);function zu(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let t=e;return Qr(t.jti)&&Qr(t.org_id)&&Qr(t.plan)&&Fn(t.seats)&&Fn(t.issued_at)&&Fn(t.expires_at)&&Fn(t.grace_days)&&
419
- t.grace_days>=0&&Array.isArray(t.features)&&t.features.every(n=>typeof n=="string")}function zn(e,t){try{let n=gt(typeof e=="string"?e:""),r=qt(n);if(r==="empty")return {ok:!1,shape:"empty",reason:"emp\
420
- ty"};if(r==="malformed")return {ok:!1,shape:"malformed",reason:"malformed"};let o=Ht(n,t);if(!o.ok||!o.payloadBytes)return {ok:!1,shape:"token",reason:Zt(o.reason??"bad signature")};let s=o.header?.typ;
421
- if(s!==Fu)return {ok:!1,shape:"token",reason:`not a license token (typ ${Zt(String(s??"none"))})`};let i;try{i=JSON.parse(new TextDecoder().decode(o.payloadBytes));}catch{return {ok:!1,shape:"token",reason:"\
422
- payload is not valid JSON"}}return zu(i)?{ok:!0,license:{token:n,payload:i}}:{ok:!1,shape:"token",reason:"license payload has the wrong field types"}}catch(n){return {ok:false,shape:"token",reason:`verifi\
423
- cation error: ${Zt(String(n))}`}}}function _t(e,t,n){return On(e,Math.floor(t/1e3),n)}var Tt=e=>e==="active"||e==="grace";function Zt(e,t=200){let n=e.replace(/[^\x20-\x7E]/g,"?");return n.length>t?`${n.
424
- slice(0,t)}...`:n}function qu(e){return `${Number((e/1e3).toFixed(3))} s`}function Hu(e){let t=e,n=typeof t?.message=="string"&&t.message!==""?t.message:String(e),r=t?.cause,o=r&&typeof r.code=="string"?
425
- r.code:r&&typeof r.message=="string"?r.message:void 0;return o?`${n} (${o})`:n}async function wi(e){let t=`${e.licenseServerUrl.replace(/\/+$/,"")}/api/license/current`,n=u=>e.serviceAccountKey?u.split(
426
- e.serviceAccountKey).join("[service key]"):u,r=new AbortController,o=false,s=setTimeout(()=>{o=true,r.abort();},e.timeoutMs);s.unref?.();let i=()=>r.abort();e.signal&&(e.signal.aborted?r.abort():e.signal.addEventListener(
427
- "abort",i,{once:true}));let a=u=>o?{kind:"unreachable",cause:`timed out after ${qu(e.timeoutMs)}`}:{kind:"unreachable",cause:Zt(n(`network error: ${Hu(u)}`))};try{let u=e.fetchImpl??globalThis.fetch,c;try{
428
- c=await u(t,{method:"GET",headers:{authorization:`Bearer ${e.serviceAccountKey}`,accept:"application/json"},signal:r.signal});}catch(f){return a(f)}if(c.status===401)return {kind:"key-unknown"};if(c.status===
429
- 404)return {kind:"no-license"};if(!c.ok)return {kind:"unreachable",cause:`HTTP ${c.status}`};let d;try{d=await c.json();}catch(f){return o||r.signal.aborted?a(f):{kind:"unreachable",cause:"unexpected res\
430
- ponse (no license token)"}}let l=d?.token;if(typeof l!="string"||l.trim()==="")return {kind:"unreachable",cause:"unexpected response (no license token)"};let p=zn(l,e.publicKey);return p.ok?{kind:"toke\
431
- n",license:p.license}:{kind:"not-verifying",reason:Zt(p.reason)}}catch(u){return a(u)}finally{clearTimeout(s),e.signal?.removeEventListener("abort",i);}}function Te(e){try{return new Date(e*1e3).toISOString().
432
- slice(0,10)}catch{return "an unknown date"}}var Xt=(e,t)=>e+t*Uu,Wu="WARNING: BIVELIO_LICENSE_KEY belongs to a different organization than BIVELIO_SERVICE_KEY and is ignored; the license of the service\
433
- key's organization is used. Unset BIVELIO_LICENSE_KEY or replace it with this organization's license key.",Ku=e=>`WARNING: the license served by savings.bivelio.com does not verify against this build\
434
- 's BiVelio key (${e}); starting with BIVELIO_LICENSE_KEY. Update @bivelio/savings-layer (npm i -g @bivelio/savings-layer).`;function Gu(e,t={}){switch(e){case "no-public-key":return "this build has no e\
449
+ ing`));}};var Co="https://savings.bivelio.com",de="https://savings.bivelio.com/dashboard/account",ft="https://savings.bivelio.com/dashboard/install",sd=1e4,ad=3e3,ia=6e4,cd=36e5,ld=7*86400,ud=3e4,dd=86400,pd="B\
450
+ VL";function Ao(e){return ut}function fd(e){return bo(e)?Object.keys(e.keys??{}).length===0:e.trim()===""}var To=e=>typeof e=="string"&&e.trim()!=="",sr=e=>typeof e=="number"&&Number.
451
+ isFinite(e);function md(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let t=e;return To(t.jti)&&To(t.org_id)&&To(t.plan)&&sr(t.seats)&&sr(t.issued_at)&&sr(t.expires_at)&&sr(t.grace_days)&&
452
+ t.grace_days>=0&&Array.isArray(t.features)&&t.features.every(n=>typeof n=="string")}function cr(e,t){try{let n=At(typeof e=="string"?e:""),r=rn(n);if(r==="empty")return {ok:!1,shape:"empty",reason:"emp\
453
+ 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;
454
+ if(i!==pd)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:"\
455
+ payload is not valid JSON"}}return md(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\
456
+ cation error: ${dn(String(n))}`}}}function Mt(e,t,n){return Xn(e,Math.floor(t/1e3),n)}var $t=e=>e==="active"||e==="grace";function dn(e,t=200){let n=e.replace(/[^\x20-\x7E]/g,"?");return n.length>t?`${n.
457
+ slice(0,t)}...`:n}function hd(e){return `${Number((e/1e3).toFixed(3))} s`}function gd(e){let t=e,n=typeof t?.message=="string"&&t.message!==""?t.message:String(e),r=t?.cause,o=r&&typeof r.code=="string"?
458
+ 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(
459
+ 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(
460
+ "abort",s,{once:true}));let a=c=>o?{kind:"unreachable",cause:`timed out after ${hd(e.timeoutMs)}`}:{kind:"unreachable",cause:dn(n(`network error: ${gd(c)}`))};try{let c=e.fetchImpl??globalThis.fetch,l;try{
461
+ 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===
462
+ 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\
463
+ 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=cr(u,e.publicKey);return p.ok?{kind:"toke\
464
+ 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().
465
+ slice(0,10)}catch{return "an unknown date"}}var pn=(e,t)=>e+t*dd,bd="WARNING: BIVELIO_LICENSE_KEY belongs to a different organization than BIVELIO_SERVICE_KEY and is ignored; the license of the service\
466
+ key's organization is used. Unset BIVELIO_LICENSE_KEY or replace it with this organization's license key.",vd=e=>`WARNING: the license served by savings.bivelio.com does not verify against this build\
467
+ 's BiVelio key (${e}); starting with BIVELIO_LICENSE_KEY. Update @bivelio/savings-layer (npm i -g @bivelio/savings-layer).`;function yd(e,t={}){switch(e){case "no-public-key":return "this build has no e\
435
468
  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\
436
- _KEY is not set. The gateway needs two things and does not start without them: an active BiVelio subscription (${ie}) and its service key (bvk_..., created at ${ot}, step 2). Export the key and relaun\
469
+ _KEY is not set. The gateway needs two things and does not start without them: an active BiVelio subscription (${de}) and its service key (bvk_..., created at ${ft}, step 2). Export the key and relaun\
437
470
  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\
438
- t looks like a license key: that one goes in BIVELIO_LICENSE_KEY.":"")+` Create a service key at ${ot} (step 2), export it and relaunch.`;case "service-key-not-recognised":return `BIVELIO_SERVICE_KEY is\
439
- not recognised by savings.bivelio.com (HTTP 401): it was deleted or rotated, or it was copied incompletely. Create a new one at ${ot} (step 2), export it and relaunch.`;case "no-license":return `your o\
440
- rganization has no active BiVelio license, and the gateway does not start without one: there is no free tier. Subscribe at ${ie} and relaunch; the license is collected automatically with your service \
441
- key.`;case "license-expired":{let n=t.expiresAt??0;return `your BiVelio license expired on ${Te(n)} and its grace period ended on ${Te(Xt(n,t.graceDays??0))}. Renew at ${ie} and relaunch.`+(t.cause?` (s\
471
+ t looks like a license key: that one goes in BIVELIO_LICENSE_KEY.":"")+` Create a service key at ${ft} (step 2), export it and relaunch.`;case "service-key-not-recognised":return `BIVELIO_SERVICE_KEY is\
472
+ not recognised by savings.bivelio.com (HTTP 401): it was deleted or rotated, or it was copied incompletely. Create a new one at ${ft} (step 2), export it and relaunch.`;case "no-license":return `your o\
473
+ rganization has no active BiVelio license, and the gateway does not start without one: there is no free tier. Subscribe at ${de} and relaunch; the license is collected automatically with your service \
474
+ 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 ${de} and relaunch.`+(t.cause?` (s\
442
475
  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\
443
476
  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.`:
444
477
  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\
445
- s in BIVELIO_SERVICE_KEY; the license key is the other value on ${ot}. Or unset BIVELIO_LICENSE_KEY: the gateway collects the license online by itself.`:`BIVELIO_LICENSE_KEY does not verify against th\
446
- is build's BiVelio key (${n}). Copy the WHOLE key again from ${ot}, or unset BIVELIO_LICENSE_KEY to collect it online; if it persists, update @bivelio/savings-layer or write to support@bivelio.com.`}case "\
478
+ s in BIVELIO_SERVICE_KEY; the license key is the other value on ${ft}. Or unset BIVELIO_LICENSE_KEY: the gateway collects the license online by itself.`:`BIVELIO_LICENSE_KEY does not verify against th\
479
+ is build's BiVelio key (${n}). Copy the WHOLE key again from ${ft}, or unset BIVELIO_LICENSE_KEY to collect it online; if it persists, update @bivelio/savings-layer or write to support@bivelio.com.`}case "\
447
480
  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\
448
- savings.bivelio.com is down, export BIVELIO_LICENSE_KEY=<your license key> (from ${ot}) as a fallback: it is verified on this machine and used only when savings.bivelio.com cannot be reached, and it \
449
- must be replaced by hand every billing period.`}}function ki(e,t,n,r){let o=e.plan.toUpperCase(),s=e.grace_days,i=Te(e.expires_at),a=t==="online"?"collected with your service key and verified on this \
450
- 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 u=Te(Xt(e.expires_at,s));
451
- return `license: ${o}, IN GRACE: expired on ${i}, keeps working until ${u}. Renew at ${ie} (${a})`}return `license: ${o}, active until ${i} (+${s} ${s===1?"day":"days"} grace), ${a}`}var _e=(e,t)=>({ok:false,
452
- code:e,message:Gu(e,t)});async function Si(e){let t=e.now??Date.now,n=to();if(Vu(n))return _e("no-public-key");let r=e.serviceAccountKey?.trim();if(!r)return _e("service-key-missing");if(!r.
453
- startsWith("bvk_"))return _e("service-key-malformed",{keyLooksLikeLicense:qt(gt(r))==="token"});let o=null;if(e.licenseKey!==void 0){let u=zn(e.licenseKey,n);if(u.ok)o=u.license;else if(u.shape!=="emp\
454
- ty")return _e("license-invalid",{tokenSource:"BIVELIO_LICENSE_KEY",shape:u.shape,reason:u.reason})}let s=o!==null&&Tt(_t(o.payload,t())),i=await wi({licenseServerUrl:e.licenseServerUrl,serviceAccountKey:r,
455
- publicKey:n,timeoutMs:e.timeoutMs??(s?Nu:Mu),...e.fetchImpl?{fetchImpl:e.fetchImpl}:{}}),a=(u,c)=>{let d=_t(o.payload,t());return Tt(d)?{ok:true,license:o,source:"offline",status:d,line:ki(o.payload,"of\
456
- fline",d,u),lineIsWarning:true,warnings:c}:_e("license-expired",{expiresAt:o.payload.expires_at,graceDays:o.payload.grace_days,...u?{cause:u}:{}})};switch(i.kind){case "key-unknown":return _e("service-ke\
457
- y-not-recognised");case "no-license":return _e("no-license");case "token":{let u=i.license,c=_t(u.payload,t()),d=o&&o.payload.org_id!==u.payload.org_id?[Wu]:[];return Tt(c)?{ok:true,license:u,source:"onli\
458
- ne",status:c,line:ki(u.payload,"online",c),lineIsWarning:c==="grace",warnings:d}:_e("license-expired",{expiresAt:u.payload.expires_at,graceDays:u.payload.grace_days})}case "not-verifying":return s?a(void 0,
459
- [Ku(i.reason)]):_e("license-invalid",{tokenSource:"savings.bivelio.com",reason:i.reason});case "unreachable":return o?a(i.cause,[]):_e("unreachable",{cause:i.cause})}}var Ju=new Set(["expired","revoked",
460
- "no-license","blocked","invalid"]);function no(e,t,n){let r=typeof t=="string"?t.trim():"";if(r!==""){let s="reported by savings.bivelio.com";return r==="license-revoked"?{serve:false,state:"revoked",detail:s}:
461
- r==="license-expired"?{serve:false,state:"expired",detail:s}:r==="no-license"?{serve:false,state:"no-license",detail:s}:{serve:false,state:"blocked",detail:s}}let o=e.status();return o==="active"||o==="grace"?
462
- {serve:true,state:o}:o==="expired"?{serve:false,state:"expired",detail:n?`grace period ended ${Te(Xt(n.expires_at,n.grace_days))}`:"grace period ended"}:o==="revoked"?{serve:false,state:"revoked",detail:"lice\
463
- nse id revoked"}:{serve:false,state:"invalid",detail:"license no longer verifies"}}var Yt="requests already in flight were not interrupted";function Yu(e){switch(e){case "expired":return `bvsala gateway: t\
464
- he BiVelio license for this organization has expired. New requests are refused until it is renewed at ${ie}; ${Yt}.`;case "revoked":return `bvsala gateway: the BiVelio license for this organization is n\
465
- o longer active (revoked or cancelled). New requests are refused; ${Yt}. Check ${ie} or write to support@bivelio.com.`;case "no-license":return `bvsala gateway: this organization has no active BiVelio l\
466
- icense. New requests are refused until you subscribe at ${ie}; ${Yt}.`;case "blocked":return `bvsala gateway: savings.bivelio.com reports the BiVelio license for this organization as not active. New req\
467
- uests are refused; ${Yt}. Check ${ie}.`;case "invalid":return `bvsala gateway: the license loaded by this gateway no longer verifies. New requests are refused; ${Yt}. Relaunch the terminal; if it persis\
468
- ts, write to support@bivelio.com.`}}function Ei(e){return JSON.stringify({type:"error",error:{type:"license_error",status:e,message:Yu(e)}})}var Zu={expired:`Renew at ${ie}`,revoked:`Check ${ie} or wr\
469
- ite to support@bivelio.com`,"no-license":`Subscribe at ${ie}`,blocked:`Check ${ie}`,invalid:"Relaunch the terminal; if it persists, write to support@bivelio.com"};function _i(e,t,n){if(!t.serve)return e===
470
- t.state?null:`[bvsala gateway] license ${t.state} (${t.detail}): new requests are refused with HTTP 402; requests in flight are not touched. ${Zu[t.state]}`;let r=Te(n.expires_at),o=Te(Xt(n.expires_at,
471
- n.grace_days));return e!==null&&Ju.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 ${ie}`:`[bvsala g\
472
- 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 ${ie}`:
473
- null}function ro(e,t,n,r){return {license:e,gate:Ln(e.token,t,{revocation:n,...r?{now:r}:{}})}}var Vn=class{constructor(t){this.o=t;}o;timer=null;enVuelo=false;parado=false;ctrl=null;avisados=new Set;ahora(){
474
- return this.o.now?this.o.now():Date.now()}start(t={}){this.parado||this.timer!==null||(this.timer=setInterval(()=>{this.check();},this.o.intervalMs??$u),this.timer.unref?.(),t.checkNow&&this.check({force:true}));}stop(){
481
+ savings.bivelio.com is down, export BIVELIO_LICENSE_KEY=<your license key> (from ${ft}) as a fallback: it is verified on this machine and used only when savings.bivelio.com cannot be reached, and it \
482
+ must be replaced by hand every billing period.`}}function oa(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 \
483
+ 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));
484
+ return `license: ${o}, IN GRACE: expired on ${s}, keeps working until ${c}. Renew at ${de} (${a})`}return `license: ${o}, active until ${s} (+${i} ${i===1?"day":"days"} grace), ${a}`}var Oe=(e,t)=>({ok:false,
485
+ code:e,message:yd(e,t)});async function aa(e){let t=e.now??Date.now,n=Ao();if(fd(n))return Oe("no-public-key");let r=e.serviceAccountKey?.trim();if(!r)return Oe("service-key-missing");if(!r.
486
+ startsWith("bvk_"))return Oe("service-key-malformed",{keyLooksLikeLicense:rn(At(r))==="token"});let o=null;if(e.licenseKey!==void 0){let c=cr(e.licenseKey,n);if(c.ok)o=c.license;else if(c.shape!=="emp\
487
+ ty")return Oe("license-invalid",{tokenSource:"BIVELIO_LICENSE_KEY",shape:c.shape,reason:c.reason})}let i=o!==null&&$t(Mt(o.payload,t())),s=await sa({licenseServerUrl:e.licenseServerUrl,serviceAccountKey:r,
488
+ publicKey:n,timeoutMs:e.timeoutMs??(i?ad:sd),...e.fetchImpl?{fetchImpl:e.fetchImpl}:{}}),a=(c,l)=>{let d=Mt(o.payload,t());return $t(d)?{ok:true,license:o,source:"offline",status:d,line:oa(o.payload,"of\
489
+ fline",d,c),lineIsWarning:true,warnings:l}:Oe("license-expired",{expiresAt:o.payload.expires_at,graceDays:o.payload.grace_days,...c?{cause:c}:{}})};switch(s.kind){case "key-unknown":return Oe("service-ke\
490
+ y-not-recognised");case "no-license":return Oe("no-license");case "token":{let c=s.license,l=Mt(c.payload,t()),d=o&&o.payload.org_id!==c.payload.org_id?[bd]:[];return $t(l)?{ok:true,license:c,source:"onli\
491
+ ne",status:l,line:oa(c.payload,"online",l),lineIsWarning:l==="grace",warnings:d}:Oe("license-expired",{expiresAt:c.payload.expires_at,graceDays:c.payload.grace_days})}case "not-verifying":return i?a(void 0,
492
+ [vd(s.reason)]):Oe("license-invalid",{tokenSource:"savings.bivelio.com",reason:s.reason});case "unreachable":return o?a(s.cause,[]):Oe("unreachable",{cause:s.cause})}}var kd=new Set(["expired","revoked",
493
+ "no-license","blocked","invalid"]);function Ro(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}:
494
+ 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"?
495
+ {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\
496
+ nse id revoked"}:{serve:false,state:"invalid",detail:"license no longer verifies"}}var un="requests already in flight were not interrupted";function xd(e){switch(e){case "expired":return `bvsala gateway: t\
497
+ he BiVelio license for this organization has expired. New requests are refused until it is renewed at ${de}; ${un}.`;case "revoked":return `bvsala gateway: the BiVelio license for this organization is n\
498
+ o longer active (revoked or cancelled). New requests are refused; ${un}. Check ${de} or write to support@bivelio.com.`;case "no-license":return `bvsala gateway: this organization has no active BiVelio l\
499
+ icense. New requests are refused until you subscribe at ${de}; ${un}.`;case "blocked":return `bvsala gateway: savings.bivelio.com reports the BiVelio license for this organization as not active. New req\
500
+ uests are refused; ${un}. Check ${de}.`;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\
501
+ ts, write to support@bivelio.com.`}}function ca(e){return JSON.stringify({type:"error",error:{type:"license_error",status:e,message:xd(e)}})}var wd={expired:`Renew at ${de}`,revoked:`Check ${de} or wr\
502
+ ite to support@bivelio.com`,"no-license":`Subscribe at ${de}`,blocked:`Check ${de}`,invalid:"Relaunch the terminal; if it persists, write to support@bivelio.com"};function la(e,t,n){if(!t.serve)return e===
503
+ t.state?null:`[bvsala gateway] license ${t.state} (${t.detail}): new requests are refused with HTTP 402; requests in flight are not touched. ${wd[t.state]}`;let r=Re(n.expires_at),o=Re(pn(n.expires_at,
504
+ n.grace_days));return e!==null&&kd.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 ${de}`:`[bvsala g\
505
+ 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 ${de}`:
506
+ null}function Io(e,t,n,r){return {license:e,gate:Qn(e.token,t,{revocation:n,...r?{now:r}:{}})}}var ar=class{constructor(t){this.o=t;}o;timer=null;enVuelo=false;parado=false;ctrl=null;avisados=new Set;ahora(){
507
+ return this.o.now?this.o.now():Date.now()}start(t={}){this.parado||this.timer!==null||(this.timer=setInterval(()=>{this.check();},this.o.intervalMs??cd),this.timer.unref?.(),t.checkNow&&this.check({force:true}));}stop(){
475
508
  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.
476
- enVuelo||this.parado)return false;let n=this.o.current(),r=Tt(_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??
477
- ju))return false;this.enVuelo=true;let s=new AbortController;this.ctrl=s;try{let i=await wi({licenseServerUrl:this.o.licenseServerUrl,serviceAccountKey:this.o.serviceAccountKey,publicKey:this.o.publicKey,timeoutMs:this.
478
- o.timeoutMs??Bu,signal:s.signal,...this.o.fetchImpl?{fetchImpl:this.o.fetchImpl}:{}});if(this.parado)return !1;let a=Te(Xt(n.payload.expires_at,n.payload.grace_days));switch(i.kind){case "token":{let u=i.
479
- license.payload,c=this.o.revocation.snapshot();if(u.jti===n.payload.jti||this.o.revocation.has(u.jti)||!Tt(_t(u,this.ahora(),c)))return !1;let d=Tt(_t(n.payload,this.ahora(),c)),l=u.org_id!==n.payload.
480
- org_id,p=u.expires_at>n.payload.expires_at;return !l&&!p&&d?!1:(this.o.onAdopt(i.license),!0)}case "key-unknown":return this.avisar("key-unknown",`[bvsala gateway] license renewal: BIVELIO_SERVICE_KEY i\
481
- s no longer recognised (HTTP 401). This session keeps its current license until ${a}; create a new key at ${ot} and relaunch.`),!1;case "no-license":return this.avisar("no-license",`[bvsala gateway] li\
482
- 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 ${ie}.`),!1;case "not-verifying":
483
- return this.avisar(`not-verifying:${i.reason}`,`[bvsala gateway] license renewal: the license served by savings.bivelio.com does not verify against this build's BiVelio key (${i.reason}); update @bive\
484
- lio/savings-layer.`),!1;case "unreachable":return !1}return !1}catch{return false}finally{this.ctrl===s&&(this.ctrl=null),this.enVuelo=false;}}};function Ti(e){let t=0,n=0;for(;;){let s=e.indexOf('"input_schema"',n);if(s<0)break;t+=1,n=s+14;}let r=0;for(n=0;;){let s=e.indexOf('"tool_reference"',n);if(s<0)break;r+=1,n=s+16;}let o=e.match(/"defer_loading"\s*:\s*true/g)?.
485
- length??0;return {definiciones:t,referencias:r,diferidas:o}}var Xu=40;function Ri(e){return e.referencias>0||(e.diferidas??0)>0||e.definiciones<Xu?null:`[bvsala gateway] your client sends ${e.definiciones}\
509
+ enVuelo||this.parado)return false;let n=this.o.current(),r=$t(Mt(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??
510
+ ld))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.
511
+ o.timeoutMs??ud,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.
512
+ license.payload,l=this.o.revocation.snapshot();if(c.jti===n.payload.jti||this.o.revocation.has(c.jti)||!$t(Mt(c,this.ahora(),l)))return !1;let d=$t(Mt(n.payload,this.ahora(),l)),u=c.org_id!==n.payload.
513
+ 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\
514
+ s no longer recognised (HTTP 401). This session keeps its current license until ${a}; create a new key at ${ft} and relaunch.`),!1;case "no-license":return this.avisar("no-license",`[bvsala gateway] li\
515
+ 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 ${de}.`),!1;case "not-verifying":
516
+ 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\
517
+ lio/savings-layer.`),!1;case "unreachable":return !1}return !1}catch{return false}finally{this.ctrl===i&&(this.ctrl=null),this.enVuelo=false;}}};function ua(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)?.
518
+ length??0;return {definiciones:t,referencias:r,diferidas:o}}var Sd=40;function da(e){return e.referencias>0||(e.diferidas??0)>0||e.definiciones<Sd?null:`[bvsala gateway] your client sends ${e.definiciones}\
486
519
  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\
487
- 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 oo=5*1024*1024,el=["authorization","x-api-key","anthropic-version","anthropic-beta","api-key","openai-organization","openai-project"];function Ii(e,t,n,r=""){return createHash(
520
+ 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 Po=5*1024*1024,_d=["authorization","x-api-key","anthropic-version","anthropic-beta","api-key","openai-organization","openai-project"];function pa(e,t,n,r=""){return createHash(
488
521
  "sha256").update(e).update(`
489
522
  `).update(t).update(`
490
523
  `).update(r).update(`
491
- `).update(n).digest("hex")}function Ai(e){return el.map(t=>`${t}=${e(t)??""}`).join(`
492
- `)}var qn=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=[],
493
- s=0,i=false;return {capturar:a=>{if(!i){if(s+=a.length,s>oo){i=true,o.length=0;return}o.push(a);}},terminar:(a,u,c)=>{let d=!i&&a>=200&&a<300;this.enVuelo.get(t)?.resolver(d?{status:a,headers:u,chunks:o,...c?
494
- {primaria:c}:{}}: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;
495
- return r&&(this.gemelas+=1),r}tieneEnVuelo(t){return this.enVuelo.has(t)}};var Ci={openai:"https://api.openai.com",anthropic:"https://api.anthropic.com"};function Di(e){let t;try{t=new URL(e).origin;}catch{return false}return Object.values(Ci).includes(t)}function Pi(e){for(let t=0;t<
496
- 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 tl(e){
497
- 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 Oi(e){if(e.flag===
524
+ `).update(n).digest("hex")}function fa(e){return _d.map(t=>`${t}=${e(t)??""}`).join(`
525
+ `)}var lr=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=[],
526
+ i=0,s=false;return {capturar:a=>{if(!s){if(i+=a.length,i>Po){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?
527
+ {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;
528
+ return r&&(this.gemelas+=1),r}tieneEnVuelo(t){return this.enVuelo.has(t)}};var ma={openai:"https://api.openai.com",anthropic:"https://api.anthropic.com"};function ha(e){let t;try{t=new URL(e).origin;}catch{return false}return Object.values(ma).includes(t)}function ga(e){for(let t=0;t<
529
+ 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 Td(e){
530
+ 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 ba(e){if(e.flag===
498
531
  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&&
499
- e.env.trim()!=="")t=e.env,n="env";else return {ok:true,upstream:void 0,origen:"none"};let r=Ci[t.trim().toLowerCase()];if(r!==void 0)return {ok:true,upstream:r,origen:n};let o={ok:false,error:`[bvsala gateway]\
500
- invalid upstream ${tl(t)}: use openai, anthropic or an http(s) origin URL`},s;try{s=new URL(t.trim());}catch{return o}return s.protocol!=="http:"&&s.protocol!=="https:"?o:s.pathname!=="/"||s.search!==
501
- ""||s.hash!==""?{ok:true,upstream:s.origin,origen:n,aviso:`[bvsala gateway] WARNING: the upstream path "${s.pathname}" is ignored: requests keep the path the client sends (for example /v1/chat/completio\
502
- ns), so put that prefix in the client's base URL instead.`}:{ok:true,upstream:s.origin,origen:n}}var Li=4096;function Mi(e){let t={marcas:0,de1h:0,deOtroTtl:0,enLaCola:false,herramientaDeServidor:false};return lr(e,(n,r)=>{t.marcas++,n.ttl==="1h"?t.de1h++:t.deOtroTtl++,(r==="raiz"||r==="ultimoMensaje")&&
503
- (t.enLaCola=true);}),t.herramientaDeServidor=ur(e),t}function Ni(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==
504
- "string"&&n.startsWith("claude-cli/")}var $i=e=>e.cache_creation_input_tokens??(e.cache_creation?.ephemeral_5m_input_tokens??0)+(e.cache_creation?.ephemeral_1h_input_tokens??0);function ji(e){if((e.cache_read_input_tokens??
505
- 0)===0&&$i(e)===0&&(e.input_tokens??0)>=Li)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 Bi(e){let{vista:t,uso:n,
506
- ttlReescritoPorLaCapa:r}=e;if(t.marcas===0)return null;if((n.cache_read_input_tokens??0)===0&&$i(n)===0&&t.enLaCola&&(n.input_tokens??0)>=Li)return "cacheIgnorada";let s=n.cache_creation;return !r&&t.de1h>
507
- 0&&t.deOtroTtl===0&&!t.herramientaDeServidor&&s!==void 0&&(s.ephemeral_1h_input_tokens??0)===0&&(s.ephemeral_5m_input_tokens??0)>0?"ttlAcortado":null}function so(e,t){let n=`[gateway] degraded traffic${t.
532
+ e.env.trim()!=="")t=e.env,n="env";else return {ok:true,upstream:void 0,origen:"none"};let r=ma[t.trim().toLowerCase()];if(r!==void 0)return {ok:true,upstream:r,origen:n};let o={ok:false,error:`[bvsala gateway]\
533
+ invalid upstream ${Td(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!==
534
+ ""||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\
535
+ ns), so put that prefix in the client's base URL instead.`}:{ok:true,upstream:i.origin,origen:n}}var Cd="other reasons",ur=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:Cd;this.noMedidas.
536
+ set(n,(this.noMedidas.get(n)??0)+1);}estado(){return {medidas:this.medidas,replicas:this.replicas,noMedidas:Object.fromEntries(this.noMedidas)}}};function va(e,t){let n=`[bvsala ${t}] metering in this r\
537
+ 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\
538
+ 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\
539
+ 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(
540
+ "; ");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",Oo="x-bvsala-request-id",Ad="/_bvsala/",Rd="bvsala.gateway.report/1",ya="bvsala.gateway.status/1";var dr=/^[A-Za-z0-9._:-]{1,200}$/;function ka(e){let t=(Array.isArray(e)?e[0]:e)?.trim().toLowerCase();return t==="1"||t==="true"}var pr=class{entradas=new Map;porRespuestaId=new Map;oyentes=new Set;capacidad;now;constructor(t={}){
541
+ 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>=
542
+ this.capacidad;){let r=this.entradas.keys().next().value;if(r===void 0)break;this.quitar(r);}this.entradas.set(t,{informe:{schema:Rd,requestId:t,responseId:null,path:n,status:"pending",reason:null,report:null},
543
+ abiertaMs:this.now()}),this.avisar();}anotarRespuesta(t,n){let r=this.entradas.get(t);!r||r.informe.responseId!==null||!n||!dr.test(n)||(r.informe.responseId=n,this.porRespuestaId.set(n,t),this.avisar());}medido(t,n){
544
+ 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.
545
+ 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=()=>{
546
+ 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){
547
+ 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);
548
+ 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;
549
+ this.quitar(n);}}avisar(){for(let t of [...this.oyentes])t();}};function xa(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==
550
+ "string"&&dr.test(n))return n;return null}function Lo(e){try{return xa(JSON.parse(e.toString("utf8")))}catch{return null}}var fr=class{resto="";leidos=0;id=null;observar(t){if(this.id!==null||this.leidos>
551
+ 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(`
552
+ `))>=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=xa(JSON.parse(i));
553
+ if(s!==null){this.id=s,this.resto="";return}}catch{}}this.leidos>262144&&(this.resto="");}valor(){return this.id}};function wa(e){try{return new URL(e).origin}catch{return "unknown"}}function Sa(e){let t;
554
+ try{t=new URL(e??"/","http://127.0.0.1");}catch{return null}return t.pathname.startsWith(Ad)?t:null}var Id=new Set(["127.0.0.1","localhost","[::1]"]);function Pd(e){if(e===void 0||e==="")return true;let t;
555
+ try{t=new URL(`http://${e}`).hostname.toLowerCase();}catch{return false}return Id.has(t)}function Do(e,t,n){e.writeHead(t,{"content-type":"application/json","cache-control":"no-store"}),e.end(JSON.stringify(
556
+ n));}function mt(e,t,n,r){Do(e,t,{type:"error",error:{type:n,message:r}});}async function Ea(e,t,n,r){if(e.resume(),!Pd(e.headers.host)){mt(t,403,"forbidden","bvsala gateway: local routes answer only to\
557
+ 127.0.0.1 or localhost");return}if(e.method!=="GET"){t.setHeader("allow","GET"),mt(t,405,"method_not_allowed","bvsala gateway: local routes only answer GET");return}if(n.pathname==="/_bvsala/v1/statu\
558
+ s"){Do(t,200,r.estado());return}let o=Number(n.searchParams.get("wait_ms")??"0");if(!Number.isFinite(o)||o<0){mt(t,400,"invalid_request","bvsala gateway: wait_ms must be a non-negative number of milli\
559
+ 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(
560
+ l[1]);}catch{u="";}if(!dr.test(u)){mt(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"){
561
+ let u=n.searchParams.get("response_id")??"";if(!dr.test(u)){mt(t,400,"invalid_request","bvsala gateway: pass ?response_id=<the id of the provider's response>");return}a=()=>r.buzon.porRespuesta(u),c=`\
562
+ response id ${u}`;}if(a===null){mt(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){mt(t,404,"not_found",
563
+ `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}Do(
564
+ t,200,d);}}var _a=4096;function Ta(e){let t={marcas:0,de1h:0,deOtroTtl:0,enLaCola:false,herramientaDeServidor:false};return $r(e,(n,r)=>{t.marcas++,n.ttl==="1h"?t.de1h++:t.deOtroTtl++,(r==="raiz"||r==="ultimoMensaje")&&
565
+ (t.enLaCola=true);}),t.herramientaDeServidor=Mr(e),t}function Ca(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==
566
+ "string"&&n.startsWith("claude-cli/")}var Aa=e=>e.cache_creation_input_tokens??(e.cache_creation?.ephemeral_5m_input_tokens??0)+(e.cache_creation?.ephemeral_1h_input_tokens??0);function Ra(e){if((e.cache_read_input_tokens??
567
+ 0)===0&&Aa(e)===0&&(e.input_tokens??0)>=_a)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 Ia(e){let{vista:t,uso:n,
568
+ ttlReescritoPorLaCapa:r}=e;if(t.marcas===0)return null;if((n.cache_read_input_tokens??0)===0&&Aa(n)===0&&t.enLaCola&&(n.input_tokens??0)>=_a)return "cacheIgnorada";let i=n.cache_creation;return !r&&t.de1h>
569
+ 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 Mo(e,t){let n=`[gateway] degraded traffic${t.
508
570
  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 \
509
571
  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\
510
572
  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 \
511
573
  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\
512
574
  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 \
513
575
  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\
514
- y hand.`+r}var Hn=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??""}`;
576
+ y hand.`+r}var mr=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??""}`;
515
577
  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.
516
- cuentas}}};function io(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) \
578
+ cuentas}}};function Pa(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) \
517
579
  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\
518
- 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 Vi='[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\
519
- o the call (Node: stream_options: { include_usage: true }); its last chunk then has an empty choices list.',ol=Vi+" Or start the gateway with BVSALA_GATEWAY_USAGE_INJECT=1 to add it for clients you ca\
520
- nnot change.",sl=Vi+" 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.",il=e=>`[bvsala gateway] POST ${e} answe\
521
- red without the provider's final usage, so it was forwarded but NOT metered. Nothing is estimated in its place.`,al=e=>`[bvsala gateway] POST ${e} is forwarded but NOT metered: the gateway reads usage\
522
- from /v1/messages, \u2026/chat/completions and \u2026/responses only.`,Ui=/\/(count_tokens|input_tokens)$/,cl=["content-encoding","content-length","transfer-encoding"],ul=new Set(["connection","keep-\
523
- alive","proxy-connection","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","expect"]);function Rt(e){let t=e?.cause;if(t==null)return String(e);let n=t instanceof
524
- AggregateError&&t.errors.length>0?t.errors.map(r=>String(r)).join("; "):String(t);return `${String(e)} \xB7 cause: ${n}`}var ao=class extends Error{code;puerto;constructor(t,n,r){super(t==="EADDRINUSE"?
580
+ 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 La='[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\
581
+ o the call (Node: stream_options: { include_usage: true }); its last chunk then has an empty choices list.',Ld=La+" Or start the gateway with BVSALA_GATEWAY_USAGE_INJECT=1 to add it for clients you ca\
582
+ nnot change.",Md=La+" 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.",$d=e=>`[bvsala gateway] POST ${e} answe\
583
+ red without the provider's final usage, so it was forwarded but NOT metered. Nothing is estimated in its place.`,Nd=e=>`[bvsala gateway] POST ${e} is forwarded but NOT metered: the gateway reads usage\
584
+ from /v1/messages, \u2026/chat/completions and \u2026/responses only.`,Da=/\/(count_tokens|input_tokens)$/,jd=["content-encoding","content-length","transfer-encoding"],Bd=new Set(["connection","keep-\
585
+ alive","proxy-connection","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","expect"]);function Nt(e){let t=e?.cause;if(t==null)return String(e);let n=t instanceof
586
+ AggregateError&&t.errors.length>0?t.errors.map(r=>String(r)).join("; "):String(t);return `${String(e)} \xB7 cause: ${n}`}var $o=class extends Error{code;puerto;constructor(t,n,r){super(t==="EADDRINUSE"?
525
587
  `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",
526
- this.code=t,this.puerto=n;}};function Fi(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 ll(e){return e.writableFinished?
527
- Promise.resolve(true):e.destroyed?Promise.resolve(false):new Promise(t=>{let n=()=>o(true),r=()=>o(e.writableFinished),o=s=>{e.off("finish",n),e.off("close",r),t(s);};e.once("finish",n),e.once("close",r);})}async function zi(e){
528
- if(!e?.license)throw new Error("arrancarGateway: a verified BiVelio license is required (LICENSE section 2)");let t=to(e.license.publicKey),n=zn(e.license.token,t);if(!n.ok)throw new Error(`arrancarGa\
529
- teway: the license token does not verify (${n.reason})`);let r=(e.upstream??"https://api.anthropic.com").replace(/\/+$/,""),o=Di(r),s=e.fetchImpl??fetch,i=e.log??(m=>console.log(m)),a=e.warn??(m=>console.
530
- error(m)),u=e.license.now??Date.now,c=e.license.licenseServerUrl?.replace(/\/+$/,""),d=new bt,l=ro(n.license,t,d,u),p;if(e.serviceAccountKey){p=new ft({url:e.meteringUrl??"https://savings.bivelio.com/\
531
- api/metering/usage",serviceAccountKey:e.serviceAccountKey,surface:"gateway",...e.fetchImpl?{fetchImpl:e.fetchImpl}:{},onAuthError:x=>z("gateway-ingest-auth",`[bvsala gateway] the usage ingest is rejec\
532
- ting the credential (${x}). 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.`)});
533
- let m=mn();e.seatId?p.setSeat(e.seatId,m):hn(e.serviceAccountKey).then(x=>p?.setSeat(x,m)).catch(()=>{}),p.start();}else z("gateway-sin-clave","[bvsala gateway] no BIVELIO_SERVICE_KEY: this in-process \
534
- gateway forwards traffic but does not meter it (the bvsala CLI refuses to start without the key).");let f=e.coalescer?new qn:null,g=e.sombra&&p?new Bn:null,y=new dn,h=new Hn,b=e.serviceAccountKey?new Un(
535
- {url:c?`${c}/api/org/entitlements`:new URL("/api/org/entitlements",e.meteringUrl??"https://savings.bivelio.com/api/metering/usage").toString(),serviceAccountKey:e.serviceAccountKey,...e.fetchImpl?{fetchImpl:e.
536
- fetchImpl}:{},...e.entitlementsTtlMs!==void 0?{ttlMs:e.entitlementsTtlMs}:{},log:i}):null,w=b!==null&&e.elision!==false,_=()=>no(l.gate,b?.blockReason()??null,l.license.payload),v=null;{let m=no(l.gate,null,
537
- l.license.payload);m.serve&&(v=m.state);}let I=m=>{let x=_i(v,m,l.license.payload);v=m.state,x&&a(x);},A,C,P=Number.NEGATIVE_INFINITY,M=new Set,q=(m,x)=>{M.has(m)||(M.add(m),i(x));},J=false,S=m=>m==="/v1/me\
538
- ssages"?new rt:m.endsWith("/responses")?new xt:m.endsWith("/chat/completions")?new Kt:null,T=(m,x,j,N,U,B)=>{i(`[gateway] ${m} ${x} \u2192 ${j}${N?" (stream)":""} \xB7 not metered: ${U}`),e.avisosDeNoMedido!==
539
- false&&(B==="chat"&&z("gateway-chat-sin-include-usage",ol),B==="chat-con-inyeccion"&&z("gateway-chat-sin-include-usage-con-inyeccion",sl),B==="uso"&&z(`gateway-sin-usage:${x}`,il(x)),B==="dialecto"&&z(`g\
540
- ateway-sin-dialecto:${x}`,al(x)));},O=(m,x,j,N)=>{let U=m instanceof xt?m.estadoFinal():null;if(U!==null&&U!=="completed")return {motivo:`the response ended as response.${U} without usage`,aviso:"uso"};
541
- if(!(m instanceof Kt&&N!=="inyectado"&&ai(x,j)!==true))return {motivo:"the stream ended without the provider's final usage event",aviso:"uso"};let F="the request did not ask for usage (stream_options.inc\
542
- lude_usage)";return N==="rechazada-por-el-upstream"?{motivo:`${F}, and the upstream rejects that option`,aviso:null}:N==="comprimido"?{motivo:`${F}; usage injection skips compressed request bodies`,aviso:"\
543
- chat-con-inyeccion"}:N!==null?{motivo:F,aviso:"chat-con-inyeccion"}:{motivo:F,aviso:"chat"}},L=(m,x,j,N,U,B,F,k,V,ct,We,de,ke,je)=>{if(!p||!j)return;let Ke=p,At=j,se=ni(x,B),X=`[gateway] POST ${U}${N?
544
- " \xB7 COALESCED (call avoided)":""}`;if(!se){i(`${X} \xB7 not metered: could not read the model from the request body${B?` (content-encoding: ${B})`:""}`),z(`gateway-sin-modelo:${U}`,`[bvsala gateway\
545
- ] could not read the model from the ${U} request body (content-encoding: ${B??"none"}); its usage is forwarded but not metered.`);return}let xe=!N&&We?We.servido:se,W=ti(xe,j,ct);if(W){let pe=N?ui(se,
546
- W,ke,wt(x,B),{suscripcion:de===true,entregada:je?.entregada===true,tierServido:je?.tierServido}):null,Be=N?li(m,se,W,F,pe?.ok?pe.credit:null):ci(m,xe,W,F,k,V,We,de===true);p.record(Be);let K=Be.cost.eliminatedInputFloorCost;
547
- i(`[gateway] POST ${U} ${N?"\xB7 COALESCED (call avoided)":""} \xB7 ${xe!==se?`${se}\u2192${xe} (sibling model)`:se} \xB7 $${W.costeUsd.toFixed(6)} (in ${W.tokens.entrada}, cache\u2191${W.tokens.cacheEscrita}${W.
548
- tokens.cacheEscrita1h?` (1h ${W.tokens.cacheEscrita1h})`:""} cache\u2193${W.tokens.cacheLeida}, out ${W.tokens.salida})`+(k?` \xB7 elision: ${k.borrados} clear(s), ${k.tokensLimpiados} tok cleared by \
549
- the provider`+(K!==void 0?` \xB7 floor $${K.toFixed(6)} (cache read price)`:k.tokensLimpiadosToolUses>0?k.atribuible?" \xB7 no cache read price in the catalog: no floor":" \xB7 your own context_managemen\
550
- t settings: counted, not credited":k.tokensLimpiados>0?" \xB7 thinking only (your config): counted, not credited":""):"")+(de&&!N&&(V||We)?" \xB7 subscription traffic: lever applied, saving not credited \
551
- (no per-token invoice)":"")+(pe?pe.ok?` \xB7 by reference: floor $${Yr(pe.credit).toFixed(6)} (cache read price${pe.credit.creditedOutputTokens>0?`, ${pe.credit.creditedOutputTokens} output tok at tem\
552
- perature 0`:", no output credited"})`:` \xB7 estimated, not by reference: ${pe.reason}`:""));let D=k?.atribuible===true&&k.tokensLimpiadosToolUses>0;g&&!N&&U==="/v1/messages"&&setImmediate(()=>{try{let ge=wt(
553
- x,B);if(!ge||typeof ge!="object")return;let Ae=g.observar({cuerpo:ge,uso:At,model:se,at:ct??Date.now(),...F?.sessionId!==void 0?{sessionId:F.sessionId}:{},...F?.agentId!==void 0?{agentId:F.agentId}:{}});
554
- if(!Ae)return;if(D){i(`[gateway] shadow estimate \xB7 ${se} \xB7 the provider already cleared context via our settings: chain advances, nothing emitted`);return}Ke.record(di(`${m}:shadow`,se,Ae.baselineUsd,
555
- Ae.politicaUsd,F)),i(`[gateway] shadow estimate \xB7 ${se} \xB7 baseline $${Ae.baselineUsd.toFixed(6)} \u2192 with elision $${Ae.politicaUsd.toFixed(6)}`);}catch{}});}else i(`${X} \xB7 not metered: model "${xe}\
556
- " has no list price in the catalog`),z(`gateway-sin-precio:${xe}`,`[bvsala gateway] model "${xe}" is not in the price catalog; its usage is forwarded but not metered.`);},Y=(m,x,j,N,U,B)=>{if(!(m!=="/v\
557
- 1/messages"||N===null||!ji(N)||(j===void 0||j===""||j==="identity")&&!x.includes('"cache_control"')))try{let k=wt(x,j);if(k===null||typeof k!="object"||Array.isArray(k))return;let V=Bi({vista:Mi(k),uso:N,
558
- ttlReescritoPorLaCapa:U});V!==null&&h.anotar(V,B)&&i(so(V,{sesion:B,entrada:N.input_tokens??0,escrita5m:N.cache_creation?.ephemeral_5m_input_tokens??0}));}catch{}},H=createServer(async(m,x)=>{let j=randomUUID(),N=Date.now(),
559
- U=_();if(I(U),!U.serve){let K=u();C&&K-P>=xi&&(P=K,C.check({force:true})),m.resume(),x.writeHead(402,{"content-type":"application/json","cache-control":"no-store","x-bvsala-license-status":U.state}),x.end(
560
- m.method==="HEAD"?void 0:Ei(U.state));let D="/";try{D=new URL(m.url??"/","http://x").pathname;}catch{}i(`[gateway] ${m.method} ${D} \u2192 402 (license ${U.state})`);return}let B=new AbortController;x.
561
- on("close",()=>{x.writableEnded||B.abort();});let F=null,k=new URL(m.url??"/",r),V=null,ct=Buffer.alloc(0),We=false,de=null,ke=null,je=false,Ke=false,At=(K,D)=>{if(K===null||de===null||!de.nuestros)return K;let ge=D?.
562
- cache_creation,Ae=D?.cache_creation_input_tokens??(ge?.ephemeral_5m_input_tokens??0)+(ge?.ephemeral_1h_input_tokens??0),Ct=(D?.input_tokens??0)+(D?.cache_read_input_tokens??0)+Ae+K.tokensLimpiados,Dt=de.
563
- triggerDelCliente!==null&&Ct>=de.triggerDelCliente;return {...K,atribuible:!Dt}},se=m.headers["content-encoding"],X=Array.isArray(se)?se[0]:se,xe=K=>{let D=Array.isArray(K)?K[0]:K;return D!==void 0&&/^[A-Za-z0-9._:/-]{1,128}$/.
564
- test(D)?D:void 0},W=xe(m.headers["x-claude-code-session-id"]),pe=xe(m.headers["x-claude-code-agent-id"]),Be=W!==void 0||pe!==void 0?{...W!==void 0?{sessionId:W}:{},...pe!==void 0?{agentId:pe}:{}}:void 0;
565
- try{let K=[];for await(let E of m)K.push(E);let D=Buffer.concat(K);ct=D,k=new URL(m.url??"/",r);let ge=f!==null&&m.method==="POST"&&D.length>0,Ae=Ai(E=>{let R=m.headers[E];return Array.isArray(R)?R.join(
566
- ", "):R}),Ct=ge?Ii("POST",k.pathname+k.search,D,Ae):"";if(ge)if(f.tieneEnVuelo(Ct)){let E=await f.esperar(Ct);if(E){let R=B.signal.aborted||x.destroyed;R||x.writeHead(E.status,E.headers);let ae=S(k.pathname)??
567
- new rt;for(let Mt of E.chunks)R||x.write(Mt),ae.observar(Mt);R||x.end();let dt=R?!1:await ll(x),Ot=ae.usageFinal()??jn(k.pathname,Buffer.concat(E.chunks));if(Ot===null){if(p&&!Ui.test(k.pathname)){let Mt=String(
568
- E.headers["content-type"]??"").includes("text/event-stream");T(m.method??"POST",k.pathname,E.status,Mt,St(k.pathname)?Mt?O(ae,D,X,null).motivo:"the response carried no usage":"no usage dialect for thi\
569
- s route",null);}return}let Lt=m.headers["anthropic-beta"],Je=Jr(k.pathname,Array.isArray(Lt)?Lt.join(", "):Lt,r);L(j,D,Ot,!0,k.pathname,X,Be,null,null,N,null,Je,E.primaria??null,{entregada:dt,tierServido:si(
570
- k.pathname,Buffer.concat(E.chunks))});return}}else F=f.registrar(Ct);let Dt=m.headers.connection,ya=new Set((Array.isArray(Dt)?Dt.join(","):Dt??"").split(",").map(E=>E.trim().toLowerCase()).filter(E=>E!==
571
- "")),Ce={};for(let[E,R]of Object.entries(m.headers))E==="host"||E==="content-length"||R===void 0||ul.has(E)||ya.has(E)||(Ce[E]=Array.isArray(R)?R.join(", "):R);let Pt={...Ce};je=Jr(k.pathname,Pt["anth\
572
- ropic-beta"],r);let ce=D;if(w&&e.dialesElision===!0&&m.method==="POST"&&k.pathname==="/v1/messages"&&b.tiene("context_elision"))try{let E=Ao(D,X);E!==null&&(ce=E.cuerpo,de={nuestros:E.nuestros,triggerDelCliente:E.
573
- triggerDelCliente},Ce["anthropic-beta"]=Do(Ce["anthropic-beta"]));}catch{}if(m.method==="POST"&&k.pathname==="/v1/messages"&&(X??"")==="")try{let E=Ti(D.toString("utf8")),R=Ri(E);R&&(z("gateway-busqued\
574
- a-herramientas",R),Ni(m.headers)&&h.anotar("busquedaApagada",W)&&i(so("busquedaApagada",{sesion:W,definiciones:E.definiciones})));}catch{}let Eo=w&&e.modeloHermano===!0&&m.method==="POST"&&(k.pathname===
575
- "/v1/messages"||k.pathname==="/v1/messages/count_tokens");if(Eo&&!b.tiene("sibling_model_routing")&&z("gateway-hermano-sin-feature","[bvsala gateway] sibling model routing: the flag is set but your or\
576
- g's license does not include sibling_model_routing; the request is forwarded unchanged (fail-closed)."),Eo&&b.tiene("sibling_model_routing"))try{let R=qo(ce,ce===D?X:"identity",{betas:Ce["anthropic-be\
577
- ta"]});R!==null&&(ce=R.cuerpo,ke=R.cambio);}catch{}let rn=!1;if(w&&fr(e.esfuerzo)&&m.method==="POST"&&k.pathname==="/v1/messages"&&b.tiene("per_turn_effort"))try{let E=ce===D?X:"identity",R=$o(ce,e.esfuerzo,
578
- E);R!==null&&(ce=R.cuerpo,Ce["anthropic-beta"]=jo(Ce["anthropic-beta"]),rn=!0);}catch{}let ut=null;if(w&&m.method==="POST"&&k.pathname==="/v1/messages"&&b.tiene("cache_ttl_tuning"))try{let R=Ye(ce,ce===
579
- D?X:"identity");if(R!==null){let ae=Oo(R),dt=`${Be?.sessionId??"sin-sesion"}:${ae.system}`,Ot=Date.now(),Lt=y.ultima(dt,Ot);if(y.anotar(dt,ae,Ot),Mo({fraccionNueva:Lo(Lt,ae)})){let Je=No(R);Je!==null&&
580
- (ce=Je.cuerpo,ut={rebajadas:Je.rebajadas,yaEran5m:Je.yaEran5m,herramientaDeServidor:Je.herramientaDeServidor},Ke=!0);}}}catch{}let lt=!1,on=null;if(m.method==="POST"&&k.pathname.endsWith("/chat/complet\
581
- ions")&&p&&e.usageInject===!0)if(J)on="rechazada-por-el-upstream";else try{let E=ii(D,X);on=E.motivo,E.cuerpo&&(ce=E.cuerpo,lt=!0);}catch{}let $,Qn=ce,er=Ce;try{$=await s(k,{method:m.method,headers:Ce,
582
- body:["GET","HEAD"].includes(m.method??"")?void 0:ce,redirect:"manual",signal:B.signal});}catch(E){F?.abortar(),x.headersSent||(x.writeHead(502,{"content-type":"application/json"}),x.end(JSON.stringify(
583
- {error:"bvsala gateway: upstream unreachable",detail:Rt(E)}))),i(`[gateway] ${m.method} ${k.pathname} \u2192 upstream unreachable: ${Rt(E)}`);return}if(((Qn!==D||!Fi(er,Pt))&&$.status===400||lt&&($.status===
584
- 400||$.status===422))&&!B.signal.aborted){let E="";try{E=(await $.text()).slice(0,300).replace(/\s+/g," ");}catch{}let R=lt;i(R?`[gateway] the upstream rejected (${$.status}) the request with stream_op\
585
- tions.include_usage added; forwarding it unchanged \xB7 ${E}`:`[gateway] the upstream rejected (400) the rewritten request${ke?` to ${ke.servido}`:""}${rn?" (per-turn effort)":""}${ut?" (cache TTL)":""}${de?
586
- " (context editing dials)":""}; forwarding it unchanged \xB7 ${E}`),ke=null,rn=!1,ut=null,Ke=!1,de=null,lt=!1,R&&(on="rechazada-por-el-upstream"),Qn=D,er=Pt;try{$=await s(k,{method:m.method,headers:Pt,
587
- body:D,redirect:"manual",signal:B.signal});}catch(ae){F?.abortar(),x.headersSent||(x.writeHead(502,{"content-type":"application/json"}),x.end(JSON.stringify({error:"bvsala gateway: upstream unreachable",
588
- detail:Rt(ae)}))),i(`[gateway] ${m.method} ${k.pathname} \u2192 upstream unreachable on retry: ${Rt(ae)}`);return}R&&$.ok&&(J=!0,z("gateway-sin-stream-options","[bvsala gateway] the upstream rejects s\
589
- tream_options, so usage injection is off for the rest of this process: streamed /v1/chat/completions answers from it are forwarded but NOT metered (stream=false answers still are)."));}let tr=Object.fromEntries(
590
- $.headers.entries());for(let E of cl)delete tr[E];x.writeHead($.status,tr);let sn=$.headers.get("content-type")??"",an=sn.includes("text/event-stream")||sn===""&&$.ok&&S(k.pathname)!==null&&!k.pathname.
591
- endsWith("/chat/completions");V=an?S(k.pathname):null;let Ge=!an&&$.ok&&p!==void 0&&m.method==="POST"&&St(k.pathname)&&($.headers.get("content-type")??"").includes("application/json")?[]:null,_o=0,To=!1;
592
- if($.body)for await(let E of $.body){let R=Buffer.from(E);x.write(R),V?.observar(R),Ge&&(_o+=R.length,_o>oo?(Ge=null,To=!0):Ge.push(R)),F?.capturar(R);}if(x.end(),F){let E=ke===null&&!rn&&de===null&&!lt&&
593
- ut===null&&Qn===D&&Fi(er,Pt),R=Ge?Buffer.concat(Ge):null,ae=$.ok&&(V?V.usageFinal()!==null:R!==null&&jn(k.pathname,R)!==null),dt=V instanceof xt&&V.estadoFinal()==="failed"||R!==null&&oi(k.pathname,R);
594
- F.terminar($.status,tr,{requestId:j,at:Date.now(),intacta:E,proveedorOficial:o,conContador:ae,suscripcion:je,fallida:dt});}if(V&&$.ok){We=!0;let E=V.usageFinal();if(E===null&&p){let R=O(V,D,X,lt?"inyec\
595
- tado":on);T(m.method??"POST",k.pathname,$.status,!0,R.motivo,R.aviso);}else {let R=At(V instanceof rt?V.elision():null,E);L(j,D,E,!1,k.pathname,X,Be,R,ut,N,ke,je),Y(k.pathname,D,X,E,Ke,W);}p||i(`[gateway\
596
- ] ${m.method} ${k.pathname} \u2192 ${$.status} (stream) \xB7 not metered: no BIVELIO_SERVICE_KEY`);}else if(Ge){let E=Buffer.concat(Ge),R=jn(k.pathname,E);if(R===null)T(m.method??"POST",k.pathname,$.status,
597
- !1,"the response carried no usage","uso");else {let ae=k.pathname==="/v1/messages"?Xs(E):null;L(j,D,R,!1,k.pathname,X,Be,At(ae,R),ut,N,ke,je),Y(k.pathname,D,X,R,Ke,W);}}else To?T(m.method??"POST",k.pathname,
598
- $.status,!1,"the response was too large to read its usage",null):p&&m.method==="POST"&&$.ok&&St(k.pathname)?T(m.method,k.pathname,$.status,!1,`the response is neither JSON nor an event stream (content\
599
- -type: ${sn===""?"none":sn.slice(0,80)})`,null):p&&m.method==="POST"&&$.ok&&!St(k.pathname)&&!Ui.test(k.pathname)?T(m.method,k.pathname,$.status,an,"no usage dialect for this route",k.pathname.startsWith(
600
- "/v1/")?"dialecto":null):i(`[gateway] ${m.method} ${k.pathname} \u2192 ${$.status}${an?" (stream)":""}`);}catch(K){if(F?.abortar(),B.signal.aborted){let D=!We&&V?V.usageFinal():null;if(D){i(`[gateway] ${m.
601
- method} ${k.pathname} \u2192 client closed after the final usage; metered anyway`);let ge=At(V instanceof rt?V.elision():null,D);L(j,ct,D,false,k.pathname,X,Be,ge,void 0,N,ke,je),Y(k.pathname,ct,X,D,Ke,W);}else
602
- i(`[gateway] ${m.method} ${k.pathname} \u2192 client aborted; upstream cancelled`);}else if(i(`[gateway] ${m.method} ${k.pathname} \u2192 error while serving: ${Rt(K)}`),!x.headersSent){x.writeHead(502,
603
- {"content-type":"application/json"}),x.end(JSON.stringify({error:"bvsala gateway: stream interrupted",detail:Rt(K)}));return}x.writableEnded||x.end();}});H.on("upgrade",(m,x)=>{i(`[gateway] ${m.method}\
604
- ${new URL(m.url??"/","http://x").pathname} \u2192 426 (WebSocket not supported; the client falls back to HTTP)`),x.once("error",()=>{}),x.once("finish",()=>x.destroy()),x.end(`HTTP/1.1 426 Upgrade Re\
605
- quired\r
588
+ this.code=t,this.puerto=n;}};function Oa(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 Ud(e){return e.writableFinished?
589
+ 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 Ma(e){
590
+ if(!e?.license)throw new Error("arrancarGateway: a verified BiVelio license is required (LICENSE section 2)");let t=Ao(e.license.publicKey),n=cr(e.license.token,t);if(!n.ok)throw new Error(`arrancarGa\
591
+ teway: the license token does not verify (${n.reason})`);let r=(e.upstream??"https://api.anthropic.com").replace(/\/+$/,""),o=ha(r),i=e.fetchImpl??fetch,s=e.log??(m=>console.log(m)),a=e.warn??(m=>console.
592
+ error(m)),c=e.license.now??Date.now,l=e.license.licenseServerUrl?.replace(/\/+$/,""),d=new Rt,u=Io(n.license,t,d,c),p;if(e.serviceAccountKey){p=new _t({url:e.meteringUrl??"https://savings.bivelio.com/\
593
+ api/metering/usage",serviceAccountKey:e.serviceAccountKey,surface:"gateway",...e.fetchImpl?{fetchImpl:e.fetchImpl}:{},onAuthError:E=>W("gateway-ingest-auth",`[bvsala gateway] the usage ingest is rejec\
594
+ ting the credential (${E}). 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.`)});
595
+ let m=On();e.seatId?p.setSeat(e.seatId,m):Ln(e.serviceAccountKey).then(E=>p?.setSeat(E,m)).catch(()=>{}),p.start();}else W("gateway-sin-clave","[bvsala gateway] no BIVELIO_SERVICE_KEY: this in-process \
596
+ gateway forwards traffic but does not meter it (the bvsala CLI refuses to start without the key).");let f=e.coalescer?new lr:null,g=e.sombra&&p?new or:null,b=new pr,h=new An,y=new mr,k=new ur,x=e.serviceAccountKey?
597
+ new ir({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?
598
+ {fetchImpl:e.fetchImpl}:{},...e.entitlementsTtlMs!==void 0?{ttlMs:e.entitlementsTtlMs}:{},log:s}):null,v=x!==null&&e.elision!==false,A=()=>Ro(u.gate,x?.blockReason()??null,u.license.payload),R=null;{let m=Ro(
599
+ u.gate,null,u.license.payload);m.serve&&(R=m.state);}let I=m=>{let E=la(R,m,u.license.payload);R=m.state,E&&a(E);},D,N,z=Number.NEGATIVE_INFINITY,G=new Set,S=(m,E)=>{G.has(m)||(G.add(m),s(E));},C=false,O=m=>m===
600
+ "/v1/messages"?new dt:m.endsWith("/responses")?new Dt:m.endsWith("/chat/completions")?new an:null,$=(m,E,L,B,q,Q,U)=>{b.noMedido(m,Q),s(`[gateway] ${E} ${L} \u2192 ${B}${q?" (stream)":""} \xB7 not metere\
601
+ d: ${Q}`),(pt(L)||L.startsWith("/v1/"))&&k.noMedida(Q),e.avisosDeNoMedido!==false&&(U==="chat"&&W("gateway-chat-sin-include-usage",Ld),U==="chat-con-inyeccion"&&W("gateway-chat-sin-include-usage-con-inye\
602
+ ccion",Md),U==="uso"&&W(`gateway-sin-usage:${L}`,$d(L)),U==="dialecto"&&W(`gateway-sin-dialecto:${L}`,Nd(L)));},X=(m,E,L,B)=>{let q=m instanceof Dt?m.estadoFinal():null;if(q!==null&&q!=="completed")return {
603
+ motivo:`the response ended as response.${q} without usage`,aviso:"uso"};if(!(m instanceof an&&B!=="inyectado"&&Hs(E,L)!==true))return {motivo:"the stream ended without the provider's final usage event",aviso:"\
604
+ uso"};let U="the request did not ask for usage (stream_options.include_usage)";return B==="rechazada-por-el-upstream"?{motivo:`${U}, and the upstream rejects that option`,aviso:null}:B==="comprimido"?
605
+ {motivo:`${U}; usage injection skips compressed request bodies`,aviso:"chat-con-inyeccion"}:B!==null?{motivo:U,aviso:"chat-con-inyeccion"}:{motivo:U,aviso:"chat"}},J=(m,E,L,B,q,Q,U,H,Ne,et,xe,Ee,_,Y)=>{
606
+ if(!p||!L){b.noMedido(m,p?"the provider reported no usage":"metering is off: the gateway has no BIVELIO_SERVICE_KEY");return}let Vt=p,Ft=L,pe=Us(E,Q),_e=`[gateway] POST ${q}${B?" \xB7 COALESCED (call avo\
607
+ ided)":""}`;if(!pe){let oe=`could not read the model from the request body${Q?` (content-encoding: ${Q})`:""}`;s(`${_e} \xB7 not metered: ${oe}`),k.noMedida(oe),b.noMedido(m,"could not read the model \
608
+ from the request body"),W(`gateway-sin-modelo:${q}`,`[bvsala gateway] could not read the model from the ${q} request body (content-encoding: ${Q??"none"}); its usage is forwarded but not metered.`);return}
609
+ let ee=!B&&xe?xe.servido:pe,re=Bs(ee,L,et);if(re){let oe=B?Ks(pe,re,_,Ot(E,Q),{suscripcion:Ee===true,entregada:Y?.entregada===true,tierServido:Y?.tierServido}):null,tt=B?Gs(m,pe,re,U,oe?.ok?oe.credit:null):
610
+ Ws(m,ee,re,U,H,Ne,xe,Ee===true);p.record(tt),B?k.replica():k.medida(),b.medido(m,tt);let vt=tt.cost.eliminatedInputFloorCost;s(`[gateway] POST ${q} ${B?"\xB7 COALESCED (call avoided)":""} \xB7 ${ee!==pe?
611
+ `${pe}\u2192${ee} (sibling model)`:pe} \xB7 $${re.costeUsd.toFixed(6)} (in ${re.tokens.entrada}, cache\u2191${re.tokens.cacheEscrita}${re.tokens.cacheEscrita1h?` (1h ${re.tokens.cacheEscrita1h})`:""} \
612
+ cache\u2193${re.tokens.cacheLeida}, out ${re.tokens.salida})`+(H?` \xB7 elision: ${H.borrados} clear(s), ${H.tokensLimpiados} tok cleared by the provider`+(vt!==void 0?` \xB7 floor $${vt.toFixed(6)} (\
613
+ 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":H.tokensLimpiados>0?
614
+ " \xB7 thinking only (your config): counted, not credited":""):"")+(Ee&&!B&&(Ne||xe)?" \xB7 subscription traffic: lever applied, saving not credited (no per-token invoice)":"")+(oe?oe.ok?` \xB7 by refere\
615
+ nce: floor $${So(oe.credit).toFixed(6)} (cache read price${oe.credit.creditedOutputTokens>0?`, ${oe.credit.creditedOutputTokens} output tok at temperature 0`:", no output credited"})`:` \xB7 estimated, n\
616
+ ot by reference: ${oe.reason}`:""));let ie=H?.atribuible===true&&H.tokensLimpiadosToolUses>0;g&&!B&&q==="/v1/messages"&&setImmediate(()=>{try{let yt=Ot(E,Q);if(!yt||typeof yt!="object")return;let fe=g.observar(
617
+ {cuerpo:yt,uso:Ft,model:pe,at:et??Date.now(),...U?.sessionId!==void 0?{sessionId:U.sessionId}:{},...U?.agentId!==void 0?{agentId:U.agentId}:{}});if(!fe)return;if(ie){s(`[gateway] shadow estimate \xB7 ${pe}\
618
+ \xB7 the provider already cleared context via our settings: chain advances, nothing emitted`);return}Vt.record(Js(`${m}:shadow`,pe,fe.baselineUsd,fe.politicaUsd,U)),s(`[gateway] shadow estimate \xB7 ${pe}\
619
+ \xB7 baseline $${fe.baselineUsd.toFixed(6)} \u2192 with elision $${fe.politicaUsd.toFixed(6)}`);}catch{}});}else b.noMedido(m,`model "${ee}" has no list price in the catalog`),s(`${_e} \xB7 not metered: m\
620
+ odel "${ee}" has no list price in the catalog`),k.noMedida(`model "${ee}" has no list price in the catalog`),W(`gateway-sin-precio:${ee}`,`[bvsala gateway] model "${ee}" is not in the price catalog; i\
621
+ ts usage is forwarded but not metered.`);},ve=(m,E,L,B,q,Q)=>{if(!(m!=="/v1/messages"||B===null||!Ra(B)||(L===void 0||L===""||L==="identity")&&!E.includes('"cache_control"')))try{let H=Ot(E,L);if(H===null||
622
+ typeof H!="object"||Array.isArray(H))return;let Ne=Ia({vista:Ta(H),uso:B,ttlReescritoPorLaCapa:q});Ne!==null&&y.anotar(Ne,Q)&&s(Mo(Ne,{sesion:Q,entrada:B.input_tokens??0,escrita5m:B.cache_creation?.ephemeral_5m_input_tokens??
623
+ 0}));}catch{}},ye=createServer(async(m,E)=>{let L=randomUUID(),B=Date.now(),q=A();if(I(q),!q.serve){let V=c();N&&V-z>=ia&&(z=V,N.check({force:true})),m.resume(),E.writeHead(402,{"content-type":"application/json","cache-co\
624
+ ntrol":"no-store","x-bvsala-license-status":q.state}),E.end(m.method==="HEAD"?void 0:ca(q.state));let M="/";try{M=new URL(m.url??"/","http://x").pathname;}catch{}s(`[gateway] ${m.method} ${M} \u2192 402 (li\
625
+ cense ${q.state})`);return}let Q=Sa(m.url);if(Q!==null){await Ea(m,E,Q,{buzon:b,estado:()=>({schema:ya,gateway:"bvsala",version:he,upstream:wa(r),license:{state:q.state,plan:u.license.payload.plan??null,
626
+ expiresAt:Re(u.license.payload.expires_at)},metering:p!==void 0,reports:{requestHeader:fn,responseHeader:Oo,capacity:b.limite}})});return}let U=ka(m.headers[fn]),H=U?new fr:null;if(U){let V="/";try{V=
627
+ new URL(m.url??"/","http://x").pathname;}catch{}b.abrir(L,V);}let Ne=V=>U?{...V,[Oo]:L}:V,et=null,xe=new AbortController;E.on("close",()=>{E.writableEnded||xe.abort();});let Ee=null,_=new URL(m.url??"/",
628
+ r),Y=null,Vt=Buffer.alloc(0),Ft=false,pe=false,_e=null,ee=null,re=false,oe=false,tt=(V,M)=>{if(V===null||_e===null||!_e.nuestros)return V;let nt=M?.cache_creation,_r=M?.cache_creation_input_tokens??(nt?.ephemeral_5m_input_tokens??
629
+ 0)+(nt?.ephemeral_1h_input_tokens??0),qt=(M?.input_tokens??0)+(M?.cache_read_input_tokens??0)+_r+V.tokensLimpiados,Ht=_e.triggerDelCliente!==null&&qt>=_e.triggerDelCliente;return {...V,atribuible:!Ht}},
630
+ vt=m.headers["content-encoding"],ie=Array.isArray(vt)?vt[0]:vt,yt=V=>{let M=Array.isArray(V)?V[0]:V;return M!==void 0&&/^[A-Za-z0-9._:/-]{1,128}$/.test(M)?M:void 0},fe=yt(m.headers["x-claude-code-sess\
631
+ ion-id"]),Er=yt(m.headers["x-claude-code-agent-id"]),zt=fe!==void 0||Er!==void 0?{...fe!==void 0?{sessionId:fe}:{},...Er!==void 0?{agentId:Er}:{}}:void 0;try{let V=[];for await(let w of m)V.push(w);let M=Buffer.
632
+ concat(V);Vt=M,_=new URL(m.url??"/",r);let nt=f!==null&&m.method==="POST"&&M.length>0,_r=fa(w=>{let T=m.headers[w];return Array.isArray(T)?T.join(", "):T}),qt=nt?pa("POST",_.pathname+_.search,M,_r):"";
633
+ if(nt)if(f.tieneEnVuelo(qt)){let w=await f.esperar(qt);if(w){let T=xe.signal.aborted||E.destroyed;T||E.writeHead(w.status,Ne(w.headers)),et=w.status;let me=O(_.pathname)??new dt;for(let St of w.chunks)
634
+ T||E.write(St),me.observar(St),H?.observar(St);H&&b.anotarRespuesta(L,H.valor()??Lo(Buffer.concat(w.chunks))),T||E.end();let wt=T?!1:await Ud(E),Kt=me.usageFinal()??rr(_.pathname,Buffer.concat(w.chunks));
635
+ if(Kt===null){if(p&&!Da.test(_.pathname)){let St=String(w.headers["content-type"]??"").includes("text/event-stream");$(L,m.method??"POST",_.pathname,w.status,St,pt(_.pathname)?St?X(me,M,ie,null).motivo:
636
+ "the response carried no usage":"no usage dialect for this route",null);}return}let Gt=m.headers["anthropic-beta"],rt=wo(_.pathname,Array.isArray(Gt)?Gt.join(", "):Gt,r);J(L,M,Kt,!0,_.pathname,ie,zt,null,
637
+ null,B,null,rt,w.primaria??null,{entregada:wt,tierServido:zs(_.pathname,Buffer.concat(w.chunks))});return}}else Ee=f.registrar(qt);let Ht=m.headers.connection,zc=new Set((Array.isArray(Ht)?Ht.join(","):
638
+ Ht??"").split(",").map(w=>w.trim().toLowerCase()).filter(w=>w!=="")),je={};for(let[w,T]of Object.entries(m.headers))w==="host"||w==="content-length"||T===void 0||Bd.has(w)||zc.has(w)||w!==fn&&(je[w]=Array.
639
+ isArray(T)?T.join(", "):T);let Wt={...je};re=wo(_.pathname,Wt["anthropic-beta"],r);let ke=M;if(v&&e.dialesElision===!0&&m.method==="POST"&&_.pathname==="/v1/messages"&&x.tiene("context_elision"))try{let w=di(
640
+ M,ie);w!==null&&(ke=w.cuerpo,_e={nuestros:w.nuestros,triggerDelCliente:w.triggerDelCliente},je["anthropic-beta"]=fi(je["anthropic-beta"]));}catch{}if(m.method==="POST"&&_.pathname==="/v1/messages"&&(ie??
641
+ "")==="")try{let w=ua(M.toString("utf8")),T=da(w);T&&(W("gateway-busqueda-herramientas",T),Ca(m.headers)&&y.anotar("busquedaApagada",fe)&&s(Mo("busquedaApagada",{sesion:fe,definiciones:w.definiciones})));}catch{}
642
+ let si=v&&e.modeloHermano===!0&&m.method==="POST"&&(_.pathname==="/v1/messages"||_.pathname==="/v1/messages/count_tokens");if(si&&!x.tiene("sibling_model_routing")&&W("gateway-hermano-sin-feature","[b\
643
+ vsala gateway] 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)."),si&&x.tiene("sibling_model_rout\
644
+ ing"))try{let T=Ri(ke,ke===M?ie:"identity",{betas:je["anthropic-beta"]});T!==null&&(ke=T.cuerpo,ee=T.cambio);}catch{}let kn=!1;if(v&&jr(e.esfuerzo)&&m.method==="POST"&&_.pathname==="/v1/messages"&&x.tiene(
645
+ "per_turn_effort"))try{let w=ke===M?ie:"identity",T=wi(ke,e.esfuerzo,w);T!==null&&(ke=T.cuerpo,je["anthropic-beta"]=Si(je["anthropic-beta"]),kn=!0);}catch{}let kt=null;if(v&&m.method==="POST"&&_.pathname===
646
+ "/v1/messages"&&x.tiene("cache_ttl_tuning"))try{let T=ot(ke,ke===M?ie:"identity");if(T!==null){let me=hi(T),wt=`${zt?.sessionId??"sin-sesion"}:${me.system}`,Kt=Date.now(),Gt=h.ultima(wt,Kt);if(h.anotar(
647
+ wt,me,Kt),bi({fraccionNueva:gi(Gt,me)})){let rt=vi(T);rt!==null&&(ke=rt.cuerpo,kt={rebajadas:rt.rebajadas,yaEran5m:rt.yaEran5m,herramientaDeServidor:rt.herramientaDeServidor},oe=!0);}}}catch{}let xt=!1,
648
+ xn=null;if(m.method==="POST"&&_.pathname.endsWith("/chat/completions")&&p&&e.usageInject===!0)if(C)xn="rechazada-por-el-upstream";else try{let w=qs(M,ie);xn=w.motivo,w.cuerpo&&(ke=w.cuerpo,xt=!0);}catch{}
649
+ let j,Tr=ke,Cr=je;try{j=await i(_,{method:m.method,headers:je,body:["GET","HEAD"].includes(m.method??"")?void 0:ke,redirect:"manual",signal:xe.signal});}catch(w){Ee?.abortar(),E.headersSent||(E.writeHead(
650
+ 502,{"content-type":"application/json"}),E.end(JSON.stringify({error:"bvsala gateway: upstream unreachable",detail:Nt(w)}))),s(`[gateway] ${m.method} ${_.pathname} \u2192 upstream unreachable: ${Nt(w)}`);
651
+ return}if(((Tr!==M||!Oa(Cr,Wt))&&j.status===400||xt&&(j.status===400||j.status===422))&&!xe.signal.aborted){let w="";try{w=(await j.text()).slice(0,300).replace(/\s+/g," ");}catch{}let T=xt;s(T?`[gatew\
652
+ ay] the 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${ee?` to ${ee.
653
+ servido}`:""}${kn?" (per-turn effort)":""}${kt?" (cache TTL)":""}${_e?" (context editing dials)":""}; forwarding it unchanged \xB7 ${w}`),ee=null,kn=!1,kt=null,oe=!1,_e=null,xt=!1,T&&(xn="rechazada-po\
654
+ r-el-upstream"),Tr=M,Cr=Wt;try{j=await i(_,{method:m.method,headers:Wt,body:M,redirect:"manual",signal:xe.signal});}catch(me){Ee?.abortar(),E.headersSent||(E.writeHead(502,{"content-type":"application/\
655
+ json"}),E.end(JSON.stringify({error:"bvsala gateway: upstream unreachable",detail:Nt(me)}))),s(`[gateway] ${m.method} ${_.pathname} \u2192 upstream unreachable on retry: ${Nt(me)}`);return}T&&j.ok&&(C=
656
+ !0,W("gateway-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 forwa\
657
+ rded but NOT metered (stream=false answers still are)."));}let Ar=Object.fromEntries(j.headers.entries());for(let w of jd)delete Ar[w];E.writeHead(j.status,Ne(Ar)),et=j.status;let wn=j.headers.get("con\
658
+ tent-type")??"",Sn=wn.includes("text/event-stream")||wn===""&&j.ok&&O(_.pathname)!==null&&!_.pathname.endsWith("/chat/completions");Y=Sn?O(_.pathname):null,pe=j.ok;let Be=!Sn&&j.ok&&p!==void 0&&m.method===
659
+ "POST"&&pt(_.pathname)&&(j.headers.get("content-type")??"").includes("application/json")?[]:null,ai=0,ci=!1;if(j.body)for await(let w of j.body){let T=Buffer.from(w);E.write(T),Y?.observar(T),H?.observar(
660
+ T),Be&&(ai+=T.length,ai>Po?(Be=null,ci=!0):Be.push(T)),Ee?.capturar(T);}if(E.end(),H&&b.anotarRespuesta(L,H.valor()??(Be?Lo(Buffer.concat(Be)):null)),Ee){let w=ee===null&&!kn&&_e===null&&!xt&&kt===null&&
661
+ Tr===M&&Oa(Cr,Wt),T=Be?Buffer.concat(Be):null,me=j.ok&&(Y?Y.usageFinal()!==null:T!==null&&rr(_.pathname,T)!==null),wt=Y instanceof Dt&&Y.estadoFinal()==="failed"||T!==null&&Fs(_.pathname,T);Ee.terminar(
662
+ j.status,Ar,{requestId:L,at:Date.now(),intacta:w,proveedorOficial:o,conContador:me,suscripcion:re,fallida:wt});}if(Y&&j.ok){Ft=!0;let w=Y.usageFinal();if(w===null&&p){let T=X(Y,M,ie,xt?"inyectado":xn);
663
+ $(L,m.method??"POST",_.pathname,j.status,!0,T.motivo,T.aviso);}else {let T=tt(Y instanceof dt?Y.elision():null,w);J(L,M,w,!1,_.pathname,ie,zt,T,kt,B,ee,re),ve(_.pathname,M,ie,w,oe,fe);}p||s(`[gateway] ${m.
664
+ method} ${_.pathname} \u2192 ${j.status} (stream) \xB7 not metered: no BIVELIO_SERVICE_KEY`);}else if(Be){let w=Buffer.concat(Be),T=rr(_.pathname,w);if(T===null)$(L,m.method??"POST",_.pathname,j.status,
665
+ !1,"the response carried no usage","uso");else {let me=_.pathname==="/v1/messages"?$s(w):null;J(L,M,T,!1,_.pathname,ie,zt,tt(me,T),kt,B,ee,re),ve(_.pathname,M,ie,T,oe,fe);}}else ci?$(L,m.method??"POST",
666
+ _.pathname,j.status,!1,"the response was too large to read its usage",null):p&&m.method==="POST"&&j.ok&&pt(_.pathname)?$(L,m.method,_.pathname,j.status,!1,`the response is neither JSON nor an event st\
667
+ ream (content-type: ${wn===""?"none":wn.slice(0,80)})`,null):p&&m.method==="POST"&&j.ok&&!pt(_.pathname)&&!Da.test(_.pathname)?$(L,m.method,_.pathname,j.status,Sn,"no usage dialect for this route",_.pathname.
668
+ startsWith("/v1/")?"dialecto":null):s(`[gateway] ${m.method} ${_.pathname} \u2192 ${j.status}${Sn?" (stream)":""}`);}catch(V){if(Ee?.abortar(),xe.signal.aborted){let M=!Ft&&Y?Y.usageFinal():null;if(M){
669
+ s(`[gateway] ${m.method} ${_.pathname} \u2192 client closed after the final usage; metered anyway`);let nt=tt(Y instanceof dt?Y.elision():null,M);J(L,Vt,M,false,_.pathname,ie,zt,nt,void 0,B,ee,re),ve(_.pathname,
670
+ Vt,ie,M,oe,fe);}else s(`[gateway] ${m.method} ${_.pathname} \u2192 client aborted; upstream cancelled`),Y&&pe&&!Ft&&k.noMedida("the client closed the stream before the provider's final usage");}else if(s(
671
+ `[gateway] ${m.method} ${_.pathname} \u2192 error while serving: ${Nt(V)}`),!E.headersSent){E.writeHead(502,{"content-type":"application/json"}),E.end(JSON.stringify({error:"bvsala gateway: stream int\
672
+ errupted",detail:Nt(V)}));return}E.writableEnded||E.end();}finally{U&&b.noMedido(L,xe.signal.aborted?"the client closed the connection before the provider's final usage":et===null?"the request did not \
673
+ get an answer from the provider":`no usage was read from the provider's answer (HTTP ${et})`);}});ye.on("upgrade",(m,E)=>{s(`[gateway] ${m.method} ${new URL(m.url??"/","http://x").pathname} \u2192 426 (WebS\
674
+ ocket not supported; the client falls back to HTTP)`),E.once("error",()=>{}),E.once("finish",()=>E.destroy()),E.end(`HTTP/1.1 426 Upgrade Required\r
606
675
  connection: close\r
607
676
  content-length: 0\r
608
677
  \r
609
- `);});let le=e.puerto??8402;try{await new Promise((m,x)=>{H.once("error",x),H.listen(le,"127.0.0.1",()=>m());});}catch(m){p?.stop();let x=m?.code;throw new ao(typeof x=="string"?x:"EUNKNOWN",le,m)}let Ie=H.
610
- address().port;return c&&(A=new Wt({url:`${c}/licenses/revocations`,publicKeyPem:t,snapshot:d,getRefreshAfter:()=>l.gate.refreshAfter?.(),nowSeconds:()=>Math.floor(u()/1e3),...e.fetchImpl?{fetchImpl:e.
611
- fetchImpl}:{},silenceWarnings:true,onEvent:m=>{m.type==="rejected"&&q(`poller:${m.reason}`,`[gateway] revocation list rejected (${m.reason}); known revocations still apply`);},...e.license.revocations??{}}),
612
- A.start(),e.serviceAccountKey&&(C=new Vn({licenseServerUrl:c,serviceAccountKey:e.serviceAccountKey,publicKey:t,revocation:d,current:()=>l.license,onAdopt:m=>{l=ro(m,t,d,u),i(`[gateway] renewed license\
613
- adopted (expires ${Te(m.payload.expires_at)})`),I(_());},onWarning:a,...e.fetchImpl?{fetchImpl:e.fetchImpl}:{},now:u,...e.license.renewal??{}}),C.start({checkNow:e.license.checkOnStart===true}))),{puerto:Ie,
614
- cerrar:async()=>{C?.stop(),A?.stop(),await p?.stopAndDrain(),await new Promise(m=>H.close(()=>m()));},licenseStatus:()=>_().state,degradaciones:()=>h.contadores()}}var co=["claude","codex","goose","qwen"];function Qt(e){return co.includes(e??"")}function uo(e,t={}){let n=t.path??process.env.PATH??"",r=t.
615
- existe??existsSync,o=null;for(let s of n.split(";").filter(i=>i.length>0)){for(let i of [".exe",".com"]){let a=join(s,e+i);if(r(a))return {tipo:"exe",ruta:a}}if(o===null)for(let i of [".cmd",".bat"]){let a=join(s,e+
616
- i);if(r(a)){o=a;break}}}return o!==null?{tipo:"solo-shim",ruta:o}:{tipo:"no-encontrado"}}function Hi(e={}){let n=(e.env??process.env).BVSALA_CODEX_AUTH?.toLowerCase();if(n==="api-key"||n==="apikey")return "\
617
- 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.auth_mode=="string"?o.auth_mode.
618
- toLowerCase().replace(/[^a-z]/g,"")==="apikey"?"api-key":"chatgpt":o.tokens!==void 0&&o.tokens!==null?"chatgpt":"api-key"}catch{return "api-key"}}var pl={"api-key":{upstream:"https://api.openai.com",prefijo:"\
619
- /v1"},chatgpt:{upstream:"https://chatgpt.com",prefijo:"/backend-api/codex"}};function Wn(e,t,n,r={},o=process.env){let s=`http://127.0.0.1:${t}`;switch(e){case "claude":return {bin:"claude",args:n,env:{
620
- ANTHROPIC_BASE_URL:s,ENABLE_TOOL_SEARCH:o.ENABLE_TOOL_SEARCH??"true"}};case "goose":return {bin:"goose",args:n,env:{ANTHROPIC_HOST:s}};case "qwen":return {bin:"qwen",args:n,env:{ANTHROPIC_BASE_URL:s},nota:'\
621
- Qwen Code only routes through here with `security.auth.selectedType: "anthropic"` in ~/.qwen/settings.json (see `bvsala doctor`).'};case "codex":{let i=r.modoCodex??"api-key",a=pl[i];return {bin:"codex",
622
- args:["-c",`openai_base_url="${s}${a.prefijo}"`,...n],env:{},upstream:a.upstream,nota:i==="chatgpt"?"ChatGPT auth detected: the gateway routes to chatgpt.com/backend-api/codex. Subscription traffic is\
623
- 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.com/v1."}}}}var fl=["gateway","doctor","skill"],Wi=new Set(["help","--help","-h"]),Ki=new Set(["version","--version","-v"]);function Gi(e){let[t,...n]=e;return t===void 0||Wi.has(t)?{tipo:"ayuda",salida:0}:Ki.has(
624
- t)?{tipo:"version"}:Qt(t)?{tipo:"arrancar",comando:t,resto:n}:fl.includes(t)?n.some(r=>Wi.has(r))?{tipo:"ayuda",salida:0}:n.some(r=>Ki.has(r))?{tipo:"version"}:{tipo:"arrancar",comando:t,resto:n}:{tipo:"\
625
- ayuda",salida:1}}function Ji(e){return e.length===1&&(e[0]==="--help"||e[0]==="-h"||e[0]==="--version")}function Yi(e,t,n){let r=e??{},o=typeof r.puerto=="number"?r.puerto:n;if(r.code==="EADDRINUSE")return `\
626
- 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: permission denied (\
627
- EACCES; ports below 1024 need privileges): use --port ${Math.max(1024,o)} or higher`;let s=e instanceof Error?e.message:String(e);return `could not start the gateway for \`bvsala ${t}\`: ${s}`}function ml(e){let t=Number.parseInt(e.slice(8,10),10);return Number.isFinite(t)&&t%2===0?"palanca":"control"}function Zi(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.
628
- activo!==false,espia:r}}function Xi(e){let{enrolamiento:t,espiaVivo:n,upstreamEnv:r,elisionEnv:o,hoyUtcIso:s}=e;if(!t)return {linea:"",aviso:false};if(!t.activo)return {linea:"A/B plan: enrolment paused (acti\
678
+ `);});let $e=e.puerto??8402;try{await new Promise((m,E)=>{ye.once("error",E),ye.listen($e,"127.0.0.1",()=>m());});}catch(m){p?.stop();let E=m?.code;throw new $o(typeof E=="string"?E:"EUNKNOWN",$e,m)}let Ke=ye.
679
+ 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.
680
+ fetchImpl}:{},silenceWarnings:true,onEvent:m=>{m.type==="rejected"&&S(`poller:${m.reason}`,`[gateway] revocation list rejected (${m.reason}); known revocations still apply`);},...e.license.revocations??{}}),
681
+ D.start(),e.serviceAccountKey&&(N=new ar({licenseServerUrl:l,serviceAccountKey:e.serviceAccountKey,publicKey:t,revocation:d,current:()=>u.license,onAdopt:m=>{u=Io(m,t,d,c),s(`[gateway] renewed license\
682
+ 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:Ke,
683
+ cerrar:async()=>{N?.stop(),D?.stop(),await p?.stopAndDrain(),await new Promise(m=>ye.close(()=>m()));},licenseStatus:()=>A().state,degradaciones:()=>y.contadores(),medicion:()=>k.estado()}}var No=["claude","codex","goose","qwen","opencode","kilo","copilot","aider"];function mn(e){return No.includes(e??"")}function jo(e,t={}){
684
+ 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 [
685
+ ".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 Ba(e={}){let n=(e.env??process.env).BVSALA_CODEX_AUTH?.toLowerCase();if(n===
686
+ "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.
687
+ 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 Fd={"api-key":{upstream:"\
688
+ https://api.openai.com",prefijo:"/v1"},chatgpt:{upstream:"https://chatgpt.com",prefijo:"/backend-api/codex"}},Na="https://api.anthropic.com",ja="https://api.openai.com",Ua={opencode:"OPENCODE_CONFIG_C\
689
+ ONTENT",kilo:"KILO_CONFIG_CONTENT"};function Va(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=
690
+ 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(
691
+ {...n,provider:{...o,anthropic:{...i,options:{...s,baseURL:t}}}})}function Fa(e){let t=e.COPILOT_PROVIDER_BASE_URL?.trim()??"";if(t==="")return {ok:false,error:"Copilot CLI goes through a base URL only wi\
692
+ 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\
693
+ 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.
694
+ 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\
695
+ 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\
696
+ 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\
697
+ 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\
698
+ irst."}}return r.origin!==Na?{ok:false,error:`COPILOT_PROVIDER_BASE_URL does not point at ${Na}: the gateway prices only the provider's own API at its list price (a local model or a reseller bills differ\
699
+ ently, or not at all), so it does not wrap it.`}:{ok:true,ruta:r.pathname.replace(/\/+$/,"")}}function za(e,t=process.env){if(e==="opencode"||e==="kilo"){let n=Ua[e];return Va(t[n],"http://127.0.0.1:1/v\
700
+ 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\
701
+ se the manual recipe in \`bvsala doctor\`.`:null}if(e==="copilot"){let n=Fa(t);return n.ok?null:n.error}return null}function hr(e,t,n,r={},o=process.env){let i=`http://127.0.0.1:${t}`;switch(e){case "c\
702
+ 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",
703
+ 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=Ua[e],
704
+ a=Va(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}: \
705
+ 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=Fa(o);return s.ok?{bin:"copilot",args:n,
706
+ 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\
707
+ ider":{if(r.upstreamElegido===ja){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:ja,nota:"OpenAI models through \
708
+ 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\
709
+ 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\
710
+ 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=Fd[s];return {
711
+ 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\
712
+ 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\
713
+ m/v1."}}}}var zd=["gateway","doctor","skill","init"],qa=new Set(["help","--help","-h"]),Ha=new Set(["version","--version","-v"]);function Wa(e){let[t,...n]=e;return t===void 0||qa.has(t)?{tipo:"ayuda",salida:0}:
714
+ Ha.has(t)?{tipo:"version"}:mn(t)?{tipo:"arrancar",comando:t,resto:n}:zd.includes(t)?n.some(r=>qa.has(r))?{tipo:"ayuda",salida:0}:n.some(r=>Ha.has(r))?{tipo:"version"}:{tipo:"arrancar",comando:t,resto:n}:
715
+ {tipo:"ayuda",salida:1}}function Ka(e){return e.length===1&&(e[0]==="--help"||e[0]==="-h"||e[0]==="--version")}function Ga(e,t,n){let r=e??{},o=typeof r.puerto=="number"?r.puerto:n;if(r.code==="EADDRI\
716
+ 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\
717
+ 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 qd(e){let t=Number.parseInt(e.slice(8,10),10);return Number.isFinite(t)&&t%2===0?"palanca":"control"}function Ja(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.
718
+ activo!==false,espia:r}}function Ya(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\
629
719
  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\
630
- 2:espia\`.`,aviso:true};let i=ml(s),a=`http://127.0.0.1:${t.espia}`,u=r!==void 0&&r!=="",c=o!==void 0&&o!=="",d=[];d.push(`A/B plan: ${s} UTC \u2192 arm ${i.toUpperCase()}`);let l=e.upstreamOrigen==="fl\
631
- ag"?"--upstream":"the environment";return d.push(u?`upstream kept from ${l} (${r})`:`chained to :${t.espia}`),c&&d.push(`elision flag kept from the environment (=${o})`),d.push("context elision dials \
632
- 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"),{...u?{}:{upstream:a},brazo:i,linea:d.join(", "),aviso:false}}var vl="check: the gateway log must show `[gateway] POST /v1/messages \u2026`; if you see `/v1/v1\
633
- /messages`, there is one /v1 too many; if you see a bare `POST /messages`, one is missing.",yl=[{id:"claude",nombre:"Claude Code",binario:"claude",configs:[],detectable:true,receta:({base:e})=>["use `bv\
720
+ 2:espia\`.`,aviso:true};let s=qd(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\
721
+ 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 \
722
+ 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 Gd="check: the gateway log must show `[gateway] POST /v1/messages \u2026`; if you see `/v1/v1\
723
+ /messages`, there is one /v1 too many; if you see a bare `POST /messages`, one is missing.",Jd=[{id:"claude",nombre:"Claude Code",binario:"claude",configs:[],detectable:true,receta:({base:e})=>["use `bv\
634
724
  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\
635
- ages)`]},{id:"codex",nombre:"Codex CLI",binario:"codex",configs:[join(".codex","config.toml"),join(".codex","auth.json")],detectable:true,receta:({base:e,rutas:t})=>["use `bvsala codex` \u2014 the base URL prefi\
636
- x depends on the auth mode and the wrapper resolves it:",` API key \u2192 openai_base_url=${e}/v1`,` ChatGPT subscription \u2192 openai_base_url=${e}/backend-api/codex (must end exactl\
637
- y there)`,`${t[1]}: only checked for existence; never read.`]},{id:"opencode",nombre:"opencode",binario:"opencode",configs:[join(".config","opencode","opencode.json")],detectable:true,receta:({baseV1:e,rutas:t})=>[
638
- `mechanism: ${t[0]} \u2192 provider.anthropic.options.baseURL (the project's opencode.json overrides the global one). WITH /v1.`,"{",' "provider": {',' "anthropic": {',` "options": { "baseURL\
639
- ": "${e}" }`," }"," }","}",'alternative: "baseURL": "{env:BVSALA_BASE_URL}" and export the variable; pitfall: without the variable, baseURL is empty.']},{id:"goose",nombre:"Goose",binario:"goose",
640
- configs:[join(".config","goose","config.yaml")],detectable:true,receta:({base:e,rutas:t})=>[`mechanism: ANTHROPIC_HOST environment variable (overrides ${t[0]}). NO /v1.`,`ANTHROPIC_HOST=${e} ANTHROPIC_API\
641
- _KEY=\u2026 goose`]},{id:"crush",nombre:"Crush",binario:"crush",configs:[join(".config","crush","crushrc")],detectable:true,receta:({baseV1:e,rutas:t})=>[`mechanism: ${t[0]} (Bash); crush.json is deprecat\
642
- ed. WITH /v1 and NO trailing slash (the Go SDK resolves relative paths: /v1/ \u2192 /v1/v1/messages).`,`provider add bvsala --type anthropic --base-url ${e} --api-key "$ANTHROPIC_API_KEY"`]},{id:"qwen",
643
- nombre:"Qwen Code",binario:"qwen",configs:[join(".qwen","settings.json")],detectable:true,receta:({base:e,rutas:t})=>[`mechanism: ANTHROPIC_BASE_URL environment variable + ${t[0]} with selectedType = anth\
644
- ropic. NO /v1 (the official TS SDK appends /v1/messages).`,`ANTHROPIC_BASE_URL=${e} ANTHROPIC_API_KEY=\u2026 qwen`,`check by hand that ${t[0]} has selectedType: anthropic \u2014 the doctor does not read th\
645
- e file.`]},{id:"droid",nombre:"Droid (Factory)",binario:"droid",configs:[join(".factory","settings.json")],detectable:true,receta:({base:e,rutas:t})=>[`mechanism: ${t[0]} \u2192 customModels[] with provider "a\
646
- nthropic". NO /v1 [inferred: validate by hand against the gateway log].`,"{",' "customModels": ['," {",' "model": "<Anthropic model id>",',' "displayName": "<display name>",',' "pro\
647
- vider": "anthropic",',` "baseUrl": "${e}",`,' "apiKey": "<your Anthropic API key>"'," }"," ]","}"]},{id:"cline",nombre:"Cline",configs:[],detectable:false,receta:({baseV1:e})=>['mechanism: \
648
- UI \u2192 Anthropic provider \u2192 tick "Use custom base URL". WITH /v1 (Cline defaults to https://api.anthropic.com/v1 and only normalizes the exact official URL).',`Base URL: ${e}`]},{id:"kilo",nombre:"\
649
- Kilo Code",configs:[],detectable:false,receta:({baseV1:e})=>['mechanism: UI \u2192 custom provider, Provider API "Anthropic Messages". Try WITH /v1 first (Cline lineage) [inferred: validate by hand].',`B\
650
- ase URL: ${e}`]},{id:"python-openai",nombre:"Python, or any OpenAI SDK (Chat Completions)",configs:[],detectable:false,estadoSinDeteccion:"no detection: any language, through the SDK's base URL",comprobar:"\
651
- check: the gateway log must show `[gateway] POST /v1/chat/completions \u2026`; if you see `/v1/v1/chat/completions`, there is one /v1 too many.",receta:({baseV1:e,puerto:t})=>[`start: bvsala gateway -\
652
- -upstream openai --port ${t} (one gateway per upstream: if Claude Code already uses this port, pick another and change the URL below to match)`,`python: client = OpenAI(base_url="${e}") (WITH /v1:\
653
- the SDK appends /chat/completions)`,`node: const client = new OpenAI({ baseURL: "${e}" })`,'streaming: pass stream_options={"include_usage": True} (Node: stream_options: { include_usage: true }) or\
654
- the stream is forwarded but NOT metered; the last chunk then has an empty choices list, so read chunk.choices only when it is not empty.',"stream=False is metered from the usage in the JSON body, and\
655
- so 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-anthropi\
656
- c",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 gat\
657
- eway --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}" }\
658
- )`,"streamed and stream=False requests are both metered."]}];function kl(e,t){let n=e.split(delimiter).filter(o=>o.length>0),r=process.platform==="win32"?["",".exe",".cmd",".bat"]:[""];return o=>n.some(s=>r.
659
- some(i=>t(join(s,o+i))))}async function Qi(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??
660
- kl(t.path??process.env.PATH??"",r),s=`http://127.0.0.1:${e}`,i=`${s}/v1`,a=[],u=[`bvsala doctor \u2014 local gateway at ${s}`,"Print only: it writes no configuration. Detection by existence (binaries \
661
- on the 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 th\
662
- at key and does not start without one.",""];for(let c of yl){let d=c.configs.map(y=>join(n,y)),l=c.binario!==void 0&&o(c.binario),p=d.filter(y=>r(y)),f=l||p.length>0;f&&a.push(c.id);let g;c.detectable?f?
663
- g=`detected \u2014 ${[...l?[`binary \`${c.binario}\` on PATH`]:[],...p.map(h=>`config present: ${h}`)].join("; ")}`:g="not detected":g=c.estadoSinDeteccion??"no automatic detection (editor extension)",
664
- u.push(`\xBB ${c.id}: ${g}`),u.push(` ${c.nombre}`);for(let y of c.receta({base:s,baseV1:i,puerto:e,rutas:d}))u.push(` ${y}`);u.push(` ${c.comprobar??vl}`),u.push("");}return u.push("BYOK rule: the \
665
- recipes for the Anthropic-compatible terminals (Goose, Qwen Code, opencode, Crush, Droid, Cline,","Kilo) are for API keys. Never route the OAuth of a Claude Pro/Max subscription through the gateway fr\
666
- om 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 no per-token invoice); the pe\
667
- r-seat license applies.","Any language through the gateway: it measures every request whose usage it can read (Anthropic Messages, OpenAI Chat","Completions and Responses) for models with a list price\
668
- , 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 license.","Per-terminal detail\
669
- : docs/terminales/<terminal>.md"),{texto:u.join(`
670
- `),detectados:a}}var ea="savings-mode";function ta(e,t){for(let n of e){let r=join(n,"skills",ea,"SKILL.md");if(t.existe(r))return r}return null}var na="<!-- bvsala:savings-mode:inicio -->",
671
- Kn="<!-- bvsala:savings-mode:fin -->";function xl(e){let t=e.replace(/^---\n[\s\S]*?\n---\n*/,"").trim();return `${na}
725
+ 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\
726
+ 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\
727
+ ds on the auth mode and the wrapper resolves it:",` API key \u2192 openai_base_url=${e}/v1`,` ChatGPT subscription \u2192 openai_base_url=${e}/backend-api/codex (must end exactly there\
728
+ )`,`${t[1]}: only checked for existence; never read.`]},{id:"opencode",nombre:"opencode",binario:"opencode",configs:[join(".config","opencode","opencode.json")],detectable:true,receta:({baseV1:e,rutas:t})=>[
729
+ "use `bvsala opencode` \u2014 routes the `anthropic` provider through the gateway with OPENCODE_CONFIG_CONTENT, which","opencode merges over the global and project files: nothing is written to disk. O\
730
+ ther providers go direct.",`by hand: ${t[0]} \u2192 provider.anthropic.options.baseURL (the project's opencode.json overrides the global one). WITH /v1.`,"{",' "provider": {',' "anthropic": {',` \
731
+ "options": { "baseURL": "${e}" }`," }"," }","}",'alternative: "baseURL": "{env:BVSALA_BASE_URL}" and export the variable; pitfall: without the variable, baseURL is empty.']},{id:"kilo",nombre:"\
732
+ Kilo Code (CLI, VS Code, JetBrains)",binario:"kilo",configs:[join(".config","kilo","kilo.json"),join(".config","kilo","kilo.jsonc")],detectable:true,receta:({baseV1:e,rutas:t})=>["use `bvsala kilo` for the \
733
+ CLI \u2014 routes the `anthropic` provider (your API key) with KILO_CONFIG_CONTENT: nothing is","written to disk. The Kilo Gateway provider (Kilo's own hosted models) and any other provider go direct.",
734
+ `by hand (the VS Code and JetBrains extensions read the same file): ${t[0]} \u2192 provider.anthropic.options.baseURL. WITH /v1.`,"{",' "provider": {',' "anthropic": {',` "options": { "baseUR\
735
+ L": "${e}" }`," }"," }","}"]},{id:"copilot",nombre:"GitHub Copilot CLI (your own key, BYOK)",binario:"copilot",configs:[join(".copilot","config.json")],detectable:true,comprobar:"check: the gateway lo\
736
+ g must show `[gateway] POST /v1/messages \u2026` (anthropic); `/v1/v1/messages` means one /v1 too many.",receta:({base:e,baseV1:t})=>["only with your own provider key (BYOK). GitHub-hosted models do n\
737
+ ot use a base URL: nothing to meter there (/usage).","anthropic type: use `bvsala copilot` with your BYOK variables exported \u2014 it keeps your model and key and points",`COPILOT_PROVIDER_BASE_URL a\
738
+ t the gateway. By hand: COPILOT_PROVIDER_TYPE=anthropic COPILOT_PROVIDER_BASE_URL=${e} (NO /v1)`,`openai type [not validated]: COPILOT_PROVIDER_BASE_URL=${t} against \`bvsala gateway --upstream opena\
739
+ i\` (WITH /v1).`,"It may call the Responses API over WebSocket, which the gateway answers with 426: keep it only if the log shows","POST /v1/responses or /v1/chat/completions lines with a cost; `did n\
740
+ ot ask for usage` \u2192 BVSALA_GATEWAY_USAGE_INJECT=1."]},{id:"aider",nombre:"Aider",binario:"aider",configs:[".aider.conf.yml"],detectable:true,receta:({base:e,baseV1:t})=>["use `bvsala aider` \u2014 Anthr\
741
+ opic models by default. Aider calls through litellm, which reads ANTHROPIC_API_BASE","before ANTHROPIC_BASE_URL and appends /v1/messages: NO /v1.",`by hand: ANTHROPIC_API_BASE=${e} aider`,`OpenAI mode\
742
+ ls: BVSALA_GATEWAY_UPSTREAM=openai bvsala aider --model <OpenAI model>; by hand, OPENAI_API_BASE=${t} (WITH /v1).`,"litellm asks for streamed usage only when it talks to api.openai.com itself: through\
743
+ the gateway, streamed OpenAI","replies are metered only with BVSALA_GATEWAY_USAGE_INJECT=1 or aider --no-stream. An --openai-api-base flag or","openai-api-base in .aider.conf.yml overrides the variab\
744
+ le."]},{id:"goose",nombre:"Goose",binario:"goose",configs:[join(".config","goose","config.yaml")],detectable:true,receta:({base:e,rutas:t})=>[`mechanism: ANTHROPIC_HOST environment variable (overrides ${t[0]}\
745
+ ). NO /v1.`,`ANTHROPIC_HOST=${e} ANTHROPIC_API_KEY=\u2026 goose`]},{id:"crush",nombre:"Crush",binario:"crush",configs:[join(".config","crush","crushrc")],detectable:true,receta:({baseV1:e,rutas:t})=>[`mec\
746
+ hanism: ${t[0]} (Bash); crush.json is deprecated. WITH /v1 and NO trailing slash (the Go SDK resolves relative paths: /v1/ \u2192 /v1/v1/messages).`,`provider add bvsala --type anthropic --base-url ${e}\
747
+ --api-key "$ANTHROPIC_API_KEY"`]},{id:"qwen",nombre:"Qwen Code",binario:"qwen",configs:[join(".qwen","settings.json")],detectable:true,receta:({base:e,rutas:t})=>[`mechanism: ANTHROPIC_BASE_URL environme\
748
+ nt variable + ${t[0]} with selectedType = anthropic. NO /v1 (the official TS SDK appends /v1/messages).`,`ANTHROPIC_BASE_URL=${e} ANTHROPIC_API_KEY=\u2026 qwen`,`check by hand that ${t[0]} has selecte\
749
+ dType: anthropic \u2014 the doctor does not read the file.`]},{id:"droid",nombre:"Droid (Factory)",binario:"droid",configs:[join(".factory","settings.json")],detectable:true,receta:({base:e,rutas:t})=>[`m\
750
+ echanism: ${t[0]} \u2192 customModels[] with provider "anthropic". NO /v1 [inferred: validate by hand against the gateway log].`,"{",' "customModels": ['," {",' "model": "<Anthropic model id>\
751
+ ",',' "displayName": "<display name>",',' "provider": "anthropic",',` "baseUrl": "${e}",`,' "apiKey": "<your Anthropic API key>"'," }"," ]","}"]},{id:"cline",nombre:"Cline",configs:[],
752
+ detectable:false,receta:({baseV1:e})=>['mechanism: UI \u2192 Anthropic provider \u2192 tick "Use custom base URL". WITH /v1 (Cline defaults to https://api.anthropic.com/v1 and only normalizes the exact official UR\
753
+ L).',`Base URL: ${e}`]},{id:"continue",nombre:"Continue (cn CLI and IDE extensions)",binario:"cn",configs:[join(".continue","config.yaml")],detectable:true,receta:({baseV1:e,rutas:t})=>[`mechanism: ${t[0]}\
754
+ \u2192 the model's apiBase. WITH /v1 (Continue adds the trailing slash and resolves \`messages\` against it).`,"models:"," - name: <display name>"," provider: anthropic"," model: <Anthropic mo\
755
+ del id>"," apiKey: <your Anthropic API key>",` apiBase: ${e}`]},{id:"vscode-copilot",nombre:"GitHub Copilot in VS Code (your own key, BYOK)",configs:[],detectable:false,receta:({baseV1:e})=>["mecha\
756
+ nism: Manage Language Models \u2192 Add Models \u2192 Custom Endpoint, API type Messages; VS Code opens","chatLanguageModels.json. Put the FULL path in the model's url (VS Code uses an explicit /messa\
757
+ ges path as-is):",`"url": "${e}/messages"`,"BYOK covers chat and utility tasks: inline suggestions and embeddings stay on GitHub and are not metered here."]},{id:"gemini",nombre:"Gemini CLI",binario:"\
758
+ gemini",configs:[join(".gemini","settings.json")],detectable:true,comprobar:null,receta:()=>["NOT metered yet: Gemini CLI speaks the Gemini API (\u2026:streamGenerateContent), and the gateway reads usage only \
759
+ from","Anthropic Messages and OpenAI Chat Completions and Responses. GOOGLE_GEMINI_BASE_URL would route it, but every","request would be forwarded with no cost line. Its own /stats model shows the tok\
760
+ en counts.","why, and what it would take: docs/terminales/no-soportados.md"]},{id:"cursor",nombre:"Cursor",binario:"cursor",configs:[".cursor"],detectable:true,comprobar:null,receta:()=>["NOT supported:\
761
+ Cursor sends every request, your own API key included, through Cursor's servers, which cannot reach","a gateway on 127.0.0.1. Cursor's usage dashboard is the meter there. See docs/terminales/no-sopor\
762
+ tados.md"]},{id:"python-openai",nombre:"Python, or any OpenAI SDK (Chat Completions)",configs:[],detectable:false,estadoSinDeteccion:"no detection: any language, through the SDK's base URL",comprobar:"ch\
763
+ eck: the gateway log must show `[gateway] POST /v1/chat/completions \u2026`; if you see `/v1/v1/chat/completions`, there is one /v1 too many.",receta:({baseV1:e,puerto:t})=>[`start: bvsala gateway --u\
764
+ pstream openai --port ${t} (one gateway per upstream: if Claude Code already uses this port, pick another and change the URL below to match)`,`python: client = OpenAI(base_url="${e}") (WITH /v1: t\
765
+ he SDK appends /chat/completions)`,`node: const client = new OpenAI({ baseURL: "${e}" })`,'streaming: pass stream_options={"include_usage": True} (Node: stream_options: { include_usage: true }) or t\
766
+ he stream is forwarded but NOT metered; the last chunk then has an empty choices list, so read chunk.choices only when it is not empty.',"stream=False is metered from the usage in the JSON body, and s\
767
+ 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",
768
+ 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\
769
+ 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}" })`,
770
+ "streamed and stream=False requests are both metered."]}];function Yd(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(
771
+ s=>t(join(i,o+s))))}async function Za(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??Yd(t.
772
+ 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\
773
+ 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\
774
+ y and does not start without one.",""];for(let l of Jd){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\
775
+ 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(
776
+ `\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??Gd}`),c.push("");}return c.push("BY\
777
+ 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\
778
+ 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\
779
+ 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\
780
+ ) 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 \
781
+ license.","Per-terminal detail: docs/terminales/<terminal>.md"),{texto:c.join(`
782
+ `),detectados:a}}var Bo=["ai-sdk","mastra","langchain","anthropic-sdk","sdk"],gn={"ai-sdk":["openai","anthropic"],mastra:["openai","anthropic"],langchain:["openai","anthropic"],"anthropic-sdk":["anthropic"],sdk:["open\
783
+ ai","anthropic"]},bn={"ai-sdk":"Vercel AI SDK",mastra:"Mastra",langchain:"LangChain.js","anthropic-sdk":"Anthropic TypeScript SDK",sdk:"the SDK directly (no framework)"},Uo={"ai-sdk":"@bivelio/savings\
784
+ -layer/ai-sdk",mastra:"@bivelio/savings-layer/mastra",langchain:"@bivelio/savings-layer/langchain","anthropic-sdk":"@bivelio/savings-layer/anthropic-sdk",sdk:"@bivelio/savings-layer"},Zd={openai:"gpt-\
785
+ 4o-mini",anthropic:"claude-haiku-4-5"},Xa="What is 2 + 2 * 3?",hn=["licenseKey: process.env.BIVELIO_LICENSE_KEY,",'licenseServerUrl: "https://savings.bivelio.com",',"serviceAccountKey: process.env.BIV\
786
+ ELIO_SERVICE_KEY,"],Xd=["onReport: (report) => {"," seen.calls += 1;"," seen.avoidedLlm = report.calls.avoidedLlm;"," seen.basis = report.cost.basis;","},"];function Qa(e,t){switch(e){case "ai-sdk":
787
+ 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\
788
+ hropic"];case "anthropic-sdk":return ["@anthropic-ai/sdk"];case "sdk":return []}}function Le(e,t){let n=" ".repeat(t);return e.map(r=>r===""?"":n+r)}function We(e){return e?"export ":""}function jt(e,t){let n=Zd[t];
789
+ 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\
790
+ velio/savings-layer/ai-sdk";'],adaptador:"savings",construir:(o,i)=>[`${We(i)}const savings = savingsMiddleware({`,...Le([...hn,...o],2),"});",...i?["","// Pass `model` wherever you pass a model today\
791
+ (generateText, streamText\u2026).","// `savings` goes LAST in the middleware list: nothing between it and the model."]:[],`${We(i)}const model = wrapLanguageModel({ model: ${r}("${n}"), middleware: s\
792
+ avings });`],exporta:["model"],importsDeUso:['import { generateText } from "ai";','import { getSavingsReport } from "@bivelio/savings-layer/ai-sdk";'],llamar:o=>[`const result = await generateText({ m\
793
+ odel, ${o==="prompt"?"prompt":`prompt: ${o}`} });`,"const text = result.text;","const basis = getSavingsReport(result)?.cost.basis;"],daBasis:true,importsDeComprobacion:['import { generateText } from "a\
794
+ i";'],preguntar:o=>[`const { text } = await generateText({ model, prompt: ${o} });`]}}case "mastra":return {imports:['import { Agent } from "@mastra/core/agent";','import { savingsProcessor } from "@biv\
795
+ elio/savings-layer/mastra";'],adaptador:"bivelio",construir:(r,o)=>[`${We(o)}const bivelio = savingsProcessor({`,...Le([...hn,...r],2),"});",...o?["","// Add `bivelio` LAST to the inputProcessors of e\
796
+ ach agent you already have;","// this one shows where. Its reports go to `onReport` if you pass one above."]:[],`${We(o)}const agent = new Agent({`,' id: "assistant",',' name: "Assistant",',' instr\
797
+ uctions: "Answer briefly.",',` model: "${t}/${n}",`," inputProcessors: [bivelio],","});"],exporta:["agent"],importsDeUso:[],llamar:r=>[`const result = await agent.generate(${r});`,"const text = resu\
798
+ lt.text;"],daBasis:false,importsDeComprobacion:[],preguntar:r=>[`const { text } = await agent.generate(${r});`]};case "langchain":return {imports:['import { createAgent } from "langchain";','import { savin\
799
+ gsAgentMiddleware } from "@bivelio/savings-layer/langchain";'],adaptador:"savings",construir:(r,o)=>[`${We(o)}const savings = savingsAgentMiddleware({`,...Le([...hn,...r],2),"});",...o?["","// Add `sa\
800
+ vings` LAST to the middleware of each agent you already have; this one shows where."]:[],`${We(o)}const agent = createAgent({ model: "${t}:${n}", tools: [], middleware: [savings] });`],exporta:["agent"],
801
+ importsDeUso:['import { getSavingsReportFromMessage } from "@bivelio/savings-layer/langchain";'],llamar:r=>[`const state = await agent.invoke({ messages: [{ role: "user", content: ${r} }] });`,"const \
802
+ last = state.messages.at(-1);",'const text = last?.text ?? "";',"const basis = getSavingsReportFromMessage(last)?.cost.basis;"],daBasis:true,importsDeComprobacion:[],preguntar:r=>[`const state = await a\
803
+ 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: \
804
+ "${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 \
805
+ Anthropic from "@anthropic-ai/sdk";','import { anthropicSavings } from "@bivelio/savings-layer/anthropic-sdk";'],adaptador:"claudeSavings",construir:(i,s)=>[`${We(s)}const claudeSavings = anthropicSav\
806
+ ings({`,...Le([...hn,...i],2),"});",...s?["","// Use `client` for messages.create(); `claudeSavings.middleware` goes LAST in the list."]:[],`${We(s)}const client = new Anthropic({ middleware: [claudeS\
807
+ avings.middleware] });`],exporta:["client","claudeSavings"],importsDeUso:[],llamar:i=>[r(i),o,"const basis = claudeSavings.reportFor(message)?.cost.basis;"],daBasis:true,importsDeComprobacion:[],preguntar:i=>[
808
+ 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\
809
+ vider({ apiKey: process.env.ANTHROPIC_API_KEY }),",i=t==="openai"?"OpenAICompatibleProvider":"AnthropicProvider";return {imports:[t==="openai"?`import { createSavingsLayer, ${i} } from "@bivelio/saving\
810
+ 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."]:
811
+ [],`${We(c)}const layer = createSavingsLayer({`,...Le([o,...hn,...a],2),"});"],exporta:["layer"],importsDeUso:[],llamar:a=>[`const { text, report } = await layer.generate({ model: "${r}", messages: [{\
812
+ role: "user", content: ${a} }] });`,"const basis = report.cost.basis;"],daBasis:true,importsDeComprobacion:[],preguntar:a=>[`const { text, report } = await layer.generate({ model: "${r}", messages: [{ \
813
+ role: "user", content: ${a} }] });`]}}}}function Vo(e,t){let n=jt(e,t);return ["// BiVelio Savings Layer: created once, when this module loads, and reused by every","// request. The exact cache lives i\
814
+ n this instance, so do not create one per request.",...n.imports,"",...n.construir([],true),""].join(`
815
+ `)}var ec=["// 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 \
816
+ 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\
817
+ ile once it says ok."];function tc(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\
818
+ 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" \
819
+ && 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\
820
+ 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\
821
+ .`;"]}function nc(e,t){let n=jt(e,t),r=Fo([...n.importsDeComprobacion,...n.imports]),o=e==="sdk"?n.construir([],false):['const seen = { calls: 0, avoidedLlm: 0, basis: "" };',...n.construir(Xd,false)];return {
822
+ imports:r,cuerpo:o}}function Fo(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=
823
+ 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 rc(e,t){
824
+ let n=jt(e,t),{imports:r,cuerpo:o}=nc(e,t);return [...ec,...r,"",...o,"","try {",...Le([...n.preguntar(JSON.stringify(Xa)),...tc(e),"console.log(line);","if (!ok) process.exitCode = 1;"],2),"} catch (e\
825
+ rr) {"," console.log(`not ok: ${err instanceof Error ? err.message : String(err)}`);"," process.exitCode = 1;","} finally {",` ${n.adaptador}.close();`,"}",""].join(`
826
+ `)}function oc(e,t){let n=jt(e,t),{imports:r,cuerpo:o}=nc(e,t);return [...ec,"// It answers only in development: in production it is a 404.",...r,"","// Run on each request, never at build time.",'expo\
827
+ rt const dynamic = "force-dynamic";',"","export async function GET() {",' if (process.env.NODE_ENV === "production") {',' return new Response("Not found", { status: 404 });'," }",...Le(o,2)," tr\
828
+ y {",...Le([...n.preguntar(JSON.stringify(Xa)),...tc(e),"return Response.json({ ok, message: line }, { status: ok ? 200 : 500 });"],4)," } catch (err) {"," return Response.json({ ok: false, messag\
829
+ e: `not ok: ${err instanceof Error ? err.message : String(err)}` }, { status: 500 });"," } finally {",` ${n.adaptador}.close();`," }","}",""].join(`
830
+ `)}function ic(e,t,n){let r=jt(e,t),o=r.daBasis?"{ text, basis }":"{ text }";return [...Fo(r.importsDeUso),`import { ${r.exporta.slice().sort().join(", ")} } from "${n.importeDelCableado}";`,"",`export\
831
+ async function POST(req${n.ts?": Request":""}) {`,` const { prompt } = ${n.ts?"(await req.json()) as { prompt: string }":"await req.json()"};`,...Le(r.llamar("prompt"),2),` return Response.json(${o}\
832
+ );`,"}",""].join(`
833
+ `)}function sc(e,t){let n=jt(e,t),r=n.daBasis?"{ text, basis }":"{ text }";return ['import express from "express";',...Fo([...n.imports,...n.importsDeUso]),"","// Created once, at startup, not inside t\
834
+ 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 {",...Le(
835
+ n.llamar('String(req.body?.prompt ?? "")'),4),` res.json(${r});`," } catch (err) {"," next(err);"," }","});","","app.listen(Number(process.env.PORT ?? 3000));",""].join(`
836
+ `)}var gr="usage: bvsala init [--write [--yes]] [--json] [--stack ai-sdk|mastra|langchain|anthropic-sdk|sdk] [--provider openai|anthropic] [--cwd <dir>]";function dc(e,t){let n={cwd:t,escribir:false,si:false,json:false};
837
+ 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.
838
+ json=true;else if(o==="--stack"){let s=i();if(!s||!Bo.includes(s))return {ok:false,mensaje:`--stack needs one of: ${Bo.join(", ")}.
839
+ ${gr}`};n.capa=s;}else if(o==="--provider"){let s=i();if(s!=="openai"&&s!=="anthropic")return {ok:false,mensaje:`--provider needs openai or anthropic.
840
+ ${gr}`};n.proveedor=s;}else if(o==="--cwd"){let s=i();if(!s)return {ok:false,mensaje:`--cwd needs a directory.
841
+ ${gr}`};n.cwd=s.startsWith("/")||/^[A-Za-z]:[\\/]/.test(s)?s:join(t,s);}else return {ok:false,mensaje:`unknown option: ${o}
842
+ ${gr}`}}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 \
843
+ --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 Qd=[["pnpm-lock.yaml","pn\
844
+ pm"],["yarn.lock","yarn"],["bun.lock","bun"],["bun.lockb","bun"],["package-lock.json","npm"]];function ep(e,t,n){if(typeof e.packageManager=="string"){let r=e.packageManager.split("@")[0];if(r==="pnpm"||
845
+ r==="yarn"||r==="bun"||r==="npm")return r}for(let r=t,o=0;o<20;o++){for(let[s,a]of Qd)if(n.existe(join(r,s)))return a;let i=dirname(r);if(i===r)break;r=i;}return "npm"}function tp(e){let t={};for(let n of [e.devDependencies,
846
+ e.dependencies])if(n&&typeof n=="object")for(let[r,o]of Object.entries(n))typeof o=="string"&&(t[r]=o);return t}function np(e,t,n,r){let o=r.leer(join(n,"node_modules",...e.split("/"),"package.json"));if(o)
847
+ 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(
848
+ t)))return `${i[1]}.${i[2]??0}.${i[3]??0}`}function Ho(e){let[t=0,n=0,r=0]=e.split(/[.+-]/).map(o=>Number.parseInt(o,10)||0);return [t,n,r]}function Wo(e,t){let n=Ho(e),r=Ho(t);for(let o=0;o<3;o++)if(n[o]!==
849
+ r[o])return n[o]>r[o];return true}var pc=[{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\
850
+ \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\
851
+ 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"}],fc=[["@mastra/core","mastra"],["langchain","\
852
+ langchain"],["ai","ai-sdk"],["@anthropic-ai/sdk","anthropic-sdk"],["openai","sdk"]];function mc(e,t){let n=t.leer(join(e,"package.json"));if(n===void 0){let u=["pyproject.toml","requirements.txt","setup\
853
+ .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\
854
+ 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\
855
+ 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\
856
+ 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\
857
+ t a JSON object. Fix it and run init again.`};let o=tp(r),i={};for(let[u,p]of Object.entries(o))i[u]=np(u,p,e,t);let s=["app","src/app"].find(u=>t.existe(join(e,...u.split("/")))),a="next"in i?"next":"e\
858
+ xpress"in i?"express":"node",c=fc.filter(([u])=>u in i).map(([,u])=>u),l={dir:e,gestor:ep(r,e,t),ts:"typescript"in i||t.existe(join(e,"tsconfig.json")),esm:r.type==="module",anfitrion:a,src:t.existe(join(
859
+ 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"},
860
+ 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}}
861
+ var cc=(e,t)=>t.some(n=>n in e.deps),rp=["openai","@ai-sdk/openai","@langchain/openai"],op=["@anthropic-ai/sdk","@ai-sdk/anthropic","@langchain/anthropic"];function ip(e,t){if(e==="anthropic-sdk")return "\
862
+ 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\
863
+ ain/anthropic"in t.deps)return "anthropic"}return cc(t,op)&&!cc(t,rp)?"anthropic":"openai"}function lc(e,t){for(let n of pc){if(n.capa!==e)continue;let r=t.deps[n.paquete];if(r!==void 0&&(!Wo(r,n.desde)||
864
+ Wo(r,n.hasta)))return `${n.paquete} ${r} is outside what the adapter supports (${n.texto})`}}var zo={npm:"npm i",pnpm:"pnpm add",yarn:"yarn add",bun:"bun add"};function sp(e){let t=e.ficherosEnv[0];return t?
865
+ `node --env-file=${t} bivelio-check.mjs`:"node bivelio-check.mjs"}function hc(e,t,n){let[r=0]=Ho(n.node);if(r<20)return {ok:false,mensaje:`Node ${n.node} is too old: @bivelio/savings-layer needs Node \u2265 20\
866
+ . Upgrade Node and run init again.`};let o=[],i=t.capa,s=[];if(i){let f=lc(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=lc(f,e);if(!g){
867
+ 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\
868
+ 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`."));
869
+ for(let f of s){let g=pc.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: ${zo[e.
870
+ gestor]} ${g}@latest`);}let a=t.proveedor??ip(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/\
871
+ savings-layer");for(let f of Qa(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&&!Wo(l,
872
+ "0.4.25")&&o.push(`@bivelio/savings-layer ${l} has no framework adapters (they arrived in 0.4.25): ${zo[e.gestor]} @bivelio/savings-layer@latest`),r<22&&(i==="mastra"||i==="ai-sdk"&&(e.deps.ai??"7").startsWith(
873
+ "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\
874
+ " 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\
875
+ 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\
876
+ ewal"}];if(i==="anthropic-sdk")d.push({nombre:"ANTHROPIC_API_KEY",puesta:n.env("ANTHROPIC_API_KEY")||n.env("ANTHROPIC_AUTH_TOKEN"),para:"needed even by the free check: the Anthropic SDK builds no requ\
877
+ est without credentials"});else {let f=a==="openai"?"OPENAI_API_KEY":"ANTHROPIC_API_KEY",g=i==="mastra"?"your provider key; the free check works without it, but Mastra logs a warning with a stack trace":
878
+ "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\
879
+ 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\
880
+ 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};
881
+ return c.length>0&&(p.comandoDeInstalacion=`${zo[e.gestor]} ${c.join(" ")}`),{ok:true,valor:p}}function gc(e,t){let n=e.deteccion,{capa:r,proveedor:o}=e,i=n.ts?"ts":n.esm||n.anfitrion==="next"?"js":"mjs",
882
+ 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){
883
+ a.push({ruta:d,proposito:"wiring",contenido:Vo(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\
884
+ r (example: ${p})`,ruta:p,contenido:ic(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:oc(r,
885
+ 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).`,
886
+ '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\
887
+ ed once at startup, then used by the route",ruta:`server.${i}`,contenido:sc(r,o)}):a.push({ruta:d,proposito:"wiring",contenido:Vo(r,o),existe:s(d)}),a.push({ruta:"bivelio-check.mjs",proposito:"check",
888
+ contenido:rc(r,o),existe:s("bivelio-check.mjs")}),l.push(`Run it: ${sp(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.
889
+ 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\
890
+ (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\
891
+ 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} -----
892
+ ${t.replace(/\n$/,"")}
893
+ ${n}`}function ap(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.
894
+ 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 cp(e){
895
+ let t=e.deteccion,n=fc.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 \
896
+ yet)"} with ${e.proveedor==="openai"?"OpenAI":"Anthropic"} models \u2192 ${Uo[e.capa]}`}function bc(e,t,n,r={}){let o=e.deteccion,i=[t,"",`Detected in ${o.dir}`,` app: ${ap(o)}`,` LLM calls: \
897
+ ${cp(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\
898
+ 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}`:
899
+ " 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.
900
+ 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/\
901
+ 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");
902
+ 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.
903
+ 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)
904
+ 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\
905
+ 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(`\
906
+
907
+ `)}function vc(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.
908
+ gestor,stacks:n.capas,installed:n.yaInstalado?n.deps["@bivelio/savings-layer"]??n.yaInstalado:null},stack:e.capa,provider:e.proveedor,adapter:Uo[e.capa],install:e.comandoDeInstalacion??null,keys:e.claves.
909
+ 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.
910
+ contenido})),check:e.comoComprobar,notes:e.avisos},null,2)}async function yc(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}\
911
+ 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\
912
+ 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(
913
+ "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\
914
+ 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(
915
+ 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(`\
916
+ could not create ${a.ruta}: ${l instanceof Error?l.message:String(l)}`));}}return {salida:s,lineas:n,creados:r}}var kc="savings-mode";function xc(e,t){for(let n of e){let r=join(n,"skills",kc,"SKILL.md");if(t.existe(r))return r}return null}var wc="<!-- bvsala:savings-mode:inicio -->",
917
+ br="<!-- bvsala:savings-mode:fin -->";function lp(e){let t=e.replace(/^---\n[\s\S]*?\n---\n*/,"").trim();return `${wc}
672
918
  ${t}
673
919
 
674
920
  _Always on (AGENTS.md has no activation step). Delete this block to turn it off; \`bvsala skill --codex --force\` restores it._
675
- ${Kn}`}function ra(e){let t=ta(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=xl(e.fs.leer(t)),
921
+ ${br}`}function Sc(e){let t=xc(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=lp(e.fs.leer(t)),
676
922
  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+`
677
- `),{ok:true,destino:o,mensaje:lo(o,"installed")};let s=e.fs.leer(o),i=s.indexOf(na),a=s.indexOf(Kn);return i===-1||a===-1||a<i?(e.fs.escribir(o,s.trimEnd()+`
923
+ `),{ok:true,destino:o,mensaje:Ko(o,"installed")};let i=e.fs.leer(o),s=i.indexOf(wc),a=i.indexOf(br);return s===-1||a===-1||a<s?(e.fs.escribir(o,i.trimEnd()+`
678
924
 
679
925
  `+n+`
680
- `),{ok:true,destino:o,mensaje:lo(o,"appended to the existing AGENTS.md")}):s.slice(i,a+Kn.length)===n?{ok:true,destino:o,mensaje:`[bvsala skill] already installed and up to date: ${o}`}:e.forzar?(e.fs.escribir(
681
- o,s.slice(0,i)+n+s.slice(a+Kn.length)),{ok:true,destino:o,mensaje:lo(o,"block updated")}):{ok:false,destino:o,mensaje:`[bvsala skill] the savings-mode block in ${o} has DIFFERENT content \u2014 not overwriting \
682
- it; use --force to update it`}}function lo(e,t){return `[bvsala skill] ${t}: ${e}
926
+ `),{ok:true,destino:o,mensaje:Ko(o,"appended to the existing AGENTS.md")}):i.slice(s,a+br.length)===n?{ok:true,destino:o,mensaje:`[bvsala skill] already installed and up to date: ${o}`}:e.forzar?(e.fs.escribir(
927
+ o,i.slice(0,s)+n+i.slice(a+br.length)),{ok:true,destino:o,mensaje:Ko(o,"block updated")}):{ok:false,destino:o,mensaje:`[bvsala skill] the savings-mode block in ${o} has DIFFERENT content \u2014 not overwriting \
928
+ it; use --force to update it`}}function Ko(e,t){return `[bvsala skill] ${t}: ${e}
683
929
  [bvsala skill] AGENTS.md is ALWAYS active in Codex (there is no activation step); delete the block to turn it off.
684
- [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 oa(e){let t=ta(e.origenes,e.fs);if(!t)return {ok:false,destino:"",
685
- 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,ea),o=join(r,"SKILL.\
686
- md"),s=e.fs.leer(t);if(e.fs.existe(o)&&!e.forzar){let i=e.fs.leer(o)===s;return {ok:i,destino:o,mensaje:i?`[bvsala skill] already installed and up to date: ${o}`:`[bvsala skill] ${o} already exists wit\
687
- h DIFFERENT content \u2014 not overwriting it; use --force to overwrite`}}return e.fs.crearDir(r),e.fs.escribir(o,s),{ok:true,destino:o,mensaje:`[bvsala skill] installed: ${o}
930
+ [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 Ec(e){let t=xc(e.origenes,e.fs);if(!t)return {ok:false,destino:"",
931
+ 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,kc),o=join(r,"SKILL.\
932
+ 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\
933
+ 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}
688
934
  [bvsala skill] start (or restart) Claude Code and ask for "savings mode" \u2014 or let it activate on its own when you mention limits.
689
- [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 po=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 s=o[0];if(/\s/.test(s)){let i=(o.
690
- match(/\n/g)??[]).length;r+=i+Math.floor(Math.max(0,o.length-1)/2);}else /[A-Za-z]/.test(s)?r+=Math.max(1,Math.ceil(o.length/4)):/\d/.test(s)?r+=Math.max(1,Math.ceil(o.length/2)):r+=1;}return Math.max(r,
691
- Math.ceil(t.length/4))}},fo=new po;var mo=class{estimators=new Map;modelToTokenizer=new Map;fallbackId;constructor(t=fo){this.fallbackId=t.id,this.estimators.set(t.id,t);}register(t){return this.estimators.set(t.id,t),this}mapModel(t,n){
935
+ [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 Go=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.
936
+ 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,
937
+ Math.ceil(t.length/4))}},Jo=new Go;var Yo=class{estimators=new Map;modelToTokenizer=new Map;fallbackId;constructor(t=Jo){this.fallbackId=t.id,this.estimators.set(t.id,t);}register(t){return this.estimators.set(t.id,t),this}mapModel(t,n){
692
938
  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.
693
- get(r);if(o)return o}}return this.estimators.get(this.fallbackId)}count(t,n){return this.resolve(n).count(t)}};new mo;var ia={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",
694
- "text-embedding-3-large"]};var jl={"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}};
695
- hr(jl);new Set(Object.values(ia).flatMap(e=>e.flatMap(t=>[t,`openai/${t}`])));function sd(e,t=300){return new Promise(n=>{let r=connect({port:e,host:"127.0.0.1"}),o=s=>{r.destroy(),n(s);};r.setTimeout(t,()=>o(false)),r.once("connect",()=>o(true)),r.once("error",()=>o(false));})}var Xn=Gi(process.
696
- argv.slice(2));function id(){console.log(`bvsala ${we} \u2014 BiVelio Savings Layer
939
+ get(r);if(o)return o}}return this.estimators.get(this.fallbackId)}count(t,n){return this.resolve(n).count(t)}};new Yo;var Tc={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",
940
+ "text-embedding-3-large"]};var Op={"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}};
941
+ Ur(Op);new Set(Object.values(Tc).flatMap(e=>e.flatMap(t=>[t,`openai/${t}`])));function Xp(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 wr=Wa(process.
942
+ argv.slice(2));function Qp(){console.log(`bvsala ${he} \u2014 BiVelio Savings Layer
697
943
 
698
944
  Commands:
699
945
  gateway [--port N] [--upstream U]
@@ -709,6 +955,17 @@ Commands:
709
955
  ChatGPT auth: chatgpt.com/backend-api/codex, metered with no commission).
710
956
  goose [args\u2026] Run Goose (ANTHROPIC_HOST) through the gateway.
711
957
  qwen [args\u2026] Run Qwen Code (ANTHROPIC_BASE_URL) through the gateway.
958
+ opencode [args\u2026] Run opencode with its anthropic provider through the gateway
959
+ (OPENCODE_CONFIG_CONTENT; nothing written to disk).
960
+ kilo [args\u2026] Run the Kilo CLI with its anthropic provider through the gateway
961
+ (KILO_CONFIG_CONTENT; nothing written to disk).
962
+ copilot [args\u2026] Run GitHub Copilot CLI through the gateway with your own Anthropic key
963
+ (BYOK, COPILOT_PROVIDER_TYPE=anthropic). GitHub-hosted models do not
964
+ use a base URL and are not metered.
965
+ aider [args\u2026] Run Aider through the gateway: Anthropic models by default
966
+ (ANTHROPIC_API_BASE); OpenAI with BVSALA_GATEWAY_UPSTREAM=openai.
967
+ Every wrapper prints, on exit, how many requests it metered and
968
+ which ones it forwarded without metering, and why.
712
969
  doctor [--port N] Detect installed terminals and print the exact configuration for each.
713
970
  skill [--codex] [--project] [--force]
714
971
  Install the "savings-mode" skill for Claude Code (~/.claude/skills;
@@ -718,8 +975,20 @@ Commands:
718
975
  (~/.codex; with --project, ./AGENTS.md) \u2014 Codex has no skills and
719
976
  AGENTS.md is always active. Its effect is measured by the gateway,
720
977
  not promised.
978
+ init [--write [--yes]] [--stack S] [--provider P] [--cwd DIR] [--json]
979
+ Set up the SDK in a JavaScript/TypeScript project (also:
980
+ npx @bivelio/savings-layer@latest init). Detects Next.js, Express, the
981
+ Vercel AI SDK, Mastra, LangChain.js, the Anthropic SDK and the OpenAI SDK,
982
+ and prints the install line, the keys that are missing, the exact code
983
+ for your adapter and a free check. Reads package.json files only, never
984
+ a .env file or a secret's value, and uses no network. It writes nothing
985
+ unless you pass --write, and then it creates new files only, after
986
+ asking (--yes without a terminal); an existing file is never overwritten.
987
+ --stack ai-sdk | mastra | langchain | anthropic-sdk | sdk (default: detected)
988
+ --provider openai | anthropic (default: detected)
989
+ --json prints the plan for a script or a coding agent.
721
990
  --version | -v Print the version only.
722
- --help | -h This help; also accepted after gateway, doctor or skill
991
+ --help | -h This help; also accepted after gateway, doctor, skill or init
723
992
  (\`bvsala gateway --help\` starts nothing; \`bvsala claude --help\` or
724
993
  \`--version\` go straight to the terminal, with no gateway).
725
994
 
@@ -767,14 +1036,15 @@ Environment:
767
1036
  model has its own cache): start it together with the terminal.
768
1037
  Off = unset the variable or =0.
769
1038
  BVSALA_GATEWAY_ESFUERZO
770
- =low|medium|high|xhigh|max sets per-turn effort (experimental):
1039
+ =low|medium sets a per-turn effort ceiling (experimental):
771
1040
  appends a message with output_config.effort to each /v1/messages
772
1041
  without touching the root (does not reset the prefix cache). Only if
773
- the license carries per_turn_effort (fail-closed) and only with
774
- claude-fable-5-1, claude-mythos-5-1 and claude-opus-5; with any other
775
- model the request travels untouched. It is the only lever that can
776
- affect response quality: OFF by default and not yet measured against
777
- the quality gate.
1042
+ the license carries per_turn_effort (fail-closed), only with
1043
+ claude-fable-5-1, claude-mythos-5-1, claude-opus-5-5 and claude-opus-5,
1044
+ and only when the level is below the model's default (high; medium on
1045
+ claude-opus-5-5): it never raises effort. Any other request travels
1046
+ untouched. It is the only lever that can affect response quality: OFF
1047
+ by default and not yet measured against the quality gate.
778
1048
  BVSALA_CODEX_AUTH api-key | chatgpt \u2014 forces the Codex auth mode.
779
1049
  BVSALA_GATEWAY_LOG =1 shows the per-request log inside the wrappers too (silenced by
780
1050
  default so it does not overwrite the TUI; use the dashboard instead).
@@ -787,43 +1057,49 @@ forwards and warns. On a Claude or ChatGPT subscription there is no per-token in
787
1057
  traffic is metered at list-price equivalent and never carries commission.
788
1058
  Your prompts, completions and provider keys never reach BiVelio: what it receives is per-request
789
1059
  usage (token counts, cost, the model id and opaque ids); LICENSE \xA75 lists every field.
790
- More: savings.bivelio.com`);}Xn.tipo==="ayuda"&&(id(),process.exit(Xn.salida));Xn.tipo==="version"&&(console.log(we),process.exit(0));var{comando:te,resto:oe}=Xn,nn=Qt(te);if(te==="skill"){let e=dirname(fileURLToPath(
791
- import.meta.url)),t={origenes:[join(e,"..",".."),join(e,"..")],home:homedir(),cwd:process.cwd(),proyecto:oe.includes("--project")||oe.includes("--proyecto"),forzar:oe.includes("--force")||oe.includes("--forzar"),
792
- fs:{existe:existsSync,leer:r=>readFileSync(r,"utf8"),escribir:(r,o)=>writeFileSync(r,o),crearDir:r=>mkdirSync(r,{recursive:true})}},n=oe.includes("--codex")?ra(t):oa(t);console.log(n.mensaje),process.exit(n.ok?0:1);}var ko=oe.indexOf("--po\
793
- rt")>=0?oe.indexOf("--port"):oe.indexOf("--puerto"),it=nn?0:ko>=0?Number(oe[ko+1]):8402;(!Number.isInteger(it)||(te==="doctor"?it<1:it<0)||it>65535)&&(console.error(`[bvsala ${te}] invalid port: ${oe[ko+
794
- 1]}`),process.exit(1));if(te==="doctor"){oe.includes("--write")&&(console.error("[bvsala doctor] --write does not exist yet: the doctor only prints; copy the block by hand."),process.exit(1));let e=await Qi(
795
- it);console.log(e.texto),process.exit(0);}function ad(e,t){Qt(e)||process.exit(1);let n=Wn(e,0,[],{}).bin;if(process.platform==="win32"){let o=uo(n);o.tipo==="exe"?n=o.ruta:o.tipo==="solo-shim"&&(console.
796
- 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 its native installer (which leaves a ${n}.exe\
797
- 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(`[bvsala ${e}] could not launch \`${n}\`: ${String(
798
- o)}. Is it installed and on the PATH?`),process.exit(127);}),r.on("exit",(o,s)=>process.exit(o??(s?1:0))),new Promise(()=>{})}nn&&Ji(oe)&&await ad(te,oe);var cd=te==="gateway"?Pi(oe):void 0,he=Oi({flag:cd,
799
- env:process.env.BVSALA_GATEWAY_UPSTREAM});he.ok||(console.error(he.error),process.exit(1));var ga=process.env.BIVELIO_SERVICE_KEY?.trim()||void 0,at=await Si({serviceAccountKey:ga,licenseKey:process.env.
800
- BIVELIO_LICENSE_KEY,licenseServerUrl:eo});at.ok||(console.error(`[bvsala ${te}] ${at.message}`),process.exit(1));var Re=nn?Wn(te,0,oe,{modoCodex:te==="codex"?Hi({leerAuth:()=>readFileSync(join(homedir(),"\
801
- .codex","auth.json"),"utf8")}):void 0}):null,ud=nn&&process.env.BVSALA_GATEWAY_LOG!=="1",yo=Re?.upstream?null:Zi(()=>readFileSync(process.env.BVSALA_ANILLO2_FICHERO??join(homedir(),".bvsala","anillo2.json"),"utf8")),tn=Xi(
802
- {enrolamiento:yo,espiaVivo:yo!==null&&await sd(yo.espia),upstreamEnv:he.upstream,...he.origen!=="none"?{upstreamOrigen:he.origen}:{},elisionEnv:process.env.BVSALA_GATEWAY_ELISION,hoyUtcIso:new Date().
803
- toISOString().slice(0,10)}),xo=he.upstream??tn.upstream,Yn=process.env.BVSALA_GATEWAY_ELISION??tn.elision,me;try{me=await zi({puerto:it,...ud?{log:()=>{},avisosDeNoMedido:!1}:{},license:{token:at.license.
804
- token,publicKey:nt,licenseServerUrl:eo,checkOnStart:at.source==="offline"},warn:e=>console.error(e),serviceAccountKey:ga,...process.env.BVSALA_SEAT_ID?{seatId:process.env.BVSALA_SEAT_ID}:{},...xo?{upstream:xo}:
805
- Re?.upstream?{upstream:Re.upstream}:{},...process.env.BVSALA_GATEWAY_COALESCE==="1"?{coalescer:!0}:{},...process.env.BVSALA_GATEWAY_USAGE_INJECT==="1"?{usageInject:!0}:{},...process.env.BVSALA_GATEWAY_SHADOW===
806
- "1"?{sombra:!0}:{},elision:Yn!=="0",...process.env.BVSALA_GATEWAY_DIALES_ELISION==="1"?{dialesElision:!0}:{},...process.env.BVSALA_GATEWAY_MODELO_HERMANO==="1"?{modeloHermano:!0}:{},...process.env.BVSALA_GATEWAY_ESFUERZO?
807
- {esfuerzo:process.env.BVSALA_GATEWAY_ESFUERZO}:{},...process.env.BVSALA_METERING_URL?{meteringUrl:process.env.BVSALA_METERING_URL}:{}});}catch(e){console.error(`[bvsala ${te}] ${Yi(e,te,it)}`),process.
808
- exit(1);}var ba=xo??Re?.upstream??"https://api.anthropic.com";console.log(`[bvsala gateway] v${we} listening on http://127.0.0.1:${me.puerto} \u2192 ${ba}`);(at.lineIsWarning?console.error:console.log)(
809
- `[bvsala gateway] ${at.line}`);for(let e of at.warnings)console.error(`[bvsala gateway] ${e}`);console.log("[bvsala gateway] metering: ON (service key present)");process.env.BVSALA_METERING_URL&&console.
810
- error(`[bvsala gateway] 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 usa\
811
- ge. The license and the entitlements channel still use savings.bivelio.com.`);he.aviso&&console.error(he.aviso);process.env.BVSALA_GATEWAY_USAGE_INJECT==="1"&&console.log("[bvsala gateway] usage injec\
812
- tion: ON (BVSALA_GATEWAY_USAGE_INJECT=1) \u2014 streamed chat completions without stream_options get include_usage; their last chunk has an empty choices list.");{let e=Co(Yn,true,process.env.BVSALA_GATEWAY_DIALES_ELISION===
813
- "1");(e.aviso?console.error:console.log)(`[bvsala gateway] ${e.linea}`);let t=Ho(process.env.BVSALA_GATEWAY_MODELO_HERMANO,true,Yn!=="0");(t.aviso?console.error:console.log)(`[bvsala gateway] ${t.linea}`);
814
- let n=Bo(process.env.BVSALA_GATEWAY_ESFUERZO,true,Yn!=="0");(n.aviso?console.error:console.log)(`[bvsala gateway] ${n.linea}`),tn.linea&&(tn.aviso?console.error:console.log)(`[bvsala gateway] ${tn.linea}`);}
815
- he.upstream&&Re?.upstream&&he.upstream!==Re.upstream&&console.error(`[bvsala ${te}] WARNING: BVSALA_GATEWAY_UPSTREAM=${he.upstream} overrides this terminal's upstream (${Re.upstream}). If that is not \
816
- what you want, unset the variable.`);te==="codex"&&!ri()&&console.error(`[bvsala codex] WARNING: this Node (${process.version}) cannot decompress zstd and Codex sends its body in zstd: traffic passes \
817
- through but is NOT metered. Use Node >= 22.15.`);if(Re&&nn){let e=Wn(te,me.puerto,oe,{...Re.upstream?{modoCodex:Re.upstream.includes("chatgpt.com")?"chatgpt":"api-key"}:{}});e.nota&&console.log(`[bvsa\
818
- la ${te}] ${e.nota}`);let t=e.bin;if(process.platform==="win32"){let r=uo(e.bin);r.tipo==="exe"?t=r.ruta:r.tipo==="solo-shim"&&(console.error(`[bvsala ${te}] \`${e.bin}\` is installed as an npm shim (${r.
819
- ruta}) and Windows cannot launch it safely 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/.`),
820
- await me.cerrar(),process.exit(127));}let n=spawn(t,e.args,{stdio:"inherit",env:{...process.env,...e.env}});n.on("error",r=>{console.error(`[bvsala ${te}] could not launch \`${e.bin}\`: ${String(r)}. Is i\
821
- t installed and on the PATH?`),me.cerrar().then(()=>process.exit(127));}),n.on("exit",(r,o)=>{let s=io(me.degradaciones());s&&console.error(s),me.cerrar().then(()=>process.exit(r??(o?1:0)));});}else {let e=new URL(
822
- ba).hostname;e==="api.openai.com"?console.log(`[bvsala gateway] point your SDK at it: base_url=http://127.0.0.1:${me.puerto}/v1 (OpenAI SDKs) \xB7 streamed chat completions are metered when the request s\
823
- ets stream_options.include_usage \xB7 bvsala doctor for recipes`):e==="api.anthropic.com"||he.upstream===void 0?console.log(`[bvsala gateway] point your terminal at it (or use \`bvsala ${co.join("|")}\
824
- \`): ANTHROPIC_BASE_URL=http://127.0.0.1:${me.puerto} claude \xB7 bvsala doctor for the others`):console.log(`[bvsala gateway] point your client at http://127.0.0.1:${me.puerto} plus the path pre\
825
- fix it already uses (for example /v1) \xB7 bvsala doctor for recipes`);}var va=async()=>{let e=io(me.degradaciones());e&&console.error(e),await me.cerrar(),process.exit(0);};process.on("SIGINT",()=>{va();});
826
- process.on("SIGTERM",()=>{va();});
1060
+ More: savings.bivelio.com`);}wr.tipo==="ayuda"&&(Qp(),process.exit(wr.salida));wr.tipo==="version"&&(console.log(he),process.exit(0));var{comando:F,resto:le}=wr,Ut=mn(F);if(F==="init"){let e=dc(le,process.
1061
+ 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=mc(t.cwd,n);r.ok||(console.error(`[bvsala init]\
1062
+ ${r.mensaje}`),process.exit(1));let o=hc(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=gc(o.valor,n);
1063
+ t.json&&(console.log(vc(i,he)),process.exit(0)),console.log(bc(i,`bvsala init \xB7 BiVelio Savings Layer ${he}`,"npx @bivelio/savings-layer@latest init",{escribira:t.escribir})),t.escribir||process.exit(
1064
+ 0),console.log("");let{createInterface:s}=await import('readline/promises'),a=await yc(i,{si:t.si,esTerminal:!!process.stdin.isTTY,preguntar:async c=>{let l=s({input:process.stdin,output:process.stdout});
1065
+ 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.
1066
+ exit(a.salida);}if(F==="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.
1067
+ 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")?Sc(t):Ec(t);console.log(n.mensaje),process.
1068
+ exit(n.ok?0:1);}var ri=le.indexOf("--port")>=0?le.indexOf("--port"):le.indexOf("--puerto"),gt=Ut?0:ri>=0?Number(le[ri+1]):8402;(!Number.isInteger(gt)||(F==="doctor"?gt<1:gt<0)||gt>65535)&&(console.error(
1069
+ `[bvsala ${F}] invalid port: ${le[ri+1]}`),process.exit(1));if(F==="doctor"){le.includes("--write")&&(console.error("[bvsala doctor] --write does not exist yet: the doctor only prints; copy the block \
1070
+ by hand."),process.exit(1));let e=await Za(gt);console.log(e.texto),process.exit(0);}function ef(e,t){mn(e)||process.exit(1);let n=hr(e,0,[],{}).bin;if(process.platform==="win32"){let o=jo(n);o.tipo===
1071
+ "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\
1072
+ 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\
1073
+ 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(()=>{})}Ut&&Ka(le)&&await ef(F,le);
1074
+ if(Ut){let e=za(F);e&&(console.error(`[bvsala ${F}] ${e}`),process.exit(1));}var tf=F==="gateway"?ga(le):void 0,ue=ba({flag:tf,env:process.env.BVSALA_GATEWAY_UPSTREAM});ue.ok||(console.error(ue.error),
1075
+ process.exit(1));var Bc=process.env.BIVELIO_SERVICE_KEY?.trim()||void 0,bt=await aa({serviceAccountKey:Bc,licenseKey:process.env.BIVELIO_LICENSE_KEY,licenseServerUrl:Co});bt.ok||(console.
1076
+ error(`[bvsala ${F}] ${bt.message}`),process.exit(1));var Me=Ut?hr(F,0,le,{modoCodex:F==="codex"?Ba({leerAuth:()=>readFileSync(join(homedir(),".codex","auth.json"),"utf8")}):void 0,...ue.upstream?{upstreamElegido:ue.upstream}:
1077
+ {}}):null,nf=Ut&&process.env.BVSALA_GATEWAY_LOG!=="1",ni=Me?.upstream?null:Ja(()=>readFileSync(process.env.BVSALA_ANILLO2_FICHERO??join(homedir(),".bvsala","anillo2.json"),"utf8")),yn=Ya({enrolamiento:ni,espiaVivo:ni!==
1078
+ null&&await Xp(ni.espia),upstreamEnv:ue.upstream,...ue.origen!=="none"?{upstreamOrigen:ue.origen}:{},elisionEnv:process.env.BVSALA_GATEWAY_ELISION,hoyUtcIso:new Date().toISOString().slice(0,10)}),oi=ue.
1079
+ upstream??yn.upstream,kr=process.env.BVSALA_GATEWAY_ELISION??yn.elision,Se;try{Se=await Ma({puerto:gt,...nf?{log:()=>{},avisosDeNoMedido:!1}:{},license:{token:bt.license.token,publicKey:ut,licenseServerUrl:Co,
1080
+ checkOnStart:bt.source==="offline"},warn:e=>console.error(e),serviceAccountKey:Bc,...process.env.BVSALA_SEAT_ID?{seatId:process.env.BVSALA_SEAT_ID}:{},...oi?{upstream:oi}:Me?.upstream?{upstream:Me.upstream}:
1081
+ {},...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:kr!==
1082
+ "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.
1083
+ env.BVSALA_GATEWAY_ESFUERZO}:{},...process.env.BVSALA_METERING_URL?{meteringUrl:process.env.BVSALA_METERING_URL}:{}});}catch(e){console.error(`[bvsala ${F}] ${Ga(e,F,gt)}`),process.exit(1);}var Uc=oi??Me?.
1084
+ upstream??"https://api.anthropic.com";console.log(`[bvsala gateway] v${he} listening on http://127.0.0.1:${Se.puerto} \u2192 ${Uc}`);(bt.lineIsWarning?console.error:console.log)(`[bvsala gateway] ${bt.
1085
+ line}`);for(let e of bt.warnings)console.error(`[bvsala gateway] ${e}`);console.log("[bvsala gateway] metering: ON (service key present)");process.env.BVSALA_METERING_URL&&console.error(`[bvsala gatew\
1086
+ 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 \
1087
+ 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\
1088
+ EWAY_USAGE_INJECT=1) \u2014 streamed chat completions without stream_options get include_usage; their last chunk has an empty choices list.");{let e=pi(kr,true,process.env.BVSALA_GATEWAY_DIALES_ELISION===
1089
+ "1");(e.aviso?console.error:console.log)(`[bvsala gateway] ${e.linea}`);let t=Ii(process.env.BVSALA_GATEWAY_MODELO_HERMANO,true,kr!=="0");(t.aviso?console.error:console.log)(`[bvsala gateway] ${t.linea}`);
1090
+ let n=Ei(process.env.BVSALA_GATEWAY_ESFUERZO,true,kr!=="0");(n.aviso?console.error:console.log)(`[bvsala gateway] ${n.linea}`),yn.linea&&(yn.aviso?console.error:console.log)(`[bvsala gateway] ${yn.linea}`);}
1091
+ ue.upstream&&Me?.upstream&&ue.upstream!==Me.upstream&&console.error(`[bvsala ${F}] WARNING: BVSALA_GATEWAY_UPSTREAM=${ue.upstream} overrides this terminal's upstream (${Me.upstream}). If that is not w\
1092
+ hat you want, unset the variable.`);F==="codex"&&!Vs()&&console.error(`[bvsala codex] WARNING: this Node (${process.version}) cannot decompress zstd and Codex sends its body in zstd: traffic passes th\
1093
+ rough but is NOT metered. Use Node >= 22.15.`);var Lc=false;function Vc(){if(Lc)return;Lc=true;let e=Pa(Se.degradaciones());e&&console.error(e),console.error(va(Se.medicion(),F));}if(Me&&Ut){let e=hr(F,Se.puerto,
1094
+ le,{...Me.upstream?{modoCodex:Me.upstream.includes("chatgpt.com")?"chatgpt":"api-key"}:{},...ue.upstream?{upstreamElegido:ue.upstream}:{}});e.nota&&console.log(`[bvsala ${F}] ${e.nota}`);let t=e.bin;if(process.
1095
+ platform==="win32"){let r=jo(e.bin);r.tipo==="exe"?t=r.ruta:r.tipo==="solo-shim"&&(console.error(`[bvsala ${F}] \`${e.bin}\` is installed as an npm shim (${r.ruta}) and Windows cannot launch it safely\
1096
+ 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 Se.cerrar(),process.exit(127));}let n=spawn(
1097
+ t,e.args,{stdio:"inherit",env:{...process.env,...e.env}});n.on("error",r=>{console.error(`[bvsala ${F}] could not launch \`${e.bin}\`: ${String(r)}. Is it installed and on the PATH?`),Se.cerrar().then(
1098
+ ()=>process.exit(127));}),n.on("exit",(r,o)=>{Vc(),Se.cerrar().then(()=>process.exit(r??(o?1:0)));});}else {let e=new URL(Uc).hostname;e==="api.openai.com"?console.log(`[bvsala gateway] point your SDK at \
1099
+ it: base_url=http://127.0.0.1:${Se.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\
1100
+ ropic.com"||ue.upstream===void 0?console.log(`[bvsala gateway] point your terminal at it (or use \`bvsala ${No.join("|")}\`): ANTHROPIC_BASE_URL=http://127.0.0.1:${Se.puerto} claude \xB7 bvsala doct\
1101
+ or for the others`):console.log(`[bvsala gateway] point your client at http://127.0.0.1:${Se.puerto} plus the path prefix it already uses (for example /v1) \xB7 bvsala doctor for recipes`);}var Fc=async()=>{
1102
+ Vc(),await Se.cerrar(),process.exit(0);};process.on("SIGINT",()=>{Fc();});process.on("SIGTERM",()=>{Fc();});
827
1103
  /*! Bundled license information:
828
1104
 
829
1105
  @noble/curves/utils.js: