@bivelio/savings-layer 0.4.24 → 0.4.25

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,35 +1,43 @@
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 Oe from'zlib';import {connect}from'net';var Qt="context-management-2025-06-27";function Hn(){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}}]}}function mo(t,e){if(e!==void 0&&e!==""&&e!=="identity")return null;try{let n=JSON.parse(t.toString("utf8"));if(n===null||typeof n!="object"||Array.isArray(n)||typeof n.model!="string"||!Array.isArray(
3
- n.messages))return null;let r=Ji(n.context_management),o=Yi(n.context_management);return n.context_management=Zi(n.context_management),{cuerpo:Buffer.from(JSON.stringify(n),"utf8"),nuestros:r,triggerDelCliente:o}}catch{
4
- return null}}function Ji(t){let e=t!==null&&typeof t=="object"&&!Array.isArray(t)?t.edits:void 0,n=(Array.isArray(e)?e:[]).filter(r=>r!==null&&typeof r=="object"&&!Array.isArray(r)&&r.type===Kn);return po(
5
- n)!==po([Hn().edits[0]])}function Yi(t){let e=t!==null&&typeof t=="object"&&!Array.isArray(t)?t.edits:void 0,n=(Array.isArray(e)?e:[]).filter(o=>o!==null&&typeof o=="object"&&!Array.isArray(o)&&o.type===
6
- Kn);if(n.length===0)return null;let r=Number.POSITIVE_INFINITY;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)&&
7
- s.value>0?s.value:1e5;i<r&&(r=i);}return r}function po(t){return JSON.stringify(t,(e,n)=>n!==null&&typeof n=="object"&&!Array.isArray(n)?Object.fromEntries(Object.keys(n).sort().map(r=>[r,n[r]])):n)}var Kn="\
8
- clear_tool_uses_20250919",fo="clear_thinking_20251015";function Zi(t){let e=Hn().edits[0],n=t!==null&&typeof t=="object"&&!Array.isArray(t)?{...t}:{},r=(Array.isArray(n.edits)?n.edits:[]).filter(i=>i!==
9
- null&&typeof i=="object"&&!Array.isArray(i)&&i.type!==Kn),o=r.filter(i=>i.type===fo),s=r.filter(i=>i.type!==fo);return {...n,edits:[...o,...s,e]}}function ho(t,e,n=false){let r=" (TTL tuning ON if your li\
10
- cence includes cache_ttl_tuning; fail-closed)",o=n?" \xB7 context elision 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 elisio\
11
- n dials OFF";return t==="0"?{linea:"savings levers: OFF (BVSALA_GATEWAY_ELISION=0) - no TTL tuning and no context elision dials; the licence channel stays open for the license status",aviso:false}:{linea:(t===
12
- "1"?"licence channel: OPEN (BVSALA_GATEWAY_ELISION=1)":"licence channel: OPEN by default (=0 turns the levers off)")+r+o,aviso:n}}function go(t){return t===
13
- void 0||t.trim()===""?Qt:t.split(",").map(n=>n.trim()).filter(n=>n.length>0).includes(Qt)?t:`${t},${Qt}`}function _e(t){let e=t.toLowerCase();return e.startsWith("gpt-")||e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4")?/^gpt-5\.6/.test(e)?1.25:1:e.startsWith("gemini")?1:1.25}function Gn(t){let e=t.
14
- toLowerCase();return e.startsWith("claude")||e.startsWith("anthropic/")?2:_e(t)}var Qi=.3,ea=4096,ta=(t,e)=>t==="cache_control"?void 0:e;function Wn(t){return t===void 0?"":JSON.stringify(t,ta)??""}function na(t){return Array.isArray(t)?t.filter(e=>!(e!==null&&typeof e=="object"&&
15
- e.defer_loading===true)):t}function Jn(t){return createHash("sha1").update(t).digest("base64url").slice(0,16)}function qe(t,e){if(e!==void 0&&e!==""&&e!=="identity")return null;try{let n=JSON.parse(t.toString("\
16
- utf8"));if(n===null||typeof n!="object"||Array.isArray(n))return null;let r=n;return typeof r.model!="string"||!Array.isArray(r.messages)?null:r}catch{return null}}function bo(t){let e=Wn(t.system),n=Wn(
17
- na(t.tools)),r=Array.isArray(t.messages)?t.messages.slice(0,ea):[],o=[],s=[];for(let i of r){let c=Wn(i);o.push(Jn(c)),s.push(Buffer.byteLength(c,"utf8"));}return {system:Jn(e),tools:Jn(n),mensajes:o,bytes:s,
18
- bytesFijos:Buffer.byteLength(e,"utf8")+Buffer.byteLength(n,"utf8")}}function vo(t,e){if(t===void 0||t.system!==e.system||t.tools!==e.tools)return 1;let n=e.bytesFijos;for(let s of e.bytes)n+=s;if(n<=0)
19
- return 1;let r=0;for(;r<t.mensajes.length&&r<e.mensajes.length&&t.mensajes[r]===e.mensajes[r];)r++;let o=0;for(let s=r;s<e.bytes.length;s++)o+=e.bytes[s]??0;return o/n}function yo(t){let{fraccionNueva:e,
20
- umbral:n=Qi}=t;return e>=n}function Yn(t,e){if(t===null||typeof t!="object")return;if(Array.isArray(t)){for(let o of t)Yn(o,e);return}let n=t,r=n.cache_control;if(r!==null&&typeof r=="object"&&!Array.
21
- isArray(r)){let o=r;o.ttl==="1h"?(o.ttl="5m",e.rebajadas++):(o.ttl==="5m"||o.ttl===void 0)&&e.yaEran5m++;}for(let[o,s]of Object.entries(n))o!=="cache_control"&&s!==null&&typeof s=="object"&&Yn(s,e);}function ko(t,e){
22
- let n=Buffer.isBuffer(t)?qe(t,e):t;if(n===null)return null;try{let r={rebajadas:0,yaEran5m:0};for(let o of ["system","messages","tools"])Yn(n[o],r);return r.rebajadas===0?null:{cuerpo:Buffer.from(JSON.
23
- stringify(n),"utf8"),rebajadas:r.rebajadas,yaEran5m:r.yaEran5m}}catch{return null}}var en=class{constructor(e=512,n=3600*1e3){this.maxEntradas=e;this.maxEdadMs=n;}maxEntradas;maxEdadMs;visto=new Map;ultima(e,n){let r=this.visto.get(e);if(r!==void 0){if(n-r.vistoMs>this.maxEdadMs){this.
24
- visto.delete(e);return}return r.huella}}anotar(e,n,r){for(this.visto.delete(e),this.visto.set(e,{huella:n,vistoMs:r});this.visto.size>this.maxEntradas;){let o=this.visto.keys().next();if(o.done===true)break;
25
- this.visto.delete(o.value);}}get tamano(){return this.visto.size}};var xo="mid-conversation-output-config-2026-07-01",Xn=["low","medium","high","xhigh","max"],ra=new Set(["claude-fable-5-1","claude-mythos-5-1","claude-opus-5"]);function oa(t){return ra.has(t)}function Qn(t){
26
- return t!==void 0&&Xn.includes(t)}function sa(t){return {role:"system",content:[],output_config:{effort:t}}}function ia(t){if(t.output_config!==void 0&&t.output_config!==null)return true;let e=t.messages;
27
- return Array.isArray(e)?e.some(n=>typeof n=="object"&&n!==null&&n.output_config!==void 0):false}function wo(t,e,n){let r=qe(t,n);if(r===null||typeof r.model!="string"||!oa(r.model)||ia(r))return null;let o=r.
28
- messages;return Array.isArray(o)?(r.messages=[...o,sa(e)],{cuerpo:Buffer.from(JSON.stringify(r),"utf8"),nivel:e}):null}function So(t){let e=(t??"").split(",").map(n=>n.trim()).filter(Boolean);return e.
29
- includes(xo)||e.push(xo),e.join(",")}function Eo(t,e,n){return t===void 0||t===""?{linea:`per-turn effort: OFF (BVSALA_GATEWAY_ESFUERZO=${Xn.join("|")} turns it on)`,aviso:false}:Qn(t)?n?{linea:`per-tu\
30
- rn effort: ARMED at "${t}" (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 cach\
31
- e: the dial 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 "${t}\
32
- " is not a level. Use one of: ${Xn.join(", ")}`,aviso:true}}var rn={"gpt-4.1":{inputPer1k:.002,outputPer1k:.008,cachedInputPer1k:5e-4},"gpt-4.1-mini":{inputPer1k:4e-4,outputPer1k:.0016,cachedInputPer1k:1e-4},"gpt-4.1-nano":{inputPer1k:1e-4,outputPer1k:4e-4,cachedInputPer1k:25e-6},
2
+ 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\
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
+ 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.
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
41
  "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,
34
42
  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},
35
43
  "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},
@@ -37,76 +45,83 @@ outputPer1k:.06},"gpt-3.5-turbo":{inputPer1k:5e-4,outputPer1k:.0015},"gpt-5":{in
37
45
  cachedInputPer1k:125e-6},"gpt-5.2":{inputPer1k:.00175,outputPer1k:.014,cachedInputPer1k:175e-6},"gpt-5.2-codex":{inputPer1k:.00175,outputPer1k:.014,cachedInputPer1k:175e-6},"gpt-5.3-codex":{inputPer1k:.00175,
38
46
  outputPer1k:.014,cachedInputPer1k:175e-6},"gpt-5.4":{inputPer1k:.0025,outputPer1k:.015,cachedInputPer1k:25e-5},"gpt-5.4-mini":{inputPer1k:75e-5,outputPer1k:.0045,cachedInputPer1k:75e-6},"gpt-5.4-nano":{
39
47
  inputPer1k:2e-4,outputPer1k:.00125,cachedInputPer1k:2e-5},"gpt-5.5":{inputPer1k:.005,outputPer1k:.03,cachedInputPer1k:5e-4},"gpt-5.6-luna":{inputPer1k:2e-4,outputPer1k:.0012,cachedInputPer1k:2e-5},"gp\
40
- t-5.6-sol":{inputPer1k:.004,outputPer1k:.02,cachedInputPer1k:4e-4},"gpt-5.6-terra":{inputPer1k:.002,outputPer1k:.012,cachedInputPer1k:2e-4},o3:{inputPer1k:.002,outputPer1k:.008,cachedInputPer1k:5e-4},
41
- "o3-mini":{inputPer1k:.0011,outputPer1k:.0044,cachedInputPer1k:55e-5},"o3-pro":{inputPer1k:.02,outputPer1k:.08},"o4-mini":{inputPer1k:.0011,outputPer1k:.0044,cachedInputPer1k:275e-6},"claude-opus-4-5":{
48
+ t-5.6-sol":{inputPer1k:.004,outputPer1k:.02,cachedInputPer1k:4e-4},"gpt-5.6-terra":{inputPer1k:.002,outputPer1k:.012,cachedInputPer1k:2e-4},"gpt-6-astra":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:.001},
49
+ "gpt-6-sol":{inputPer1k:.002,outputPer1k:.01,cachedInputPer1k:2e-4},"gpt-6-luna":{inputPer1k:1e-4,outputPer1k:5e-4,cachedInputPer1k:1e-5},o3:{inputPer1k:.002,outputPer1k:.008,cachedInputPer1k:5e-4},"o\
50
+ 3-mini":{inputPer1k:.0011,outputPer1k:.0044,cachedInputPer1k:55e-5},"o3-pro":{inputPer1k:.02,outputPer1k:.08},"o4-mini":{inputPer1k:.0011,outputPer1k:.0044,cachedInputPer1k:275e-6},"claude-opus-4-5":{
42
51
  inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},"claude-opus-4-6":{inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},"claude-opus-4-7":{inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},
43
- "claude-opus-4-8":{inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},"claude-opus-5":{inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},"claude-opus-4":{inputPer1k:.015,outputPer1k:.075,cachedInputPer1k:.0015},
44
- "claude-sonnet-4-5":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-sonnet-4-6":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-sonnet-5":{inputPer1k:.002,outputPer1k:.01,
45
- cachedInputPer1k:2e-4},"claude-fable-5":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:.001},"claude-fable-5-1":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:25e-5},"claude-mythos-5-1":{inputPer1k:.01,
46
- outputPer1k:.05,cachedInputPer1k:25e-5},"claude-mythos-5":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:.001},"claude-sonnet-4":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-haik\
47
- u-4-5":{inputPer1k:.001,outputPer1k:.005,cachedInputPer1k:1e-4},"claude-3-5-sonnet":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-3-5-haiku":{inputPer1k:8e-4,outputPer1k:.004,cachedInputPer1k:8e-5},
48
- "claude-3-opus":{inputPer1k:.015,outputPer1k:.075,cachedInputPer1k:.0015},"claude-3-haiku":{inputPer1k:25e-5,outputPer1k:.00125,cachedInputPer1k:3e-5},"gemini-3.7-flash":{inputPer1k:75e-5,outputPer1k:.00375,
49
- cachedInputPer1k:75e-6},"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-\
50
- preview":{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}};
51
- function er(t,e,n){if(!n)return;let r=t[n];if(r)return r;let o=n.lastIndexOf("/"),s=o>=0?n.slice(o+1):n,i=t[s];if(i)return i;for(let c of e){if(!s.startsWith(c))continue;let l=s.charAt(c.length);if(l!==
52
- ""&&l!=="-"&&l!=="."&&l!=="_")continue;let a=s.slice(c.length+1);if(!(/^\d/.test(a)&&!/^\d{4}/.test(a)))return t[c]}}function tr(t){return Object.keys(t).sort((e,n)=>n.length-e.length)}var aa=["o3-dee\
53
- p-research","o4-mini-deep-research"],nn={...rn,...Object.fromEntries(aa.map(t=>[t,null]))},_o=tr(nn);function me(t){return er(nn,_o,t)??void 0}var ca=Object.fromEntries(Object.keys(nn).map(t=>[t,nn[t]===
54
- null?null:t]));function Rt(t){return er(ca,_o,t)??void 0}var la=/^\d{4}-?\d{2}-?\d{2}$/;function on(t){let e=Rt(t);if(e===void 0)return;let n=t.lastIndexOf("/"),r=n>=0?t.slice(n+1):t;if(!(e!==t&&e!==r&&
55
- !la.test(r.slice(e.length+1))))return rn[e]}var To={"claude-fable-5":"claude-fable-5-1"};function ua(t,e){let n=me(t),r=me(e);if(n===void 0||r===void 0||n.inputPer1k!==r.inputPer1k||n.outputPer1k!==r.outputPer1k||_e(t)!==_e(e))return false;let o=n.
56
- cachedInputPer1k??n.inputPer1k;return (r.cachedInputPer1k??r.inputPer1k)<o}function da(t){let e=Rt(t);if(e===void 0||e!==t)return null;let n=To[e];return n===void 0||n===e||!ua(e,n)?null:{solicitado:t,
57
- servido:n}}var pa=/(^|,)\s*context-1m/i;function fa(t){let e=t.tool_choice;if(e===null||typeof e!="object")return false;let n=e.type;return n==="any"||n==="tool"}function Ro(t,e,n={}){if(n.betas!==void 0&&
58
- pa.test(n.betas))return null;let r=qe(t,e);if(r===null||fa(r))return null;let o=da(r.model);return o===null?null:(r.model=o.servido,{cuerpo:Buffer.from(JSON.stringify(r),"utf8"),cambio:o})}function Ao(t,e,n){
59
- let r=Object.entries(To).map(([o,s])=>`${o}\u2192${s}`).join(", ");return t!=="1"?{linea:"sibling model routing: OFF (BVSALA_GATEWAY_MODELO_HERMANO=1 turns it on)",aviso:false}:n?{linea:`sibling model \
52
+ "claude-opus-4-8":{inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},"claude-opus-5":{inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},"claude-opus-5-5":{inputPer1k:.004,outputPer1k:.02,cachedInputPer1k:2e-4},
53
+ "claude-opus-4":{inputPer1k:.015,outputPer1k:.075,cachedInputPer1k:.0015},"claude-sonnet-4-5":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-sonnet-4-6":{inputPer1k:.003,outputPer1k:.015,
54
+ cachedInputPer1k:3e-4},"claude-sonnet-5":{inputPer1k:.002,outputPer1k:.01,cachedInputPer1k:2e-4},"claude-fable-5":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:.001},"claude-fable-5-1":{inputPer1k:.01,
55
+ outputPer1k:.05,cachedInputPer1k:25e-5},"claude-mythos-5-1":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:25e-5},"claude-mythos-5":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:.001},"claude-son\
56
+ net-4":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-haiku-4-5":{inputPer1k:.001,outputPer1k:.005,cachedInputPer1k:1e-4},"claude-3-5-sonnet":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},
57
+ "claude-3-5-haiku":{inputPer1k:8e-4,outputPer1k:.004,cachedInputPer1k:8e-5},"claude-3-opus":{inputPer1k:.015,outputPer1k:.075,cachedInputPer1k:.0015},"claude-3-haiku":{inputPer1k:25e-5,outputPer1k:.00125,
58
+ cachedInputPer1k:3e-5},"gemini-3.8-flash":{inputPer1k:75e-5,outputPer1k:.00375,cachedInputPer1k:75e-6},"gemini-3.7-flash":{inputPer1k:75e-5,outputPer1k:.00375,cachedInputPer1k:75e-6},"gemini-3.6-flash":{
59
+ 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
+ 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
+ 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:{
63
+ 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 \
60
75
  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\
61
76
  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_\
62
- ELISION=0 turns off the levers",aviso:true}}var Io=new Set;function z(t,e){Io.has(t)||(Io.add(t),console.warn(e));}var Le="0.4.24",nr="x-bvsala-version";var ot=class{options;now;flushIntervalMs;maxBatch;maxBuffer;buffer=[];seatId;ci;timer;inflight=null;fallosSeguidos=0;constructor(e){this.options=e,this.now=e.now??(()=>Date.now()),this.flushIntervalMs=
63
- e.flushIntervalMs??15e3,this.maxBatch=e.maxBatch??50,this.maxBuffer=e.maxBuffer??1e3,this.ci=e.ci??false;}setSeat(e,n){e&&(this.seatId=e),this.ci=n;}record(e){this.buffer.push({report:e,at:this.now()}),this.
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=
78
+ 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.
64
79
  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.
65
- flushIntervalMs),this.timer.unref?.());}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0),this.flush();}async stopAndDrain(e){this.timer&&(clearInterval(this.timer),this.timer=void 0);let n=e??
80
+ 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??
66
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.
67
- inflight)return this.inflight;if(this.buffer.length!==0){this.inflight=this.hacerFlush();try{await this.inflight;}finally{this.inflight=null;}}}async hacerFlush(){let e=this.options.fetchImpl??globalThis.
68
- fetch;if(!e)return;let n=this.buffer.splice(0,this.maxBatch);try{let r=n.map(s=>this.toWire(s)),o=await e(this.options.url,{method:"POST",headers:{"content-type":"application/json",authorization:`Bear\
69
- er ${this.options.serviceAccountKey}`,[nr]:`${this.options.surface??"sdk"}/${Le}`},body:JSON.stringify(r)});o.ok?this.fallosSeguidos=0:o.status>=500?(this.fallosSeguidos++,this.requeue(n),this.avisarDeFallo(
82
+ 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(
70
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\
71
86
  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?.(
72
87
  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.
73
- fallosSeguidos++,this.requeue(n),this.avisarDeFallo(r instanceof Error?r.message:"network error");}}avisarDeFallo(e){if(this.options.silenceWarnings)return;let n=this.fallosSeguidos;n<3||(n-3)%12!==0||
74
- console.warn(`[bv-sala] usage reporting has failed ${n} times in a row against ${this.options.url} (${e}). Requests keep working, but usage is not arriving: the dashboard will say it sees no traffic a\
75
- nd billable seats will show zero. Check 'meteringUrl' \u2014 by default it is \`\${licenseServerUrl}/api/metering/usage\`.`);}requeue(e){this.buffer=[...e,...this.buffer],this.buffer.length>this.maxBuffer&&
76
- (this.buffer.length=this.maxBuffer);}toWire(e){let n=e.report;return {orgId:this.options.orgId??"self",...this.seatId?{seatId:this.seatId}:{},...this.ci?{ci:true}:{},requestId:n.requestId,model:n.model,at:e.
88
+ 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||
89
+ console.warn(`[bv-sala] usage reporting has failed ${n} times in a row against ${this.options.url} (${t}). Requests keep working, but usage is not arriving: the dashboard will say it sees no traffic a\
90
+ nd billable seats will show zero. Check 'meteringUrl' \u2014 by default it is \`\${licenseServerUrl}/api/metering/usage\`.`);}requeue(t){this.buffer=[...t,...this.buffer],this.buffer.length>this.maxBuffer&&
91
+ (this.buffer.length=this.maxBuffer);}toWire(t){let n=t.report;return {orgId:this.options.orgId??"self",...this.seatId?{seatId:this.seatId}:{},...this.ci?{ci:true}:{},requestId:n.requestId,model:n.model,at:t.
77
92
  at,avoidedLlm:n.calls.avoidedLlm,actualLlm:n.calls.actualLlm,baselineInputTokens:n.tokens.baselineInput,actualInputTokens:n.tokens.actualInput,eliminatedInputTokens:n.tokens.eliminatedInput,compressedInputTokens:n.
78
93
  tokens.compressedInput,baselineOutputTokens:n.tokens.baselineOutput,actualOutputTokens:n.tokens.actualOutput,providerCachedInputTokens:n.tokens.providerCachedInput??0,cacheResult:n.cache.result,...n.cost.
79
94
  eliminatedInputFloorCost!==void 0&&Number.isFinite(n.cost.eliminatedInputFloorCost)&&n.cost.eliminatedInputFloorCost>0&&n.tokens.eliminatedInput>0?{eliminatedInputFloorCost:n.cost.eliminatedInputFloorCost}:
80
95
  {},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}$/.
81
96
  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.
82
- attribution.sessionId}:{},...n.attribution?.agentId?{agentId:n.attribution.agentId}:{}}}};function sn(){return globalThis.process}function ma(t){if(/^[0-9a-f]{12}$/.test(t)||/^\d{1,3}(\.\d{1,3}){3}$/.test(t)||/^ip-\d{1,3}(-\d{1,3}){3}$/i.test(t))return true;let e="[bcdfghjklmnpqrstvwxz2456789\
83
- ]";return new RegExp(`-${e}{8,10}-${e}{5}$`).test(t)}function ha(t){return !!(t.AWS_LAMBDA_FUNCTION_NAME??t.LAMBDA_TASK_ROOT??t.VERCEL??t.VERCEL_ENV??t.K_SERVICE??t.FUNCTION_TARGET??t.FUNCTIONS_WORKER_RUNTIME??
84
- t.NETLIFY)}async function ga(){if(sn()?.execPath)try{let e=await import(["node","os"].join(":")),n=typeof e.hostname=="function"?e.hostname():"";return n.length>0?n:void 0}catch{return}}async function ba(t,e=ga){
85
- if(t.KUBERNETES_SERVICE_HOST||ha(t))return;let n=t.HOSTNAME??t.COMPUTERNAME??await e();if(!(!n||ma(n)))return n}async function va(){let t=sn();if(!t||!t.env)return;let e=t.env,n=await ba(e),r=[t.platform,
86
- t.arch,t.execPath,n,e.USER??e.USERNAME??e.LOGNAME,e.HOME??e.USERPROFILE].filter(o=>typeof o=="string"&&o.length>0);return r.length?r.join("|"):void 0}var ya=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTI\
87
- ONS","GITLAB_CI","CIRCLECI","TRAVIS","JENKINS_URL","BUILDKITE","TF_BUILD","TEAMCITY_VERSION","BITBUCKET_BUILD_NUMBER","CODEBUILD_BUILD_ID","HEROKU_TEST_RUN_ID","DRONE"];function an(){let t=sn()?.env;if(!t)
88
- return false;for(let e of ya){let n=t[e];if(n&&n!=="false"&&n!=="0")return true}return false}async function ka(t,e){let n=globalThis.crypto,r=new TextEncoder;if(n?.subtle)try{let i=await n.subtle.importKey("raw",
89
- r.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),c=await n.subtle.sign("HMAC",i,r.encode(e));return [...new Uint8Array(c)].map(l=>l.toString(16).padStart(2,"0")).join("")}catch{}let o=2166136261,s=`${t}\
90
- |${e}`;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 cn(t){let n=sn()?.env?.BVSALA_SEAT_ID;if(n&&xa.test(n))return n;let r=await va();
91
- if(!r)return;let o=await ka(t,r);if(o)return `m-${o.slice(0,32)}`}var xa=/^[A-Za-z0-9._:/-]{1,128}$/;function rr(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function ln(t,e=""){if(typeof t!="number"){let n=e&&
92
- `"${e}" `;throw new TypeError(`${n}expected number, got ${typeof t}`)}if(!Number.isSafeInteger(t)||t<0){let n=e&&`"${e}" `;throw new RangeError(`${n}expected integer >= 0, got ${t}`)}}function he(t,e,n=""){
93
- let r=rr(t),o=t?.length,s=e!==void 0;if(!r||s&&o!==e){let i=n&&`"${n}" `,c=s?` of length ${e}`:"",l=r?`length=${o}`:`type=${typeof t}`,a=i+"expected Uint8Array"+c+", got "+l;throw r?new RangeError(a):
94
- new TypeError(a)}return t}function or(t,e=true){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Oo(t,e){he(t,void 0,"digestInt\
95
- o() output");let n=e.outputLen;if(t.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function At(...t){for(let e=0;e<t.length;e++)t[e].fill(0);}function un(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var Do=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",wa=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function dn(t){if(he(t),Do)return t.toHex();
96
- let e="";for(let n=0;n<t.length;n++)e+=wa[t[n]];return e}var Te={_0:48,_9:57,A:65,F:70,a:97,f:102};function Co(t){if(t>=Te._0&&t<=Te._9)return t-Te._0;if(t>=Te.A&&t<=Te.F)return t-(Te.A-10);if(t>=Te.a&&
97
- t<=Te.f)return t-(Te.a-10)}function It(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(Do)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?
98
- new RangeError(o.message):o}let e=t.length,n=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(n);for(let o=0,s=0;o<n;o++,s+=2){let i=Co(t.charCodeAt(
99
- s)),c=Co(t.charCodeAt(s+1));if(i===void 0||c===void 0){let l=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+l+'" at index '+s)}r[o]=i*16+c;}return r}function sr(...t){let e=0;for(let r=0;r<t.length;r++){let o=t[r];he(o),e+=o.length;}let n=new Uint8Array(e);for(let r=0,o=0;r<t.length;r++){let s=t[r];n.set(s,o),o+=s.length;}return n}function Po(t,e={}){let n=(o,s)=>t(s).update(o).digest(),r=t(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=o=>t(o),Object.assign(n,e),Object.freeze(n)}function Lo(t=32){
100
- ln(t,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(t>65536)throw new RangeError(
101
- `"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}var Mo=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});var pn=class{blockLen;outputLen;canXOF=false;padOffset;isLE;buffer;view;finished=false;length=0;pos=0;destroyed=false;constructor(e,n,r,o){this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=
102
- new Uint8Array(e),this.view=un(this.buffer);}update(e){or(this),he(e);let{view:n,buffer:r,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let c=Math.min(o-this.pos,s-i);if(c===o){let l=un(e);for(;o<=s-i;i+=
103
- o)this.process(l,i);continue}r.set(e.subarray(i,i+c),this.pos),this.pos+=c,i+=c,this.pos===o&&(this.process(n,0),this.pos=0);}return this.length+=e.length,this.roundClean(),this}digestInto(e){or(this),
104
- Oo(e,this),this.finished=true;let{buffer:n,view:r,blockLen:o,isLE:s}=this,{pos:i}=this;n[i++]=128,At(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(r,0),i=0);for(let u=i;u<o;u++)n[u]=0;r.setBigUint64(
105
- o-8,BigInt(this.length*8),s),this.process(r,0);let c=un(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let a=l/4,d=this.get();if(a>d.length)throw new Error("_s\
106
- ha2: outputLen bigger than state");for(let u=0;u<a;u++)c.setUint32(4*u,d[u],s);}digest(){let{buffer:e,outputLen:n}=this;this.digestInto(e);let r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||=new this.
107
- constructor,e.set(...this.get());let{blockLen:n,buffer:r,length:o,finished:s,destroyed:i,pos:c}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=c,o%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}};var ee=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var fn=BigInt(4294967295),No=BigInt(32);function Sa(t,e=false){return e?{h:Number(t&fn),l:Number(t>>No&fn)}:{h:Number(t>>No&fn)|0,l:Number(t&fn)|0}}function $o(t,e=false){let n=t.length,r=new Uint32Array(n),
108
- o=new Uint32Array(n);for(let s=0;s<n;s++){let{h:i,l:c}=Sa(t[s],e);[r[s],o[s]]=[i,c];}return [r,o]}var ir=(t,e,n)=>t>>>n,ar=(t,e,n)=>t<<32-n|e>>>n,He=(t,e,n)=>t>>>n|e<<32-n,Ke=(t,e,n)=>t<<32-n|e>>>n,Ct=(t,e,n)=>t<<64-n|e>>>n-32,Ot=(t,e,n)=>t>>>n-32|e<<64-n;function be(t,e,n,r){let o=(e>>>0)+(r>>>0);return {h:t+n+(o/2**32|0)|0,l:o|0}}var Bo=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),jo=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Uo=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Vo=(t,e,n,r,o)=>e+
109
- n+r+o+(t/2**32|0)|0,Fo=(t,e,n,r,o)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(o>>>0),zo=(t,e,n,r,o,s)=>e+n+r+o+s+(t/2**32|0)|0;var qo=$o(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242",
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",
110
125
  "0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc6\
111
126
  8b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","\
112
127
  0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3\
@@ -114,532 +129,571 @@ c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a6
114
129
  x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5d\
115
130
  efb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0x\
116
131
  eada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c1\
117
- 00d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),_a=qo[0],Ta=qo[1],Me=new Uint32Array(80),Ne=new Uint32Array(80),cr=class extends pn{constructor(e){
118
- super(128,e,16,false);}get(){let{Ah:e,Al:n,Bh:r,Bl:o,Ch:s,Cl:i,Dh:c,Dl:l,Eh:a,El:d,Fh:u,Fl:p,Gh:f,Gl:g,Hh:y,Hl:m}=this;return [e,n,r,o,s,i,c,l,a,d,u,p,f,g,y,m]}set(e,n,r,o,s,i,c,l,a,d,u,p,f,g,y,m){this.Ah=
119
- e|0,this.Al=n|0,this.Bh=r|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=c|0,this.Dl=l|0,this.Eh=a|0,this.El=d|0,this.Fh=u|0,this.Fl=p|0,this.Gh=f|0,this.Gl=g|0,this.Hh=y|0,this.Hl=m|0;}process(e,n){for(let E=0;E<
120
- 16;E++,n+=4)Me[E]=e.getUint32(n),Ne[E]=e.getUint32(n+=4);for(let E=16;E<80;E++){let v=Me[E-15]|0,R=Ne[E-15]|0,I=He(v,R,1)^He(v,R,8)^ir(v,R,7),C=Ke(v,R,1)^Ke(v,R,8)^ar(v,R,7),D=Me[E-2]|0,M=Ne[E-2]|0,F=He(
121
- D,M,19)^Ct(D,M,61)^ir(D,M,6),q=Ke(D,M,19)^Ot(D,M,61)^ar(D,M,6),k=Uo(C,q,Ne[E-7],Ne[E-16]),T=Vo(k,I,F,Me[E-7],Me[E-16]);Me[E]=T|0,Ne[E]=k|0;}let{Ah:r,Al:o,Bh:s,Bl:i,Ch:c,Cl:l,Dh:a,Dl:d,Eh:u,El:p,Fh:f,Fl:g,
122
- Gh:y,Gl:m,Hh:b,Hl:w}=this;for(let E=0;E<80;E++){let v=He(u,p,14)^He(u,p,18)^Ct(u,p,41),R=Ke(u,p,14)^Ke(u,p,18)^Ot(u,p,41),I=u&f^~u&y,C=p&g^~p&m,D=Fo(w,R,C,Ta[E],Ne[E]),M=zo(D,b,v,I,_a[E],Me[E]),F=D|0,
123
- q=He(r,o,28)^Ct(r,o,34)^Ct(r,o,39),k=Ke(r,o,28)^Ot(r,o,34)^Ot(r,o,39),T=r&s^r&c^s&c,O=o&i^o&l^i&l;b=y|0,w=m|0,y=f|0,m=g|0,f=u|0,g=p|0,{h:u,l:p}=be(a|0,d|0,M|0,F|0),a=c|0,d=l|0,c=s|0,l=i|0,s=r|0,i=o|0;
124
- let L=Bo(F,k,O);r=jo(L,M,q,T),o=L|0;}(({h:r,l:o}=be(this.Ah|0,this.Al|0,r|0,o|0))),{h:s,l:i}=be(this.Bh|0,this.Bl|0,s|0,i|0),{h:c,l}=be(this.Ch|0,this.Cl|0,c|0,l|0),{h:a,l:d}=be(this.Dh|0,this.Dl|0,a|0,d|
125
- 0),{h:u,l:p}=be(this.Eh|0,this.El|0,u|0,p|0),{h:f,l:g}=be(this.Fh|0,this.Fl|0,f|0,g|0),{h:y,l:m}=be(this.Gh|0,this.Gl|0,y|0,m|0),{h:b,l:w}=be(this.Hh|0,this.Hl|0,b|0,w|0),this.set(r,o,s,i,c,l,a,d,u,p,
126
- f,g,y,m,b,w);}roundClean(){At(Me,Ne);}destroy(){this.destroyed=true,At(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}},lr=class extends cr{Ah=ee[0]|0;Al=ee[1]|0;Bh=ee[2]|0;Bl=ee[3]|0;Ch=ee[4]|0;Cl=ee[5]|
127
- 0;Dh=ee[6]|0;Dl=ee[7]|0;Eh=ee[8]|0;El=ee[9]|0;Fh=ee[10]|0;Fl=ee[11]|0;Gh=ee[12]|0;Gl=ee[13]|0;Hh=ee[14]|0;Hl=ee[15]|0;constructor(){super(64);}};var mn=Po(()=>new lr,Mo(3));var J=(t,e,n)=>he(t,e,n),dr=ln,pr=dn,ve=(...t)=>sr(...t),Ho=t=>It(t),bn=rr,Ko=t=>Lo(t),gn=BigInt(0),ur=BigInt(1);function st(t,e=""){if(typeof t!="boolean"){let n=e&&`"${e}" `;throw new TypeError(n+"e\
128
- xpected boolean, got type="+typeof t)}return t}function Ra(t){if(typeof t=="bigint"){if(!hn(t))throw new RangeError("positive bigint expected, got "+t)}else dr(t);return t}function Re(t,e=""){if(typeof t!=
129
- "number"){let n=e&&`"${e}" `;throw new TypeError(n+"expected number, got type="+typeof t)}if(!Number.isSafeInteger(t)){let n=e&&`"${e}" `;throw new RangeError(n+"expected safe integer, got "+t)}}function Go(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?gn:BigInt("0x"+t)}function fr(t){return Go(dn(t))}function Ae(t){return Go(dn(Dt(he(t)).reverse()))}
130
- function mr(t,e){if(ln(e),e===0)throw new RangeError("zero length");t=Ra(t);let n=t.toString(16);if(n.length>e*2)throw new RangeError("number too large");return It(n.padStart(e*2,"0"))}function Wo(t,e){
131
- return mr(t,e).reverse()}function Jo(t,e){if(t=J(t),e=J(e),t.length!==e.length)return false;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}function Dt(t){return Uint8Array.from(J(t))}var hn=t=>typeof t=="bigint"&&gn<=t;function Aa(t,e,n){return hn(t)&&hn(e)&&hn(n)&&e<=t&&t<n}function hr(t,e,n,r){if(!Aa(e,n,r))throw new RangeError(
132
- "expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function gr(t){if(t<gn)throw new Error("expected non-negative bigint, got "+t);let e;for(e=0;t>gn;t>>=ur,e+=1);return e}var Yo=t=>(ur<<BigInt(t))-ur;function Ge(t,e={},n={}){if(Object.prototype.toString.call(t)!=="[object Object]")throw new TypeError("expected valid options object");function r(s,i,c){if(!c&&i!=="function"&&!Object.hasOwn(t,s))throw new TypeError(
133
- `param "${s}" is invalid: expected own property`);let l=t[s];if(c&&l===void 0)return;let a=typeof l;if(a!==i||l===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${a}`)}let o=(s,i)=>Object.
134
- entries(s).forEach(([c,l])=>r(c,l,i));o(e,false),o(n,true);}var br=()=>{throw new Error("not implemented")};var te=BigInt(0),Z=BigInt(1),We=BigInt(2),es=BigInt(3),ts=BigInt(4),ns=BigInt(5),Ia=BigInt(7),rs=BigInt(8),Ca=BigInt(9),os=BigInt(16);function G(t,e){if(e<=te)throw new Error("mod: expected positive m\
135
- odulus, got "+e);let n=t%e;return n>=te?n:e+n}function ge(t,e,n){if(e<te)throw new Error("pow2: expected non-negative exponent, got "+e);let r=t;for(;e-- >te;)r*=r,r%=n;return r}function Zo(t,e){if(t===te)throw new Error("invert: expected non-zer\
136
- o number");if(e<=te)throw new Error("invert: expected positive modulus, got "+e);let n=G(t,e),r=e,o=te,i=Z;for(;n!==te;){let a=r/n,d=r-n*a,u=o-i*a;r=n,n=d,o=i,i=u;}if(r!==Z)throw new Error(
137
- "invert: does not exist");return G(o,e)}function vr(t,e,n){let r=t;if(!r.eql(r.sqr(e),n))throw new Error("Cannot find square root")}function ss(t,e){let n=t,r=(n.ORDER+Z)/ts,o=n.pow(e,r);return vr(n,o,
138
- e),o}function Oa(t,e){let n=t,r=(n.ORDER-ns)/rs,o=n.mul(e,We),s=n.pow(o,r),i=n.mul(e,s),c=n.mul(n.mul(i,We),s),l=n.mul(i,n.sub(c,n.ONE));return vr(n,l,e),l}function Da(t){let e=xn(t),n=is(t),r=n(e,e.neg(
139
- e.ONE)),o=n(e,r),s=n(e,e.neg(r)),i=(t+Ia)/os;return((c,l)=>{let a=c,d=a.pow(l,i),u=a.mul(d,r),p=a.mul(d,o),f=a.mul(d,s),g=a.eql(a.sqr(u),l),y=a.eql(a.sqr(p),l);d=a.cmov(d,u,g),u=a.cmov(f,p,y);let m=a.
140
- eql(a.sqr(u),l),b=a.cmov(d,u,m);return vr(a,b,l),b})}function is(t){if(t<es)throw new Error("sqrt is not defined for small field");let e=t-Z,n=0;for(;e%We===te;)e/=We,n++;let r=We,o=xn(t);for(;Xo(o,r)===
141
- 1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return ss;let s=o.pow(r,e),i=(e+Z)/We;return function(l,a){let d=l;if(d.is0(a))return a;if(Xo(d,a)!==1)throw new Error(
142
- "Cannot find square root");let u=n,p=d.mul(d.ONE,s),f=d.pow(a,e),g=d.pow(a,i);for(;!d.eql(f,d.ONE);){if(d.is0(f))return d.ZERO;let y=1,m=d.sqr(f);for(;!d.eql(m,d.ONE);)if(y++,m=d.sqr(m),y===u)throw new Error(
143
- "Cannot find square root");let b=Z<<BigInt(u-y-1),w=d.pow(p,b);u=y,p=d.sqr(w),f=d.mul(f,p),g=d.mul(g,w);}return g}}function Pa(t){return t%ts===es?ss:t%rs===ns?Oa:t%os===Ca?Da(t):is(t)}var Ie=(t,e)=>(G(
144
- t,e)&Z)===Z,La=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function as(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},n=La.
145
- reduce((r,o)=>(r[o]="function",r),e);if(Ge(t,n),Re(t.BYTES,"BYTES"),Re(t.BITS,"BITS"),t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=Z)throw new Error("inval\
146
- id field: expected ORDER > 1, got "+t.ORDER);return t}function Ma(t,e,n){let r=t;if(n<te)throw new Error("invalid exponent, negatives unsupported");if(n===te)return r.ONE;if(n===Z)return e;let o=r.ONE,
147
- s=e;for(;n>te;)n&Z&&(o=r.mul(o,s)),s=r.sqr(s),n>>=Z;return o}function kn(t,e,n=false){let r=t,o=new Array(e.length).fill(n?r.ZERO:void 0),s=e.reduce((c,l,a)=>r.is0(l)?c:(o[a]=c,r.mul(c,l)),r.ONE),i=r.inv(
148
- s);return e.reduceRight((c,l,a)=>r.is0(l)?c:(o[a]=r.mul(c,o[a]),r.mul(c,l)),i),o}function Xo(t,e){let n=t,r=(n.ORDER-Z)/We,o=n.pow(e,r),s=n.eql(o,n.ONE),i=n.eql(o,n.ZERO),c=n.eql(o,n.neg(n.ONE));if(!s&&!i&&!c)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function Na(t,e){if(e!==void 0&&dr(e),t<=te)throw new Error("invalid n length: expected positive n, got "+t);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);
149
- let n=gr(t);if(e!==void 0&&e<n)throw new Error(`invalid n length: expected bit length (${n}) >= n.length (${e})`);let r=e!==void 0?e:n,o=Math.ceil(r/8);return {nBitLength:r,nByteLength:o}}var Qo=new WeakMap,
150
- yn=class{ORDER;BITS;BYTES;isLE;ZERO=te;ONE=Z;_lengths;_mod;constructor(e,n={}){if(e<=Z)throw new Error("invalid field: expected ORDER > 1, got "+e);let r;this.isLE=false,n!=null&&typeof n=="object"&&(typeof n.
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.
151
166
  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.
152
- freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:s}=Na(e,r);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2\
153
- 048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this);}create(e){return G(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got\
154
- "+typeof e);return te<=e&&e<this.ORDER}is0(e){return e===te}isValidNot0(e){return !this.is0(e)&&this.isValid(e)}isOdd(e){return (e&Z)===Z}neg(e){return G(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return G(
155
- e*e,this.ORDER)}add(e,n){return G(e+n,this.ORDER)}sub(e,n){return G(e-n,this.ORDER)}mul(e,n){return G(e*n,this.ORDER)}pow(e,n){return Ma(this,e,n)}div(e,n){return G(e*Zo(n,this.ORDER),this.ORDER)}sqrN(e){
156
- return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return Zo(e,this.ORDER)}sqrt(e){let n=Qo.get(this);return n||Qo.set(this,n=Pa(this.ORDER)),n(this,e)}toBytes(e){return this.
157
- isLE?Wo(e,this.BYTES):mr(e,this.BYTES)}fromBytes(e,n=false){J(e);let{_lengths:r,BYTES:o,isLE:s,ORDER:i,_mod:c}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>o)throw new Error("Field.fromBytes\
158
- : expected "+r+" bytes, got "+e.length);let a=new Uint8Array(o);a.set(e,s?0:a.length-e.length),e=a;}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let l=s?Ae(e):
159
- fr(e);if(c&&(l=G(l,i)),!n&&!this.isValid(l))throw new Error("invalid field element: outside of range 0..ORDER");return l}invertBatch(e){return kn(this,e)}cmov(e,n,r){return st(r,"condition"),r?n:e}};Object.
160
- freeze(yn.prototype);function xn(t,e={}){return new yn(t,e)}var wn=BigInt(0),wr=BigInt(1);function cs(t,e){let n=e.negate();return t?n:e}function En(t,e){let n=kn(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function ps(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)
161
- throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function yr(t,e){ps(t,e);let n=Math.ceil(e/t)+1,r=2**(t-1),o=2**t,s=Yo(t),i=BigInt(t);return {windows:n,windowSize:r,mask:s,maxNumber:o,
162
- shiftBy:i}}function ls(t,e,n){let{windowSize:r,mask:o,maxNumber:s,shiftBy:i}=n,c=Number(t&o),l=t>>i;c>r&&(c-=s,l+=wr);let a=e*r,d=a+Math.abs(c)-1,u=c===0,p=c<0,f=e%2!==0;return {nextN:l,offset:d,isZero:u,
163
- isNeg:p,isNegF:f,offsetF:a}}var kr=new WeakMap,fs=new WeakMap;function xr(t){return fs.get(t)||1}function us(t){if(t!==wn)throw new Error("invalid wNAF")}var Sn=class{BASE;ZERO;Fn;bits;constructor(e,n){this.BASE=e.BASE,this.ZERO=
164
- e.ZERO,this.Fn=e.Fn,this.bits=n;}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>wn;)n&wr&&(r=r.add(o)),o=o.double(),n>>=wr;return r}precomputeWindow(e,n){let{windows:r,windowSize:o}=yr(n,this.bits),s=[],
165
- i=e,c=i;for(let l=0;l<r;l++){c=i,s.push(c);for(let a=1;a<o;a++)c=c.add(i),s.push(c);i=c.double();}return s}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,
166
- i=yr(e,this.bits);for(let c=0;c<i.windows;c++){let{nextN:l,offset:a,isZero:d,isNeg:u,isNegF:p,offsetF:f}=ls(r,c,i);r=l,d?s=s.add(cs(p,n[f])):o=o.add(cs(u,n[a]));}return us(r),{p:o,f:s}}wNAFUnsafe(e,n,r,o=this.
167
- ZERO){let s=yr(e,this.bits);for(let i=0;i<s.windows&&r!==wn;i++){let{nextN:c,offset:l,isZero:a,isNeg:d}=ls(r,i,s);if(r=c,!a){let u=n[l];o=o.add(d?u.negate():u);}}return us(r),o}getPrecomputes(e,n,r){let o=kr.
168
- get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),kr.set(n,o))),o}cached(e,n,r){let o=xr(e);return this.wNAF(o,this.getPrecomputes(o,e,r),n)}unsafe(e,n,r,o){let s=xr(
169
- e);return s===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),n,o)}createCache(e,n){ps(n,this.bits),fs.set(e,n),kr.delete(e);}hasCache(e){return xr(e)!==1}};function ds(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return as(e),e}else return xn(t,{isLE:n})}function ms(t,e,n={},r){if(r===void 0&&(r=t==="edwar\
170
- ds"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let l of ["p","n","h"]){let a=e[l];if(!(typeof a=="bigint"&&a>wn))throw new Error(`CURVE.${l} must be positive bigint`)}
171
- let o=ds(e.p,n.Fp,r),s=ds(e.n,n.Fn,r),c=["Gx","Gy","a","d"];for(let l of c)if(!o.isValid(e[l]))throw new Error(`CURVE.${l} must be valid field element of CURVE.Fp`);return e=Object.
172
- freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function hs(t,e){return function(r){let o=t(r);return {secretKey:o,publicKey:e(o)}}}var $e=BigInt(0),X=BigInt(1),Sr=BigInt(2),$a=BigInt(8);function Ba(t,e,n,r){let o=t.sqr(n),s=t.sqr(r),i=t.add(t.mul(e.a,o),s),c=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,c)}function gs(t,e={}){
173
- let n=e,r=ms("edwards",t,n,n.FpFnLE),{Fp:o,Fn:s}=r,i=r.CURVE,{h:c}=i;Ge(n,{},{uvRatio:"function"});let l=Sr<<BigInt(s.BYTES*8)-X,a=y=>o.create(y),d=n.uvRatio===void 0?(y,m)=>{try{return {isValid:!0,value:o.
174
- sqrt(o.div(y,m))}}catch{return {isValid:false,value:$e}}}:n.uvRatio;if(!Ba(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function u(y,m,b=false){let w=b?X:$e;return hr("coordinate "+y,m,
175
- w,l),m}function p(y){if(!(y instanceof f))throw new Error("EdwardsPoint expected")}class f{static BASE=new f(i.Gx,i.Gy,X,a(i.Gx*i.Gy));static ZERO=new f($e,X,X,$e);static Fp=o;static Fn=s;X;Y;Z;T;constructor(m,b,w,E){
176
- this.X=u("x",m),this.Y=u("y",b),this.Z=u("z",w,true),this.T=u("t",E),Object.freeze(this);}static CURVE(){return i}static fromAffine(m){if(m instanceof f)throw new Error("extended point not allowed");let{
177
- x:b,y:w}=m||{};return u("x",b),u("y",w),new f(b,w,X,a(b*w))}static fromBytes(m,b=false){let w=o.BYTES,{a:E,d:v}=i;m=Dt(J(m,w,"point")),st(b,"zip215");let R=Dt(m),I=m[w-1];R[w-1]=I&-129;let C=Ae(R),D=b?l:
178
- o.ORDER;hr("point.y",C,$e,D);let M=a(C*C),F=a(M-X),q=a(v*M-E),{isValid:k,value:T}=d(F,q);if(!k)throw new Error("bad point: invalid y coordinate");let O=(T&X)===X,L=(I&128)!==0;if(!b&&T===$e&&L)throw new Error(
179
- "bad point: x=0 and x_0=1");return L!==O&&(T=a(-T)),f.fromAffine({x:T,y:C})}static fromHex(m,b=false){return f.fromBytes(Ho(m),b)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,b=true){
180
- return g.createCache(this,m),b||this.multiply(Sr),this}assertValidity(){let m=this,{a:b,d:w}=i;if(m.is0())throw new Error("bad point: ZERO");let{X:E,Y:v,Z:R,T:I}=m,C=a(E*E),D=a(v*v),M=a(R*R),F=a(M*M),
181
- q=a(C*b),k=a(M*a(q+D)),T=a(F+a(w*a(C*D)));if(k!==T)throw new Error("bad point: equation left != right (1)");let O=a(E*v),L=a(R*I);if(O!==L)throw new Error("bad point: equation left != right (2)")}equals(m){
182
- p(m);let{X:b,Y:w,Z:E}=this,{X:v,Y:R,Z:I}=m,C=a(b*I),D=a(v*E),M=a(w*I),F=a(R*E);return C===D&&M===F}is0(){return this.equals(f.ZERO)}negate(){return new f(a(-this.X),this.Y,this.Z,a(-this.T))}double(){
183
- let{a:m}=i,{X:b,Y:w,Z:E}=this,v=a(b*b),R=a(w*w),I=a(Sr*a(E*E)),C=a(m*v),D=b+w,M=a(a(D*D)-v-R),F=C+R,q=F-I,k=C-R,T=a(M*q),O=a(F*k),L=a(M*k),Y=a(q*F);return new f(T,O,Y,L)}add(m){p(m);let{a:b,d:w}=i,{X:E,
184
- Y:v,Z:R,T:I}=this,{X:C,Y:D,Z:M,T:F}=m,q=a(E*C),k=a(v*D),T=a(I*w*F),O=a(R*M),L=a((E+v)*(C+D)-q-k),Y=O-T,ne=O+T,h=a(k-b*q),x=a(L*Y),H=a(ne*h),$=a(L*h),B=a(Y*ne);return new f(x,H,B,$)}subtract(m){return p(
185
- m),this.add(m.negate())}multiply(m){if(!s.isValidNot0(m))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:b,f:w}=g.cached(this,m,E=>En(f,E));return En(f,[b,w])[0]}multiplyUnsafe(m){
186
- if(!s.isValid(m))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return m===$e?f.ZERO:this.is0()||m===X?this:g.unsafe(this,m,b=>En(f,b))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){
187
- return g.unsafe(this,i.n).is0()}toAffine(m){let b=this,w=m,{X:E,Y:v,Z:R}=b,I=b.is0();w==null&&(w=I?$a:o.inv(R));let C=a(E*w),D=a(v*w),M=o.mul(R,w);if(I)return {x:$e,y:X};if(M!==X)throw new Error("invZ \
188
- was invalid");return {x:C,y:D}}clearCofactor(){return c===X?this:this.multiplyUnsafe(c)}toBytes(){let{x:m,y:b}=this.toAffine(),w=o.toBytes(b);return w[w.length-1]|=m&X?128:0,w}toHex(){return pr(this.toBytes())}toString(){
189
- return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let g=new Sn(f,s.BITS);return s.BITS>=8&&f.BASE.precompute(8),Object.freeze(f.prototype),Object.freeze(f),f}var _n=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){
190
- this.ep=e;}static fromBytes(e){br();}static fromHex(e){br();}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity();}toAffine(e){
191
- return this.ep.toAffine(e)}toHex(){return pr(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return true}isSmallOrder(){return false}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){
192
- return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.
193
- ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,n){return this.ep.precompute(e,n),this}};function bs(t,e,n={}){if(typeof e!="function")throw new Error('"hash" function param is r\
194
- equired');let r=e,o=n;Ge(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:c,Fn:l}=t,a=r.
195
- outputLen,d=2*c.BYTES;if(a!==void 0&&(Re(a,"hash.outputLen"),a!==d))throw new Error(`hash.outputLen must be ${d}, got ${a}`);let u=o.randomBytes===void 0?Ko:o.randomBytes,p=o.adjustScalarBytes===void 0?
196
- k=>k:o.adjustScalarBytes,f=o.domain===void 0?(k,T,O)=>{if(st(O,"phflag"),T.length||O)throw new Error("Contexts/pre-hash are not supported");return k}:o.domain;function g(k){return l.create(Ae(k))}function y(k){
197
- let T=C.secretKey;J(k,C.secretKey,"secretKey");let O=J(r(k),2*T,"hashedSecretKey"),L=p(O.slice(0,T)),Y=O.slice(T,2*T),ne=g(L);return {head:L,prefix:Y,scalar:ne}}function m(k){let{head:T,prefix:O,scalar:L}=y(
198
- k),Y=i.multiply(L),ne=Y.toBytes();return {head:T,prefix:O,scalar:L,point:Y,pointBytes:ne}}function b(k){return m(k).pointBytes}function w(k=Uint8Array.of(),...T){let O=ve(...T);return g(r(f(O,J(k,void 0,
199
- "context"),!!s)))}function E(k,T,O={}){k=J(k,void 0,"message"),s&&(k=s(k));let{prefix:L,scalar:Y,pointBytes:ne}=m(T),h=w(O.context,L,k),x=i.multiply(h).toBytes(),H=w(O.context,x,ne,k),$=l.create(h+H*Y);
200
- if(!l.isValid($))throw new Error("sign failed: invalid s");let B=ve(x,l.toBytes($));return J(B,C.signature,"result")}let v={zip215:o.zip215};function R(k,T,O,L=v){let{context:Y}=L,ne=L.zip215===void 0?
201
- !!v.zip215:L.zip215,h=C.signature;k=J(k,h,"signature"),T=J(T,void 0,"message"),O=J(O,C.publicKey,"publicKey"),ne!==void 0&&st(ne,"zip215"),s&&(T=s(T));let x=h/2,H=k.subarray(0,x),$=Ae(k.subarray(x,h)),
202
- B,V,U;try{B=t.fromBytes(O,ne),V=t.fromBytes(H,ne),U=i.multiplyUnsafe($);}catch{return false}if(!ne&&B.isSmallOrder())return false;let S=w(Y,H,O,T);return V.add(B.multiplyUnsafe(S)).subtract(U).clearCofactor().
203
- is0()}let I=c.BYTES,C={secretKey:I,publicKey:I,signature:2*I,seed:I};function D(k){return k=k===void 0?u(C.seed):k,J(k,C.seed,"seed")}function M(k){return bn(k)&&k.length===C.secretKey}function F(k,T){
204
- try{return !!t.fromBytes(k,T===void 0?v.zip215:T)}catch{return false}}let q={getExtendedPublicKey:m,randomSecretKey:D,isValidSecretKey:M,isValidPublicKey:F,toMontgomery(k){let{y:T}=t.fromBytes(k),O=C.publicKey,
205
- L=O===32;if(!L&&O!==57)throw new Error("only defined for 25519 and 448");let Y=L?c.div(X+T,X-T):c.div(T-X,T+X);return c.toBytes(Y)},toMontgomerySecret(k){let T=C.secretKey;J(k,T);let O=r(k.subarray(0,
206
- T));return p(O).subarray(0,T)}};return Object.freeze(C),Object.freeze(q),Object.freeze({keygen:hs(D,b),getPublicKey:b,sign:E,verify:R,utils:q,Point:t,lengths:C})}var Va=BigInt(0),Ce=BigInt(1),ys=BigInt(2);var Fa=BigInt(5),za=BigInt(8),it=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Ar={p:it,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:za,
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){
207
+ 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,
207
222
  a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6d\
208
- c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function qa(t){let e=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),s=it,c=t*t%
209
- s*t%s,l=ge(c,ys,s)*c%s,a=ge(l,Ce,s)*t%s,d=ge(a,Fa,s)*a%s,u=ge(d,e,s)*d%s,p=ge(u,n,s)*u%s,f=ge(p,r,s)*p%s,g=ge(f,o,s)*f%s,y=ge(g,o,s)*f%s,m=ge(y,e,s)*d%s;return {pow_p_5_8:ge(m,ys,s)*t%s,b2:c}}function Ha(t){
210
- return t[0]&=248,t[31]&=127,t[31]|=64,t}var _r=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Ir(t,e){let n=it,r=G(e*e*e,n),o=G(r*r*e,n),s=qa(t*o).pow_p_5_8,
211
- i=G(t*r*s,n),c=G(e*i*i,n),l=i,a=G(i*_r,n),d=c===t,u=c===G(-t,n),p=c===G(-t*_r,n);return d&&(i=l),(u||p)&&(i=a),Ie(i,n)&&(i=G(-i,n)),{isValid:d||u,value:i}}var je=gs(Ar,{uvRatio:Ir}),Be=je.Fp,ws=je.Fn;function Ka(t){return bs(je,mn,Object.assign({adjustScalarBytes:Ha,zip215:true},t))}var Ss=Ka({});var Tr=_r;BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");var Wa=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt(
212
- "1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var ks=t=>Ir(Ce,t),Za=BigInt("0x7\
213
- fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Rr=t=>Be.create(Ae(t)&Za);var Ue=class t extends _n{static BASE=new t(
214
- je.BASE);static ZERO=new t(je.ZERO);static Fp=Be;static Fn=ws;constructor(e){super(e);}static fromAffine(e){return new t(je.fromAffine(e))}assertSame(e){if(!(e instanceof t))throw new Error("RistrettoP\
215
- oint expected")}init(e){return new t(e)}static fromBytes(e){he(e,32);let{a:n,d:r}=Ar,o=it,s=v=>Be.create(v),i=Rr(e);if(!Jo(Be.toBytes(i),e)||Ie(i,o))throw new Error("invalid ristretto255 encoding 1");
216
- let c=s(i*i),l=s(Ce+n*c),a=s(Ce-n*c),d=s(l*l),u=s(a*a),p=s(n*r*d-u),{isValid:f,value:g}=ks(s(p*u)),y=s(g*a),m=s(g*y*p),b=s((i+i)*y);Ie(b,o)&&(b=s(-b));let w=s(l*m),E=s(b*w);if(!f||Ie(E,o)||w===Va)throw new Error(
217
- "invalid ristretto255 encoding 2");return new t(new je(b,w,Ce,E))}static fromHex(e){return t.fromBytes(It(e))}toBytes(){let{X:e,Y:n,Z:r,T:o}=this.ep,s=it,i=m=>Be.create(m),c=i(i(r+n)*i(r-n)),l=i(e*n),
218
- a=i(l*l),{value:d}=ks(i(c*a)),u=i(d*c),p=i(d*l),f=i(u*p*o),g;if(Ie(o*f,s)){let m=i(n*Tr),b=i(e*Tr);e=m,n=b,g=i(u*Wa);}else g=p;Ie(e*f,s)&&(n=i(-n));let y=i((r-n)*g);return Ie(y,s)&&(y=i(-y)),Be.toBytes(
219
- y)}equals(e){this.assertSame(e);let{X:n,Y:r}=this.ep,{X:o,Y:s}=e.ep,i=a=>Be.create(a),c=i(n*s)===i(r*o),l=i(r*s)===i(n*o);return c||l}is0(){return this.equals(t.ZERO)}};Object.freeze(Ue.BASE);Object.freeze(
220
- Ue.ZERO);Object.freeze(Ue.prototype);Object.freeze(Ue);var Je=`-----BEGIN PUBLIC KEY-----
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-----
221
236
  MCowBQYDK2VwAyEAWBiklf0kmDIVmM7nMiCxwiEAkwQIiqWGuRiRDJonsFY=
222
- -----END PUBLIC KEY-----`;function Es(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function Cr(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.
223
- length%4?"=".repeat(4-e.length%4):"";return Es(e+n)}function Qa(t){let e=t.replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=Es(e);return n.subarray(n.length-32)}var ec=new TextEncoder,_s=new TextDecoder;
224
- function Or(t){return typeof t=="object"&&t!==null&&"keys"in t}function at(t){let e=t.trim(),n=/^(["'])([\s\S]*)\1$/.exec(e);return n&&(e=n[2].trim()),e=e.replace(/^bearer\s+/i,""),e.trim()}var tc=/^[A-Za-z0-9_-]+$/;
225
- function Ts(t){let e=t.split(".");return e.length===3&&e.every(n=>tc.test(n))}function Lt(t){return t===""?"empty":Ts(t)?"token":"malformed"}function Mt(t,e){if(!Ts(t))return {ok:false,reason:"malformed t\
226
- oken"};let n=t.split("."),r=n[0],o=n[1],s=n[2],i;try{i=JSON.parse(_s.decode(Cr(r)));}catch{return {ok:false,reason:"header is not valid JSON"}}let c;if(Or(e)){let d=typeof i.kid=="string"?i.kid:e.defaultKid,
227
- u=e.keys[d];if(!u)return {ok:false,reason:`unknown key id "${d}"`};c=u;}else {if(!e)return {ok:false,reason:"no verification key"};c=e;}let l;try{if(l=Qa(c),l.length!==32)return {ok:!1,reason:"invalid public key"}}catch{
228
- return {ok:false,reason:"invalid public key"}}let a=false;try{a=Ss.verify(Cr(s),ec.encode(`${r}.${o}`),l);}catch{return {ok:false,reason:"signature verification error"}}return a?{ok:true,header:i,payloadBytes:Cr(o)}:
229
- {ok:false,reason:"bad signature"}}function Dr(t,e){let n=Mt(t,e);if(!n.ok||!n.payloadBytes)return {signatureValid:false,...n.reason?{reason:n.reason}:{}};try{return {signatureValid:!0,payload:JSON.parse(_s.decode(
230
- n.payloadBytes))}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function Tn(t,e,n){if(n?.has(t.jti))return "revoked";let r=t.expires_at+t.grace_days*86400;return e<=t.expires_at?"\
231
- active":e<=r?"grace":"expired"}var Rs="BVSALA-REVOC",nc=300,rc=new TextDecoder;function As(t,e,n={}){let r=a=>({ok:false,seq:-1,asOf:0,revoked:new Set,reason:a}),o=Mt(t,e);if(!o.ok||!o.payloadBytes)return r(o.reason??"bad signature");
232
- if(o.header?.typ!==Rs)return r(`unexpected token type "${String(o.header?.typ??"")}" (want ${Rs})`);let s;try{s=JSON.parse(rc.decode(o.payloadBytes));}catch{return r("payload is not valid JSON")}if(typeof s.
233
- 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 c=n.
234
- nowSeconds??Math.floor(Date.now()/1e3),l=n.maxSkewSeconds??nc;return s.asOf>c+l?r(`asOf too far in the future (${s.asOf} > ${c+l})`):{ok:true,seq:s.seq,asOf:s.asOf,revoked:new Set(s.revoked)}}var ct=class{_seq=-1;_asOf=0;_lastContactAt=0;set=new Set;get seq(){
235
- return this._seq}get asOf(){return this._asOf}get lastContactAt(){return this._lastContactAt}markContact(e){e>this._lastContactAt&&(this._lastContactAt=e);}has(e){return this.set.has(e)}snapshot(){return this.
236
- set}apply(e){if(e.seq<this._seq)return false;let n=this.set.size;for(let s of e.revoked)this.set.add(s);let r=this.set.size>n,o=e.seq>this._seq;return e.seq>this._seq&&(this._seq=e.seq),e.asOf>this._asOf&&
237
- (this._asOf=e.asOf),r||o}};function Rn(t,e,n){let r=()=>Math.floor((n.now?n.now():Date.now())/1e3),o=n.startedAt??r(),s=at(t),i=Lt(s),c=i==="token"?Dr(s,e):{signatureValid:false,reason:i},l=c.signatureValid?c.payload:void 0,a=new Set(
238
- l?.features??[]),d=()=>{if(i==="empty")return "none";if(!l)return "invalid";let p=Tn(l,r(),n.revocation.snapshot());if(n.maxStalenessSeconds!=null&&(p==="active"||p==="grace")){let f=l.expires_at+l.grace_days*
239
- 86400,g=Math.min(o,f),y=Math.max(n.revocation.lastContactAt,g);if(r()-y>n.maxStalenessSeconds)return "stale"}return p},u=()=>{let p=d();return p==="active"||p==="grace"};return {isEntitled:p=>u()&&a.has(
240
- p),isActive:()=>u(),status:d,reason:()=>l?void 0:c.reason,refreshAfter:()=>{if(l)return Math.min(l.expires_at,r()+86400)}}}var lt={pollIntervalSeconds:900,floorSeconds:300,maxIntervalSeconds:3600,jitterRatio:.1,maxSkewSeconds:300,requestTimeoutMs:3e4},Is=3,oc=12;function sc(t){let e=t.random??Math.random,n;if(t.consecutiveFailures>
241
- 0){let o=Math.pow(2,Math.min(t.consecutiveFailures,4));n=Math.min(t.maxIntervalSeconds,t.floorSeconds*o);}else {let o=t.refreshAfter!=null?t.refreshAfter-t.nowSeconds:t.pollIntervalSeconds,s=o<0?t.pollIntervalSeconds:
242
- o;n=Math.min(t.pollIntervalSeconds,Math.max(t.floorSeconds,s));}let r=1+(e()*2-1)*t.jitterRatio;return Math.max(t.floorSeconds,n*r)}var ic=10,Nt=class{constructor(e){this.opts=e;}opts;timer=null;controller=null;consecutiveFailures=0;stopped=false;started=false;warnedNoFetch=false;lastEtag=null;consecutive304=0;now(){
243
- return this.opts.nowSeconds?this.opts.nowSeconds():Math.floor(Date.now()/1e3)}resolveFetch(){return this.opts.fetchImpl?this.opts.fetchImpl:typeof fetch<"u"?fetch:void 0}async pollOnce(){let e=this.resolveFetch();
244
- if(!e){this.warnedNoFetch||(this.warnedNoFetch=true,console.warn("[bv-sala] no global fetch available; revocation call-home disabled (offline). License expiry is still enforced from the token.")),this.opts.
245
- onEvent?.({type:"no-fetch"});return}let n=new AbortController;this.controller=n;let r=this.opts.requestTimeoutMs??lt.requestTimeoutMs,o=setTimeout(()=>n.abort(),r);o.unref?.();let s={accept:"applicati\
246
- on/json"};this.lastEtag&&(s["if-none-match"]=this.lastEtag);try{let i=await e(this.opts.url,{signal:n.signal,headers:s});if(i.status===304){this.consecutiveFailures=0,this.opts.snapshot.markContact(this.
247
- now()),this.opts.onEvent?.({type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=ic&&(this.consecutive304=0,this.lastEtag=null);return}if(this.consecutive304=0,!i.
248
- ok)throw new Error(`revocations HTTP ${i.status}`);let c=i.headers.get("etag"),l=await i.json();if(!l.list)throw new Error("response missing `list`");this.consecutiveFailures=0;let a=As(l.list,this.opts.
249
- publicKeyPem,{minSeq:this.opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??lt.maxSkewSeconds});if(!a.ok){let u=a.reason??"rejected";this.opts.onEvent?.({type:"rejected",
250
- 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\
251
- . Check ${this.opts.url}.`);return}c&&(this.lastEtag=c),this.opts.snapshot.markContact(this.now());let d=this.opts.snapshot.apply(a);this.opts.onEvent?.(d?{type:"applied",seq:a.seq,size:this.opts.snapshot.
252
- snapshot().size}:{type:"unchanged",seq:a.seq});}catch(i){this.consecutiveFailures++,this.opts.onEvent?.({type:"error",error:i}),this.avisarFalloDeRed(i);}finally{clearTimeout(o),this.controller=null;}}callado(){
253
- return !!(this.opts.silenceWarnings??this.opts.silenciarAvisos)}avisar(e,n){this.callado()||z(`poller:${this.opts.url}:${e}`,n);}avisarFalloDeRed(e){if(this.callado())return;let n=this.consecutiveFailures;
254
- if(n<Is||(n-Is)%oc!==0)return;let r=e instanceof Error?e.message:String(e);console.warn(`[bv-sala] could not reach the revocation server ${n} times in a row (${r}). The license KEEPS working and known\
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(){
250
+ 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(){
258
+ 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
+ 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\
255
270
  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(){
256
- if(this.stopped)return;let e=sc({refreshAfter:this.opts.getRefreshAfter?.(),nowSeconds:this.now(),consecutiveFailures:this.consecutiveFailures,floorSeconds:this.opts.floorSeconds??lt.floorSeconds,pollIntervalSeconds:this.
257
- opts.pollIntervalSeconds??lt.pollIntervalSeconds,maxIntervalSeconds:this.opts.maxIntervalSeconds??lt.maxIntervalSeconds,jitterRatio:this.opts.jitterRatio??lt.jitterRatio,...this.opts.random?{random:this.
258
- opts.random}:{}});this.timer=setTimeout(()=>{this.pollOnce().finally(()=>this.schedule());},e*1e3),this.timer.unref?.();}stop(){this.stopped=true,this.timer&&(clearTimeout(this.timer),this.timer=null),this.
259
- controller?.abort();}};var Cs={flex:.5,default:1,auto:1,priority:1,fast:1,scale:1,standard:1,batch:.5};Math.min(...Object.values(Cs).filter(t=>t<1));function $t(t){if(t==null||t==="")return null;let e=Cs[t];return e==null?{servido:t,factor:null,conDescuento:false}:{servido:t,factor:e,conDescuento:e<1}}var cc={"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.\
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.
273
+ 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.\
260
289
  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\
261
- .6-luna":true,"gpt-5.6-sol":true,"gpt-5.6-terra":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,"claude-opus-4-8":false,"claude-opus-5":true,"clau\
262
- de-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-mythos-5-1":true,"claude-mythos-5":true,"claude-sonnet-4":false,"claude-haik\
263
- u-4-5":false,"claude-3-5-sonnet":false,"claude-3-5-haiku":false,"claude-3-opus":false,"claude-3-haiku":false,"gemini-3.7-flash":true,"gemini-3.5-flash":true,"gemini-3.5-flash-lite":true,"gemini-3.1-pro-preview":true,"gemini\
264
- -2.5-pro":true,"gemini-2.5-flash":true},lc=new Set(["claude-opus-4-7","claude-opus-4-8"]),uc=[/^o\d/,/^gpt-5/,/^gpt-oss/,/^gemini-(2\.5|[3-9])/,/^claude-[a-z]+-([5-9]|\d{2})/,/^grok-(3-mini|[4-9])/,/reason/,
265
- /think/,/(^|[-_.])r\d($|[-_.])/,/^qwq/,/^qwen3/,/^glm-(4\.[5-9]|[5-9])/,/magistral/];function Pr(t){let e=t.lastIndexOf("/"),n=(e>=0?t.slice(e+1):t).toLowerCase();if(uc.some(s=>s.test(n)))return "reaso\
266
- ning-model";let r=Rt(t);if(r===void 0)return "unclassified-model";let o=cc[r];if(o===true)return "reasoning-model";if(o!==false)return "unclassified-model";if(lc.has(r))return "temperature-ignored"}var An=class{decoder;resto="";crPendiente=false;alPrincipio=true;datos="";evento="";ultimoId;push(e){let n=typeof e=="string"?e:(this.decoder??=new TextDecoder("utf-8")).decode(e,{stream:true});return this.procesar(
267
- n)}end(){let e=[];if(this.decoder){let n=this.decoder.decode();n!==""&&e.push(...this.procesar(n));}return this.resto!==""&&(this.linea(this.resto,e),this.resto=""),this.despachar(e),this.crPendiente=false,
268
- e}procesar(e){let n=[];if(e==="")return n;let r=e;if(this.alPrincipio&&(this.alPrincipio=false,r.charCodeAt(0)===65279&&(r=r.slice(1)),r===""))return n;let o=0;this.crPendiente&&(this.crPendiente=false,r.charCodeAt(
290
+ .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
+ "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
+ 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(
300
+ 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
+ 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(
269
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.
270
- crPendiente=true),o++,s=o;}return this.resto+=r.slice(s),n}linea(e,n){if(e===""){this.despachar(n);return}if(e.charCodeAt(0)===58)return;let r=e.indexOf(":"),o,s;switch(r===-1?(o=e,s=""):(o=e.slice(0,r),
271
- s=e.slice(r+1),s.charCodeAt(0)===32&&(s=s.slice(1))),o){case "data":this.datos+=s+`
272
- `;break;case "event":this.evento=s;break;case "id":s.includes("\0")||(this.ultimoId=s);break;}}despachar(e){if(this.datos===""){this.evento="";return}e.push({event:this.evento===""?"message":
273
- this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};var Ye=class{resto="";uso=null;elisionObservada=null;eventos={};observar(e){this.resto+=typeof e=="string"?e:e.toString("utf8");let n;for(;(n=this.resto.indexOf(`
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(`
274
307
 
275
308
  `))>=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;
276
- let s=/^data: (.+)$/m.exec(r)?.[1];if(s)try{let i=JSON.parse(s),c=Ps(i.context_management);c&&(this.elisionObservada=c);let l=i.usage??i.message?.usage;if(l){let a=l.cache_creation||this.uso?.cache_creation?
277
- {...this.uso?.cache_creation,...l.cache_creation}:void 0;this.uso={...this.uso,...l,...a?{cache_creation:a}:{}};}}catch{}}}usage(){return this.uso}usageFinal(){return (this.eventos.message_delta??0)>0?this.
278
- uso:null}elision(){return this.elisionObservada}};function dc(t,e){if(!e||e.atribuible!==true||!(e.tokensLimpiadosToolUses>0))return 0;let n=t.cachedInputPer1k;return typeof n!="number"||!Number.isFinite(
279
- n)||n<=0?0:e.tokensLimpiadosToolUses/1e3*n}function Ps(t){if(t===null||typeof t!="object")return null;let e=t.applied_edits;if(!Array.isArray(e)||e.length===0)return null;let n=0,r=0;for(let o of e){let s=o.
280
- cleared_input_tokens;typeof s=="number"&&Number.isFinite(s)&&s>0&&(n+=s,o.type==="clear_tool_uses_20250919"&&(r+=s));}return {borrados:e.length,tokensLimpiados:n,tokensLimpiadosToolUses:r}}function Ls(t){
281
- try{let e=JSON.parse(typeof t=="string"?t:t.toString("utf8"));return Ps(e.context_management)}catch{return null}}var ut=class{resto="";uso=null;final=null;eventos={};observar(e){this.resto+=typeof e==
282
- "string"?e:e.toString("utf8");let n;for(;(n=this.resto.indexOf(`
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==
315
+ "string"?t:t.toString("utf8");let n;for(;(n=this.resto.indexOf(`
283
316
 
284
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.
285
- parse(s),c=o??i.type,l=c!==void 0&&Object.hasOwn(Os,c)?Os[c]:void 0;if(l===void 0)continue;this.final=l;let a=i.response?.usage;if(!a)continue;l==="completed"?this.uso=In(a):typeof a.input_tokens=="nu\
286
- mber"&&typeof a.output_tokens=="number"&&(this.uso=In(a));}catch{}}}usage(){return this.uso}usageFinal(){return this.uso}estadoFinal(){return this.final}},Os={"response.completed":"completed","response\
287
- .incomplete":"incomplete","response.failed":"failed"};function In(t){let e=Math.max(0,t.input_tokens??0),n=Math.min(Math.max(0,t.input_tokens_details?.cached_tokens??0),e),r=Math.min(Math.max(0,t.input_tokens_details?.
288
- cache_write_tokens??0),e-n);return {input_tokens:e-n-r,output_tokens:Math.max(0,t.output_tokens??0),cache_read_input_tokens:n,cache_creation_input_tokens:r}}function Ms(t){return !t||typeof t.prompt_tokens!=
289
- "number"||typeof t.completion_tokens!="number"?null:In({input_tokens:t.prompt_tokens,output_tokens:t.completion_tokens,input_tokens_details:{...t.prompt_tokens_details?.cached_tokens!==void 0?{cached_tokens:t.
290
- prompt_tokens_details.cached_tokens}:{},...t.prompt_tokens_details?.cache_write_tokens!==void 0?{cache_write_tokens:t.prompt_tokens_details.cache_write_tokens}:{}}})}var Bt=class{parser=new An;ultimoUso=null;vioUsoFinal=false;vioDone=false;eventos={};observar(e){
291
- for(let n of this.parser.push(e))this.mensaje(n);}usage(){return this.vioUsoFinal||this.vioDone?this.ultimoUso:null}usageFinal(){for(let e of this.parser.end())this.mensaje(e);return this.usage()}mensaje(e){
292
- if(e.data==="[DONE]"){this.vioDone=true,this.eventos.done=(this.eventos.done??0)+1;return}let n;try{n=JSON.parse(e.data);}catch{return}if(n===null||typeof n!="object"||(this.eventos.chunk=(this.eventos.chunk??
293
- 0)+1,n.usage===null||typeof n.usage!="object"))return;let r=Ms(n.usage);r!==null&&(this.ultimoUso=r,Array.isArray(n.choices)&&n.choices.length===0&&(this.vioUsoFinal=true));}};function Ns(t,e,n){let r=t.
294
- cachedInputPer1k??t.inputPer1k;return e.entrada/1e3*t.inputPer1k+e.cacheLeida/1e3*r+(e.cacheEscrita-e.cacheEscrita1h)/1e3*t.inputPer1k*_e(n)+e.cacheEscrita1h/1e3*t.inputPer1k*2+e.salida/1e3*t.outputPer1k}
295
- function $s(t,e){let n=me(t);if(!n)return null;let r=e.input_tokens??0,o=e.output_tokens??0,s=e.cache_read_input_tokens??0,i=e.cache_creation,c=e.cache_creation_input_tokens??(i?.ephemeral_5m_input_tokens??
296
- 0)+(i?.ephemeral_1h_input_tokens??0),l=Math.min(i?.ephemeral_1h_input_tokens??0,c),a={entrada:r,salida:o,cacheLeida:s,cacheEscrita:c,cacheEscrita1h:l};return {costeUsd:Ns(n,a,t),precio:n,tokens:a}}function Bs(t,e){
297
- let r=jt(t,e)?.model;return typeof r=="string"?r:""}function jt(t,e){try{let n=t,r={maxOutputLength:pc};switch((e??"").trim().toLowerCase()){case "gzip":case "x-gzip":n=Oe.gunzipSync(t,r);break;case "def\
298
- late":n=Oe.inflateSync(t,r);break;case "br":n=Oe.brotliDecompressSync(t,r);break;case "zstd":{let o=Oe.zstdDecompressSync;if(typeof o!="function")return null;n=o(t,r);break}default:break}return JSON.parse(
299
- n.toString("utf8"))}catch{return null}}var pc=5*1024*1024;function js(){return typeof Oe.zstdDecompressSync=="function"}function fc(t){try{return JSON.parse(typeof t=="string"?t:t.toString("utf8")).usage??
300
- null}catch{return null}}function Cn(t,e){if(t==="/v1/messages")return fc(e);if(!dt(t))return null;try{let n=JSON.parse(typeof e=="string"?e:e.toString("utf8"));if(n===null||typeof n!="object")return null;
301
- if(t.endsWith("/chat/completions"))return Ms(n.usage);let r=n.usage;return r&&typeof r.input_tokens=="number"&&typeof r.output_tokens=="number"?In(r):null}catch{return null}}function Us(t,e){if(!t.endsWith(
302
- "/responses"))return false;try{let n=JSON.parse(typeof e=="string"?e:e.toString("utf8"));return n!==null&&typeof n=="object"&&n.status==="failed"}catch{return false}}function Vs(t,e){let n=typeof e=="string"?
303
- e:e.toString("utf8"),r=s=>{if(s===null||typeof s!="object")return;let i=s,c=a=>a!==null&&typeof a=="object"?a.service_tier:void 0,l;return t==="/v1/messages"?(l=c(i.usage),l===void 0&&i.message!==null&&
304
- typeof i.message=="object"&&(l=c(i.message.usage))):t.endsWith("/chat/completions")?l=i.service_tier:t.endsWith("/responses")&&(l=i.service_tier,l===void 0&&i.response!==null&&typeof i.response=="obje\
305
- ct"&&(l=i.response.service_tier)),typeof l=="string"&&l!==""?l:void 0};try{return r(JSON.parse(n))}catch{}let o;for(let s of n.split(`
306
- `)){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 dt(t){return t==="/v1/messages"||t.endsWith("/chat/complet\
307
- ions")||t.endsWith("/responses")}var mc=Buffer.from('"stream_options":{"include_usage":true},',"utf8");function Fs(t,e){let n=(e??"").trim().toLowerCase();if(n!==""&&n!=="identity")return {cuerpo:null,
308
- motivo:"comprimido"};let r;try{r=JSON.parse(t.toString("utf8").replace(/^\uFEFF/,""));}catch{return {cuerpo:null,motivo:"ilegible"}}if(r===null||typeof r!="object"||Array.isArray(r))return {cuerpo:null,motivo:"\
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){
324
+ 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
+ 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,
342
+ 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:"\
309
343
  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,
310
- motivo:"cliente-decide"};let s=0;for(;s<t.length;){let i=t[s];if(i===32||i===9||i===10||i===13){s++;continue}if(i===239&&t[s+1]===187&&t[s+2]===191){s+=3;continue}break}return t[s]!==123?{cuerpo:null,
311
- motivo:"ilegible"}:{cuerpo:Buffer.concat([t.subarray(0,s+1),mc,t.subarray(s+1)]),motivo:"inyectado"}}function zs(t,e){let n=jt(t,e);if(n===null||typeof n!="object")return null;let r=n;return r.stream!==
312
- true?null:r.stream_options?.include_usage===true}function Lr(t,e,n){if((e??"").split(",").some(r=>r.trim().startsWith("oauth-"))||t.startsWith("/backend-api/"))return true;try{let r=new URL(n).hostname.toLowerCase();
313
- return r==="chatgpt.com"||r.endsWith(".chatgpt.com")}catch{return false}}function qs(t,e,n,r,o,s,i,c){return Ws(t,e,n,false,r,o,s,i,c)}var hc=new Set(["auto","default","priority","standard_only"]);function gc(t){
314
- if(t==null)return 1;if(typeof t!="string")return null;if(hc.has(t))return 1;let e=$t(t);return e!==null&&e.conDescuento&&e.factor!==null?e.factor:null}function bc(t){if(t===void 0)return 1;if(t==="sca\
315
- le")return null;let e=$t(t);return e!==null&&e.factor!==null?e.factor:null}function Hs(t,e,n,r,o){if(!n||!n.conContador)return {ok:false,reason:"no-primary-record"};if(n.suscripcion||o.suscripcion)return {
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 {
316
350
  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\
317
- ed"};if(!o.entregada)return {ok:false,reason:"client-disconnected"};let s=r!==null&&typeof r=="object"&&!Array.isArray(r)?r:{},i=gc(s.service_tier),c=bc(o.tierServido);if(i===null||c===null)return {ok:false,reason:"\
318
- service-tier"};let l=Math.min(i,c),a=on(t),d=a?.cachedInputPer1k;if(!a||typeof d!="number"||!Number.isFinite(d)||!(d>0)||!Number.isFinite(a.inputPer1k)||d>a.inputPer1k||!Number.isFinite(a.outputPer1k)||
319
- a.outputPer1k<0)return {ok:false,reason:"no-cached-price"};let u=e.tokens,p=u.entrada+u.cacheLeida+u.cacheEscrita,f=y=>Number.isInteger(y)&&y>=0;if(!f(u.entrada)||!f(u.cacheLeida)||!f(u.cacheEscrita)||!f(
320
- u.salida)||!(p>0))return {ok:false,reason:"no-credit"};let g=s.temperature===0&&Pr(t)===void 0;return {ok:true,credit:{requestId:n.requestId,at:n.at,inputTokens:p,outputTokens:u.salida,creditedInputTokens:p,
321
- creditedOutputTokens:g?Math.floor(.95*u.salida):0,cachedInputPer1k:d,outputPer1k:a.outputPer1k,tierFactor:l}}}function Mr(t){return t.tierFactor*(t.creditedInputTokens/1e3*t.cachedInputPer1k+t.creditedOutputTokens/
322
- 1e3*t.outputPer1k)}function Ks(t,e,n,r,o){let s=o?Mr(o):0;return !o||!(s>0)||!Number.isFinite(s)?Ws(t,e,n,true,r):{requestId:t,model:e,...r&&(r.sessionId||r.agentId)?{attribution:r}:{},calls:{avoidedLlm:1,
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,
323
357
  actualLlm:0},tokens:{baselineInput:o.creditedInputTokens,actualInput:0,eliminatedInput:0,compressedInput:0,baselineOutput:o.creditedOutputTokens,actualOutput:0,providerCachedInput:0},cache:{result:"si\
324
- ngleflight",reference:o},cost:{baselineEstimate:s,actual:0,netSavings:1,basis:"reference"}}}function Gs(t,e,n,r,o){return {requestId:t,model:e,...o&&(o.sessionId||o.agentId)?{attribution:o}:{},calls:{avoidedLlm:0,
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,
325
359
  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>
326
- 0?Math.max(-100,Math.min(1,(n-r)/n)):0,basis:"shadow"}}}function vc(t,e){let n=me(t.solicitado);return n===void 0?0:Math.max(0,Ns(n,e.tokens,t.solicitado)-e.costeUsd)}function Ws(t,e,n,r,o,s,i,c,l=false){
327
- let a=n.tokens.entrada+n.tokens.cacheLeida+n.tokens.cacheEscrita,d=!r&&!l,u=n.tokens.cacheEscrita-n.tokens.cacheEscrita1h,p=d&&i&&i.rebajadas>0&&i.yaEran5m===0&&u>0?u/1e3*n.precio.inputPer1k*(2-1.25):
328
- 0,f=d&&c?vc(c,n):0,g=n.costeUsd+p+f,y=p+f,m=r?0:dc(n.precio,s);return {requestId:t,model:e,...o&&(o.sessionId||o.agentId)?{attribution:o}:{},calls:r?{avoidedLlm:1,actualLlm:0}:{avoidedLlm:0,actualLlm:1},
329
- tokens:{baselineInput:a,actualInput:r?0:a,eliminatedInput:r?0:s?.tokensLimpiados??0,compressedInput:0,baselineOutput:n.tokens.salida,actualOutput:r?0:n.tokens.salida,providerCachedInput:r?0:n.tokens.cacheLeida},
330
- 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(-100,Math.min(1,y/g)):
331
- 0,basis:"measured",...m>0?{eliminatedInputFloorCost:m}:{}}}}var yc=1024,Ut=120,kc=8,xc=256*1024,wc=/error|exception|traceback|warn|fatal|fail|panic|assert|denied|refused|timeout|\bat\s+\S+:\d+/i,Zs=/^\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)/;
332
- function Sc(t){return Buffer.byteLength(typeof t=="string"?t:JSON.stringify(t??""))}function Ec(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?
333
- e.text:"").join(`
334
- `):""}var _c=/^\s*\d+[\t→]/;function Xs(t){return t.replace(_c,"")}function Tc(t){if(!t)return "otro";let e=t.split(`
335
- `),n=Math.max(1,e.length),r=0,o=0,s=0;for(let i of e){let c=Xs(i);(/^[+-](?![+-])/.test(c)||c.startsWith("@@")||c.startsWith("diff --git"))&&(r+=1),Zs.test(c)&&(o+=1),(/^\s*(\d{4}-\d{2}-\d{2}|\[\d|\d{2}:\d{2}:\d{2})/.
336
- test(c)||/\b(INFO|DEBUG|TRACE|WARN|ERROR)\b/.test(c))&&(s+=1);}return r/n>.25?"diff":s/n>.3?"log":o/n>.08?"codigo":"otro"}function Rc(t,e){if(e==="diff"||e==="otro")return Buffer.byteLength(t);let n=t.
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?
364
+ 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"?
367
+ 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.
337
371
  split(`
338
- `),r=new Set;for(let s=0;s<n.length;s++){let i=Xs(n[s]);(e==="log"?wc.test(i):Zs.test(i))&&(r.add(s),e==="log"&&(s>0&&r.add(s-1),s<n.length-1&&r.add(s+1)));}let o=Ut;for(let s of r)o+=Buffer.byteLength(
339
- n[s])+1;return Math.min(o,Buffer.byteLength(t))}var Ac=(t,e)=>t==="cache_control"?void 0:e;function Ic(t){if(typeof t=="string")return `text:${t}`;if(!t||typeof t!="object"||Array.isArray(t))return `jso\
340
- n:${JSON.stringify(t??"")}`;let e=t;return e.type==="text"&&typeof e.text=="string"&&Object.keys(e).every(n=>n==="type"||n==="text"||n==="cache_control")?`text:${e.text}`:`json:${JSON.stringify(e,Ac)}`}
341
- function Cc(t){return createHash("sha256").update(Ic(t)).digest("hex").slice(0,16)}function Oc(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t.cache_control;return !e||typeof e!="object"?null:
342
- e.ttl==="1h"?"1h":"5m"}function Qs(t){let e=[],n=(r,o)=>{let s=Sc(o),i={clave:Cc(o),tipo:r,marca:Oc(o),bytes:s,bytesV1:s,clase:"otro",esError:false};if(r.endsWith(":tool_result")&&o&&typeof o=="object"){
343
- let c=o;i.esError=c.is_error===true;let l=Ec(c.content);i.clase=Tc(l);let a=s-Buffer.byteLength(l);i.bytesV1=Math.min(s,Math.max(0,a)+Rc(l,i.clase));}e.push(i);};if(Array.isArray(t.tools))for(let r of t.tools)
344
- n("tools",r);if(Array.isArray(t.system))for(let r of t.system)n("system",r);else (t.system??void 0)!==void 0&&n("system",t.system);for(let r of Array.isArray(t.messages)?t.messages:[]){if(!r||typeof r!=
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)
378
+ 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!=
345
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}\
346
- :${i?.type??"?"}`,i);}return e}function Dc(){return {nacimiento:new Map,turno:0,elididosV2m:new Set}}function Pc(t,e){let n=t.turno++;for(let r of e)t.nacimiento.has(r.clave)||t.nacimiento.set(r.clave,n);
347
- return n}function ei(t,e,n,r,o=xc){let s=e.reduce((u,p,f)=>p.tipo.endsWith(":tool_result")?f:u,-1),i=(u,p)=>u.tipo.endsWith(":tool_result")&&u.bytes>=yc&&p!==s;return e.map((u,p)=>{if(!i(u,
348
- p))return {clave:u.clave,bytes:u.bytes};let f=r-(n.nacimiento.get(u.clave)??r);return f>=2&&f*u.bytes/1024>=kc?{clave:`${u.clave}:e`,bytes:Ut}:{clave:u.clave,bytes:u.bytes}});}function Lc(t){let e=me(t);return e?{inputPer1k:e.inputPer1k,lecturaPer1k:e.cachedInputPer1k??e.inputPer1k,escrituraPer1k:e.inputPer1k*
349
- _e(t),escritura1hPer1k:e.inputPer1k*Gn(t)}:null}function Js(){return {lecturaUsd:0,escrituraUsd:0,entradaUsd:0,totalUsd:0,tokensLeidos:0,tokensEscritos:0,tokensEntrada:0,tokensInvalidados:0,invalidacionUsd:0}}
350
- var $r={"1h":36e5,"5m":3e5},Mc=20,Nc=6e3,$c=2e4,pt=class{constructor(e=$c){this.tope=e;}tope;entradas=new Map;get size(){return this.entradas.size}viva(e,n){let r=this.entradas.get(e);return r&&n<=r.expira?
351
- r:null}escribir(e,n,r){this.entradas.delete(e),this.entradas.set(e,{expira:n+$r[r],ttl:r}),this.entradas.size>this.tope&&this.podar(n);}refrescar(e,n){let r=this.entradas.get(e);r&&(this.entradas.delete(
352
- e),this.entradas.set(e,{expira:n+$r[r.ttl],ttl:r.ttl}));}podar(e){for(let[n,r]of this.entradas)e>r.expira&&this.entradas.delete(n);for(;this.entradas.size>this.tope;){let n=this.entradas.keys().next().
353
- value;if(n===void 0)break;this.entradas.delete(n);}}};function Bc(t,e){let n=new Array(e.length),r=createHash("sha256").update(`model:${t}`).digest("hex");for(let o=0;o<e.length;o++)r=createHash("sha256").update(r).update(
354
- "|").update(e[o]).digest("hex").slice(0,32),n[o]=r;return n}function jc(t){let e=new Array(t.length),n=-1,r="";for(let o=0;o<t.length;o++){let s=t[o],i=s.endsWith(":tool_use")||s.endsWith(":tool_resul\
355
- t");i&&s===r||(n+=1),r=i?s:"",e[o]=n;}return e}function Ys(t,e){return t.endsWith(":image")?Math.min(e,Nc):e}var Vt=class{constructor(e,n){this.transformar=e;this.cache=n??new pt;}transformar;estado=Dc();cache;previo=[];previoUltimoBp=-1;previoTtl="\
356
- 5m";hayPrevio=false;atPrevio=0;acumulado=Js();paso(e){let n=Js(),r=Pc(this.estado,e.bloques),o=Lc(e.model),s=this.transformar(e.bloques,this.estado,r);if(!o||e.entradaReal<=0||s.length===0)return this.previo=
357
- s,this.previoUltimoBp=-1,this.previoTtl="5m",this.hayPrevio=true,this.atPrevio=e.at,n;let i=s.map((v,R)=>e.bloques[R]?.tipo??""),c=s.map((v,R)=>e.bloques[R]?.marca??null),l=e.bloques.reduce((v,R)=>v+Ys(
358
- R.tipo,R.bytes),0),a=l>0?e.entradaReal/l:0,d=s.map((v,R)=>Ys(i[R],v.bytes)*a),u=Bc(e.model,s.map(v=>v.clave)),p=jc(i),f=c.map((v,R)=>v?R:-1).filter(v=>v>=0);if(f.length===0){for(let v=0;v<s.length;v++)
359
- 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=e.at,this.acumulado.tokensEntrada+=
360
- n.tokensEntrada,this.acumulado.entradaUsd+=n.entradaUsd,this.acumulado.totalUsd+=n.totalUsd,n}let g=-1;for(let v of f){let R=p[v]-(Mc-1);for(let I=v;I>=0&&p[I]>=R;I--)if(this.cache.viva(u[I],e.at)){I>
361
- g&&(g=I);break}}for(let v=0;v<=g;v++)this.cache.refrescar(u[v],e.at);let y=f[f.length-1];for(let v of f)v>g&&this.cache.escribir(u[v],e.at,c[v]);let m=0,w=this.hayPrevio&&e.at-this.atPrevio>$r[this.previoTtl]?
362
- []:this.previo.slice(g+1,this.previoUltimoBp+1),E=0;for(let v=0;v<s.length;v++){let R=s[v],I=d[v];if(v<=g){n.tokensLeidos+=I,n.lecturaUsd+=I/1e3*o.lecturaPer1k;continue}if(v>y){n.tokensEntrada+=I,n.entradaUsd+=
363
- I/1e3*o.inputPer1k;continue}for(;f[m]<v;)m+=1;let C=c[f[m]]==="1h"?o.escritura1hPer1k:o.escrituraPer1k;n.tokensEscritos+=I,n.escrituraUsd+=I/1e3*C;let D=E;for(;D<w.length&&w[D].clave!==R.clave;)D+=1;D<
364
- w.length&&(w[D].bytes===R.bytes&&(n.tokensInvalidados+=I,n.invalidacionUsd+=I/1e3*(C-o.lecturaPer1k)),E=D+1);}return this.previo=s,this.previoUltimoBp=y,this.previoTtl=c[y]??"5m",this.hayPrevio=true,this.
365
- atPrevio=e.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.
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.
399
+ 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.
366
400
  totalUsd+=n.totalUsd,this.acumulado.tokensLeidos+=n.tokensLeidos,this.acumulado.tokensEscritos+=n.tokensEscritos,this.acumulado.tokensEntrada+=n.tokensEntrada,this.acumulado.tokensInvalidados+=n.tokensInvalidados,
367
- this.acumulado.invalidacionUsd+=n.invalidacionUsd,n}};function ti(t){return t.map(e=>({clave:e.clave,bytes:e.bytes}))}var Vc=64,On=class{cadenas=new Map;cachesPorModelo=new Map;observar(e){let n=e.uso.cache_creation_input_tokens??(e.uso.cache_creation?.ephemeral_5m_input_tokens??0)+(e.uso.cache_creation?.ephemeral_1h_input_tokens??
368
- 0),r=(e.uso.input_tokens??0)+(e.uso.cache_read_input_tokens??0)+n;if(r<=0)return null;let o={bloques:Qs(e.cuerpo),at:e.at,model:e.model,entradaReal:r,escritura1h:(e.uso.cache_creation?.ephemeral_1h_input_tokens??
369
- 0)>0};if(o.bloques.length===0)return null;let s=this.cadenaPara(this.clave(e),e.model),i=s.base.paso(o),c=s.v0.paso(o);return i.totalUsd<=0&&c.totalUsd<=0?null:{baselineUsd:i.totalUsd,politicaUsd:c.totalUsd}}clave(e){
370
- if(e.sessionId)return `s:${e.sessionId}\xB7a:${e.agentId??""}\xB7${e.model}`;let n=Array.isArray(e.cuerpo.messages)?e.cuerpo.messages[0]:void 0;return `m:${createHash("sha256").update(JSON.stringify(n??null)).digest(
371
- "hex").slice(0,16)}\xB7${e.model}`}cachesDe(e){let n=this.cachesPorModelo.get(e);return n||(n={base:new pt,v0:new pt},this.cachesPorModelo.set(e,n)),n}cadenaPara(e,n){let r=this.cadenas.get(e);if(!r){
372
- let o=this.cachesDe(n);if(r={base:new Vt(s=>ti(s),o.base),v0:new Vt((s,i,c)=>ei("v0",s,i,c),o.v0),ultimoUso:0},this.cadenas.set(e,r),this.cadenas.size>Vc){let s=null,i=1/0;for(let[c,l]of this.cadenas)
373
- l.ultimoUso<i&&(i=l.ultimoUso,s=c);s!==null&&this.cadenas.delete(s);}}return r.ultimoUso=Date.now(),r}};var Fc="[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\
374
- oard/install and relaunch",Dn=class{url;clave;ttlMs;fetchImpl;log;features=new Set;razonDeBloqueo=null;validoHasta=0;enVuelo=null;avisado=false;constructor(e){this.url=e.url,this.clave=e.serviceAccountKey,
375
- this.ttlMs=e.ttlMs??3e5,this.fetchImpl=e.fetchImpl??fetch,this.log=e.log??(()=>{}),this.refrescar();}tiene(e){return this.refrescarSiVencio(),this.features.has(e)}blockReason(){return this.refrescarSiVencio(),
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){
404
+ 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,
409
+ 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(),
376
410
  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===
377
- null&&this.refrescar();}async pedir(){try{let e=await this.fetchImpl(this.url,{method:"GET",headers:{authorization:`Bearer ${this.clave}`},signal:AbortSignal.timeout(1e4)});if(e.status===401){this.cerrar(
378
- "entitlements HTTP 401",Fc);return}if(!e.ok){this.cerrar(`entitlements HTTP ${e.status}`);return}let n=await e.json();if(!Array.isArray(n.features)||!n.features.every(o=>typeof o=="string")){this.cerrar(
411
+ 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(
379
413
  "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==
380
- "number"&&n.refreshAfterSeconds>0?Math.min(n.refreshAfterSeconds*1e3,this.ttlMs):this.ttlMs;this.validoHasta=Date.now()+r,this.avisado=!1;}catch(e){this.cerrar(String(e));}}cerrar(e,n){this.features=new Set,
381
- this.validoHasta=Date.now()+Math.min(6e4,this.ttlMs),this.avisado||(this.avisado=true,this.log(n??`[gateway] entitlements unavailable (${e}) \u2014 savings features disabled (fail-closed); traffic keeps flow\
382
- ing`));}};var jr="https://savings.bivelio.com",se="https://savings.bivelio.com/dashboard/account",Ze="https://savings.bivelio.com/dashboard/install",zc=1e4,qc=3e3,ri=6e4,Hc=36e5,Kc=7*86400,Gc=3e4,Wc=86400,Jc="B\
383
- VL";function Ur(t){return Je}function Yc(t){return Or(t)?Object.keys(t.keys??{}).length===0:t.trim()===""}var Br=t=>typeof t=="string"&&t.trim()!=="",Pn=t=>typeof t=="number"&&Number.
384
- isFinite(t);function Zc(t){if(t===null||typeof t!="object"||Array.isArray(t))return false;let e=t;return Br(e.jti)&&Br(e.org_id)&&Br(e.plan)&&Pn(e.seats)&&Pn(e.issued_at)&&Pn(e.expires_at)&&Pn(e.grace_days)&&
385
- e.grace_days>=0&&Array.isArray(e.features)&&e.features.every(n=>typeof n=="string")}function Mn(t,e){try{let n=at(typeof t=="string"?t:""),r=Lt(n);if(r==="empty")return {ok:!1,shape:"empty",reason:"emp\
386
- ty"};if(r==="malformed")return {ok:!1,shape:"malformed",reason:"malformed"};let o=Mt(n,e);if(!o.ok||!o.payloadBytes)return {ok:!1,shape:"token",reason:zt(o.reason??"bad signature")};let s=o.header?.typ;
387
- if(s!==Jc)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:"\
388
- payload is not valid JSON"}}return Zc(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\
389
- cation error: ${zt(String(n))}`}}}function ft(t,e,n){return Tn(t,Math.floor(e/1e3),n)}var mt=t=>t==="active"||t==="grace";function zt(t,e=200){let n=t.replace(/[^\x20-\x7E]/g,"?");return n.length>e?`${n.
390
- slice(0,e)}...`:n}function Xc(t){return `${Number((t/1e3).toFixed(3))} s`}function Qc(t){let e=t,n=typeof e?.message=="string"&&e.message!==""?e.message:String(t),r=e?.cause,o=r&&typeof r.code=="string"?
391
- r.code:r&&typeof r.message=="string"?r.message:void 0;return o?`${n} (${o})`:n}async function oi(t){let e=`${t.licenseServerUrl.replace(/\/+$/,"")}/api/license/current`,n=l=>t.serviceAccountKey?l.split(
392
- t.serviceAccountKey).join("[service key]"):l,r=new AbortController,o=false,s=setTimeout(()=>{o=true,r.abort();},t.timeoutMs);s.unref?.();let i=()=>r.abort();t.signal&&(t.signal.aborted?r.abort():t.signal.addEventListener(
393
- "abort",i,{once:true}));let c=l=>o?{kind:"unreachable",cause:`timed out after ${Xc(t.timeoutMs)}`}:{kind:"unreachable",cause:zt(n(`network error: ${Qc(l)}`))};try{let l=t.fetchImpl??globalThis.fetch,a;try{
394
- a=await l(e,{method:"GET",headers:{authorization:`Bearer ${t.serviceAccountKey}`,accept:"application/json"},signal:r.signal});}catch(f){return c(f)}if(a.status===401)return {kind:"key-unknown"};if(a.status===
395
- 404)return {kind:"no-license"};if(!a.ok)return {kind:"unreachable",cause:`HTTP ${a.status}`};let d;try{d=await a.json();}catch(f){return o||r.signal.aborted?c(f):{kind:"unreachable",cause:"unexpected res\
396
- 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=Mn(u,t.publicKey);return p.ok?{kind:"toke\
397
- n",license:p.license}:{kind:"not-verifying",reason:zt(p.reason)}}catch(l){return c(l)}finally{clearTimeout(s),t.signal?.removeEventListener("abort",i);}}function ke(t){try{return new Date(t*1e3).toISOString().
398
- slice(0,10)}catch{return "an unknown date"}}var qt=(t,e)=>t+e*Wc,el="WARNING: BIVELIO_LICENSE_KEY belongs to a different organization than BIVELIO_SERVICE_KEY and is ignored; the license of the service\
399
- key's organization is used. Unset BIVELIO_LICENSE_KEY or replace it with this organization's license key.",tl=t=>`WARNING: the license served by savings.bivelio.com does not verify against this build\
400
- 's BiVelio key (${t}); starting with BIVELIO_LICENSE_KEY. Update @bivelio/savings-layer (npm i -g @bivelio/savings-layer).`;function nl(t,e={}){switch(t){case "no-public-key":return "this build has no e\
414
+ "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
+ 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\
401
435
  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\
402
- _KEY is not set. The gateway needs two things and does not start without them: an active BiVelio subscription (${se}) and its service key (bvk_..., created at ${Ze}, step 2). Export the key and relaun\
403
- 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_)."+(e.keyLooksLikeLicense?" I\
404
- t looks like a license key: that one goes in BIVELIO_LICENSE_KEY.":"")+` Create a service key at ${Ze} (step 2), export it and relaunch.`;case "service-key-not-recognised":return `BIVELIO_SERVICE_KEY is\
405
- not recognised by savings.bivelio.com (HTTP 401): it was deleted or rotated, or it was copied incompletely. Create a new one at ${Ze} (step 2), export it and relaunch.`;case "no-license":return `your o\
406
- rganization has no active BiVelio license, and the gateway does not start without one: there is no free tier. Subscribe at ${se} and relaunch; the license is collected automatically with your service \
407
- key.`;case "license-expired":{let n=e.expiresAt??0;return `your BiVelio license expired on ${ke(n)} and its grace period ended on ${ke(qt(n,e.graceDays??0))}. Renew at ${se} and relaunch.`+(e.cause?` (s\
408
- avings.bivelio.com could not be reached to look for a renewed license: ${e.cause})`:"")}case "license-invalid":{let n=e.reason??"bad signature";return e.tokenSource==="savings.bivelio.com"?`the license\
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\
437
+ 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\
442
+ 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\
409
443
  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.`:
410
- e.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\
411
- s in BIVELIO_SERVICE_KEY; the license key is the other value on ${Ze}. Or unset BIVELIO_LICENSE_KEY: the gateway collects the license online by itself.`:`BIVELIO_LICENSE_KEY does not verify against th\
412
- is build's BiVelio key (${n}). Copy the WHOLE key again from ${Ze}, or unset BIVELIO_LICENSE_KEY to collect it online; if it persists, update @bivelio/savings-layer or write to support@bivelio.com.`}case "\
413
- unreachable":return `could not collect your license from savings.bivelio.com (${e.cause??"unknown cause"}). The gateway does not start without a verified license. Check your connection and relaunch. If\
414
- savings.bivelio.com is down, export BIVELIO_LICENSE_KEY=<your license key> (from ${Ze}) as a fallback: it is verified on this machine and used only when savings.bivelio.com cannot be reached, and it \
415
- must be replaced by hand every billing period.`}}function ni(t,e,n,r){let o=t.plan.toUpperCase(),s=t.grace_days,i=ke(t.expires_at),c=e==="online"?"collected with your service key and verified on this \
416
- 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 l=ke(qt(t.expires_at,s));
417
- return `license: ${o}, IN GRACE: expired on ${i}, keeps working until ${l}. Renew at ${se} (${c})`}return `license: ${o}, active until ${i} (+${s} ${s===1?"day":"days"} grace), ${c}`}var ye=(t,e)=>({ok:false,
418
- code:t,message:nl(t,e)});async function si(t){let e=t.now??Date.now,n=Ur();if(Yc(n))return ye("no-public-key");let r=t.serviceAccountKey?.trim();if(!r)return ye("service-key-missing");if(!r.
419
- startsWith("bvk_"))return ye("service-key-malformed",{keyLooksLikeLicense:Lt(at(r))==="token"});let o=null;if(t.licenseKey!==void 0){let l=Mn(t.licenseKey,n);if(l.ok)o=l.license;else if(l.shape!=="emp\
420
- ty")return ye("license-invalid",{tokenSource:"BIVELIO_LICENSE_KEY",shape:l.shape,reason:l.reason})}let s=o!==null&&mt(ft(o.payload,e())),i=await oi({licenseServerUrl:t.licenseServerUrl,serviceAccountKey:r,
421
- publicKey:n,timeoutMs:t.timeoutMs??(s?qc:zc),...t.fetchImpl?{fetchImpl:t.fetchImpl}:{}}),c=(l,a)=>{let d=ft(o.payload,e());return mt(d)?{ok:true,license:o,source:"offline",status:d,line:ni(o.payload,"of\
422
- fline",d,l),lineIsWarning:true,warnings:a}:ye("license-expired",{expiresAt:o.payload.expires_at,graceDays:o.payload.grace_days,...l?{cause:l}:{}})};switch(i.kind){case "key-unknown":return ye("service-ke\
423
- y-not-recognised");case "no-license":return ye("no-license");case "token":{let l=i.license,a=ft(l.payload,e()),d=o&&o.payload.org_id!==l.payload.org_id?[el]:[];return mt(a)?{ok:true,license:l,source:"onli\
424
- ne",status:a,line:ni(l.payload,"online",a),lineIsWarning:a==="grace",warnings:d}:ye("license-expired",{expiresAt:l.payload.expires_at,graceDays:l.payload.grace_days})}case "not-verifying":return s?c(void 0,
425
- [tl(i.reason)]):ye("license-invalid",{tokenSource:"savings.bivelio.com",reason:i.reason});case "unreachable":return o?c(i.cause,[]):ye("unreachable",{cause:i.cause})}}var rl=new Set(["expired","revoked",
426
- "no-license","blocked","invalid"]);function Vr(t,e,n){let r=typeof e=="string"?e.trim():"";if(r!==""){let s="reported by savings.bivelio.com";return r==="license-revoked"?{serve:false,state:"revoked",detail:s}:
427
- 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=t.status();return o==="active"||o==="grace"?
428
- {serve:true,state:o}:o==="expired"?{serve:false,state:"expired",detail:n?`grace period ended ${ke(qt(n.expires_at,n.grace_days))}`:"grace period ended"}:o==="revoked"?{serve:false,state:"revoked",detail:"lice\
429
- nse id revoked"}:{serve:false,state:"invalid",detail:"license no longer verifies"}}var Ft="requests already in flight were not interrupted";function ol(t){switch(t){case "expired":return `bvsala gateway: t\
430
- he BiVelio license for this organization has expired. New requests are refused until it is renewed at ${se}; ${Ft}.`;case "revoked":return `bvsala gateway: the BiVelio license for this organization is n\
431
- o longer active (revoked or cancelled). New requests are refused; ${Ft}. Check ${se} or write to support@bivelio.com.`;case "no-license":return `bvsala gateway: this organization has no active BiVelio l\
432
- icense. New requests are refused until you subscribe at ${se}; ${Ft}.`;case "blocked":return `bvsala gateway: savings.bivelio.com reports the BiVelio license for this organization as not active. New req\
433
- uests are refused; ${Ft}. Check ${se}.`;case "invalid":return `bvsala gateway: the license loaded by this gateway no longer verifies. New requests are refused; ${Ft}. Relaunch the terminal; if it persis\
434
- ts, write to support@bivelio.com.`}}function ii(t){return JSON.stringify({type:"error",error:{type:"license_error",status:t,message:ol(t)}})}var sl={expired:`Renew at ${se}`,revoked:`Check ${se} or wr\
435
- ite to support@bivelio.com`,"no-license":`Subscribe at ${se}`,blocked:`Check ${se}`,invalid:"Relaunch the terminal; if it persists, write to support@bivelio.com"};function ai(t,e,n){if(!e.serve)return t===
436
- e.state?null:`[bvsala gateway] license ${e.state} (${e.detail}): new requests are refused with HTTP 402; requests in flight are not touched. ${sl[e.state]}`;let r=ke(n.expires_at),o=ke(qt(n.expires_at,
437
- n.grace_days));return t!==null&&rl.has(t)?e.state==="grace"?`[bvsala gateway] license in grace again (it expired on ${r} and keeps working until ${o}): serving new requests. Renew at ${se}`:`[bvsala g\
438
- ateway] license ${e.state} again (expires ${r}): serving new requests`:e.state==="grace"&&t!=="grace"?`[bvsala gateway] license in grace: it expired on ${r} and keeps working until ${o}. Renew at ${se}`:
439
- null}function Fr(t,e,n,r){return {license:t,gate:Rn(t.token,e,{revocation:n,...r?{now:r}:{}})}}var Ln=class{constructor(e){this.o=e;}o;timer=null;enVuelo=false;parado=false;ctrl=null;avisados=new Set;ahora(){
440
- return this.o.now?this.o.now():Date.now()}start(e={}){this.parado||this.timer!==null||(this.timer=setInterval(()=>{this.check();},this.o.intervalMs??Hc),this.timer.unref?.(),e.checkNow&&this.check({force:true}));}stop(){
441
- this.parado=true,this.timer!==null&&(clearInterval(this.timer),this.timer=null),this.ctrl?.abort();}avisar(e,n){this.avisados.has(e)||(this.avisados.add(e),this.o.onWarning(n));}async check(e={}){if(this.
442
- enVuelo||this.parado)return false;let n=this.o.current(),r=mt(ft(n.payload,this.ahora(),this.o.revocation.snapshot())),o=n.payload.expires_at-Math.floor(this.ahora()/1e3);if(!e.force&&r&&o>(this.o.leadSeconds??
443
- Kc))return false;this.enVuelo=true;let s=new AbortController;this.ctrl=s;try{let i=await oi({licenseServerUrl:this.o.licenseServerUrl,serviceAccountKey:this.o.serviceAccountKey,publicKey:this.o.publicKey,timeoutMs:this.
444
- o.timeoutMs??Gc,signal:s.signal,...this.o.fetchImpl?{fetchImpl:this.o.fetchImpl}:{}});if(this.parado)return !1;let c=ke(qt(n.payload.expires_at,n.payload.grace_days));switch(i.kind){case "token":{let l=i.
445
- license.payload,a=this.o.revocation.snapshot();if(l.jti===n.payload.jti||this.o.revocation.has(l.jti)||!mt(ft(l,this.ahora(),a)))return !1;let d=mt(ft(n.payload,this.ahora(),a)),u=l.org_id!==n.payload.
446
- org_id,p=l.expires_at>n.payload.expires_at;return !u&&!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\
447
- s no longer recognised (HTTP 401). This session keeps its current license until ${c}; create a new key at ${Ze} and relaunch.`),!1;case "no-license":return this.avisar("no-license",`[bvsala gateway] li\
448
- cense renewal: savings.bivelio.com reports no active license for this organization (HTTP 404). This session keeps its current license until ${c}; subscribe or renew at ${se}.`),!1;case "not-verifying":
444
+ 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 "\
447
+ 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(){
475
+ 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":
449
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\
450
- lio/savings-layer.`),!1;case "unreachable":return !1}return !1}catch{return false}finally{this.ctrl===s&&(this.ctrl=null),this.enVuelo=false;}}};function ci(t){let e=0,n=0;for(;;){let o=t.indexOf('"input_schema"',n);if(o<0)break;e+=1,n=o+14;}let r=0;for(n=0;;){let o=t.indexOf('"tool_reference"',n);if(o<0)break;r+=1,n=o+16;}return {definiciones:e,
451
- referencias:r}}var il=40;function li(t){return t.referencias>0||t.definiciones<il?null:`[bvsala gateway] your client sends ${t.definiciones} FULL tool definitions in every request and does not use too\
452
- l 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. If you launched the terminal by hand, export ENABLE_TOOL_SEAR\
453
- CH=true. In our own corpus that block was 24.5% of input spend.`}var zr=5*1024*1024,cl=["authorization","x-api-key","anthropic-version","anthropic-beta","api-key","openai-organization","openai-project"];function ui(t,e,n,r=""){return createHash(
454
- "sha256").update(t).update(`
455
- `).update(e).update(`
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}\
486
+ 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(
488
+ "sha256").update(e).update(`
489
+ `).update(t).update(`
456
490
  `).update(r).update(`
457
- `).update(n).digest("hex")}function di(t){return cl.map(e=>`${e}=${t(e)??""}`).join(`
458
- `)}var Nn=class{enVuelo=new Map;primarias=0;gemelas=0;registrar(e){if(this.enVuelo.has(e))return null;this.primarias+=1;let n,r=new Promise(c=>n=c);this.enVuelo.set(e,{promesa:r,resolver:n});let o=[],
459
- s=0,i=false;return {capturar:c=>{if(!i){if(s+=c.length,s>zr){i=true,o.length=0;return}o.push(c);}},terminar:(c,l,a)=>{let d=!i&&c>=200&&c<300;this.enVuelo.get(e)?.resolver(d?{status:c,headers:l,chunks:o,...a?
460
- {primaria:a}:{}}:null),this.enVuelo.delete(e);},abortar:()=>{this.enVuelo.get(e)?.resolver(null),this.enVuelo.delete(e);}}}async esperar(e){let n=this.enVuelo.get(e);if(!n)return null;let r=await n.promesa;
461
- return r&&(this.gemelas+=1),r}tieneEnVuelo(e){return this.enVuelo.has(e)}};var pi={openai:"https://api.openai.com",anthropic:"https://api.anthropic.com"};function fi(t){let e;try{e=new URL(t).origin;}catch{return false}return Object.values(pi).includes(e)}function mi(t){for(let e=0;e<
462
- t.length;e++){let n=t[e];if(n==="--upstream"){let r=t[e+1];return r!==void 0&&!r.startsWith("--")?r:null}if(n.startsWith("--upstream=")){let r=n.slice(11);return r.trim()!==""?r:null}}}function ll(t){
463
- let e=t.trim();return /^(sk-|sk_|bvk_|rk_|pk_|key-)/i.test(e)||e.length>=32&&!/[\s:/.]/.test(e)?"(value hidden: it looks like a key)":`"${e.length>80?`${e.slice(0,80)}\u2026`:e}"`}function hi(t){if(t.flag===
464
- null)return {ok:false,error:"[bvsala gateway] --upstream needs a value: openai, anthropic or an origin URL such as https://api.openai.com"};let e,n;if(t.flag!==void 0)e=t.flag,n="flag";else if(t.env!==void 0&&
465
- t.env.trim()!=="")e=t.env,n="env";else return {ok:true,upstream:void 0,origen:"none"};let r=pi[e.trim().toLowerCase()];if(r!==void 0)return {ok:true,upstream:r,origen:n};let o={ok:false,error:`[bvsala gateway]\
466
- invalid upstream ${ll(e)}: use openai, anthropic or an http(s) origin URL`},s;try{s=new URL(e.trim());}catch{return o}return s.protocol!=="http:"&&s.protocol!=="https:"?o:s.pathname!=="/"||s.search!==
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===
498
+ 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!==
467
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\
468
- ns), so put that prefix in the client's base URL instead.`}:{ok:true,upstream:s.origin,origen:n}}var bi='[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\
469
- o the call (Node: stream_options: { include_usage: true }); its last chunk then has an empty choices list.',pl=bi+" Or start the gateway with BVSALA_GATEWAY_USAGE_INJECT=1 to add it for clients you ca\
470
- nnot change.",fl=bi+" 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.",ml=t=>`[bvsala gateway] POST ${t} answe\
471
- red without the provider's final usage, so it was forwarded but NOT metered. Nothing is estimated in its place.`,hl=t=>`[bvsala gateway] POST ${t} is forwarded but NOT metered: the gateway reads usage\
472
- from /v1/messages, \u2026/chat/completions and \u2026/responses only.`,gi=/\/(count_tokens|input_tokens)$/,gl=["content-encoding","content-length","transfer-encoding"],bl=new Set(["connection","keep-\
473
- alive","proxy-connection","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","expect"]);function ht(t){let e=t?.cause;if(e==null)return String(t);let n=e instanceof
474
- AggregateError&&e.errors.length>0?e.errors.map(r=>String(r)).join("; "):String(e);return `${String(t)} \xB7 cause: ${n}`}var qr=class extends Error{code;puerto;constructor(e,n,r){super(e==="EADDRINUSE"?
475
- `port ${n} is already in use: the gateway could not start`:e==="EACCES"?`port ${n} cannot be opened: permission denied`:`could not listen on 127.0.0.1:${n} (${e})`,{cause:r}),this.name="ErrorDeEscucha",
476
- this.code=e,this.puerto=n;}};function vl(t,e){if(t===e)return true;let n=Object.keys(t);return n.length!==Object.keys(e).length?false:n.every(r=>Object.hasOwn(e,r)&&t[r]===e[r])}function yl(t){return t.writableFinished?
477
- Promise.resolve(true):t.destroyed?Promise.resolve(false):new Promise(e=>{let n=()=>o(true),r=()=>o(t.writableFinished),o=s=>{t.off("finish",n),t.off("close",r),e(s);};t.once("finish",n),t.once("close",r);})}async function vi(t){
478
- if(!t?.license)throw new Error("arrancarGateway: a verified BiVelio license is required (LICENSE section 2)");let e=Ur(t.license.publicKey),n=Mn(t.license.token,e);if(!n.ok)throw new Error(`arrancarGa\
479
- teway: the license token does not verify (${n.reason})`);let r=(t.upstream??"https://api.anthropic.com").replace(/\/+$/,""),o=fi(r),s=t.fetchImpl??fetch,i=t.log??(h=>console.log(h)),c=t.warn??(h=>console.
480
- error(h)),l=t.license.now??Date.now,a=t.license.licenseServerUrl?.replace(/\/+$/,""),d=new ct,u=Fr(n.license,e,d,l),p;if(t.serviceAccountKey){p=new ot({url:t.meteringUrl??"https://savings.bivelio.com/\
481
- api/metering/usage",serviceAccountKey:t.serviceAccountKey,surface:"gateway",...t.fetchImpl?{fetchImpl:t.fetchImpl}:{},onAuthError:x=>z("gateway-ingest-auth",`[bvsala gateway] the usage ingest is rejec\
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.
508
+ 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
+ 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
+ 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
+ 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
+ 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
+ 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??""}`;
515
+ 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) \
517
+ 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"?
525
+ `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\
482
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.`)});
483
- let h=an();t.seatId?p.setSeat(t.seatId,h):cn(t.serviceAccountKey).then(x=>p?.setSeat(x,h)).catch(()=>{}),p.start();}else z("gateway-sin-clave","[bvsala gateway] no BIVELIO_SERVICE_KEY: this in-process \
484
- gateway forwards traffic but does not meter it (the bvsala CLI refuses to start without the key).");let f=t.coalescer?new Nn:null,g=t.sombra&&p?new On:null,y=new en,m=t.serviceAccountKey?new Dn({url:a?
485
- `${a}/api/org/entitlements`:new URL("/api/org/entitlements",t.meteringUrl??"https://savings.bivelio.com/api/metering/usage").toString(),serviceAccountKey:t.serviceAccountKey,...t.fetchImpl?{fetchImpl:t.
486
- fetchImpl}:{},...t.entitlementsTtlMs!==void 0?{ttlMs:t.entitlementsTtlMs}:{},log:i}):null,b=m!==null&&t.elision!==false,w=()=>Vr(u.gate,m?.blockReason()??null,u.license.payload),E=null;{let h=Vr(u.gate,null,
487
- u.license.payload);h.serve&&(E=h.state);}let v=h=>{let x=ai(E,h,u.license.payload);E=h.state,x&&c(x);},R,I,C=Number.NEGATIVE_INFINITY,D=new Set,M=(h,x)=>{D.has(h)||(D.add(h),i(x));},F=false,q=h=>h==="/v1/me\
488
- ssages"?new Ye:h.endsWith("/responses")?new ut:h.endsWith("/chat/completions")?new Bt:null,k=(h,x,H,$,B,V)=>{i(`[gateway] ${h} ${x} \u2192 ${H}${$?" (stream)":""} \xB7 not metered: ${B}`),t.avisosDeNoMedido!==
489
- false&&(V==="chat"&&z("gateway-chat-sin-include-usage",pl),V==="chat-con-inyeccion"&&z("gateway-chat-sin-include-usage-con-inyeccion",fl),V==="uso"&&z(`gateway-sin-usage:${x}`,ml(x)),V==="dialecto"&&z(`g\
490
- ateway-sin-dialecto:${x}`,hl(x)));},T=(h,x,H,$)=>{let B=h instanceof ut?h.estadoFinal():null;if(B!==null&&B!=="completed")return {motivo:`the response ended as response.${B} without usage`,aviso:"uso"};
491
- if(!(h instanceof Bt&&$!=="inyectado"&&zs(x,H)!==true))return {motivo:"the stream ended without the provider's final usage event",aviso:"uso"};let U="the request did not ask for usage (stream_options.inc\
492
- lude_usage)";return $==="rechazada-por-el-upstream"?{motivo:`${U}, and the upstream rejects that option`,aviso:null}:$==="comprimido"?{motivo:`${U}; usage injection skips compressed request bodies`,aviso:"\
493
- chat-con-inyeccion"}:$!==null?{motivo:U,aviso:"chat-con-inyeccion"}:{motivo:U,aviso:"chat"}},O=(h,x,H,$,B,V,U,S,W,bt,Ve,ue,de,Pe)=>{if(!p||!H)return;let vt=p,yt=H,j=Bs(x,V),kt=`[gateway] POST ${B}${$?
494
- " \xB7 COALESCED (call avoided)":""}`;if(!j){i(`${kt} \xB7 not metered: could not read the model from the request body${V?` (content-encoding: ${V})`:""}`),z(`gateway-sin-modelo:${B}`,`[bvsala gateway\
495
- ] could not read the model from the ${B} request body (content-encoding: ${V??"none"}); its usage is forwarded but not metered.`);return}let pe=!$&&Ve?Ve.servido:j,oe=$s(pe,H);if(oe){let ie=$?Hs(j,oe,
496
- de,jt(x,V),{suscripcion:ue===true,entregada:Pe?.entregada===true,tierServido:Pe?.tierServido}):null,K=$?Ks(h,j,oe,U,ie?.ok?ie.credit:null):qs(h,pe,oe,U,S,W,Ve,ue===true);p.record(K);let P=K.cost.eliminatedInputFloorCost;
497
- i(`[gateway] POST ${B} ${$?"\xB7 COALESCED (call avoided)":""} \xB7 ${pe!==j?`${j}\u2192${pe} (sibling model)`:j} \xB7 $${oe.costeUsd.toFixed(6)} (in ${oe.tokens.entrada}, cache\u2191${oe.tokens.cacheEscrita}${oe.
498
- tokens.cacheEscrita1h?` (1h ${oe.tokens.cacheEscrita1h})`:""} cache\u2193${oe.tokens.cacheLeida}, out ${oe.tokens.salida})`+(S?` \xB7 elision: ${S.borrados} clear(s), ${S.tokensLimpiados} tok cleared \
499
- by the provider`+(P!==void 0?` \xB7 floor $${P.toFixed(6)} (cache read price)`:S.tokensLimpiadosToolUses>0?S.atribuible?" \xB7 no cache read price in the catalog: no floor":" \xB7 your own context_manage\
500
- ment settings: counted, not credited":S.tokensLimpiados>0?" \xB7 thinking only (your config): counted, not credited":""):"")+(ue&&!$&&(W||Ve)?" \xB7 subscription traffic: lever applied, saving not credit\
501
- ed (no per-token invoice)":"")+(ie?ie.ok?` \xB7 by reference: floor $${Mr(ie.credit).toFixed(6)} (cache read price${ie.credit.creditedOutputTokens>0?`, ${ie.credit.creditedOutputTokens} output tok at \
502
- temperature 0`:", no output credited"})`:` \xB7 estimated, not by reference: ${ie.reason}`:""));let Se=S?.atribuible===true&&S.tokensLimpiadosToolUses>0;g&&!$&&B==="/v1/messages"&&setImmediate(()=>{try{
503
- let Fe=jt(x,V);if(!Fe||typeof Fe!="object")return;let fe=g.observar({cuerpo:Fe,uso:yt,model:j,at:bt??Date.now(),...U?.sessionId!==void 0?{sessionId:U.sessionId}:{},...U?.agentId!==void 0?{agentId:U.agentId}:
504
- {}});if(!fe)return;if(Se){i(`[gateway] shadow estimate \xB7 ${j} \xB7 the provider already cleared context via our settings: chain advances, nothing emitted`);return}vt.record(Gs(`${h}:shadow`,j,fe.baselineUsd,
505
- fe.politicaUsd,U)),i(`[gateway] shadow estimate \xB7 ${j} \xB7 baseline $${fe.baselineUsd.toFixed(6)} \u2192 with elision $${fe.politicaUsd.toFixed(6)}`);}catch{}});}else i(`${kt} \xB7 not metered: model "${pe}\
506
- " has no list price in the catalog`),z(`gateway-sin-precio:${pe}`,`[bvsala gateway] model "${pe}" is not in the price catalog; its usage is forwarded but not metered.`);},L=createServer(async(h,x)=>{let H=randomUUID(),$=Date.
507
- now(),B=w();if(v(B),!B.serve){let K=l();I&&K-C>=ri&&(C=K,I.check({force:true})),h.resume(),x.writeHead(402,{"content-type":"application/json","cache-control":"no-store","x-bvsala-license-status":B.state}),
508
- x.end(h.method==="HEAD"?void 0:ii(B.state));let P="/";try{P=new URL(h.url??"/","http://x").pathname;}catch{}i(`[gateway] ${h.method} ${P} \u2192 402 (license ${B.state})`);return}let V=new AbortController;
509
- x.on("close",()=>{x.writableEnded||V.abort();});let U=null,S=new URL(h.url??"/",r),W=null,bt=Buffer.alloc(0),Ve=false,ue=null,de=null,Pe=false,vt=(K,P)=>{if(K===null||ue===null||!ue.nuestros)return K;let Se=P?.
510
- cache_creation,Fe=P?.cache_creation_input_tokens??(Se?.ephemeral_5m_input_tokens??0)+(Se?.ephemeral_1h_input_tokens??0),fe=(P?.input_tokens??0)+(P?.cache_read_input_tokens??0)+Fe+K.tokensLimpiados,xt=ue.
511
- triggerDelCliente!==null&&fe>=ue.triggerDelCliente;return {...K,atribuible:!xt}},yt=h.headers["content-encoding"],j=Array.isArray(yt)?yt[0]:yt,kt=K=>{let P=Array.isArray(K)?K[0]:K;return P!==void 0&&/^[A-Za-z0-9._:/-]{1,128}$/.
512
- test(P)?P:void 0},pe=kt(h.headers["x-claude-code-session-id"]),oe=kt(h.headers["x-claude-code-agent-id"]),ie=pe!==void 0||oe!==void 0?{...pe!==void 0?{sessionId:pe}:{},...oe!==void 0?{agentId:oe}:{}}:
513
- void 0;try{let K=[];for await(let _ of h)K.push(_);let P=Buffer.concat(K);bt=P,S=new URL(h.url??"/",r);let Se=f!==null&&h.method==="POST"&&P.length>0,Fe=di(_=>{let A=h.headers[_];return Array.isArray(
514
- A)?A.join(", "):A}),fe=Se?ui("POST",S.pathname+S.search,P,Fe):"";if(Se)if(f.tieneEnVuelo(fe)){let _=await f.esperar(fe);if(_){let A=V.signal.aborted||x.destroyed;A||x.writeHead(_.status,_.headers);let ae=q(
515
- S.pathname)??new Ye;for(let Tt of _.chunks)A||x.write(Tt),ae.observar(Tt);A||x.end();let nt=A?!1:await yl(x),Et=ae.usageFinal()??Cn(S.pathname,Buffer.concat(_.chunks));if(Et===null){if(p&&!gi.test(S.pathname)){
516
- let Tt=String(_.headers["content-type"]??"").includes("text/event-stream");k(h.method??"POST",S.pathname,_.status,Tt,dt(S.pathname)?Tt?T(ae,P,j,null).motivo:"the response carried no usage":"no usage d\
517
- ialect for this route",null);}return}let _t=h.headers["anthropic-beta"],rt=Lr(S.pathname,Array.isArray(_t)?_t.join(", "):_t,r);O(H,P,Et,!0,S.pathname,j,ie,null,null,$,null,rt,_.primaria??null,{entregada:nt,
518
- tierServido:Vs(S.pathname,Buffer.concat(_.chunks))});return}}else U=f.registrar(fe);let xt=h.headers.connection,Gi=new Set((Array.isArray(xt)?xt.join(","):xt??"").split(",").map(_=>_.trim().toLowerCase()).
519
- filter(_=>_!=="")),Ee={};for(let[_,A]of Object.entries(h.headers))_==="host"||_==="content-length"||A===void 0||bl.has(_)||Gi.has(_)||(Ee[_]=Array.isArray(A)?A.join(", "):A);let Jt={...Ee};Pe=Lr(S.pathname,
520
- Jt["anthropic-beta"],r);let ce=P;if(b&&t.dialesElision===!0&&h.method==="POST"&&S.pathname==="/v1/messages"&&m.tiene("context_elision"))try{let _=mo(P,j);_!==null&&(ce=_.cuerpo,ue={nuestros:_.nuestros,
521
- triggerDelCliente:_.triggerDelCliente},Ee["anthropic-beta"]=go(Ee["anthropic-beta"]));}catch{}if(h.method==="POST"&&S.pathname==="/v1/messages"&&(j??"")==="")try{let _=li(ci(P.toString("utf8")));_&&z("\
522
- gateway-busqueda-herramientas",_);}catch{}let io=b&&t.modeloHermano===!0&&h.method==="POST"&&(S.pathname==="/v1/messages"||S.pathname==="/v1/messages/count_tokens");if(io&&!m.tiene("sibling_model_routi\
523
- ng")&&z("gateway-hermano-sin-feature","[bvsala 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-c\
524
- losed)."),io&&m.tiene("sibling_model_routing"))try{let A=Ro(ce,ce===P?j:"identity",{betas:Ee["anthropic-beta"]});A!==null&&(ce=A.cuerpo,de=A.cambio);}catch{}let wt=!1;if(b&&Qn(t.esfuerzo)&&h.method==="\
525
- POST"&&S.pathname==="/v1/messages"&&m.tiene("per_turn_effort"))try{let _=ce===P?j:"identity",A=wo(ce,t.esfuerzo,_);A!==null&&(ce=A.cuerpo,Ee["anthropic-beta"]=So(Ee["anthropic-beta"]),wt=!0);}catch{}let St=null;
526
- if(b&&h.method==="POST"&&S.pathname==="/v1/messages"&&m.tiene("cache_ttl_tuning"))try{let A=qe(ce,ce===P?j:"identity");if(A!==null){let ae=bo(A),nt=`${ie?.sessionId??"sin-sesion"}:${ae.system}`,Et=Date.
527
- now(),_t=y.ultima(nt,Et);if(y.anotar(nt,ae,Et),yo({fraccionNueva:vo(_t,ae)})){let rt=ko(A);rt!==null&&(ce=rt.cuerpo,St={rebajadas:rt.rebajadas,yaEran5m:rt.yaEran5m});}}}catch{}let tt=!1,Yt=null;if(h.method===
528
- "POST"&&S.pathname.endsWith("/chat/completions")&&p&&t.usageInject===!0)if(F)Yt="rechazada-por-el-upstream";else try{let _=Fs(P,j);Yt=_.motivo,_.cuerpo&&(ce=_.cuerpo,tt=!0);}catch{}let N,ao=ce,co=Ee;try{
529
- N=await s(S,{method:h.method,headers:Ee,body:["GET","HEAD"].includes(h.method??"")?void 0:ce,redirect:"manual",signal:V.signal});}catch(_){U?.abortar(),x.headersSent||(x.writeHead(502,{"content-type":"\
530
- application/json"}),x.end(JSON.stringify({error:"bvsala gateway: upstream unreachable",detail:ht(_)}))),i(`[gateway] ${h.method} ${S.pathname} \u2192 upstream unreachable: ${ht(_)}`);return}if(((de!==
531
- null||wt)&&N.status===400||tt&&(N.status===400||N.status===422))&&!V.signal.aborted){let _="";try{_=(await N.text()).slice(0,300).replace(/\s+/g," ");}catch{}let A=tt;i(A?`[gateway] the upstream reject\
532
- ed (${N.status}) the request with stream_options.include_usage added; forwarding it unchanged \xB7 ${_}`:`[gateway] the upstream rejected (400) the rewritten request${de?` to ${de.servido}`:""}${wt?" \
533
- (per-turn effort)":""}; forwarding it unchanged \xB7 ${_}`),de=null,wt=!1,St=null,ue=null,tt=!1,A&&(Yt="rechazada-por-el-upstream"),ao=P,co=Jt;try{N=await s(S,{method:h.method,headers:Jt,body:P,redirect:"\
534
- manual",signal:V.signal});}catch(ae){U?.abortar(),x.headersSent||(x.writeHead(502,{"content-type":"application/json"}),x.end(JSON.stringify({error:"bvsala gateway: upstream unreachable",detail:ht(ae)}))),
535
- i(`[gateway] ${h.method} ${S.pathname} \u2192 upstream unreachable on retry: ${ht(ae)}`);return}A&&N.ok&&(F=!0,z("gateway-sin-stream-options","[bvsala gateway] the upstream rejects stream_options, so \
536
- 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 qn=Object.fromEntries(N.headers.
537
- entries());for(let _ of gl)delete qn[_];x.writeHead(N.status,qn);let Zt=N.headers.get("content-type")??"",Xt=Zt.includes("text/event-stream")||Zt===""&&N.ok&&q(S.pathname)!==null&&!S.pathname.endsWith(
538
- "/chat/completions");W=Xt?q(S.pathname):null;let ze=!Xt&&N.ok&&p!==void 0&&h.method==="POST"&&dt(S.pathname)&&(N.headers.get("content-type")??"").includes("application/json")?[]:null,lo=0,uo=!1;if(N.body)
539
- for await(let _ of N.body){let A=Buffer.from(_);x.write(A),W?.observar(A),ze&&(lo+=A.length,lo>zr?(ze=null,uo=!0):ze.push(A)),U?.capturar(A);}if(x.end(),U){let _=de===null&&!wt&&ue===null&&!tt&&St===null&&
540
- ao===P&&vl(co,Jt),A=ze?Buffer.concat(ze):null,ae=N.ok&&(W?W.usageFinal()!==null:A!==null&&Cn(S.pathname,A)!==null),nt=W instanceof ut&&W.estadoFinal()==="failed"||A!==null&&Us(S.pathname,A);U.terminar(
541
- N.status,qn,{requestId:H,at:Date.now(),intacta:_,proveedorOficial:o,conContador:ae,suscripcion:Pe,fallida:nt});}if(W&&N.ok){Ve=!0;let _=W.usageFinal();if(_===null&&p){let A=T(W,P,j,tt?"inyectado":Yt);k(
542
- h.method??"POST",S.pathname,N.status,!0,A.motivo,A.aviso);}else {let A=vt(W instanceof Ye?W.elision():null,_);O(H,P,_,!1,S.pathname,j,ie,A,St,$,de,Pe);}p||i(`[gateway] ${h.method} ${S.pathname} \u2192 ${N.
543
- status} (stream) \xB7 not metered: no BIVELIO_SERVICE_KEY`);}else if(ze){let _=Buffer.concat(ze),A=Cn(S.pathname,_);if(A===null)k(h.method??"POST",S.pathname,N.status,!1,"the response carried no usage",
544
- "uso");else {let ae=S.pathname==="/v1/messages"?Ls(_):null;O(H,P,A,!1,S.pathname,j,ie,vt(ae,A),St,$,de,Pe);}}else uo?k(h.method??"POST",S.pathname,N.status,!1,"the response was too large to read its usa\
545
- ge",null):p&&h.method==="POST"&&N.ok&&dt(S.pathname)?k(h.method,S.pathname,N.status,!1,`the response is neither JSON nor an event stream (content-type: ${Zt===""?"none":Zt.slice(0,80)})`,null):p&&h.method===
546
- "POST"&&N.ok&&!dt(S.pathname)&&!gi.test(S.pathname)?k(h.method,S.pathname,N.status,Xt,"no usage dialect for this route",S.pathname.startsWith("/v1/")?"dialecto":null):i(`[gateway] ${h.method} ${S.pathname}\
547
- \u2192 ${N.status}${Xt?" (stream)":""}`);}catch(K){if(U?.abortar(),V.signal.aborted){let P=!Ve&&W?W.usageFinal():null;if(P){i(`[gateway] ${h.method} ${S.pathname} \u2192 client closed after the final usage\
548
- ; metered anyway`);let Se=vt(W instanceof Ye?W.elision():null,P);O(H,bt,P,false,S.pathname,j,ie,Se,void 0,$,de,Pe);}else i(`[gateway] ${h.method} ${S.pathname} \u2192 client aborted; upstream cancelled`);}else if(i(
549
- `[gateway] ${h.method} ${S.pathname} \u2192 error while serving: ${ht(K)}`),!x.headersSent){x.writeHead(502,{"content-type":"application/json"}),x.end(JSON.stringify({error:"bvsala gateway: stream int\
550
- errupted",detail:ht(K)}));return}x.writableEnded||x.end();}});L.on("upgrade",(h,x)=>{i(`[gateway] ${h.method} ${new URL(h.url??"/","http://x").pathname} \u2192 426 (WebSocket not supported; the client falls\
551
- back to HTTP)`),x.once("error",()=>{}),x.once("finish",()=>x.destroy()),x.end(`HTTP/1.1 426 Upgrade Required\r
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
552
606
  connection: close\r
553
607
  content-length: 0\r
554
608
  \r
555
- `);});let Y=t.puerto??8402;try{await new Promise((h,x)=>{L.once("error",x),L.listen(Y,"127.0.0.1",()=>h());});}catch(h){p?.stop();let x=h?.code;throw new qr(typeof x=="string"?x:"EUNKNOWN",Y,h)}let ne=L.
556
- address().port;return a&&(R=new Nt({url:`${a}/licenses/revocations`,publicKeyPem:e,snapshot:d,getRefreshAfter:()=>u.gate.refreshAfter?.(),nowSeconds:()=>Math.floor(l()/1e3),...t.fetchImpl?{fetchImpl:t.
557
- fetchImpl}:{},silenceWarnings:true,onEvent:h=>{h.type==="rejected"&&M(`poller:${h.reason}`,`[gateway] revocation list rejected (${h.reason}); known revocations still apply`);},...t.license.revocations??{}}),
558
- R.start(),t.serviceAccountKey&&(I=new Ln({licenseServerUrl:a,serviceAccountKey:t.serviceAccountKey,publicKey:e,revocation:d,current:()=>u.license,onAdopt:h=>{u=Fr(h,e,d,l),i(`[gateway] renewed license\
559
- adopted (expires ${ke(h.payload.expires_at)})`),v(w());},onWarning:c,...t.fetchImpl?{fetchImpl:t.fetchImpl}:{},now:l,...t.license.renewal??{}}),I.start({checkNow:t.license.checkOnStart===true}))),{puerto:ne,
560
- cerrar:async()=>{I?.stop(),R?.stop(),await p?.stopAndDrain(),await new Promise(h=>L.close(()=>h()));},licenseStatus:()=>w().state}}var Hr=["claude","codex","goose","qwen"];function Ht(t){return Hr.includes(t??"")}function Kr(t,e={}){let n=e.path??process.env.PATH??"",r=e.
561
- existe??existsSync,o=null;for(let s of n.split(";").filter(i=>i.length>0)){for(let i of [".exe",".com"]){let c=join(s,t+i);if(r(c))return {tipo:"exe",ruta:c}}if(o===null)for(let i of [".cmd",".bat"]){let c=join(s,t+
562
- i);if(r(c)){o=c;break}}}return o!==null?{tipo:"solo-shim",ruta:o}:{tipo:"no-encontrado"}}function ki(t={}){let n=(t.env??process.env).BVSALA_CODEX_AUTH?.toLowerCase();if(n==="api-key"||n==="apikey")return "\
563
- api-key";if(n==="chatgpt")return "chatgpt";let r=null;try{r=t.leerAuth?t.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.
564
- toLowerCase().replace(/[^a-z]/g,"")==="apikey"?"api-key":"chatgpt":o.tokens!==void 0&&o.tokens!==null?"chatgpt":"api-key"}catch{return "api-key"}}var xl={"api-key":{upstream:"https://api.openai.com",prefijo:"\
565
- /v1"},chatgpt:{upstream:"https://chatgpt.com",prefijo:"/backend-api/codex"}};function $n(t,e,n,r={},o=process.env){let s=`http://127.0.0.1:${e}`;switch(t){case "claude":return {bin:"claude",args:n,env:{
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:{
566
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:'\
567
- 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",c=xl[i];return {bin:"codex",
568
- args:["-c",`openai_base_url="${s}${c.prefijo}"`,...n],env:{},upstream:c.upstream,nota:i==="chatgpt"?"ChatGPT auth detected: the gateway routes to chatgpt.com/backend-api/codex. Subscription traffic is\
569
- 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 wl=["gateway","doctor","skill"],xi=new Set(["help","--help","-h"]),wi=new Set(["version","--version","-v"]);function Si(t){let[e,...n]=t;return e===void 0||xi.has(e)?{tipo:"ayuda",salida:0}:wi.has(
570
- e)?{tipo:"version"}:Ht(e)?{tipo:"arrancar",comando:e,resto:n}:wl.includes(e)?n.some(r=>xi.has(r))?{tipo:"ayuda",salida:0}:n.some(r=>wi.has(r))?{tipo:"version"}:{tipo:"arrancar",comando:e,resto:n}:{tipo:"\
571
- ayuda",salida:1}}function Ei(t){return t.length===1&&(t[0]==="--help"||t[0]==="-h"||t[0]==="--version")}function _i(t,e,n){let r=t??{},o=typeof r.puerto=="number"?r.puerto:n;if(r.code==="EADDRINUSE")return `\
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 `\
572
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 (\
573
- EACCES; ports below 1024 need privileges): use --port ${Math.max(1024,o)} or higher`;let s=t instanceof Error?t.message:String(t);return `could not start the gateway for \`bvsala ${e}\`: ${s}`}function Sl(t){let e=Number.parseInt(t.slice(8,10),10);return Number.isFinite(e)&&e%2===0?"palanca":"control"}function Ti(t){let e;try{e=JSON.parse(t());}catch{return null}if(typeof e!="object"||e===null)return null;let n=e,r=n.espia;return typeof r!="number"||!Number.isInteger(r)||r<1||r>65535?null:{activo:n.
574
- activo!==false,espia:r}}function Ri(t){let{enrolamiento:e,espiaVivo:n,upstreamEnv:r,elisionEnv:o,hoyUtcIso:s}=t;if(!e)return {linea:"",aviso:false};if(!e.activo)return {linea:"A/B plan: enrolment paused (acti\
575
- vo:false)",aviso:false};if(!n)return {linea:`A/B plan: enrolled but the capture proxy is NOT listening on :${e.espia} \u2014 NOT chaining (today's traffic will not enter the corpus). Start it with \`pnpm anillo\
576
- 2:espia\`.`,aviso:true};let i=Sl(s),c=`http://127.0.0.1:${e.espia}`,l=r!==void 0&&r!=="",a=o!==void 0&&o!=="",d=[];d.push(`A/B plan: ${s} UTC \u2192 arm ${i.toUpperCase()}`);let u=t.upstreamOrigen==="fl\
577
- ag"?"--upstream":"the environment";return d.push(l?`upstream kept from ${u} (${r})`:`chained to :${e.espia}`),a&&d.push(`elision flag kept from the environment (=${o})`),d.push("context elision dials \
578
- 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"),{...l?{}:{upstream:c},brazo:i,linea:d.join(", "),aviso:false}}var Rl="check: the gateway log must show `[gateway] POST /v1/messages \u2026`; if you see `/v1/v1\
579
- /messages`, there is one /v1 too many; if you see a bare `POST /messages`, one is missing.",Al=[{id:"claude",nombre:"Claude Code",binario:"claude",configs:[],detectable:true,receta:({base:t})=>["use `bv\
580
- 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=${t} claude (no /v1: the client appends /v1/mess\
581
- ages)`]},{id:"codex",nombre:"Codex CLI",binario:"codex",configs:[join(".codex","config.toml"),join(".codex","auth.json")],detectable:true,receta:({base:t,rutas:e})=>["use `bvsala codex` \u2014 the base URL prefi\
582
- x depends on the auth mode and the wrapper resolves it:",` API key \u2192 openai_base_url=${t}/v1`,` ChatGPT subscription \u2192 openai_base_url=${t}/backend-api/codex (must end exactl\
583
- y there)`,`${e[1]}: only checked for existence; never read.`]},{id:"opencode",nombre:"opencode",binario:"opencode",configs:[join(".config","opencode","opencode.json")],detectable:true,receta:({baseV1:t,rutas:e})=>[
584
- `mechanism: ${e[0]} \u2192 provider.anthropic.options.baseURL (the project's opencode.json overrides the global one). WITH /v1.`,"{",' "provider": {',' "anthropic": {',` "options": { "baseURL\
585
- ": "${t}" }`," }"," }","}",'alternative: "baseURL": "{env:BVSALA_BASE_URL}" and export the variable; pitfall: without the variable, baseURL is empty.']},{id:"goose",nombre:"Goose",binario:"goose",
586
- configs:[join(".config","goose","config.yaml")],detectable:true,receta:({base:t,rutas:e})=>[`mechanism: ANTHROPIC_HOST environment variable (overrides ${e[0]}). NO /v1.`,`ANTHROPIC_HOST=${t} ANTHROPIC_API\
587
- _KEY=\u2026 goose`]},{id:"crush",nombre:"Crush",binario:"crush",configs:[join(".config","crush","crushrc")],detectable:true,receta:({baseV1:t,rutas:e})=>[`mechanism: ${e[0]} (Bash); crush.json is deprecat\
588
- 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 ${t} --api-key "$ANTHROPIC_API_KEY"`]},{id:"qwen",
589
- nombre:"Qwen Code",binario:"qwen",configs:[join(".qwen","settings.json")],detectable:true,receta:({base:t,rutas:e})=>[`mechanism: ANTHROPIC_BASE_URL environment variable + ${e[0]} with selectedType = anth\
590
- ropic. NO /v1 (the official TS SDK appends /v1/messages).`,`ANTHROPIC_BASE_URL=${t} ANTHROPIC_API_KEY=\u2026 qwen`,`check by hand that ${e[0]} has selectedType: anthropic \u2014 the doctor does not read th\
591
- e file.`]},{id:"droid",nombre:"Droid (Factory)",binario:"droid",configs:[join(".factory","settings.json")],detectable:true,receta:({base:t,rutas:e})=>[`mechanism: ${e[0]} \u2192 customModels[] with provider "a\
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\
629
+ 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\
634
+ 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\
592
646
  nthropic". NO /v1 [inferred: validate by hand against the gateway log].`,"{",' "customModels": ['," {",' "model": "<Anthropic model id>",',' "displayName": "<display name>",',' "pro\
593
- vider": "anthropic",',` "baseUrl": "${t}",`,' "apiKey": "<your Anthropic API key>"'," }"," ]","}"]},{id:"cline",nombre:"Cline",configs:[],detectable:false,receta:({baseV1:t})=>['mechanism: \
594
- 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: ${t}`]},{id:"kilo",nombre:"\
595
- Kilo Code",configs:[],detectable:false,receta:({baseV1:t})=>['mechanism: UI \u2192 custom provider, Provider API "Anthropic Messages". Try WITH /v1 first (Cline lineage) [inferred: validate by hand].',`B\
596
- ase URL: ${t}`]},{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:"\
597
- 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:t,puerto:e})=>[`start: bvsala gateway -\
598
- -upstream openai --port ${e} (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="${t}") (WITH /v1:\
599
- the SDK appends /chat/completions)`,`node: const client = new OpenAI({ baseURL: "${t}" })`,'streaming: pass stream_options={"include_usage": True} (Node: stream_options: { include_usage: true }) or\
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\
600
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\
601
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\
602
- c",nombre:"Python, or any Anthropic SDK (Messages)",configs:[],detectable:false,estadoSinDeteccion:"no detection: any language, through the SDK's base URL",receta:({base:t,puerto:e})=>[`start: bvsala gat\
603
- eway --port ${e} (Anthropic is the default upstream)`,`python: client = Anthropic(base_url="${t}") (NO /v1: the SDK appends /v1/messages)`,`node: const client = new Anthropic({ baseURL: "${t}" }\
604
- )`,"streamed and stream=False requests are both metered."]}];function Il(t,e){let n=t.split(delimiter).filter(o=>o.length>0),r=process.platform==="win32"?["",".exe",".cmd",".bat"]:[""];return o=>n.some(s=>r.
605
- some(i=>e(join(s,o+i))))}async function Ai(t,e={}){if(!Number.isInteger(t)||t<1||t>65535)throw new RangeError(`[bvsala doctor] invalid port: ${String(t)}`);let n=e.home??homedir(),r=e.existe??existsSync,o=e.enPath??
606
- Il(e.path??process.env.PATH??"",r),s=`http://127.0.0.1:${t}`,i=`${s}/v1`,c=[],l=[`bvsala doctor \u2014 local gateway at ${s}`,"Print only: it writes no configuration. Detection by existence (binaries \
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 \
607
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\
608
- at key and does not start without one.",""];for(let a of Al){let d=a.configs.map(y=>join(n,y)),u=a.binario!==void 0&&o(a.binario),p=d.filter(y=>r(y)),f=u||p.length>0;f&&c.push(a.id);let g;a.detectable?f?
609
- g=`detected \u2014 ${[...u?[`binary \`${a.binario}\` on PATH`]:[],...p.map(m=>`config present: ${m}`)].join("; ")}`:g="not detected":g=a.estadoSinDeteccion??"no automatic detection (editor extension)",
610
- l.push(`\xBB ${a.id}: ${g}`),l.push(` ${a.nombre}`);for(let y of a.receta({base:s,baseV1:i,puerto:t,rutas:d}))l.push(` ${y}`);l.push(` ${a.comprobar??Rl}`),l.push("");}return l.push("BYOK rule: the \
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 \
611
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\
612
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\
613
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\
614
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\
615
- : docs/terminales/<terminal>.md"),{texto:l.join(`
616
- `),detectados:c}}var Ii="savings-mode";function Ci(t,e){for(let n of t){let r=join(n,"skills",Ii,"SKILL.md");if(e.existe(r))return r}return null}var Oi="<!-- bvsala:savings-mode:inicio -->",
617
- Bn="<!-- bvsala:savings-mode:fin -->";function Cl(t){let e=t.replace(/^---\n[\s\S]*?\n---\n*/,"").trim();return `${Oi}
618
- ${e}
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}
672
+ ${t}
619
673
 
620
674
  _Always on (AGENTS.md has no activation step). Delete this block to turn it off; \`bvsala skill --codex --force\` restores it._
621
- ${Bn}`}function Di(t){let e=Ci(t.origenes,t.fs);if(!e)return {ok:false,destino:"",mensaje:`[bvsala skill] cannot find the bundled SKILL.md (roots tried: ${t.origenes.join(", ")})`};let n=Cl(t.fs.leer(e)),
622
- r=t.proyecto?t.cwd:join(t.home,".codex"),o=join(r,"AGENTS.md");if(!t.fs.existe(o))return t.fs.crearDir(r),t.fs.escribir(o,n+`
623
- `),{ok:true,destino:o,mensaje:Gr(o,"installed")};let s=t.fs.leer(o),i=s.indexOf(Oi),c=s.indexOf(Bn);return i===-1||c===-1||c<i?(t.fs.escribir(o,s.trimEnd()+`
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)),
676
+ 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()+`
624
678
 
625
679
  `+n+`
626
- `),{ok:true,destino:o,mensaje:Gr(o,"appended to the existing AGENTS.md")}):s.slice(i,c+Bn.length)===n?{ok:true,destino:o,mensaje:`[bvsala skill] already installed and up to date: ${o}`}:t.forzar?(t.fs.escribir(
627
- o,s.slice(0,i)+n+s.slice(c+Bn.length)),{ok:true,destino:o,mensaje:Gr(o,"block updated")}):{ok:false,destino:o,mensaje:`[bvsala skill] the savings-mode block in ${o} has DIFFERENT content \u2014 not overwriting \
628
- it; use --force to update it`}}function Gr(t,e){return `[bvsala skill] ${e}: ${t}
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}
629
683
  [bvsala skill] AGENTS.md is ALWAYS active in Codex (there is no activation step); delete the block to turn it off.
630
- [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 Pi(t){let e=Ci(t.origenes,t.fs);if(!e)return {ok:false,destino:"",
631
- mensaje:`[bvsala skill] cannot find the bundled SKILL.md (roots tried: ${t.origenes.join(", ")})`};let n=t.proyecto?join(t.cwd,".claude","skills"):join(t.home,".claude","skills"),r=join(n,Ii),o=join(r,"SKILL.\
632
- md"),s=t.fs.leer(e);if(t.fs.existe(o)&&!t.forzar){let i=t.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\
633
- h DIFFERENT content \u2014 not overwriting it; use --force to overwrite`}}return t.fs.crearDir(r),t.fs.escribir(o,s),{ok:true,destino:o,mensaje:`[bvsala skill] installed: ${o}
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}
634
688
  [bvsala skill] start (or restart) Claude Code and ask for "savings mode" \u2014 or let it activate on its own when you mention limits.
635
- [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 Wr=class{id;exact=false;constructor(e="heuristic"){this.id=e;}count(e){if(e.length===0)return 0;let n=e.match(/[A-Za-z]+|\d+|\s+|[^\sA-Za-z\d]/g)??[],r=0;for(let o of n){let s=o[0];if(/\s/.test(s)){let i=(o.
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.
636
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,
637
- Math.ceil(e.length/4))}},Jr=new Wr;var Yr=class{estimators=new Map;modelToTokenizer=new Map;fallbackId;constructor(e=Jr){this.fallbackId=e.id,this.estimators.set(e.id,e);}register(e){return this.estimators.set(e.id,e),this}mapModel(e,n){
638
- return this.modelToTokenizer.set(e,n),this}resolve(e){let n=e.tokenizer?this.estimators.get(e.tokenizer):void 0;if(n)return n;if(e.model){let r=this.modelToTokenizer.get(e.model);if(r){let o=this.estimators.
639
- get(r);if(o)return o}}return this.estimators.get(this.fallbackId)}count(e,n){return this.resolve(n).count(e)}};new Yr;var Mi={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",
640
- "text-embedding-3-large"]};var ql={"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}};
641
- tr(ql);new Set(Object.values(Mi).flatMap(t=>t.flatMap(e=>[e,`openai/${e}`])));function Xl(t,e=300){return new Promise(n=>{let r=connect({port:t,host:"127.0.0.1"}),o=s=>{r.destroy(),n(s);};r.setTimeout(e,()=>o(false)),r.once("connect",()=>o(true)),r.once("error",()=>o(false));})}var zn=Si(process.
642
- argv.slice(2));function Ql(){console.log(`bvsala ${Le} \u2014 BiVelio Savings Layer
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){
692
+ 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
643
697
 
644
698
  Commands:
645
699
  gateway [--port N] [--upstream U]
@@ -731,42 +785,45 @@ BiVelio license. It never interrupts a request in flight: if the license lapses,
731
785
  are refused (HTTP 402) until it is renewed. Metering is best-effort: with ingestion down, it
732
786
  forwards and warns. On a Claude or ChatGPT subscription there is no per-token invoice: that
733
787
  traffic is metered at list-price equivalent and never carries commission.
734
- Your prompts never leave your machine \u2014 only counts and cost. More: savings.bivelio.com`);}zn.tipo==="ayuda"&&(Ql(),process.exit(zn.salida));zn.tipo==="version"&&(console.log(Le),process.exit(0));
735
- var{comando:Q,resto:re}=zn,Wt=Ht(Q);if(Q==="skill"){let t=dirname(fileURLToPath(import.meta.url)),e={origenes:[join(t,"..",".."),join(t,"..")],home:homedir(),cwd:process.cwd(),proyecto:re.includes("--project")||re.includes("-\
736
- -proyecto"),forzar:re.includes("--force")||re.includes("--forzar"),fs:{existe:existsSync,leer:r=>readFileSync(r,"utf8"),escribir:(r,o)=>writeFileSync(r,o),crearDir:r=>mkdirSync(r,{recursive:true})}},n=re.includes("--codex")?Di(e):Pi(e);console.
737
- log(n.mensaje),process.exit(n.ok?0:1);}var no=re.indexOf("--port")>=0?re.indexOf("--port"):re.indexOf("--puerto"),Qe=Wt?0:no>=0?Number(re[no+1]):8402;(!Number.isInteger(Qe)||(Q==="doctor"?Qe<1:Qe<0)||Qe>
738
- 65535)&&(console.error(`[bvsala ${Q}] invalid port: ${re[no+1]}`),process.exit(1));if(Q==="doctor"){re.includes("--write")&&(console.error("[bvsala doctor] --write does not exist yet: the doctor only \
739
- prints; copy the block by hand."),process.exit(1));let t=await Ai(Qe);console.log(t.texto),process.exit(0);}function eu(t,e){Ht(t)||process.exit(1);let n=$n(t,0,[],{}).bin;if(process.platform==="win32"){
740
- let o=Kr(n);o.tipo==="exe"?n=o.ruta:o.tipo==="solo-shim"&&(console.error(`[bvsala ${t}] \`${n}\` is installed as an npm shim (${o.ruta}) and Windows cannot launch it safely with arguments (CVE-2024-27\
741
- 980). Install it with 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,e,{stdio:"inherit"});return r.on("error",
742
- o=>{console.error(`[bvsala ${t}] could not launch \`${n}\`: ${String(o)}. Is it installed and on the PATH?`),process.exit(127);}),r.on("exit",(o,s)=>process.exit(o??(s?1:0))),new Promise(()=>{})}Wt&&Ei(
743
- re)&&await eu(Q,re);var tu=Q==="gateway"?mi(re):void 0,le=hi({flag:tu,env:process.env.BVSALA_GATEWAY_UPSTREAM});le.ok||(console.error(le.error),process.exit(1));var qi=process.env.BIVELIO_SERVICE_KEY?.
744
- trim()||void 0,et=await si({serviceAccountKey:qi,licenseKey:process.env.BIVELIO_LICENSE_KEY,licenseServerUrl:jr});et.ok||(console.error(`[bvsala ${Q}] ${et.message}`),process.exit(1));var we=Wt?
745
- $n(Q,0,re,{modoCodex:Q==="codex"?ki({leerAuth:()=>readFileSync(join(homedir(),".codex","auth.json"),"utf8")}):void 0}):null,nu=Wt&&process.env.BVSALA_GATEWAY_LOG!=="1",to=we?.upstream?null:Ti(()=>readFileSync(process.env.BVSALA_ANILLO2_FICHERO??
746
- join(homedir(),".bvsala","anillo2.json"),"utf8")),Gt=Ri({enrolamiento:to,espiaVivo:to!==null&&await Xl(to.espia),upstreamEnv:le.upstream,...le.origen!=="none"?{upstreamOrigen:le.origen}:{},elisionEnv:process.
747
- env.BVSALA_GATEWAY_ELISION,hoyUtcIso:new Date().toISOString().slice(0,10)}),ro=le.upstream??Gt.upstream,Vn=process.env.BVSALA_GATEWAY_ELISION??Gt.elision,xe;try{xe=await vi({puerto:Qe,...nu?{log:()=>{},
748
- avisosDeNoMedido:!1}:{},license:{token:et.license.token,publicKey:Je,licenseServerUrl:jr,checkOnStart:et.source==="offline"},warn:t=>console.error(t),serviceAccountKey:qi,...process.env.BVSALA_SEAT_ID?
749
- {seatId:process.env.BVSALA_SEAT_ID}:{},...ro?{upstream:ro}:we?.upstream?{upstream:we.upstream}:{},...process.env.BVSALA_GATEWAY_COALESCE==="1"?{coalescer:!0}:{},...process.env.BVSALA_GATEWAY_USAGE_INJECT===
750
- "1"?{usageInject:!0}:{},...process.env.BVSALA_GATEWAY_SHADOW==="1"?{sombra:!0}:{},elision:Vn!=="0",...process.env.BVSALA_GATEWAY_DIALES_ELISION==="1"?{dialesElision:!0}:{},...process.env.BVSALA_GATEWAY_MODELO_HERMANO===
751
- "1"?{modeloHermano:!0}:{},...process.env.BVSALA_GATEWAY_ESFUERZO?{esfuerzo:process.env.BVSALA_GATEWAY_ESFUERZO}:{},...process.env.BVSALA_METERING_URL?{meteringUrl:process.env.BVSALA_METERING_URL}:{}});}catch(t){
752
- console.error(`[bvsala ${Q}] ${_i(t,Q,Qe)}`),process.exit(1);}var Hi=ro??we?.upstream??"https://api.anthropic.com";console.log(`[bvsala gateway] v${Le} listening on http://127.0.0.1:${xe.puerto} \u2192 ${Hi}`);
753
- (et.lineIsWarning?console.error:console.log)(`[bvsala gateway] ${et.line}`);for(let t of et.warnings)console.error(`[bvsala gateway] ${t}`);console.log("[bvsala gateway] metering: ON (service key pres\
754
- ent)");process.env.BVSALA_METERING_URL&&console.error(`[bvsala gateway] WARNING: BVSALA_METERING_URL=${process.env.BVSALA_METERING_URL} redirects usage reporting away from savings.bivelio.com (develop\
755
- ment only): your dashboard will not see this usage. The license and the entitlements channel still use savings.bivelio.com.`);le.aviso&&console.error(le.aviso);process.env.BVSALA_GATEWAY_USAGE_INJECT===
756
- "1"&&console.log("[bvsala gateway] usage injection: ON (BVSALA_GATEWAY_USAGE_INJECT=1) \u2014 streamed chat completions without stream_options get include_usage; their last chunk has an empty choices list.");
757
- {let t=ho(Vn,true,process.env.BVSALA_GATEWAY_DIALES_ELISION==="1");(t.aviso?console.error:console.log)(`[bvsala gateway] ${t.linea}`);let e=Ao(process.env.BVSALA_GATEWAY_MODELO_HERMANO,true,Vn!=="0");(e.aviso?
758
- console.error:console.log)(`[bvsala gateway] ${e.linea}`);let n=Eo(process.env.BVSALA_GATEWAY_ESFUERZO,true,Vn!=="0");(n.aviso?console.error:console.log)(`[bvsala gateway] ${n.linea}`),Gt.linea&&(Gt.aviso?
759
- console.error:console.log)(`[bvsala gateway] ${Gt.linea}`);}le.upstream&&we?.upstream&&le.upstream!==we.upstream&&console.error(`[bvsala ${Q}] WARNING: BVSALA_GATEWAY_UPSTREAM=${le.upstream} overrides \
760
- this terminal's upstream (${we.upstream}). If that is not what you want, unset the variable.`);Q==="codex"&&!js()&&console.error(`[bvsala codex] WARNING: this Node (${process.version}) cannot decompre\
761
- ss zstd and Codex sends its body in zstd: traffic passes through but is NOT metered. Use Node >= 22.15.`);if(we&&Wt){let t=$n(Q,xe.puerto,re,{...we.upstream?{modoCodex:we.upstream.includes("chatgpt.co\
762
- m")?"chatgpt":"api-key"}:{}});t.nota&&console.log(`[bvsala ${Q}] ${t.nota}`);let e=t.bin;if(process.platform==="win32"){let r=Kr(t.bin);r.tipo==="exe"?e=r.ruta:r.tipo==="solo-shim"&&(console.error(`[b\
763
- vsala ${Q}] \`${t.bin}\` is installed as an npm shim (${r.ruta}) and Windows cannot launch it safely with arguments (CVE-2024-27980). Install it with its native installer (which leaves a ${t.bin}.exe \
764
- on the PATH) or use the manual recipe in docs/terminales/.`),await xe.cerrar(),process.exit(127));}let n=spawn(e,t.args,{stdio:"inherit",env:{...process.env,...t.env}});n.on("error",r=>{console.error(`[bv\
765
- sala ${Q}] could not launch \`${t.bin}\`: ${String(r)}. Is it installed and on the PATH?`),xe.cerrar().then(()=>process.exit(127));}),n.on("exit",(r,o)=>{xe.cerrar().then(()=>process.exit(r??(o?1:0)));});}else {
766
- let t=new URL(Hi).hostname;t==="api.openai.com"?console.log(`[bvsala gateway] point your SDK at it: base_url=http://127.0.0.1:${xe.puerto}/v1 (OpenAI SDKs) \xB7 streamed chat completions are metered when\
767
- the request sets stream_options.include_usage \xB7 bvsala doctor for recipes`):t==="api.anthropic.com"||le.upstream===void 0?console.log(`[bvsala gateway] point your terminal at it (or use \`bvsala ${Hr.
768
- join("|")}\`): ANTHROPIC_BASE_URL=http://127.0.0.1:${xe.puerto} claude \xB7 bvsala doctor for the others`):console.log(`[bvsala gateway] point your client at http://127.0.0.1:${xe.puerto} plus th\
769
- e path prefix it already uses (for example /v1) \xB7 bvsala doctor for recipes`);}var Ki=async()=>{await xe.cerrar(),process.exit(0);};process.on("SIGINT",()=>{Ki();});process.on("SIGTERM",()=>{Ki();});
788
+ Your prompts, completions and provider keys never reach BiVelio: what it receives is per-request
789
+ 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();});
770
827
  /*! Bundled license information:
771
828
 
772
829
  @noble/curves/utils.js: