@bivelio/savings-layer 0.5.0 → 0.5.2

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,48 +1,48 @@
1
1
  #!/usr/bin/env node
2
- import {spawn}from'child_process';import {existsSync,writeFileSync,mkdirSync,readFileSync}from'fs';import {homedir}from'os';import {join,dirname,posix,delimiter}from'path';import {fileURLToPath}from'url';import {randomUUID,createHash}from'crypto';import {createServer}from'http';import*as st from'zlib';import {connect}from'net';var Bn="context-management-2025-06-27";function Yr(){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 ku=new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});function wu(e){try{return ku.decode(e)}catch{return null}}function xu(e){return /^(?:0|[1-9]\d{0,9})$/.test(e)&&Number(e)<4294967295}function Su(e){
3
- return e===32||e===10||e===13||e===9}function Eu(e){let t=e.length,n=[],r=0;for(;r<t;){let o=e.charCodeAt(r);if(o===123){n.push(new Set),r++;continue}if(o===91){n.push(null),r++;continue}if(o===125||o===
4
- 93){n.pop(),r++;continue}if(o===34){let i=r,s=false;for(r++;;){if(r>=t)return false;let c=e.charCodeAt(r);if(c===92){s=true,r+=2;continue}if(c===34)break;r++;}r++;let a=r;for(;a<t&&Su(e.charCodeAt(a));)a++;if(a<
5
- t&&e.charCodeAt(a)===58){let c=e.slice(i+1,r-1);if(s)try{c=JSON.parse(e.slice(i,r));}catch{return false}if(xu(c))return false;let l=n.at(-1);if(l){if(l.has(c))return false;l.add(c);}}continue}if(o===45||o>=48&&o<=57){
6
- let i=r;for(r++;r<t;){let a=e.charCodeAt(r);if(a>=48&&a<=57||a===46||a===101||a===69||a===43||a===45)r++;else break}let s=e.slice(i,r);if(String(Number(s))!==s)return false;continue}r++;}return true}function Un(e,t){
7
- if(t!==void 0&&t!==""&&t!=="identity")return null;let n=wu(e);if(n===null)return null;let r;try{r=JSON.parse(n);}catch{return null}return Eu(n)?r:null}function ss(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=Cu(n.context_management),o=Tu(n.context_management);
8
- return n.context_management=Ru(n.context_management),{cuerpo:Buffer.from(JSON.stringify(n),"utf8"),nuestros:r,triggerDelCliente:o}}catch{return null}}function Cu(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===Zr);return os(n)!==os([Yr().edits[0]])}function Tu(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===Zr);if(n.length===0)return null;let r=Number.POSITIVE_INFINITY;
11
- for(let o of n){let i=o.trigger,s=i!==null&&typeof i=="object"&&i.type==="input_tokens"&&typeof i.value=="number"&&Number.isFinite(i.value)&&i.value>0?i.value:1e5;s<r&&(r=s);}return r}function os(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 Zr="clear_tool_uses_20250919",is="clear_thinking_20251015";function Ru(e){
13
- let t=Yr().edits[0],n=e!==null&&typeof e=="object"&&!Array.isArray(e)?{...e}:{},r=(Array.isArray(n.edits)?n.edits:[]).filter(s=>s!==null&&typeof s=="object"&&!Array.isArray(s)&&s.type!==Zr),o=r.filter(
14
- s=>s.type===is),i=r.filter(s=>s.type!==is);return {...n,edits:[...o,...i,t]}}function as(e,t,n=false){let r=" (TTL tuning ON if your licence includes cache_ttl_tuning; fail-closed)",o=n?" \xB7 context elisio\
2
+ import {spawn}from'child_process';import {existsSync,writeFileSync,mkdirSync,readFileSync}from'fs';import {homedir}from'os';import {join,dirname,posix,delimiter}from'path';import {fileURLToPath}from'url';import {randomUUID,createHash}from'crypto';import {createServer}from'http';import*as ct from'zlib';import {connect}from'net';var Vn="context-management-2025-06-27";function to(){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 Iu=new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});function Pu(e){try{return Iu.decode(e)}catch{return null}}function Du(e){return /^(?:0|[1-9]\d{0,9})$/.test(e)&&Number(e)<4294967295}function Ou(e){
3
+ return e===32||e===10||e===13||e===9}function Lu(e){let t=e.length,n=[],r=0;for(;r<t;){let o=e.charCodeAt(r);if(o===123){n.push(new Set),r++;continue}if(o===91){n.push(null),r++;continue}if(o===125||o===
4
+ 93){n.pop(),r++;continue}if(o===34){let i=r,s=false;for(r++;;){if(r>=t)return false;let c=e.charCodeAt(r);if(c===92){s=true,r+=2;continue}if(c===34)break;r++;}r++;let a=r;for(;a<t&&Ou(e.charCodeAt(a));)a++;if(a<
5
+ t&&e.charCodeAt(a)===58){let c=e.slice(i+1,r-1);if(s)try{c=JSON.parse(e.slice(i,r));}catch{return false}if(Du(c))return false;let l=n.at(-1);if(l){if(l.has(c))return false;l.add(c);}}continue}if(o===45||o>=48&&o<=57){
6
+ let i=r;for(r++;r<t;){let a=e.charCodeAt(r);if(a>=48&&a<=57||a===46||a===101||a===69||a===43||a===45)r++;else break}let s=e.slice(i,r);if(String(Number(s))!==s)return false;continue}r++;}return true}function qn(e,t){
7
+ if(t!==void 0&&t!==""&&t!=="identity")return null;let n=Pu(e);if(n===null)return null;let r;try{r=JSON.parse(n);}catch{return null}return Lu(n)?r:null}function fs(e,t){try{let n=qn(e,t);if(n===null||typeof n!="object"||Array.isArray(n)||typeof n.model!="string"||!Array.isArray(n.messages))return null;let r=Mu(n.context_management),o=Nu(n.context_management);
8
+ return n.context_management=ju(n.context_management),{cuerpo:Buffer.from(JSON.stringify(n),"utf8"),nuestros:r,triggerDelCliente:o}}catch{return null}}function Mu(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===no);return ds(n)!==ds([to().edits[0]])}function Nu(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===no);if(n.length===0)return null;let r=Number.POSITIVE_INFINITY;
11
+ for(let o of n){let i=o.trigger,s=i!==null&&typeof i=="object"&&i.type==="input_tokens"&&typeof i.value=="number"&&Number.isFinite(i.value)&&i.value>0?i.value:1e5;s<r&&(r=s);}return r}function ds(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 no="clear_tool_uses_20250919",ps="clear_thinking_20251015";function ju(e){
13
+ let t=to().edits[0],n=e!==null&&typeof e=="object"&&!Array.isArray(e)?{...e}:{},r=(Array.isArray(n.edits)?n.edits:[]).filter(s=>s!==null&&typeof s=="object"&&!Array.isArray(s)&&s.type!==no),o=r.filter(
14
+ s=>s.type===ps),i=r.filter(s=>s.type!==ps);return {...n,edits:[...o,...i,t]}}function ms(e,t,n=false){let r=" (TTL tuning ON if your licence includes cache_ttl_tuning; fail-closed)",o=n?" \xB7 context elisio\
15
15
  n dials FORCED ON BY HAND (BVSALA_GATEWAY_DIALES_ELISION=1): they measure as a net loss, R=4.05 vs R*=0.0127":" \xB7 context elision dials OFF";return e==="0"?{linea:"savings levers: OFF (BVSALA_GATEW\
16
16
  AY_ELISION=0) - no TTL tuning and no context elision dials; the licence channel stays open for the license status",aviso:false}:{linea:(e==="1"?"licence channel: OPEN (BVSALA_GATEWAY_ELISION=1)":"licen\
17
- ce channel: OPEN by default (=0 turns the levers off)")+r+o,aviso:n}}function cs(e){return e===void 0||e.trim()===""?Bn:e.split(",").map(n=>n.trim()).filter(
18
- n=>n.length>0).includes(Bn)?e:`${e},${Bn}`}function ls(e){let t=e.toLowerCase(),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Au(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 ve(e){let t=ls(e);return t.startsWith("gpt-")||t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4")?Au(t)?1.25:1:t.startsWith("gemini")?1:1.25}function jt(e){let t=e.toLowerCase();return t.startsWith("claude")||t.startsWith("anthropic/")||ls(t).startsWith("claude")?2:ve(e)}var Pu=1.25,Du=2,Ou=.3,Lu=/^(custom|bash_|text_editor_|computer_|browser_|memory_)/;function to(e){return Array.isArray(e.mcp_servers)&&e.mcp_servers.length>0?true:Array.isArray(e.tools)?e.tools.some(t=>{
20
- let n=t!==null&&typeof t=="object"?t.type:void 0;return typeof n=="string"&&!Lu.test(n)}):false}var $u=4096,Mu=(e,t)=>e==="cache_control"?void 0:t;function Xr(e){return e===void 0?"":JSON.stringify(e,Mu)??
21
- ""}function Nu(e){return Array.isArray(e)?e.filter(t=>!(t!==null&&typeof t=="object"&&t.defer_loading===true)):e}function Qr(e){return createHash("sha1").update(e).digest("base64url").slice(0,16)}function ct(e,t){
22
- let n=Un(e,t);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}function no(e){let t=Xr(e.system),n=Xr(Nu(e.tools)),
23
- r=Array.isArray(e.messages)?e.messages.slice(0,$u):[],o=[],i=[];for(let s of r){let a=Xr(s);o.push(Qr(a)),i.push(Buffer.byteLength(a,"utf8"));}return {system:Qr(t),tools:Qr(n),mensajes:o,bytes:i,bytesFijos:Buffer.
24
- byteLength(t,"utf8")+Buffer.byteLength(n,"utf8")}}function ro(e,t){if(e===void 0||e.system!==t.system||e.tools!==t.tools)return 1;let n=t.bytesFijos;for(let i of t.bytes)n+=i;if(n<=0)return 1;let r=0;
25
- for(;r<e.mensajes.length&&r<t.mensajes.length&&e.mensajes[r]===t.mensajes[r];)r++;let o=0;for(let i=r;i<t.bytes.length;i++)o+=t.bytes[i]??0;return o/n}function oo(e){let{fraccionNueva:t,umbral:n=Ou}=e;
26
- return t>=n}function ju(e,t){e.ttl==="1h"?(e.ttl="5m",t.rebajadas++):(e.ttl==="5m"||e.ttl===void 0)&&t.yaEran5m++;}var sn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),eo=e=>sn(e)&&sn(e.cache_control)?
27
- e.cache_control:null,Bu=8;function Fn(e,t,n,r){if(!(!Array.isArray(e)||r>Bu))for(let o of e){let i=eo(o);if(i&&n(i,t),!sn(o))continue;Array.isArray(o.content)&&Fn(o.content,t,n,r+1);let s=o.source;sn(
28
- s)&&s.type==="content"&&Array.isArray(s.content)&&Fn(s.content,t,n,r+1);}}function io(e,t){let n=eo(e);if(n&&t(n,"raiz"),Fn(e.system,"system",t,0),Array.isArray(e.tools))for(let r of e.tools){let o=eo(
29
- r);o&&t(o,"tools");}if(Array.isArray(e.messages)){let r=e.messages.length-1;e.messages.forEach((o,i)=>{sn(o)&&Fn(o.content,i===r?"ultimoMensaje":"mensaje",t,0);});}}function so(e,t){let n=Buffer.isBuffer(
30
- e)?ct(e,t):e;if(n===null)return null;try{let r={rebajadas:0,yaEran5m:0};return io(n,o=>ju(o,r)),r.rebajadas===0?null:{cuerpo:Buffer.from(JSON.stringify(n),"utf8"),rebajadas:r.rebajadas,yaEran5m:r.yaEran5m,
31
- herramientaDeServidor:to(n)}}catch{return null}}function Uu(e){let{cacheEscrita5m:t,inputPer1k:n,yaEran5m:r,herramientaDeServidor:o}=e;return r>0||o||t<=0||n<=0?0:t/1e3*n*(Du-Pu)}function us(e,t,n){return e.
32
- rebajadas<=0?0:Uu({cacheEscrita5m:t,inputPer1k:n,yaEran5m:e.yaEran5m,herramientaDeServidor:e.herramientaDeServidor})}var zn=class{constructor(t=512,n=3600*1e3){this.maxEntradas=t;this.maxEdadMs=n;}maxEntradas;maxEdadMs;visto=new Map;ultima(t,n){
17
+ ce channel: OPEN by default (=0 turns the levers off)")+r+o,aviso:n}}function hs(e){return e===void 0||e.trim()===""?Vn:e.split(",").map(n=>n.trim()).filter(
18
+ n=>n.length>0).includes(Vn)?e:`${e},${Vn}`}function gs(e){let t=e.toLowerCase(),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Bu(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 xe(e){let t=gs(e);return t.startsWith("gpt-")||t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4")?Bu(t)?1.25:1:t.startsWith("gemini")?1:1.25}function qt(e){let t=e.toLowerCase();return t.startsWith("claude")||t.startsWith("anthropic/")||gs(t).startsWith("claude")?2:xe(e)}var so=1.25,ao=2,Fu=.3,zu=/^(custom|bash_|text_editor_|computer_|browser_|memory_)/;function co(e){return Array.isArray(e.mcp_servers)&&e.mcp_servers.length>0?true:Array.isArray(e.tools)?e.tools.some(t=>{
20
+ let n=t!==null&&typeof t=="object"?t.type:void 0;return typeof n=="string"&&!zu.test(n)}):false}var Vu=4096,qu=(e,t)=>e==="cache_control"?void 0:t;function ro(e){return e===void 0?"":JSON.stringify(e,qu)??
21
+ ""}function Hu(e){return Array.isArray(e)?e.filter(t=>!(t!==null&&typeof t=="object"&&t.defer_loading===true)):e}function oo(e){return createHash("sha1").update(e).digest("base64url").slice(0,16)}function ht(e,t){
22
+ let n=qn(e,t);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}function lo(e){let t=ro(e.system),n=ro(Hu(e.tools)),
23
+ r=Array.isArray(e.messages)?e.messages.slice(0,Vu):[],o=[],i=[];for(let s of r){let a=ro(s);o.push(oo(a)),i.push(Buffer.byteLength(a,"utf8"));}return {system:oo(t),tools:oo(n),mensajes:o,bytes:i,bytesFijos:Buffer.
24
+ byteLength(t,"utf8")+Buffer.byteLength(n,"utf8")}}function uo(e,t){if(e===void 0||e.system!==t.system||e.tools!==t.tools)return 1;let n=t.bytesFijos;for(let i of t.bytes)n+=i;if(n<=0)return 1;let r=0;
25
+ for(;r<e.mensajes.length&&r<t.mensajes.length&&e.mensajes[r]===t.mensajes[r];)r++;let o=0;for(let i=r;i<t.bytes.length;i++)o+=t.bytes[i]??0;return o/n}function po(e){let{fraccionNueva:t,umbral:n=Fu}=e;
26
+ return t>=n}function Gu(e,t){e.ttl==="1h"?(e.ttl="5m",t.rebajadas++):(e.ttl==="5m"||e.ttl===void 0)&&t.yaEran5m++;}var un=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),io=e=>un(e)&&un(e.cache_control)?
27
+ e.cache_control:null,Wu=8;function Hn(e,t,n,r){if(!(!Array.isArray(e)||r>Wu))for(let o of e){let i=io(o);if(i&&n(i,t),!un(o))continue;Array.isArray(o.content)&&Hn(o.content,t,n,r+1);let s=o.source;un(
28
+ s)&&s.type==="content"&&Array.isArray(s.content)&&Hn(s.content,t,n,r+1);}}function fo(e,t){let n=io(e);if(n&&t(n,"raiz"),Hn(e.system,"system",t,0),Array.isArray(e.tools))for(let r of e.tools){let o=io(
29
+ r);o&&t(o,"tools");}if(Array.isArray(e.messages)){let r=e.messages.length-1;e.messages.forEach((o,i)=>{un(o)&&Hn(o.content,i===r?"ultimoMensaje":"mensaje",t,0);});}}function mo(e,t){let n=Buffer.isBuffer(
30
+ e)?ht(e,t):e;if(n===null)return null;try{let r={rebajadas:0,yaEran5m:0};return fo(n,o=>Gu(o,r)),r.rebajadas===0?null:{cuerpo:Buffer.from(JSON.stringify(n),"utf8"),rebajadas:r.rebajadas,yaEran5m:r.yaEran5m,
31
+ herramientaDeServidor:co(n)}}catch{return null}}function Ku(e){let{cacheEscrita5m:t,inputPer1k:n,yaEran5m:r,herramientaDeServidor:o}=e;return r>0||o||t<=0||n<=0?0:t/1e3*n*(ao-so)}function bs(e,t,n){return e.
32
+ rebajadas<=0?0:Ku({cacheEscrita5m:t,inputPer1k:n,yaEran5m:e.yaEran5m,herramientaDeServidor:e.herramientaDeServidor})}var Gn=class{constructor(t=512,n=3600*1e3){this.maxEntradas=t;this.maxEdadMs=n;}maxEntradas;maxEdadMs;visto=new Map;ultima(t,n){
33
33
  let r=this.visto.get(t);if(r!==void 0){if(n-r.vistoMs>this.maxEdadMs){this.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.
34
- size>this.maxEntradas;){let o=this.visto.keys().next();if(o.done===true)break;this.visto.delete(o.value);}}get tamano(){return this.visto.size}};var ao="mid-conversation-output-config-2026-07-01",Hn=["low","medium","high","xhigh","max"],Fu=new Set(["claude-fable-5-1","claude-mythos-5-1","claude-opus-5-5","claude-opus-5"]),ds={"claude-fable-5-1":"\
35
- high","claude-mythos-5-1":"high","claude-opus-5-5":"medium","claude-opus-5":"high"};function zu(e){return fs(e)?ds[e]:void 0}function ps(e,t){let n=zu(e);return n!==void 0&&Hn.indexOf(t)<Hn.indexOf(n)}
36
- var qn=Hn.filter(e=>Object.keys(ds).some(t=>ps(t,e)));function fs(e){return Fu.has(e)}function co(e){return e!==void 0&&Hn.includes(e)}function Vu(e){return {role:"system",content:[],output_config:{effort:e}}}
37
- function qu(e){if(e.output_config!==void 0&&e.output_config!==null)return true;let t=e.messages;return Array.isArray(t)?t.some(n=>typeof n=="object"&&n!==null&&n.output_config!==void 0):false}function ms(e,t,n){
38
- let r=ct(e,n);if(r===null||typeof r.model!="string"||!fs(r.model)||!ps(r.model,t)||qu(r))return null;let o=r.messages;return Array.isArray(o)?(r.messages=[...o,Vu(t)],{cuerpo:Buffer.from(JSON.stringify(
39
- r),"utf8"),nivel:t}):null}function hs(e){return e===void 0||e.trim()===""?ao:e.split(",").map(n=>n.trim()).includes(ao)?e:`${e},${ao}`}function gs(e,t,n){return e===void 0||e===""?{linea:`per-turn eff\
40
- ort: OFF (BVSALA_GATEWAY_EFFORT=${qn.join("|")} turns it on)`,aviso:false}:co(e)?qn.includes(e)?n?{linea:`per-turn effort: ARMED at "${e}" (ON if your licence includes per_turn_effort; fail-closed). On\
34
+ size>this.maxEntradas;){let o=this.visto.keys().next();if(o.done===true)break;this.visto.delete(o.value);}}get tamano(){return this.visto.size}};var ho="mid-conversation-output-config-2026-07-01",Kn=["low","medium","high","xhigh","max"],Ju=new Set(["claude-fable-5-1","claude-mythos-5-1","claude-opus-5-5","claude-opus-5"]),vs={"claude-fable-5-1":"\
35
+ high","claude-mythos-5-1":"high","claude-opus-5-5":"medium","claude-opus-5":"high"};function Yu(e){return ks(e)?vs[e]:void 0}function ys(e,t){let n=Yu(e);return n!==void 0&&Kn.indexOf(t)<Kn.indexOf(n)}
36
+ var Wn=Kn.filter(e=>Object.keys(vs).some(t=>ys(t,e)));function ks(e){return Ju.has(e)}function go(e){return e!==void 0&&Kn.includes(e)}function Zu(e){return {role:"system",content:[],output_config:{effort:e}}}
37
+ function Xu(e){if(e.output_config!==void 0&&e.output_config!==null)return true;let t=e.messages;return Array.isArray(t)?t.some(n=>typeof n=="object"&&n!==null&&n.output_config!==void 0):false}function ws(e,t,n){
38
+ let r=ht(e,n);if(r===null||typeof r.model!="string"||!ks(r.model)||!ys(r.model,t)||Xu(r))return null;let o=r.messages;return Array.isArray(o)?(r.messages=[...o,Zu(t)],{cuerpo:Buffer.from(JSON.stringify(
39
+ r),"utf8"),nivel:t}):null}function xs(e){return e===void 0||e.trim()===""?ho:e.split(",").map(n=>n.trim()).includes(ho)?e:`${e},${ho}`}function Ss(e,t,n){return e===void 0||e===""?{linea:`per-turn eff\
40
+ ort: OFF (BVSALA_GATEWAY_EFFORT=${Wn.join("|")} turns it on)`,aviso:false}:go(e)?Wn.includes(e)?n?{linea:`per-turn effort: ARMED at "${e}" (ON if your licence includes per_turn_effort; fail-closed). On\
41
41
  ly fable-5-1, mythos-5-1, opus-5-5 and opus-5, and only below the model's default effort (high; medium on opus-5-5${e==="medium"?", so opus-5-5 passes through unchanged at this level":""}); every othe\
42
42
  r request passes through unchanged. Does NOT reset the prefix cache: the dial is appended at the end and nothing earlier is rewritten. Not yet verified against the quality gate`,aviso:false}:{linea:"per-\
43
43
  turn effort: NOT ARMED - BVSALA_GATEWAY_ELISION=0 turns off the levers",aviso:true}:{linea:`per-turn effort: NOT ARMED \u2014 "${e}" is not below any supported model's default effort (high; medium on claude-opus-5-5), s\
44
- o it could only leave the bill as it is or raise it. This lever only lowers effort: use ${qn.join(" or ")}`,aviso:true}:{linea:`per-turn effort: NOT ARMED \u2014 "${e}" is not a level. Use one of: ${qn.
45
- join(", ")}`,aviso:true}}var cn={"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},
44
+ o it could only leave the bill as it is or raise it. This lever only lowers effort: use ${Wn.join(" or ")}`,aviso:true}:{linea:`per-turn effort: NOT ARMED \u2014 "${e}" is not a level. Use one of: ${Wn.
45
+ join(", ")}`,aviso:true}}var pn={"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},
46
46
  "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,
47
47
  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},
48
48
  "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},
@@ -64,30 +64,30 @@ cachedInputPer1k:.0015},"gemini-3.8-flash":{inputPer1k:75e-5,outputPer1k:.00375,
64
64
  h":{inputPer1k:75e-5,outputPer1k:.00375,cachedInputPer1k:75e-6},"gemini-3.1-flash-lite":{inputPer1k:25e-5,outputPer1k:.0015,cachedInputPer1k:25e-6},"gemini-3-flash-preview":{inputPer1k:5e-4,outputPer1k:.003,
65
65
  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\
66
66
  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}},
67
- Hu={"gemini-3.8-flash":{vigenteHasta:"2027-01-01"},"gemini-3.7-flash":{vigenteHasta:"2027-01-01"},"gemini-3.6-flash":{vigenteHasta:"2027-01-01"}},Gu={"gemini-3.8-flash":[{vigenteDesde:"2027-01-01",precio:{
67
+ Qu={"gemini-3.8-flash":{vigenteHasta:"2027-01-01"},"gemini-3.7-flash":{vigenteHasta:"2027-01-01"},"gemini-3.6-flash":{vigenteHasta:"2027-01-01"}},ed={"gemini-3.8-flash":[{vigenteDesde:"2027-01-01",precio:{
68
68
  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:"\
69
- 2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}]},Wu=Object.fromEntries(Object.keys(cn).map(e=>[e,[{...Hu[e],precio:cn[e]},...Gu[e]??[]]]));var Ku=864e13;function bs(e){let t=e instanceof Date?e.getTime():e,n=typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<=Ku?t:Date.now();return new Date(n).toISOString().slice(0,10)}function vs(e,t){
70
- for(let n of Wu[e]??[])if(!(n.vigenteDesde!==void 0&&t<n.vigenteDesde)&&!(n.vigenteHasta!==void 0&&t>=n.vigenteHasta))return n.precio}function ys(e,t,n){if(!n)return;let r=e[n];if(r)return r;let o=n.lastIndexOf("/"),i=o>=0?n.slice(o+1):n,s=e[i];if(s)return s;for(let a of t){if(!i.startsWith(a))continue;let c=i.charAt(a.length);if(c!==
71
- ""&&c!=="-"&&c!=="."&&c!=="_")continue;let l=i.slice(a.length+1);if(!(/^\d/.test(l)&&!/^\d{4}/.test(l)))return e[a]}}function uo(e){return Object.keys(e).sort((t,n)=>n.length-t.length)}var Ju=["o3-dee\
72
- 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"],lo={...cn,...Object.
73
- fromEntries(Ju.map(e=>[e,null]))},Yu=uo(lo);function Le(e,t){let n=vt(e);return n===void 0?void 0:vs(n,bs(t))}var Zu=Object.fromEntries(Object.keys(lo).map(e=>[e,lo[e]===null?null:e]));function vt(e){
74
- return ys(Zu,Yu,e)??void 0}var Xu=/^\d{4}-?\d{2}-?\d{2}$/;function Bt(e,t){let n=vt(e);if(n===void 0)return;let r=e.lastIndexOf("/"),o=r>=0?e.slice(r+1):e;if(!(n!==e&&n!==o&&!Xu.test(o.slice(n.length+
75
- 1))))return vs(n,bs(t))}var ks={"claude-fable-5":"claude-fable-5-1"};function Qu(e,t){let n=Le(e),r=Le(t);if(n===void 0||r===void 0||n.inputPer1k!==r.inputPer1k||n.outputPer1k!==r.outputPer1k||ve(e)!==ve(t))return false;let o=n.
76
- cachedInputPer1k??n.inputPer1k;return (r.cachedInputPer1k??r.inputPer1k)<o}function ed(e){let t=vt(e);if(t===void 0||t!==e)return null;let n=ks[t];return n===void 0||n===t||!Qu(t,n)?null:{solicitado:e,
77
- servido:n}}var td=/(^|,)\s*context-1m/i;function nd(e){let t=e.tool_choice;if(t===null||typeof t!="object")return false;let n=t.type;return n==="any"||n==="tool"}function po(e,t,n={}){if(n.betas!==void 0&&
78
- td.test(n.betas))return null;let r=ct(e,t);if(r===null||nd(r))return null;let o=ed(r.model);return o===null?null:(r.model=o.servido,{cuerpo:Buffer.from(JSON.stringify(r),"utf8"),cambio:o})}function ws(e,t,n){
79
- let r=Object.entries(ks).map(([o,i])=>`${o}\u2192${i}`).join(", ");return e!=="1"?{linea:"sibling model routing: OFF (BVSALA_GATEWAY_SIBLING_MODEL=1 turns it on)",aviso:false}:n?{linea:`sibling model r\
69
+ 2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}]},td=Object.fromEntries(Object.keys(pn).map(e=>[e,[{...Qu[e],precio:pn[e]},...ed[e]??[]]]));var nd=864e13;function Es(e){let t=e instanceof Date?e.getTime():e,n=typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<=nd?t:Date.now();return new Date(n).toISOString().slice(0,10)}function _s(e,t){
70
+ for(let n of td[e]??[])if(!(n.vigenteDesde!==void 0&&t<n.vigenteDesde)&&!(n.vigenteHasta!==void 0&&t>=n.vigenteHasta))return n.precio}function Cs(e,t,n){if(!n)return;let r=e[n];if(r)return r;let o=n.lastIndexOf("/"),i=o>=0?n.slice(o+1):n,s=e[i];if(s)return s;for(let a of t){if(!i.startsWith(a))continue;let c=i.charAt(a.length);if(c!==
71
+ ""&&c!=="-"&&c!=="."&&c!=="_")continue;let l=i.slice(a.length+1);if(!(/^\d/.test(l)&&!/^\d{4}/.test(l)))return e[a]}}function vo(e){return Object.keys(e).sort((t,n)=>n.length-t.length)}var rd=["o3-dee\
72
+ 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"],bo={...pn,...Object.
73
+ fromEntries(rd.map(e=>[e,null]))},od=vo(bo);function Ne(e,t){let n=Ct(e);return n===void 0?void 0:_s(n,Es(t))}var id=Object.fromEntries(Object.keys(bo).map(e=>[e,bo[e]===null?null:e]));function Ct(e){
74
+ return Cs(id,od,e)??void 0}var sd=/^\d{4}-?\d{2}-?\d{2}$/;function Ht(e,t){let n=Ct(e);if(n===void 0)return;let r=e.lastIndexOf("/"),o=r>=0?e.slice(r+1):e;if(!(n!==e&&n!==o&&!sd.test(o.slice(n.length+
75
+ 1))))return _s(n,Es(t))}var Ts={"claude-fable-5":"claude-fable-5-1"};function ad(e,t){let n=Ne(e),r=Ne(t);if(n===void 0||r===void 0||n.inputPer1k!==r.inputPer1k||n.outputPer1k!==r.outputPer1k||xe(e)!==xe(t))return false;let o=n.
76
+ cachedInputPer1k??n.inputPer1k;return (r.cachedInputPer1k??r.inputPer1k)<o}function cd(e){let t=Ct(e);if(t===void 0||t!==e)return null;let n=Ts[t];return n===void 0||n===t||!ad(t,n)?null:{solicitado:e,
77
+ servido:n}}var ld=/(^|,)\s*context-1m/i;function ud(e){let t=e.tool_choice;if(t===null||typeof t!="object")return false;let n=t.type;return n==="any"||n==="tool"}function yo(e,t,n={}){if(n.betas!==void 0&&
78
+ ld.test(n.betas))return null;let r=ht(e,t);if(r===null||ud(r))return null;let o=cd(r.model);return o===null?null:(r.model=o.servido,{cuerpo:Buffer.from(JSON.stringify(r),"utf8"),cambio:o})}function Rs(e,t,n){
79
+ let r=Object.entries(Ts).map(([o,i])=>`${o}\u2192${i}`).join(", ");return e!=="1"?{linea:"sibling model routing: OFF (BVSALA_GATEWAY_SIBLING_MODEL=1 turns it on)",aviso:false}:n?{linea:`sibling model r\
80
80
  outing: 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 mid\
81
81
  -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_E\
82
- LISION=0 turns off the levers",aviso:true}}var xs=new Set;function ee(e,t){xs.has(e)||(xs.add(e),console.warn(t));}var ye="0.5.0",fo="x-bvsala-version";var Ut=class{options;now;flushIntervalMs;maxBatch;maxBuffer;buffer=[];seatId;ci;timer;inflight=null;fallosSeguidos=0;constructor(t){this.options=t,this.now=t.now??(()=>Date.now()),this.flushIntervalMs=
82
+ LISION=0 turns off the levers",aviso:true}}var As=new Set;function Q(e,t){As.has(e)||(As.add(e),console.warn(t));}var Se="0.5.2",ko="x-bvsala-version";var Gt=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=
83
83
  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){let n=this.now();this.buffer.push({report:t,at:n});
84
- let r=rd(t);r&&this.buffer.push({report:r,at:n}),this.buffer.length>this.maxBuffer&&this.buffer.splice(0,this.buffer.length-this.maxBuffer),this.buffer.length>=this.maxBatch&&this.flush();}start(){this.
84
+ let r=dd(t);r&&this.buffer.push({report:r,at:n}),this.buffer.length>this.maxBuffer&&this.buffer.splice(0,this.buffer.length-this.maxBuffer),this.buffer.length>=this.maxBatch&&this.flush();}start(){this.
85
85
  timer||(this.timer=setInterval(()=>{this.flush();},this.flushIntervalMs),this.timer.unref?.());}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0),this.flush();}async stopAndDrain(t){this.timer&&
86
86
  (clearInterval(this.timer),this.timer=void 0);let n=t??Math.ceil(this.maxBuffer/this.maxBatch)+4,r=0;for(let o=0;o<n&&this.buffer.length>0;o++){let i=this.buffer.length;if(await this.flush(),r=this.buffer.
87
87
  length>=i?r+1:0,r>=2)break}}async flush(){if(this.inflight)return this.inflight;if(this.buffer.length!==0){this.inflight=this.hacerFlush();try{await this.inflight;}finally{this.inflight=null;}}}async hacerFlush(){
88
88
  let t=this.options.fetchImpl??globalThis.fetch;if(!t)return;let n=this.buffer.splice(0,this.maxBatch);try{let r=n.map(i=>this.toWire(i)),o=await t(this.options.url,{method:"POST",headers:{"content-typ\
89
- e":"application/json",authorization:`Bearer ${this.options.serviceAccountKey}`,[fo]:`${this.options.surface??"sdk"}/${ye}`},body:JSON.stringify(r)});o.ok?this.fallosSeguidos=0:o.status>=500?(this.fallosSeguidos++,
90
- this.requeue(n),this.avisarDeFallo(`the server responded ${o.status}`)):o.status===401||o.status===403?(ee(`metering-auth-${o.status}`,`[bv-sala] usage reporting is being rejected with HTTP ${o.status}\
89
+ e":"application/json",authorization:`Bearer ${this.options.serviceAccountKey}`,[ko]:`${this.options.surface??"sdk"}/${Se}`},body:JSON.stringify(r)});o.ok?this.fallosSeguidos=0:o.status>=500?(this.fallosSeguidos++,
90
+ this.requeue(n),this.avisarDeFallo(`the server responded ${o.status}`)):o.status===401||o.status===403?(Q(`metering-auth-${o.status}`,`[bv-sala] usage reporting is being rejected with HTTP ${o.status}\
91
91
  at ${this.options.url}. Check 'serviceAccountKey' (rotated? revoked? from another organization?). Until it works, no usage is reported: the dashboard will say it sees no traffic and billable seats wi\
92
92
  ll show zero.`),this.options.onAuthError?.(o.status)):(this.fallosSeguidos++,this.avisarDeFallo(o.status===404||o.status===405?`HTTP ${o.status}: the reporting URL looks wrong`:`the server rejected th\
93
93
  e batch with HTTP ${o.status}`));}catch(r){this.fallosSeguidos++,this.requeue(n),this.avisarDeFallo(r instanceof Error?r.message:"network error");}}avisarDeFallo(t){if(this.options.silenceWarnings)return;
@@ -97,40 +97,40 @@ buffer],this.buffer.length>this.maxBuffer&&(this.buffer.length=this.maxBuffer);}
97
97
  {},requestId:n.requestId,model:n.model,at:t.at,avoidedLlm:n.calls.avoidedLlm,actualLlm:n.calls.actualLlm,baselineInputTokens:n.tokens.baselineInput,actualInputTokens:n.tokens.actualInput,eliminatedInputTokens:n.
98
98
  tokens.eliminatedInput,compressedInputTokens:n.tokens.compressedInput,baselineOutputTokens:n.tokens.baselineOutput,actualOutputTokens:n.tokens.actualOutput,providerCachedInputTokens:n.tokens.providerCachedInput??
99
99
  0,cacheResult:n.cache.result,...n.cost.eliminatedInputFloorCost!==void 0&&Number.isFinite(n.cost.eliminatedInputFloorCost)&&n.cost.eliminatedInputFloorCost>0&&n.tokens.eliminatedInput>0?{eliminatedInputFloorCost:n.
100
- cost.eliminatedInputFloorCost}:{},...od(n),baselineCost:n.cost.baselineEstimate,actualCost:n.cost.actual,netSavings:n.cost.netSavingsRatio,...n.cost.basis?{basis:n.cost.basis}:{},...n.cost.basis==="re\
100
+ cost.eliminatedInputFloorCost}:{},...pd(n),baselineCost:n.cost.baselineEstimate,actualCost:n.cost.actual,netSavings:n.cost.netSavingsRatio,...n.cost.basis?{basis:n.cost.basis}:{},...n.cost.basis==="re\
101
101
  ference"&&n.cache.reference&&/^[A-Za-z0-9._:/-]{1,128}$/.test(n.cache.reference.requestId)&&Number.isInteger(n.cache.reference.at)?{referenceRequestId:n.cache.reference.requestId,referenceAt:n.cache.reference.
102
- at}:{},...n.attribution?.sessionId?{sessionId:n.attribution.sessionId}:{},...n.attribution?.agentId?{agentId:n.attribution.agentId}:{}}}};function rd(e){let t=e.measure;if(!t)return null;let n=t.wouldHaveSaved.
102
+ at}:{},...n.attribution?.sessionId?{sessionId:n.attribution.sessionId}:{},...n.attribution?.agentId?{agentId:n.attribution.agentId}:{}}}};function dd(e){let t=e.measure;if(!t)return null;let n=t.wouldHaveSaved.
103
103
  usd;if(!(Number.isFinite(n)&&n>0))return null;let r=`${e.requestId}:shadow`;if(!/^[A-Za-z0-9._:/-]{1,128}$/.test(r))return null;let o=Math.max(0,e.cost.actual),i=Math.max(0,o-n),s=o>0?Math.min(1,(o-i)/
104
- o):0,{measure:a,nativeSavings:c,...l}=e;return {...l,requestId:r,cache:{...e.cache,result:"miss"},cost:{baselineEstimate:o,actual:i,netSavingsRatio:s,netSavingsUsd:o-i,basis:"shadow"}}}function od(e){let t=e.
104
+ o):0,{measure:a,nativeSavings:c,...l}=e;return {...l,requestId:r,cache:{...e.cache,result:"miss"},cost:{baselineEstimate:o,actual:i,netSavingsRatio:s,netSavingsUsd:o-i,basis:"shadow"}}}function pd(e){let t=e.
105
105
  nativeSavings;if(!t||t.basis!=="measured")return {};let n=r=>Number.isFinite(r)&&r>=0;return !n(t.readDiscountUsd)||!n(t.writePremiumUsd)?{}:!(t.readDiscountUsd>0)&&!(t.writePremiumUsd>0)?{}:{...t.readDiscountUsd>
106
- 0?{nativeCacheReadSavings:t.readDiscountUsd}:{},...t.writePremiumUsd>0?{nativeCacheWritePremium:t.writePremiumUsd}:{}}}function Gn(){return globalThis.process}function id(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\
107
- ]";return new RegExp(`-${t}{8,10}-${t}{5}$`).test(e)}function sd(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??
108
- e.NETLIFY)}async function ad(){if(Gn()?.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 cd(e,t=ad){
109
- if(e.KUBERNETES_SERVICE_HOST||sd(e))return;let n=e.HOSTNAME??e.COMPUTERNAME??await t();if(!(!n||id(n)))return n}async function ld(){let e=Gn();if(!e||!e.env)return;let t=e.env,n=await cd(t),r=[e.platform,
110
- 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 ud=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTI\
111
- ONS","GITLAB_CI","CIRCLECI","TRAVIS","JENKINS_URL","BUILDKITE","TF_BUILD","TEAMCITY_VERSION","BITBUCKET_BUILD_NUMBER","CODEBUILD_BUILD_ID","HEROKU_TEST_RUN_ID","DRONE"];function Wn(){let e=Gn()?.env;if(!e)
112
- return false;for(let t of ud){let n=e[t];if(n&&n!=="false"&&n!=="0")return true}return false}async function dd(e,t){let n=globalThis.crypto,r=new TextEncoder;if(n?.subtle)try{let s=await n.subtle.importKey("raw",
106
+ 0?{nativeCacheReadSavings:t.readDiscountUsd}:{},...t.writePremiumUsd>0?{nativeCacheWritePremium:t.writePremiumUsd}:{}}}function Jn(){return globalThis.process}function fd(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\
107
+ ]";return new RegExp(`-${t}{8,10}-${t}{5}$`).test(e)}function md(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??
108
+ e.NETLIFY)}async function hd(){if(Jn()?.execPath)try{let t=await import(["node","os"].join(":")),n=typeof t.hostname=="function"?t.hostname():"";return n.length>0?n:void 0}catch{return}}async function gd(e,t=hd){
109
+ if(e.KUBERNETES_SERVICE_HOST||md(e))return;let n=e.HOSTNAME??e.COMPUTERNAME??await t();if(!(!n||fd(n)))return n}async function bd(){let e=Jn();if(!e||!e.env)return;let t=e.env,n=await gd(t),r=[e.platform,
110
+ 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 vd=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTI\
111
+ ONS","GITLAB_CI","CIRCLECI","TRAVIS","JENKINS_URL","BUILDKITE","TF_BUILD","TEAMCITY_VERSION","BITBUCKET_BUILD_NUMBER","CODEBUILD_BUILD_ID","HEROKU_TEST_RUN_ID","DRONE"];function Yn(){let e=Jn()?.env;if(!e)
112
+ return false;for(let t of vd){let n=e[t];if(n&&n!=="false"&&n!=="0")return true}return false}async function yd(e,t){let n=globalThis.crypto,r=new TextEncoder;if(n?.subtle)try{let s=await n.subtle.importKey("raw",
113
113
  r.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await n.subtle.sign("HMAC",s,r.encode(t));return [...new Uint8Array(a)].map(c=>c.toString(16).padStart(2,"0")).join("")}catch{}let o=2166136261,i=`${e}\
114
- |${t}`;for(let s=0;s<i.length;s++)o^=i.charCodeAt(s),o=Math.imul(o,16777619);return (o>>>0).toString(16).padStart(8,"0")}async function Kn(e){let n=Gn()?.env?.BVSALA_SEAT_ID;if(n&&pd.test(n))return n;let r=await ld();
115
- if(!r)return;let o=await dd(e,r);if(o)return `m-${o.slice(0,32)}`}var pd=/^[A-Za-z0-9._:/-]{1,128}$/;function mo(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Jn(e,t=""){if(typeof e!="number"){let n=t&&
116
- `"${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 $e(e,t,n=""){
117
- let r=mo(e),o=e?.length,i=t!==void 0;if(!r||i&&o!==t){let s=n&&`"${n}" `,a=i?` of length ${t}`:"",c=r?`length=${o}`:`type=${typeof e}`,l=s+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):
118
- new TypeError(l)}return e}function ho(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 Es(e,t){$e(e,void 0,"digestInt\
119
- o() output");let n=t.outputLen;if(e.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function ln(...e){for(let t=0;t<e.length;t++)e[t].fill(0);}function Yn(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var _s=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",fd=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Zn(e){if($e(e),_s)return e.toHex();
120
- let t="";for(let n=0;n<e.length;n++)t+=fd[e[n]];return t}var tt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ss(e){if(e>=tt._0&&e<=tt._9)return e-tt._0;if(e>=tt.A&&e<=tt.F)return e-(tt.A-10);if(e>=tt.a&&
121
- e<=tt.f)return e-(tt.a-10)}function un(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);if(_s)try{return Uint8Array.fromHex(e)}catch(o){throw o instanceof SyntaxError?
122
- new RangeError(o.message):o}let t=e.length,n=t/2;if(t%2)throw new RangeError("hex string expected, got unpadded hex of length "+t);let r=new Uint8Array(n);for(let o=0,i=0;o<n;o++,i+=2){let s=Ss(e.charCodeAt(
123
- i)),a=Ss(e.charCodeAt(i+1));if(s===void 0||a===void 0){let c=e[i]+e[i+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}r[o]=s*16+a;}return r}function go(...e){let t=0;for(let r=0;r<e.length;r++){let o=e[r];$e(o),t+=o.length;}let n=new Uint8Array(t);for(let r=0,o=0;r<e.length;r++){let i=e[r];n.set(i,o),o+=i.length;}return n}function Cs(e,t={}){let n=(o,i)=>e(i).update(o).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=o=>e(o),Object.assign(n,t),Object.freeze(n)}function Ts(e=32){
124
- Jn(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(
125
- `"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}var Rs=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});var Xn=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=
126
- new Uint8Array(t),this.view=Yn(this.buffer);}update(t){ho(this),$e(t);let{view:n,buffer:r,blockLen:o}=this,i=t.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=Yn(t);for(;o<=i-s;s+=
127
- o)this.process(c,s);continue}r.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(n,0),this.pos=0);}return this.length+=t.length,this.roundClean(),this}digestInto(t){ho(this),
128
- Es(t,this),this.finished=true;let{buffer:n,view:r,blockLen:o,isLE:i}=this,{pos:s}=this;n[s++]=128,ln(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(r,0),s=0);for(let u=s;u<o;u++)n[u]=0;r.setBigUint64(
129
- o-8,BigInt(this.length*8),i),this.process(r,0);let a=Yn(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,p=this.get();if(l>p.length)throw new Error("_s\
130
- ha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,p[u],i);}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let r=t.slice(0,n);return this.destroy(),r}_cloneInto(t){t||=new this.
131
- constructor,t.set(...this.get());let{blockLen:n,buffer:r,length:o,finished:i,destroyed:s,pos:a}=this;return t.destroyed=s,t.finished=i,t.length=o,t.pos=a,o%n&&t.buffer.set(r),t}clone(){return this._cloneInto()}};var ue=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Qn=BigInt(4294967295),As=BigInt(32);function md(e,t=false){return t?{h:Number(e&Qn),l:Number(e>>As&Qn)}:{h:Number(e>>As&Qn)|0,l:Number(e&Qn)|0}}function Is(e,t=false){let n=e.length,r=new Uint32Array(n),
132
- o=new Uint32Array(n);for(let i=0;i<n;i++){let{h:s,l:a}=md(e[i],t);[r[i],o[i]]=[s,a];}return [r,o]}var bo=(e,t,n)=>e>>>n,vo=(e,t,n)=>e<<32-n|t>>>n,yt=(e,t,n)=>e>>>n|t<<32-n,kt=(e,t,n)=>e<<32-n|t>>>n,dn=(e,t,n)=>e<<64-n|t>>>n-32,pn=(e,t,n)=>e>>>n-32|t<<64-n;function Ve(e,t,n,r){let o=(t>>>0)+(r>>>0);return {h:e+n+(o/2**32|0)|0,l:o|0}}var Ps=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Ds=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Os=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Ls=(e,t,n,r,o)=>t+
133
- n+r+o+(e/2**32|0)|0,$s=(e,t,n,r,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(o>>>0),Ms=(e,t,n,r,o,i)=>t+n+r+o+i+(e/2**32|0)|0;var Ns=Is(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242",
114
+ |${t}`;for(let s=0;s<i.length;s++)o^=i.charCodeAt(s),o=Math.imul(o,16777619);return (o>>>0).toString(16).padStart(8,"0")}async function Zn(e){let n=Jn()?.env?.BVSALA_SEAT_ID;if(n&&kd.test(n))return n;let r=await bd();
115
+ if(!r)return;let o=await yd(e,r);if(o)return `m-${o.slice(0,32)}`}var kd=/^[A-Za-z0-9._:/-]{1,128}$/;function wo(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Xn(e,t=""){if(typeof e!="number"){let n=t&&
116
+ `"${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 je(e,t,n=""){
117
+ let r=wo(e),o=e?.length,i=t!==void 0;if(!r||i&&o!==t){let s=n&&`"${n}" `,a=i?` of length ${t}`:"",c=r?`length=${o}`:`type=${typeof e}`,l=s+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):
118
+ new TypeError(l)}return e}function xo(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 Ps(e,t){je(e,void 0,"digestInt\
119
+ o() output");let n=t.outputLen;if(e.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function fn(...e){for(let t=0;t<e.length;t++)e[t].fill(0);}function Qn(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var Ds=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",wd=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function er(e){if(je(e),Ds)return e.toHex();
120
+ let t="";for(let n=0;n<e.length;n++)t+=wd[e[n]];return t}var rt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Is(e){if(e>=rt._0&&e<=rt._9)return e-rt._0;if(e>=rt.A&&e<=rt.F)return e-(rt.A-10);if(e>=rt.a&&
121
+ e<=rt.f)return e-(rt.a-10)}function mn(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);if(Ds)try{return Uint8Array.fromHex(e)}catch(o){throw o instanceof SyntaxError?
122
+ new RangeError(o.message):o}let t=e.length,n=t/2;if(t%2)throw new RangeError("hex string expected, got unpadded hex of length "+t);let r=new Uint8Array(n);for(let o=0,i=0;o<n;o++,i+=2){let s=Is(e.charCodeAt(
123
+ i)),a=Is(e.charCodeAt(i+1));if(s===void 0||a===void 0){let c=e[i]+e[i+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}r[o]=s*16+a;}return r}function So(...e){let t=0;for(let r=0;r<e.length;r++){let o=e[r];je(o),t+=o.length;}let n=new Uint8Array(t);for(let r=0,o=0;r<e.length;r++){let i=e[r];n.set(i,o),o+=i.length;}return n}function Os(e,t={}){let n=(o,i)=>e(i).update(o).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=o=>e(o),Object.assign(n,t),Object.freeze(n)}function Ls(e=32){
124
+ Xn(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(
125
+ `"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}var $s=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});var tr=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=
126
+ new Uint8Array(t),this.view=Qn(this.buffer);}update(t){xo(this),je(t);let{view:n,buffer:r,blockLen:o}=this,i=t.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=Qn(t);for(;o<=i-s;s+=
127
+ o)this.process(c,s);continue}r.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(n,0),this.pos=0);}return this.length+=t.length,this.roundClean(),this}digestInto(t){xo(this),
128
+ Ps(t,this),this.finished=true;let{buffer:n,view:r,blockLen:o,isLE:i}=this,{pos:s}=this;n[s++]=128,fn(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(r,0),s=0);for(let u=s;u<o;u++)n[u]=0;r.setBigUint64(
129
+ o-8,BigInt(this.length*8),i),this.process(r,0);let a=Qn(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,d=this.get();if(l>d.length)throw new Error("_s\
130
+ ha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],i);}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let r=t.slice(0,n);return this.destroy(),r}_cloneInto(t){t||=new this.
131
+ constructor,t.set(...this.get());let{blockLen:n,buffer:r,length:o,finished:i,destroyed:s,pos:a}=this;return t.destroyed=s,t.finished=i,t.length=o,t.pos=a,o%n&&t.buffer.set(r),t}clone(){return this._cloneInto()}};var pe=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var nr=BigInt(4294967295),Ms=BigInt(32);function xd(e,t=false){return t?{h:Number(e&nr),l:Number(e>>Ms&nr)}:{h:Number(e>>Ms&nr)|0,l:Number(e&nr)|0}}function Ns(e,t=false){let n=e.length,r=new Uint32Array(n),
132
+ o=new Uint32Array(n);for(let i=0;i<n;i++){let{h:s,l:a}=xd(e[i],t);[r[i],o[i]]=[s,a];}return [r,o]}var Eo=(e,t,n)=>e>>>n,_o=(e,t,n)=>e<<32-n|t>>>n,Tt=(e,t,n)=>e>>>n|t<<32-n,Rt=(e,t,n)=>e<<32-n|t>>>n,hn=(e,t,n)=>e<<64-n|t>>>n-32,gn=(e,t,n)=>e>>>n-32|t<<64-n;function qe(e,t,n,r){let o=(t>>>0)+(r>>>0);return {h:e+n+(o/2**32|0)|0,l:o|0}}var js=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Bs=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Us=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Fs=(e,t,n,r,o)=>t+
133
+ n+r+o+(e/2**32|0)|0,zs=(e,t,n,r,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(o>>>0),Vs=(e,t,n,r,o,i)=>t+n+r+o+i+(e/2**32|0)|0;var qs=Ns(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242",
134
134
  "0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc6\
135
135
  8b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","\
136
136
  0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3\
@@ -138,797 +138,812 @@ c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a6
138
138
  x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5d\
139
139
  efb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0x\
140
140
  eada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c1\
141
- 00d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),gd=Ns[0],bd=Ns[1],lt=new Uint32Array(80),ut=new Uint32Array(80),yo=class extends Xn{constructor(t){
142
- super(128,t,16,false);}get(){let{Ah:t,Al:n,Bh:r,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:l,El:p,Fh:u,Fl:f,Gh:m,Gl:b,Hh:k,Hl:g}=this;return [t,n,r,o,i,s,a,c,l,p,u,f,m,b,k,g]}set(t,n,r,o,i,s,a,c,l,p,u,f,m,b,k,g){this.Ah=
143
- t|0,this.Al=n|0,this.Bh=r|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=p|0,this.Fh=u|0,this.Fl=f|0,this.Gh=m|0,this.Gl=b|0,this.Hh=k|0,this.Hl=g|0;}process(t,n){for(let E=0;E<
144
- 16;E++,n+=4)lt[E]=t.getUint32(n),ut[E]=t.getUint32(n+=4);for(let E=16;E<80;E++){let y=lt[E-15]|0,R=ut[E-15]|0,P=yt(y,R,1)^yt(y,R,8)^bo(y,R,7),L=kt(y,R,1)^kt(y,R,8)^vo(y,R,7),M=lt[E-2]|0,B=ut[E-2]|0,K=yt(
145
- M,B,19)^dn(M,B,61)^bo(M,B,6),J=kt(M,B,19)^pn(M,B,61)^vo(M,B,6),C=Os(L,J,ut[E-7],ut[E-16]),I=Ls(C,P,K,lt[E-7],lt[E-16]);lt[E]=I|0,ut[E]=C|0;}let{Ah:r,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:p,Eh:u,El:f,Fh:m,Fl:b,
146
- Gh:k,Gl:g,Hh:v,Hl:x}=this;for(let E=0;E<80;E++){let y=yt(u,f,14)^yt(u,f,18)^dn(u,f,41),R=kt(u,f,14)^kt(u,f,18)^pn(u,f,41),P=u&m^~u&k,L=f&b^~f&g,M=$s(x,R,L,bd[E],ut[E]),B=Ms(M,v,y,P,gd[E],lt[E]),K=M|0,
147
- J=yt(r,o,28)^dn(r,o,34)^dn(r,o,39),C=kt(r,o,28)^pn(r,o,34)^pn(r,o,39),I=r&i^r&a^i&a,N=o&s^o&c^s&c;v=k|0,x=g|0,k=m|0,g=b|0,m=u|0,b=f|0,{h:u,l:f}=Ve(l|0,p|0,B|0,K|0),l=a|0,p=c|0,a=i|0,c=s|0,i=r|0,s=o|0;
148
- let U=Ps(K,C,N);r=Ds(U,B,J,I),o=U|0;}(({h:r,l:o}=Ve(this.Ah|0,this.Al|0,r|0,o|0))),{h:i,l:s}=Ve(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Ve(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:p}=Ve(this.Dh|0,this.Dl|0,l|0,
149
- p|0),{h:u,l:f}=Ve(this.Eh|0,this.El|0,u|0,f|0),{h:m,l:b}=Ve(this.Fh|0,this.Fl|0,m|0,b|0),{h:k,l:g}=Ve(this.Gh|0,this.Gl|0,k|0,g|0),{h:v,l:x}=Ve(this.Hh|0,this.Hl|0,v|0,x|0),this.set(r,o,i,s,a,c,l,p,u,
150
- f,m,b,k,g,v,x);}roundClean(){ln(lt,ut);}destroy(){this.destroyed=true,ln(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}},ko=class extends yo{Ah=ue[0]|0;Al=ue[1]|0;Bh=ue[2]|0;Bl=ue[3]|0;Ch=ue[4]|0;Cl=ue[5]|
151
- 0;Dh=ue[6]|0;Dl=ue[7]|0;Eh=ue[8]|0;El=ue[9]|0;Fh=ue[10]|0;Fl=ue[11]|0;Gh=ue[12]|0;Gl=ue[13]|0;Hh=ue[14]|0;Hl=ue[15]|0;constructor(){super(64);}};var er=Cs(()=>new ko,Rs(3));var se=(e,t,n)=>$e(e,t,n),xo=Jn,So=Zn,qe=(...e)=>go(...e),js=e=>un(e),rr=mo,Bs=e=>Ts(e),nr=BigInt(0),wo=BigInt(1);function Ft(e,t=""){if(typeof e!="boolean"){let n=t&&`"${t}" `;throw new TypeError(n+"\
152
- expected boolean, got type="+typeof e)}return e}function vd(e){if(typeof e=="bigint"){if(!tr(e))throw new RangeError("positive bigint expected, got "+e)}else xo(e);return e}function nt(e,t=""){if(typeof e!=
153
- "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 Us(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);return e===""?nr:BigInt("0x"+e)}function Eo(e){return Us(Zn(e))}function rt(e){return Us(Zn(fn($e(e)).reverse()))}
154
- function _o(e,t){if(Jn(t),t===0)throw new RangeError("zero length");e=vd(e);let n=e.toString(16);if(n.length>t*2)throw new RangeError("number too large");return un(n.padStart(t*2,"0"))}function Fs(e,t){
155
- return _o(e,t).reverse()}function zs(e,t){if(e=se(e),t=se(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 fn(e){return Uint8Array.from(se(e))}var tr=e=>typeof e=="bigint"&&nr<=e;function yd(e,t,n){return tr(e)&&tr(t)&&tr(n)&&t<=e&&e<n}function Co(e,t,n,r){if(!yd(t,n,r))throw new RangeError(
156
- "expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function To(e){if(e<nr)throw new Error("expected non-negative bigint, got "+e);let t;for(t=0;e>nr;e>>=wo,t+=1);return t}var Vs=e=>(wo<<BigInt(e))-wo;function wt(e,t={},n={}){if(Object.prototype.toString.call(e)!=="[object Object]")throw new TypeError("expected valid options object");function r(i,s,a){if(!a&&s!=="function"&&!Object.hasOwn(e,i))throw new TypeError(
141
+ 00d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),Ed=qs[0],_d=qs[1],gt=new Uint32Array(80),bt=new Uint32Array(80),Co=class extends tr{constructor(t){
142
+ super(128,t,16,false);}get(){let{Ah:t,Al:n,Bh:r,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:l,El:d,Fh:u,Fl:f,Gh:m,Gl:b,Hh:y,Hl:g}=this;return [t,n,r,o,i,s,a,c,l,d,u,f,m,b,y,g]}set(t,n,r,o,i,s,a,c,l,d,u,f,m,b,y,g){this.Ah=
143
+ t|0,this.Al=n|0,this.Bh=r|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=d|0,this.Fh=u|0,this.Fl=f|0,this.Gh=m|0,this.Gl=b|0,this.Hh=y|0,this.Hl=g|0;}process(t,n){for(let C=0;C<
144
+ 16;C++,n+=4)gt[C]=t.getUint32(n),bt[C]=t.getUint32(n+=4);for(let C=16;C<80;C++){let k=gt[C-15]|0,R=bt[C-15]|0,A=Tt(k,R,1)^Tt(k,R,8)^Eo(k,R,7),D=Rt(k,R,1)^Rt(k,R,8)^_o(k,R,7),$=gt[C-2]|0,j=bt[C-2]|0,J=Tt(
145
+ $,j,19)^hn($,j,61)^Eo($,j,6),ee=Rt($,j,19)^gn($,j,61)^_o($,j,6),S=Us(D,ee,bt[C-7],bt[C-16]),P=Fs(S,A,J,gt[C-7],gt[C-16]);gt[C]=P|0,bt[C]=S|0;}let{Ah:r,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:d,Eh:u,El:f,Fh:m,
146
+ Fl:b,Gh:y,Gl:g,Hh:v,Hl:x}=this;for(let C=0;C<80;C++){let k=Tt(u,f,14)^Tt(u,f,18)^hn(u,f,41),R=Rt(u,f,14)^Rt(u,f,18)^gn(u,f,41),A=u&m^~u&y,D=f&b^~f&g,$=zs(x,R,D,_d[C],bt[C]),j=Vs($,v,k,A,Ed[C],gt[C]),J=$|
147
+ 0,ee=Tt(r,o,28)^hn(r,o,34)^hn(r,o,39),S=Rt(r,o,28)^gn(r,o,34)^gn(r,o,39),P=r&i^r&a^i&a,N=o&s^o&c^s&c;v=y|0,x=g|0,y=m|0,g=b|0,m=u|0,b=f|0,{h:u,l:f}=qe(l|0,d|0,j|0,J|0),l=a|0,d=c|0,a=i|0,c=s|0,i=r|0,s=o|
148
+ 0;let z=js(J,S,N);r=Bs(z,j,ee,P),o=z|0;}(({h:r,l:o}=qe(this.Ah|0,this.Al|0,r|0,o|0))),{h:i,l:s}=qe(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=qe(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:d}=qe(this.Dh|0,this.Dl|0,
149
+ l|0,d|0),{h:u,l:f}=qe(this.Eh|0,this.El|0,u|0,f|0),{h:m,l:b}=qe(this.Fh|0,this.Fl|0,m|0,b|0),{h:y,l:g}=qe(this.Gh|0,this.Gl|0,y|0,g|0),{h:v,l:x}=qe(this.Hh|0,this.Hl|0,v|0,x|0),this.set(r,o,i,s,a,c,l,
150
+ d,u,f,m,b,y,g,v,x);}roundClean(){fn(gt,bt);}destroy(){this.destroyed=true,fn(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}},To=class extends Co{Ah=pe[0]|0;Al=pe[1]|0;Bh=pe[2]|0;Bl=pe[3]|0;Ch=pe[4]|
151
+ 0;Cl=pe[5]|0;Dh=pe[6]|0;Dl=pe[7]|0;Eh=pe[8]|0;El=pe[9]|0;Fh=pe[10]|0;Fl=pe[11]|0;Gh=pe[12]|0;Gl=pe[13]|0;Hh=pe[14]|0;Hl=pe[15]|0;constructor(){super(64);}};var rr=Os(()=>new To,$s(3));var oe=(e,t,n)=>je(e,t,n),Ao=Xn,Io=er,He=(...e)=>So(...e),Hs=e=>mn(e),sr=wo,Gs=e=>Ls(e),ir=BigInt(0),Ro=BigInt(1);function Wt(e,t=""){if(typeof e!="boolean"){let n=t&&`"${t}" `;throw new TypeError(n+"\
152
+ expected boolean, got type="+typeof e)}return e}function Cd(e){if(typeof e=="bigint"){if(!or(e))throw new RangeError("positive bigint expected, got "+e)}else Ao(e);return e}function ot(e,t=""){if(typeof e!=
153
+ "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 Ws(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);return e===""?ir:BigInt("0x"+e)}function Po(e){return Ws(er(e))}function it(e){return Ws(er(bn(je(e)).reverse()))}
154
+ function Do(e,t){if(Xn(t),t===0)throw new RangeError("zero length");e=Cd(e);let n=e.toString(16);if(n.length>t*2)throw new RangeError("number too large");return mn(n.padStart(t*2,"0"))}function Ks(e,t){
155
+ return Do(e,t).reverse()}function Js(e,t){if(e=oe(e),t=oe(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 bn(e){return Uint8Array.from(oe(e))}var or=e=>typeof e=="bigint"&&ir<=e;function Td(e,t,n){return or(e)&&or(t)&&or(n)&&t<=e&&e<n}function Oo(e,t,n,r){if(!Td(t,n,r))throw new RangeError(
156
+ "expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function Lo(e){if(e<ir)throw new Error("expected non-negative bigint, got "+e);let t;for(t=0;e>ir;e>>=Ro,t+=1);return t}var Ys=e=>(Ro<<BigInt(e))-Ro;function At(e,t={},n={}){if(Object.prototype.toString.call(e)!=="[object Object]")throw new TypeError("expected valid options object");function r(i,s,a){if(!a&&s!=="function"&&!Object.hasOwn(e,i))throw new TypeError(
157
157
  `param "${i}" is invalid: expected own property`);let c=e[i];if(a&&c===void 0)return;let l=typeof c;if(l!==s||c===null)throw new TypeError(`param "${i}" is invalid: expected ${s}, got ${l}`)}let o=(i,s)=>Object.
158
- entries(i).forEach(([a,c])=>r(a,c,s));o(t,false),o(n,true);}var Ro=()=>{throw new Error("not implemented")};var de=BigInt(0),ae=BigInt(1),xt=BigInt(2),Ws=BigInt(3),Ks=BigInt(4),Js=BigInt(5),kd=BigInt(7),Ys=BigInt(8),wd=BigInt(9),Zs=BigInt(16);function re(e,t){if(t<=de)throw new Error("mod: expected positive\
159
- modulus, got "+t);let n=e%t;return n>=de?n:t+n}function Me(e,t,n){if(t<de)throw new Error("pow2: expected non-negative exponent, got "+t);let r=e;for(;t-- >de;)r*=r,r%=n;return r}function qs(e,t){if(e===de)throw new Error("invert: expected non-zer\
160
- o number");if(t<=de)throw new Error("invert: expected positive modulus, got "+t);let n=re(e,t),r=t,o=de,s=ae;for(;n!==de;){let l=r/n,p=r-n*l,u=o-s*l;r=n,n=p,o=s,s=u;}if(r!==ae)
161
- throw new Error("invert: does not exist");return re(o,t)}function Ao(e,t,n){let r=e;if(!r.eql(r.sqr(t),n))throw new Error("Cannot find square root")}function Xs(e,t){let n=e,r=(n.ORDER+ae)/Ks,o=n.pow(
162
- t,r);return Ao(n,o,t),o}function xd(e,t){let n=e,r=(n.ORDER-Js)/Ys,o=n.mul(t,xt),i=n.pow(o,r),s=n.mul(t,i),a=n.mul(n.mul(s,xt),i),c=n.mul(s,n.sub(a,n.ONE));return Ao(n,c,t),c}function Sd(e){let t=ar(e),
163
- n=Qs(e),r=n(t,t.neg(t.ONE)),o=n(t,r),i=n(t,t.neg(r)),s=(e+kd)/Zs;return((a,c)=>{let l=a,p=l.pow(c,s),u=l.mul(p,r),f=l.mul(p,o),m=l.mul(p,i),b=l.eql(l.sqr(u),c),k=l.eql(l.sqr(f),c);p=l.cmov(p,u,b),u=l.
164
- cmov(m,f,k);let g=l.eql(l.sqr(u),c),v=l.cmov(p,u,g);return Ao(l,v,c),v})}function Qs(e){if(e<Ws)throw new Error("sqrt is not defined for small field");let t=e-ae,n=0;for(;t%xt===de;)t/=xt,n++;let r=xt,
165
- o=ar(e);for(;Hs(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Xs;let i=o.pow(r,t),s=(t+ae)/xt;return function(c,l){let p=c;if(p.is0(l))return l;
166
- if(Hs(p,l)!==1)throw new Error("Cannot find square root");let u=n,f=p.mul(p.ONE,i),m=p.pow(l,t),b=p.pow(l,s);for(;!p.eql(m,p.ONE);){if(p.is0(m))return p.ZERO;let k=1,g=p.sqr(m);for(;!p.eql(g,p.ONE);)if(k++,
167
- g=p.sqr(g),k===u)throw new Error("Cannot find square root");let v=ae<<BigInt(u-k-1),x=p.pow(f,v);u=k,f=p.sqr(x),m=p.mul(m,f),b=p.mul(b,x);}return b}}function Ed(e){return e%Ks===Ws?Xs:e%Ys===Js?xd:e%Zs===
168
- wd?Sd(e):Qs(e)}var ot=(e,t)=>(re(e,t)&ae)===ae,_d=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ea(e){let t={ORDER:"bigin\
169
- t",BYTES:"number",BITS:"number"},n=_d.reduce((r,o)=>(r[o]="function",r),t);if(wt(e,n),nt(e.BYTES,"BYTES"),nt(e.BITS,"BITS"),e.BYTES<1||e.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");
170
- if(e.ORDER<=ae)throw new Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function Cd(e,t,n){let r=e;if(n<de)throw new Error("invalid exponent, negatives unsupported");if(n===de)return r.
171
- ONE;if(n===ae)return t;let o=r.ONE,i=t;for(;n>de;)n&ae&&(o=r.mul(o,i)),i=r.sqr(i),n>>=ae;return o}function sr(e,t,n=false){let r=e,o=new Array(t.length).fill(n?r.ZERO:void 0),i=t.reduce((a,c,l)=>r.is0(c)?
172
- a:(o[l]=a,r.mul(a,c)),r.ONE),s=r.inv(i);return t.reduceRight((a,c,l)=>r.is0(c)?a:(o[l]=r.mul(a,o[l]),r.mul(a,c)),s),o}function Hs(e,t){let n=e,r=(n.ORDER-ae)/xt,o=n.pow(t,r),i=n.eql(o,n.ONE),s=n.eql(o,n.ZERO),a=n.eql(o,n.neg(n.ONE));if(!i&&!s&&!a)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function Td(e,t){if(t!==void 0&&xo(t),e<=de)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);
173
- let n=To(e);if(t!==void 0&&t<n)throw new Error(`invalid n length: expected bit length (${n}) >= n.length (${t})`);let r=t!==void 0?t:n,o=Math.ceil(r/8);return {nBitLength:r,nByteLength:o}}var Gs=new WeakMap,
174
- ir=class{ORDER;BITS;BYTES;isLE;ZERO=de;ONE=ae;_lengths;_mod;constructor(t,n={}){if(t<=ae)throw new Error("invalid field: expected ORDER > 1, got "+t);let r;this.isLE=false,n!=null&&typeof n=="object"&&(typeof n.
158
+ entries(i).forEach(([a,c])=>r(a,c,s));o(t,false),o(n,true);}var $o=()=>{throw new Error("not implemented")};var fe=BigInt(0),ce=BigInt(1),It=BigInt(2),ea=BigInt(3),ta=BigInt(4),na=BigInt(5),Rd=BigInt(7),ra=BigInt(8),Ad=BigInt(9),oa=BigInt(16);function re(e,t){if(t<=fe)throw new Error("mod: expected positive\
159
+ modulus, got "+t);let n=e%t;return n>=fe?n:t+n}function Be(e,t,n){if(t<fe)throw new Error("pow2: expected non-negative exponent, got "+t);let r=e;for(;t-- >fe;)r*=r,r%=n;return r}function Zs(e,t){if(e===fe)throw new Error("invert: expected non-zer\
160
+ o number");if(t<=fe)throw new Error("invert: expected positive modulus, got "+t);let n=re(e,t),r=t,o=fe,s=ce;for(;n!==fe;){let l=r/n,d=r-n*l,u=o-s*l;r=n,n=d,o=s,s=u;}if(r!==ce)
161
+ throw new Error("invert: does not exist");return re(o,t)}function Mo(e,t,n){let r=e;if(!r.eql(r.sqr(t),n))throw new Error("Cannot find square root")}function ia(e,t){let n=e,r=(n.ORDER+ce)/ta,o=n.pow(
162
+ t,r);return Mo(n,o,t),o}function Id(e,t){let n=e,r=(n.ORDER-na)/ra,o=n.mul(t,It),i=n.pow(o,r),s=n.mul(t,i),a=n.mul(n.mul(s,It),i),c=n.mul(s,n.sub(a,n.ONE));return Mo(n,c,t),c}function Pd(e){let t=ur(e),
163
+ n=sa(e),r=n(t,t.neg(t.ONE)),o=n(t,r),i=n(t,t.neg(r)),s=(e+Rd)/oa;return((a,c)=>{let l=a,d=l.pow(c,s),u=l.mul(d,r),f=l.mul(d,o),m=l.mul(d,i),b=l.eql(l.sqr(u),c),y=l.eql(l.sqr(f),c);d=l.cmov(d,u,b),u=l.
164
+ cmov(m,f,y);let g=l.eql(l.sqr(u),c),v=l.cmov(d,u,g);return Mo(l,v,c),v})}function sa(e){if(e<ea)throw new Error("sqrt is not defined for small field");let t=e-ce,n=0;for(;t%It===fe;)t/=It,n++;let r=It,
165
+ o=ur(e);for(;Xs(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return ia;let i=o.pow(r,t),s=(t+ce)/It;return function(c,l){let d=c;if(d.is0(l))return l;
166
+ if(Xs(d,l)!==1)throw new Error("Cannot find square root");let u=n,f=d.mul(d.ONE,i),m=d.pow(l,t),b=d.pow(l,s);for(;!d.eql(m,d.ONE);){if(d.is0(m))return d.ZERO;let y=1,g=d.sqr(m);for(;!d.eql(g,d.ONE);)if(y++,
167
+ g=d.sqr(g),y===u)throw new Error("Cannot find square root");let v=ce<<BigInt(u-y-1),x=d.pow(f,v);u=y,f=d.sqr(x),m=d.mul(m,f),b=d.mul(b,x);}return b}}function Dd(e){return e%ta===ea?ia:e%ra===na?Id:e%oa===
168
+ Ad?Pd(e):sa(e)}var st=(e,t)=>(re(e,t)&ce)===ce,Od=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function aa(e){let t={ORDER:"bigin\
169
+ t",BYTES:"number",BITS:"number"},n=Od.reduce((r,o)=>(r[o]="function",r),t);if(At(e,n),ot(e.BYTES,"BYTES"),ot(e.BITS,"BITS"),e.BYTES<1||e.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");
170
+ if(e.ORDER<=ce)throw new Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function Ld(e,t,n){let r=e;if(n<fe)throw new Error("invalid exponent, negatives unsupported");if(n===fe)return r.
171
+ ONE;if(n===ce)return t;let o=r.ONE,i=t;for(;n>fe;)n&ce&&(o=r.mul(o,i)),i=r.sqr(i),n>>=ce;return o}function lr(e,t,n=false){let r=e,o=new Array(t.length).fill(n?r.ZERO:void 0),i=t.reduce((a,c,l)=>r.is0(c)?
172
+ a:(o[l]=a,r.mul(a,c)),r.ONE),s=r.inv(i);return t.reduceRight((a,c,l)=>r.is0(c)?a:(o[l]=r.mul(a,o[l]),r.mul(a,c)),s),o}function Xs(e,t){let n=e,r=(n.ORDER-ce)/It,o=n.pow(t,r),i=n.eql(o,n.ONE),s=n.eql(o,n.ZERO),a=n.eql(o,n.neg(n.ONE));if(!i&&!s&&!a)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function $d(e,t){if(t!==void 0&&Ao(t),e<=fe)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);
173
+ let n=Lo(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 Qs=new WeakMap,
174
+ cr=class{ORDER;BITS;BYTES;isLE;ZERO=fe;ONE=ce;_lengths;_mod;constructor(t,n={}){if(t<=ce)throw new Error("invalid field: expected ORDER > 1, got "+t);let r;this.isLE=false,n!=null&&typeof n=="object"&&(typeof n.
175
175
  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.
176
- freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:i}=Td(t,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2\
176
+ freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:i}=$d(t,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2\
177
177
  048 bytes");this.ORDER=t,this.BITS=o,this.BYTES=i,Object.freeze(this);}create(t){return re(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new TypeError("invalid field element: expected bigint, go\
178
- t "+typeof t);return de<=t&&t<this.ORDER}is0(t){return t===de}isValidNot0(t){return !this.is0(t)&&this.isValid(t)}isOdd(t){return (t&ae)===ae}neg(t){return re(-t,this.ORDER)}eql(t,n){return t===n}sqr(t){
179
- return re(t*t,this.ORDER)}add(t,n){return re(t+n,this.ORDER)}sub(t,n){return re(t-n,this.ORDER)}mul(t,n){return re(t*n,this.ORDER)}pow(t,n){return Cd(this,t,n)}div(t,n){return re(t*qs(n,this.ORDER),this.
180
- ORDER)}sqrN(t){return t*t}addN(t,n){return t+n}subN(t,n){return t-n}mulN(t,n){return t*n}inv(t){return qs(t,this.ORDER)}sqrt(t){let n=Gs.get(this);return n||Gs.set(this,n=Ed(this.ORDER)),n(this,t)}toBytes(t){
181
- return this.isLE?Fs(t,this.BYTES):_o(t,this.BYTES)}fromBytes(t,n=false){se(t);let{_lengths:r,BYTES:o,isLE:i,ORDER:s,_mod:a}=this;if(r){if(t.length<1||!r.includes(t.length)||t.length>o)throw new Error("Fi\
178
+ t "+typeof t);return fe<=t&&t<this.ORDER}is0(t){return t===fe}isValidNot0(t){return !this.is0(t)&&this.isValid(t)}isOdd(t){return (t&ce)===ce}neg(t){return re(-t,this.ORDER)}eql(t,n){return t===n}sqr(t){
179
+ return re(t*t,this.ORDER)}add(t,n){return re(t+n,this.ORDER)}sub(t,n){return re(t-n,this.ORDER)}mul(t,n){return re(t*n,this.ORDER)}pow(t,n){return Ld(this,t,n)}div(t,n){return re(t*Zs(n,this.ORDER),this.
180
+ ORDER)}sqrN(t){return t*t}addN(t,n){return t+n}subN(t,n){return t-n}mulN(t,n){return t*n}inv(t){return Zs(t,this.ORDER)}sqrt(t){let n=Qs.get(this);return n||Qs.set(this,n=Dd(this.ORDER)),n(this,t)}toBytes(t){
181
+ return this.isLE?Ks(t,this.BYTES):Do(t,this.BYTES)}fromBytes(t,n=false){oe(t);let{_lengths:r,BYTES:o,isLE:i,ORDER:s,_mod:a}=this;if(r){if(t.length<1||!r.includes(t.length)||t.length>o)throw new Error("Fi\
182
182
  eld.fromBytes: expected "+r+" bytes, got "+t.length);let l=new Uint8Array(o);l.set(t,i?0:l.length-t.length),t=l;}if(t.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);
183
- let c=i?rt(t):Eo(t);if(a&&(c=re(c,s)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return sr(this,t)}cmov(t,n,r){return Ft(r,"condit\
184
- ion"),r?n:t}};Object.freeze(ir.prototype);function ar(e,t={}){return new ir(e,t)}var cr=BigInt(0),Oo=BigInt(1);function ta(e,t){let n=t.negate();return e?n:t}function ur(e,t){let n=sr(e.Fp,t.map(r=>r.Z));return t.map((r,o)=>e.fromAffine(r.toAffine(n[o])))}function ia(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)
185
- throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Io(e,t){ia(e,t);let n=Math.ceil(t/e)+1,r=2**(e-1),o=2**e,i=Vs(e),s=BigInt(e);return {windows:n,windowSize:r,mask:i,maxNumber:o,
186
- shiftBy:s}}function na(e,t,n){let{windowSize:r,mask:o,maxNumber:i,shiftBy:s}=n,a=Number(e&o),c=e>>s;a>r&&(a-=i,c+=Oo);let l=t*r,p=l+Math.abs(a)-1,u=a===0,f=a<0,m=t%2!==0;return {nextN:c,offset:p,isZero:u,
187
- isNeg:f,isNegF:m,offsetF:l}}var Po=new WeakMap,sa=new WeakMap;function Do(e){return sa.get(e)||1}function ra(e){if(e!==cr)throw new Error("invalid wNAF")}var lr=class{BASE;ZERO;Fn;bits;constructor(t,n){this.BASE=t.BASE,this.ZERO=
188
- t.ZERO,this.Fn=t.Fn,this.bits=n;}_unsafeLadder(t,n,r=this.ZERO){let o=t;for(;n>cr;)n&Oo&&(r=r.add(o)),o=o.double(),n>>=Oo;return r}precomputeWindow(t,n){let{windows:r,windowSize:o}=Io(n,this.bits),i=[],
183
+ let c=i?it(t):Po(t);if(a&&(c=re(c,s)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return lr(this,t)}cmov(t,n,r){return Wt(r,"condit\
184
+ ion"),r?n:t}};Object.freeze(cr.prototype);function ur(e,t={}){return new cr(e,t)}var dr=BigInt(0),Uo=BigInt(1);function ca(e,t){let n=t.negate();return e?n:t}function fr(e,t){let n=lr(e.Fp,t.map(r=>r.Z));return t.map((r,o)=>e.fromAffine(r.toAffine(n[o])))}function pa(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)
185
+ throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function No(e,t){pa(e,t);let n=Math.ceil(t/e)+1,r=2**(e-1),o=2**e,i=Ys(e),s=BigInt(e);return {windows:n,windowSize:r,mask:i,maxNumber:o,
186
+ shiftBy:s}}function la(e,t,n){let{windowSize:r,mask:o,maxNumber:i,shiftBy:s}=n,a=Number(e&o),c=e>>s;a>r&&(a-=i,c+=Uo);let l=t*r,d=l+Math.abs(a)-1,u=a===0,f=a<0,m=t%2!==0;return {nextN:c,offset:d,isZero:u,
187
+ isNeg:f,isNegF:m,offsetF:l}}var jo=new WeakMap,fa=new WeakMap;function Bo(e){return fa.get(e)||1}function ua(e){if(e!==dr)throw new Error("invalid wNAF")}var pr=class{BASE;ZERO;Fn;bits;constructor(t,n){this.BASE=t.BASE,this.ZERO=
188
+ t.ZERO,this.Fn=t.Fn,this.bits=n;}_unsafeLadder(t,n,r=this.ZERO){let o=t;for(;n>dr;)n&Uo&&(r=r.add(o)),o=o.double(),n>>=Uo;return r}precomputeWindow(t,n){let{windows:r,windowSize:o}=No(n,this.bits),i=[],
189
189
  s=t,a=s;for(let c=0;c<r;c++){a=s,i.push(a);for(let l=1;l<o;l++)a=a.add(s),i.push(a);s=a.double();}return i}wNAF(t,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,i=this.BASE,
190
- s=Io(t,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:l,isZero:p,isNeg:u,isNegF:f,offsetF:m}=na(r,a,s);r=c,p?i=i.add(ta(f,n[m])):o=o.add(ta(u,n[l]));}return ra(r),{p:o,f:i}}wNAFUnsafe(t,n,r,o=this.
191
- ZERO){let i=Io(t,this.bits);for(let s=0;s<i.windows&&r!==cr;s++){let{nextN:a,offset:c,isZero:l,isNeg:p}=na(r,s,i);if(r=a,!l){let u=n[c];o=o.add(p?u.negate():u);}}return ra(r),o}getPrecomputes(t,n,r){let o=Po.
192
- get(n);return o||(o=this.precomputeWindow(n,t),t!==1&&(typeof r=="function"&&(o=r(o)),Po.set(n,o))),o}cached(t,n,r){let o=Do(t);return this.wNAF(o,this.getPrecomputes(o,t,r),n)}unsafe(t,n,r,o){let i=Do(
193
- t);return i===1?this._unsafeLadder(t,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,t,r),n,o)}createCache(t,n){ia(n,this.bits),sa.set(t,n),Po.delete(t);}hasCache(t){return Do(t)!==1}};function oa(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return ea(t),t}else return ar(e,{isLE:n})}function aa(e,t,n={},r){if(r===void 0&&(r=e==="edwar\
194
- ds"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(let c of ["p","n","h"]){let l=t[c];if(!(typeof l=="bigint"&&l>cr))throw new Error(`CURVE.${c} must be positive bigint`)}
195
- let o=oa(t.p,n.Fp,r),i=oa(t.n,n.Fn,r),a=["Gx","Gy","a","d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.
196
- freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:i}}function ca(e,t){return function(r){let o=e(r);return {secretKey:o,publicKey:t(o)}}}var dt=BigInt(0),ce=BigInt(1),Lo=BigInt(2),Rd=BigInt(8);function Ad(e,t,n,r){let o=e.sqr(n),i=e.sqr(r),s=e.add(e.mul(t.a,o),i),a=e.add(e.ONE,e.mul(t.d,e.mul(o,i)));return e.eql(s,a)}function la(e,t={}){
197
- let n=t,r=aa("edwards",e,n,n.FpFnLE),{Fp:o,Fn:i}=r,s=r.CURVE,{h:a}=s;wt(n,{},{uvRatio:"function"});let c=Lo<<BigInt(i.BYTES*8)-ce,l=k=>o.create(k),p=n.uvRatio===void 0?(k,g)=>{try{return {isValid:!0,value:o.
198
- sqrt(o.div(k,g))}}catch{return {isValid:false,value:dt}}}:n.uvRatio;if(!Ad(o,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function u(k,g,v=false){let x=v?ce:dt;return Co("coordinate "+k,
199
- g,x,c),g}function f(k){if(!(k instanceof m))throw new Error("EdwardsPoint expected")}class m{static BASE=new m(s.Gx,s.Gy,ce,l(s.Gx*s.Gy));static ZERO=new m(dt,ce,ce,dt);static Fp=o;static Fn=i;X;Y;Z;T;constructor(g,v,x,E){
200
- this.X=u("x",g),this.Y=u("y",v),this.Z=u("z",x,true),this.T=u("t",E),Object.freeze(this);}static CURVE(){return s}static fromAffine(g){if(g instanceof m)throw new Error("extended point not allowed");let{
201
- x:v,y:x}=g||{};return u("x",v),u("y",x),new m(v,x,ce,l(v*x))}static fromBytes(g,v=false){let x=o.BYTES,{a:E,d:y}=s;g=fn(se(g,x,"point")),Ft(v,"zip215");let R=fn(g),P=g[x-1];R[x-1]=P&-129;let L=rt(R),M=v?
202
- c:o.ORDER;Co("point.y",L,dt,M);let B=l(L*L),K=l(B-ce),J=l(y*B-E),{isValid:C,value:I}=p(K,J);if(!C)throw new Error("bad point: invalid y coordinate");let N=(I&ce)===ce,U=(P&128)!==0;if(!v&&I===dt&&U)throw new Error(
203
- "bad point: x=0 and x_0=1");return U!==N&&(I=l(-I)),m.fromAffine({x:I,y:L})}static fromHex(g,v=false){return m.fromBytes(js(g),v)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,v=true){
204
- return b.createCache(this,g),v||this.multiply(Lo),this}assertValidity(){let g=this,{a:v,d:x}=s;if(g.is0())throw new Error("bad point: ZERO");let{X:E,Y:y,Z:R,T:P}=g,L=l(E*E),M=l(y*y),B=l(R*R),K=l(B*B),
205
- J=l(L*v),C=l(B*l(J+M)),I=l(K+l(x*l(L*M)));if(C!==I)throw new Error("bad point: equation left != right (1)");let N=l(E*y),U=l(R*P);if(N!==U)throw new Error("bad point: equation left != right (2)")}equals(g){
206
- f(g);let{X:v,Y:x,Z:E}=this,{X:y,Y:R,Z:P}=g,L=l(v*P),M=l(y*E),B=l(x*P),K=l(R*E);return L===M&&B===K}is0(){return this.equals(m.ZERO)}negate(){return new m(l(-this.X),this.Y,this.Z,l(-this.T))}double(){
207
- let{a:g}=s,{X:v,Y:x,Z:E}=this,y=l(v*v),R=l(x*x),P=l(Lo*l(E*E)),L=l(g*y),M=v+x,B=l(l(M*M)-y-R),K=L+R,J=K-P,C=L-R,I=l(B*J),N=l(K*C),U=l(B*C),oe=l(J*K);return new m(I,N,oe,U)}add(g){f(g);let{a:v,d:x}=s,{
208
- X:E,Y:y,Z:R,T:P}=this,{X:L,Y:M,Z:B,T:K}=g,J=l(E*L),C=l(y*M),I=l(P*x*K),N=l(R*B),U=l((E+y)*(L+M)-J-C),oe=N-I,Q=N+I,Te=l(C-v*J),Re=l(U*oe),je=l(Q*Te),Ae=l(U*Te),Be=l(oe*Q);return new m(Re,je,Be,Ae)}subtract(g){
209
- return f(g),this.add(g.negate())}multiply(g){if(!i.isValidNot0(g))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:v,f:x}=b.cached(this,g,E=>ur(m,E));return ur(m,[v,x])[0]}multiplyUnsafe(g){
210
- if(!i.isValid(g))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return g===dt?m.ZERO:this.is0()||g===ce?this:b.unsafe(this,g,v=>ur(m,v))}isSmallOrder(){return this.clearCofactor().
211
- is0()}isTorsionFree(){return b.unsafe(this,s.n).is0()}toAffine(g){let v=this,x=g,{X:E,Y:y,Z:R}=v,P=v.is0();x==null&&(x=P?Rd:o.inv(R));let L=l(E*x),M=l(y*x),B=o.mul(R,x);if(P)return {x:dt,y:ce};if(B!==ce)
212
- throw new Error("invZ was invalid");return {x:L,y:M}}clearCofactor(){return a===ce?this:this.multiplyUnsafe(a)}toBytes(){let{x:g,y:v}=this.toAffine(),x=o.toBytes(v);return x[x.length-1]|=g&ce?128:0,x}toHex(){
213
- return So(this.toBytes())}toString(){return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let b=new lr(m,i.BITS);return i.BITS>=8&&m.BASE.precompute(8),Object.freeze(m.prototype),Object.freeze(m),m}var dr=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(t){
214
- this.ep=t;}static fromBytes(t){Ro();}static fromHex(t){Ro();}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity();}toAffine(t){
215
- return this.ep.toAffine(t)}toHex(){return So(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){
216
- 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.
217
- ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,n){return this.ep.precompute(t,n),this}};function ua(e,t,n={}){if(typeof t!="function")throw new Error('"hash" function param is r\
218
- equired');let r=t,o=n;wt(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:i}=o,{BASE:s,Fp:a,Fn:c}=e,l=r.
219
- outputLen,p=2*a.BYTES;if(l!==void 0&&(nt(l,"hash.outputLen"),l!==p))throw new Error(`hash.outputLen must be ${p}, got ${l}`);let u=o.randomBytes===void 0?Bs:o.randomBytes,f=o.adjustScalarBytes===void 0?
220
- C=>C:o.adjustScalarBytes,m=o.domain===void 0?(C,I,N)=>{if(Ft(N,"phflag"),I.length||N)throw new Error("Contexts/pre-hash are not supported");return C}:o.domain;function b(C){return c.create(rt(C))}function k(C){
221
- let I=L.secretKey;se(C,L.secretKey,"secretKey");let N=se(r(C),2*I,"hashedSecretKey"),U=f(N.slice(0,I)),oe=N.slice(I,2*I),Q=b(U);return {head:U,prefix:oe,scalar:Q}}function g(C){let{head:I,prefix:N,scalar:U}=k(
222
- C),oe=s.multiply(U),Q=oe.toBytes();return {head:I,prefix:N,scalar:U,point:oe,pointBytes:Q}}function v(C){return g(C).pointBytes}function x(C=Uint8Array.of(),...I){let N=qe(...I);return b(r(m(N,se(C,void 0,
223
- "context"),!!i)))}function E(C,I,N={}){C=se(C,void 0,"message"),i&&(C=i(C));let{prefix:U,scalar:oe,pointBytes:Q}=g(I),Te=x(N.context,U,C),Re=s.multiply(Te).toBytes(),je=x(N.context,Re,Q,C),Ae=c.create(
224
- Te+je*oe);if(!c.isValid(Ae))throw new Error("sign failed: invalid s");let Be=qe(Re,c.toBytes(Ae));return se(Be,L.signature,"result")}let y={zip215:o.zip215};function R(C,I,N,U=y){let{context:oe}=U,Q=U.
225
- zip215===void 0?!!y.zip215:U.zip215,Te=L.signature;C=se(C,Te,"signature"),I=se(I,void 0,"message"),N=se(N,L.publicKey,"publicKey"),Q!==void 0&&Ft(Q,"zip215"),i&&(I=i(I));let Re=Te/2,je=C.subarray(0,Re),
226
- Ae=rt(C.subarray(Re,Te)),Be,On,h;try{Be=e.fromBytes(N,Q),On=e.fromBytes(je,Q),h=s.multiplyUnsafe(Ae);}catch{return false}if(!Q&&Be.isSmallOrder())return false;let S=x(oe,je,N,I);return On.add(Be.multiplyUnsafe(
227
- S)).subtract(h).clearCofactor().is0()}let P=a.BYTES,L={secretKey:P,publicKey:P,signature:2*P,seed:P};function M(C){return C=C===void 0?u(L.seed):C,se(C,L.seed,"seed")}function B(C){return rr(C)&&C.length===
228
- L.secretKey}function K(C,I){try{return !!e.fromBytes(C,I===void 0?y.zip215:I)}catch{return false}}let J={getExtendedPublicKey:g,randomSecretKey:M,isValidSecretKey:B,isValidPublicKey:K,toMontgomery(C){let{y:I}=e.
229
- fromBytes(C),N=L.publicKey,U=N===32;if(!U&&N!==57)throw new Error("only defined for 25519 and 448");let oe=U?a.div(ce+I,ce-I):a.div(I-ce,I+ce);return a.toBytes(oe)},toMontgomerySecret(C){let I=L.secretKey;
230
- se(C,I);let N=r(C.subarray(0,I));return f(N).subarray(0,I)}};return Object.freeze(L),Object.freeze(J),Object.freeze({keygen:ca(M,v),getPublicKey:v,sign:E,verify:R,utils:J,Point:e,lengths:L})}var Dd=BigInt(0),it=BigInt(1),pa=BigInt(2);var Od=BigInt(5),Ld=BigInt(8),zt=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Bo={p:zt,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Ld,
190
+ s=No(t,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:l,isZero:d,isNeg:u,isNegF:f,offsetF:m}=la(r,a,s);r=c,d?i=i.add(ca(f,n[m])):o=o.add(ca(u,n[l]));}return ua(r),{p:o,f:i}}wNAFUnsafe(t,n,r,o=this.
191
+ ZERO){let i=No(t,this.bits);for(let s=0;s<i.windows&&r!==dr;s++){let{nextN:a,offset:c,isZero:l,isNeg:d}=la(r,s,i);if(r=a,!l){let u=n[c];o=o.add(d?u.negate():u);}}return ua(r),o}getPrecomputes(t,n,r){let o=jo.
192
+ get(n);return o||(o=this.precomputeWindow(n,t),t!==1&&(typeof r=="function"&&(o=r(o)),jo.set(n,o))),o}cached(t,n,r){let o=Bo(t);return this.wNAF(o,this.getPrecomputes(o,t,r),n)}unsafe(t,n,r,o){let i=Bo(
193
+ t);return i===1?this._unsafeLadder(t,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,t,r),n,o)}createCache(t,n){pa(n,this.bits),fa.set(t,n),jo.delete(t);}hasCache(t){return Bo(t)!==1}};function da(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return aa(t),t}else return ur(e,{isLE:n})}function ma(e,t,n={},r){if(r===void 0&&(r=e==="edwar\
194
+ ds"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(let c of ["p","n","h"]){let l=t[c];if(!(typeof l=="bigint"&&l>dr))throw new Error(`CURVE.${c} must be positive bigint`)}
195
+ let o=da(t.p,n.Fp,r),i=da(t.n,n.Fn,r),a=["Gx","Gy","a","d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.
196
+ freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:i}}function ha(e,t){return function(r){let o=e(r);return {secretKey:o,publicKey:t(o)}}}var vt=BigInt(0),le=BigInt(1),Fo=BigInt(2),Md=BigInt(8);function Nd(e,t,n,r){let o=e.sqr(n),i=e.sqr(r),s=e.add(e.mul(t.a,o),i),a=e.add(e.ONE,e.mul(t.d,e.mul(o,i)));return e.eql(s,a)}function ga(e,t={}){
197
+ let n=t,r=ma("edwards",e,n,n.FpFnLE),{Fp:o,Fn:i}=r,s=r.CURVE,{h:a}=s;At(n,{},{uvRatio:"function"});let c=Fo<<BigInt(i.BYTES*8)-le,l=y=>o.create(y),d=n.uvRatio===void 0?(y,g)=>{try{return {isValid:!0,value:o.
198
+ sqrt(o.div(y,g))}}catch{return {isValid:false,value:vt}}}:n.uvRatio;if(!Nd(o,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function u(y,g,v=false){let x=v?le:vt;return Oo("coordinate "+y,
199
+ g,x,c),g}function f(y){if(!(y instanceof m))throw new Error("EdwardsPoint expected")}class m{static BASE=new m(s.Gx,s.Gy,le,l(s.Gx*s.Gy));static ZERO=new m(vt,le,le,vt);static Fp=o;static Fn=i;X;Y;Z;T;constructor(g,v,x,C){
200
+ this.X=u("x",g),this.Y=u("y",v),this.Z=u("z",x,true),this.T=u("t",C),Object.freeze(this);}static CURVE(){return s}static fromAffine(g){if(g instanceof m)throw new Error("extended point not allowed");let{
201
+ x:v,y:x}=g||{};return u("x",v),u("y",x),new m(v,x,le,l(v*x))}static fromBytes(g,v=false){let x=o.BYTES,{a:C,d:k}=s;g=bn(oe(g,x,"point")),Wt(v,"zip215");let R=bn(g),A=g[x-1];R[x-1]=A&-129;let D=it(R),$=v?
202
+ c:o.ORDER;Oo("point.y",D,vt,$);let j=l(D*D),J=l(j-le),ee=l(k*j-C),{isValid:S,value:P}=d(J,ee);if(!S)throw new Error("bad point: invalid y coordinate");let N=(P&le)===le,z=(A&128)!==0;if(!v&&P===vt&&z)
203
+ throw new Error("bad point: x=0 and x_0=1");return z!==N&&(P=l(-P)),m.fromAffine({x:P,y:D})}static fromHex(g,v=false){return m.fromBytes(Hs(g),v)}get x(){return this.toAffine().x}get y(){return this.toAffine().
204
+ y}precompute(g=8,v=true){return b.createCache(this,g),v||this.multiply(Fo),this}assertValidity(){let g=this,{a:v,d:x}=s;if(g.is0())throw new Error("bad point: ZERO");let{X:C,Y:k,Z:R,T:A}=g,D=l(C*C),$=l(
205
+ k*k),j=l(R*R),J=l(j*j),ee=l(D*v),S=l(j*l(ee+$)),P=l(J+l(x*l(D*$)));if(S!==P)throw new Error("bad point: equation left != right (1)");let N=l(C*k),z=l(R*A);if(N!==z)throw new Error("bad point: equation\
206
+ left != right (2)")}equals(g){f(g);let{X:v,Y:x,Z:C}=this,{X:k,Y:R,Z:A}=g,D=l(v*A),$=l(k*C),j=l(x*A),J=l(R*C);return D===$&&j===J}is0(){return this.equals(m.ZERO)}negate(){return new m(l(-this.X),this.
207
+ Y,this.Z,l(-this.T))}double(){let{a:g}=s,{X:v,Y:x,Z:C}=this,k=l(v*v),R=l(x*x),A=l(Fo*l(C*C)),D=l(g*k),$=v+x,j=l(l($*$)-k-R),J=D+R,ee=J-A,S=D-R,P=l(j*ee),N=l(J*S),z=l(j*S),ie=l(ee*J);return new m(P,N,ie,
208
+ z)}add(g){f(g);let{a:v,d:x}=s,{X:C,Y:k,Z:R,T:A}=this,{X:D,Y:$,Z:j,T:J}=g,ee=l(C*D),S=l(k*$),P=l(A*x*J),N=l(R*j),z=l((C+k)*(D+$)-ee-S),ie=N-P,se=N+P,me=l(S-v*ee),Fe=l(z*ie),Oe=l(se*me),ze=l(z*me),Te=l(
209
+ ie*se);return new m(Fe,Oe,Te,ze)}subtract(g){return f(g),this.add(g.negate())}multiply(g){if(!i.isValidNot0(g))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:v,f:x}=b.cached(
210
+ this,g,C=>fr(m,C));return fr(m,[v,x])[0]}multiplyUnsafe(g){if(!i.isValid(g))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return g===vt?m.ZERO:this.is0()||g===le?this:b.unsafe(this,
211
+ g,v=>fr(m,v))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return b.unsafe(this,s.n).is0()}toAffine(g){let v=this,x=g,{X:C,Y:k,Z:R}=v,A=v.is0();x==null&&(x=A?Md:o.inv(R));let D=l(C*
212
+ x),$=l(k*x),j=o.mul(R,x);if(A)return {x:vt,y:le};if(j!==le)throw new Error("invZ was invalid");return {x:D,y:$}}clearCofactor(){return a===le?this:this.multiplyUnsafe(a)}toBytes(){let{x:g,y:v}=this.toAffine(),
213
+ x=o.toBytes(v);return x[x.length-1]|=g&le?128:0,x}toHex(){return Io(this.toBytes())}toString(){return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let b=new pr(m,i.BITS);return i.BITS>=8&&m.BASE.precompute(
214
+ 8),Object.freeze(m.prototype),Object.freeze(m),m}var mr=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(t){this.ep=t;}static fromBytes(t){$o();}static fromHex(t){$o();}get x(){return this.
215
+ toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity();}toAffine(t){return this.ep.toAffine(t)}toHex(){return Io(this.toBytes())}toString(){
216
+ return this.toHex()}isTorsionFree(){return true}isSmallOrder(){return false}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){return this.assertSame(t),this.init(this.ep.subtract(t.ep))}multiply(t){
217
+ return this.init(this.ep.multiply(t))}multiplyUnsafe(t){return this.init(this.ep.multiplyUnsafe(t))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,n){
218
+ return this.ep.precompute(t,n),this}};function ba(e,t,n={}){if(typeof t!="function")throw new Error('"hash" function param is required');let r=t,o=n;At(o,{},{adjustScalarBytes:"function",randomBytes:"\
219
+ function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:i}=o,{BASE:s,Fp:a,Fn:c}=e,l=r.outputLen,d=2*a.BYTES;if(l!==void 0&&(ot(l,"hash.outputLen"),l!==d))throw new Error(
220
+ `hash.outputLen must be ${d}, got ${l}`);let u=o.randomBytes===void 0?Gs:o.randomBytes,f=o.adjustScalarBytes===void 0?S=>S:o.adjustScalarBytes,m=o.domain===void 0?(S,P,N)=>{if(Wt(N,"phflag"),P.length||
221
+ N)throw new Error("Contexts/pre-hash are not supported");return S}:o.domain;function b(S){return c.create(it(S))}function y(S){let P=D.secretKey;oe(S,D.secretKey,"secretKey");let N=oe(r(S),2*P,"hashed\
222
+ SecretKey"),z=f(N.slice(0,P)),ie=N.slice(P,2*P),se=b(z);return {head:z,prefix:ie,scalar:se}}function g(S){let{head:P,prefix:N,scalar:z}=y(S),ie=s.multiply(z),se=ie.toBytes();return {head:P,prefix:N,scalar:z,
223
+ point:ie,pointBytes:se}}function v(S){return g(S).pointBytes}function x(S=Uint8Array.of(),...P){let N=He(...P);return b(r(m(N,oe(S,void 0,"context"),!!i)))}function C(S,P,N={}){S=oe(S,void 0,"message"),
224
+ i&&(S=i(S));let{prefix:z,scalar:ie,pointBytes:se}=g(P),me=x(N.context,z,S),Fe=s.multiply(me).toBytes(),Oe=x(N.context,Fe,se,S),ze=c.create(me+Oe*ie);if(!c.isValid(ze))throw new Error("sign failed: inv\
225
+ alid s");let Te=He(Fe,c.toBytes(ze));return oe(Te,D.signature,"result")}let k={zip215:o.zip215};function R(S,P,N,z=k){let{context:ie}=z,se=z.zip215===void 0?!!k.zip215:z.zip215,me=D.signature;S=oe(S,me,
226
+ "signature"),P=oe(P,void 0,"message"),N=oe(N,D.publicKey,"publicKey"),se!==void 0&&Wt(se,"zip215"),i&&(P=i(P));let Fe=me/2,Oe=S.subarray(0,Fe),ze=it(S.subarray(Fe,me)),Te,cn,Nn;try{Te=e.fromBytes(N,se),
227
+ cn=e.fromBytes(Oe,se),Nn=s.multiplyUnsafe(ze);}catch{return false}if(!se&&Te.isSmallOrder())return false;let h=x(ie,Oe,N,P);return cn.add(Te.multiplyUnsafe(h)).subtract(Nn).clearCofactor().is0()}let A=a.BYTES,
228
+ D={secretKey:A,publicKey:A,signature:2*A,seed:A};function $(S){return S=S===void 0?u(D.seed):S,oe(S,D.seed,"seed")}function j(S){return sr(S)&&S.length===D.secretKey}function J(S,P){try{return !!e.fromBytes(
229
+ S,P===void 0?k.zip215:P)}catch{return false}}let ee={getExtendedPublicKey:g,randomSecretKey:$,isValidSecretKey:j,isValidPublicKey:J,toMontgomery(S){let{y:P}=e.fromBytes(S),N=D.publicKey,z=N===32;if(!z&&N!==
230
+ 57)throw new Error("only defined for 25519 and 448");let ie=z?a.div(le+P,le-P):a.div(P-le,P+le);return a.toBytes(ie)},toMontgomerySecret(S){let P=D.secretKey;oe(S,P);let N=r(S.subarray(0,P));return f(
231
+ N).subarray(0,P)}};return Object.freeze(D),Object.freeze(ee),Object.freeze({keygen:ha($,v),getPublicKey:v,sign:C,verify:R,utils:ee,Point:e,lengths:D})}var Ud=BigInt(0),at=BigInt(1),ya=BigInt(2);var Fd=BigInt(5),zd=BigInt(8),Kt=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Go={p:Kt,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:zd,
231
232
  a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6d\
232
- c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function $d(e){let t=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),i=zt,a=e*e%
233
- i*e%i,c=Me(a,pa,i)*a%i,l=Me(c,it,i)*e%i,p=Me(l,Od,i)*l%i,u=Me(p,t,i)*p%i,f=Me(u,n,i)*u%i,m=Me(f,r,i)*f%i,b=Me(m,o,i)*m%i,k=Me(b,o,i)*m%i,g=Me(k,t,i)*p%i;return {pow_p_5_8:Me(g,pa,i)*e%i,b2:a}}function Md(e){
234
- return e[0]&=248,e[31]&=127,e[31]|=64,e}var Mo=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Uo(e,t){let n=zt,r=re(t*t*t,n),o=re(r*r*t,n),i=$d(e*o).pow_p_5_8,
235
- s=re(e*r*i,n),a=re(t*s*s,n),c=s,l=re(s*Mo,n),p=a===e,u=a===re(-e,n),f=a===re(-e*Mo,n);return p&&(s=c),(u||f)&&(s=l),ot(s,n)&&(s=re(-s,n)),{isValid:p||u,value:s}}var ft=la(Bo,{uvRatio:Uo}),pt=ft.Fp,ha=ft.
236
- Fn;function Nd(e){return ua(ft,er,Object.assign({adjustScalarBytes:Md,zip215:true},e))}var ga=Nd({});var No=Mo;BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");var Bd=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt(
237
- "1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var fa=e=>Uo(it,e),zd=BigInt("0x7\
238
- fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),jo=e=>pt.create(rt(e)&zd);var mt=class e extends dr{static BASE=new e(
239
- ft.BASE);static ZERO=new e(ft.ZERO);static Fp=pt;static Fn=ha;constructor(t){super(t);}static fromAffine(t){return new e(ft.fromAffine(t))}assertSame(t){if(!(t instanceof e))throw new Error("RistrettoP\
240
- oint expected")}init(t){return new e(t)}static fromBytes(t){$e(t,32);let{a:n,d:r}=Bo,o=zt,i=y=>pt.create(y),s=jo(t);if(!zs(pt.toBytes(s),t)||ot(s,o))throw new Error("invalid ristretto255 encoding 1");
241
- let a=i(s*s),c=i(it+n*a),l=i(it-n*a),p=i(c*c),u=i(l*l),f=i(n*r*p-u),{isValid:m,value:b}=fa(i(f*u)),k=i(b*l),g=i(b*k*f),v=i((s+s)*k);ot(v,o)&&(v=i(-v));let x=i(c*g),E=i(v*x);if(!m||ot(E,o)||x===Dd)throw new Error(
242
- "invalid ristretto255 encoding 2");return new e(new ft(v,x,it,E))}static fromHex(t){return e.fromBytes(un(t))}toBytes(){let{X:t,Y:n,Z:r,T:o}=this.ep,i=zt,s=g=>pt.create(g),a=s(s(r+n)*s(r-n)),c=s(t*n),
243
- l=s(c*c),{value:p}=fa(s(a*l)),u=s(p*a),f=s(p*c),m=s(u*f*o),b;if(ot(o*m,i)){let g=s(n*No),v=s(t*No);t=g,n=v,b=s(u*Bd);}else b=f;ot(t*m,i)&&(n=s(-n));let k=s((r-n)*b);return ot(k,i)&&(k=s(-k)),pt.toBytes(
244
- k)}equals(t){this.assertSame(t);let{X:n,Y:r}=this.ep,{X:o,Y:i}=t.ep,s=l=>pt.create(l),a=s(n*i)===s(r*o),c=s(r*i)===s(n*o);return a||c}is0(){return this.equals(e.ZERO)}};Object.freeze(mt.BASE);Object.freeze(
245
- mt.ZERO);Object.freeze(mt.prototype);Object.freeze(mt);function pr(e){if(e.plan!=="measure"||typeof e.measure_expires_at!="number"||!Number.isFinite(e.measure_expires_at))return e;let t=typeof e.measure_grace_days=="number"&&Number.isFinite(e.measure_grace_days)?
246
- e.measure_grace_days:0;return {...e,expires_at:e.measure_expires_at,grace_days:Math.max(0,t)}}var St=`-----BEGIN PUBLIC KEY-----
233
+ c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Vd(e){let t=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),i=Kt,a=e*e%
234
+ i*e%i,c=Be(a,ya,i)*a%i,l=Be(c,at,i)*e%i,d=Be(l,Fd,i)*l%i,u=Be(d,t,i)*d%i,f=Be(u,n,i)*u%i,m=Be(f,r,i)*f%i,b=Be(m,o,i)*m%i,y=Be(b,o,i)*m%i,g=Be(y,t,i)*d%i;return {pow_p_5_8:Be(g,ya,i)*e%i,b2:a}}function qd(e){
235
+ return e[0]&=248,e[31]&=127,e[31]|=64,e}var Vo=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Wo(e,t){let n=Kt,r=re(t*t*t,n),o=re(r*r*t,n),i=Vd(e*o).pow_p_5_8,
236
+ s=re(e*r*i,n),a=re(t*s*s,n),c=s,l=re(s*Vo,n),d=a===e,u=a===re(-e,n),f=a===re(-e*Vo,n);return d&&(s=c),(u||f)&&(s=l),st(s,n)&&(s=re(-s,n)),{isValid:d||u,value:s}}var kt=ga(Go,{uvRatio:Wo}),yt=kt.Fp,xa=kt.
237
+ Fn;function Hd(e){return ba(kt,rr,Object.assign({adjustScalarBytes:qd,zip215:true},e))}var Sa=Hd({});var qo=Vo;BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");var Wd=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt(
238
+ "1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var ka=e=>Wo(at,e),Yd=BigInt("0x7\
239
+ fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Ho=e=>yt.create(it(e)&Yd);var wt=class e extends mr{static BASE=new e(
240
+ kt.BASE);static ZERO=new e(kt.ZERO);static Fp=yt;static Fn=xa;constructor(t){super(t);}static fromAffine(t){return new e(kt.fromAffine(t))}assertSame(t){if(!(t instanceof e))throw new Error("RistrettoP\
241
+ oint expected")}init(t){return new e(t)}static fromBytes(t){je(t,32);let{a:n,d:r}=Go,o=Kt,i=k=>yt.create(k),s=Ho(t);if(!Js(yt.toBytes(s),t)||st(s,o))throw new Error("invalid ristretto255 encoding 1");
242
+ let a=i(s*s),c=i(at+n*a),l=i(at-n*a),d=i(c*c),u=i(l*l),f=i(n*r*d-u),{isValid:m,value:b}=ka(i(f*u)),y=i(b*l),g=i(b*y*f),v=i((s+s)*y);st(v,o)&&(v=i(-v));let x=i(c*g),C=i(v*x);if(!m||st(C,o)||x===Ud)throw new Error(
243
+ "invalid ristretto255 encoding 2");return new e(new kt(v,x,at,C))}static fromHex(t){return e.fromBytes(mn(t))}toBytes(){let{X:t,Y:n,Z:r,T:o}=this.ep,i=Kt,s=g=>yt.create(g),a=s(s(r+n)*s(r-n)),c=s(t*n),
244
+ l=s(c*c),{value:d}=ka(s(a*l)),u=s(d*a),f=s(d*c),m=s(u*f*o),b;if(st(o*m,i)){let g=s(n*qo),v=s(t*qo);t=g,n=v,b=s(u*Wd);}else b=f;st(t*m,i)&&(n=s(-n));let y=s((r-n)*b);return st(y,i)&&(y=s(-y)),yt.toBytes(
245
+ y)}equals(t){this.assertSame(t);let{X:n,Y:r}=this.ep,{X:o,Y:i}=t.ep,s=l=>yt.create(l),a=s(n*i)===s(r*o),c=s(r*i)===s(n*o);return a||c}is0(){return this.equals(e.ZERO)}};Object.freeze(wt.BASE);Object.freeze(
246
+ wt.ZERO);Object.freeze(wt.prototype);Object.freeze(wt);function hr(e){if(e.plan!=="measure"||typeof e.measure_expires_at!="number"||!Number.isFinite(e.measure_expires_at))return e;let t=typeof e.measure_grace_days=="number"&&Number.isFinite(e.measure_grace_days)?
247
+ e.measure_grace_days:0;return {...e,expires_at:e.measure_expires_at,grace_days:Math.max(0,t)}}var Pt=`-----BEGIN PUBLIC KEY-----
247
248
  MCowBQYDK2VwAyEAWBiklf0kmDIVmM7nMiCxwiEAkwQIiqWGuRiRDJonsFY=
248
- -----END PUBLIC KEY-----`;function ba(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 Fo(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.
249
- length%4?"=".repeat(4-t.length%4):"";return ba(t+n)}function qd(e){let t=e.replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=ba(t);return n.subarray(n.length-32)}var Hd=new TextEncoder,va=new TextDecoder;
250
- function zo(e){return typeof e=="object"&&e!==null&&"keys"in e}function Vt(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 Gd=/^[A-Za-z0-9_-]+$/;
251
- function ya(e){let t=e.split(".");return t.length===3&&t.every(n=>Gd.test(n))}function hn(e){return e===""?"empty":ya(e)?"token":"malformed"}function gn(e,t){if(!ya(e))return {ok:false,reason:"malformed t\
252
- oken"};let n=e.split("."),r=n[0],o=n[1],i=n[2],s;try{s=JSON.parse(va.decode(Fo(r)));}catch{return {ok:false,reason:"header is not valid JSON"}}let a;if(zo(t)){let p=typeof s.kid=="string"?s.kid:t.defaultKid,
253
- u=t.keys[p];if(!u)return {ok:false,reason:`unknown key id "${p}"`};a=u;}else {if(!t)return {ok:false,reason:"no verification key"};a=t;}let c;try{if(c=qd(a),c.length!==32)return {ok:!1,reason:"invalid public key"}}catch{
254
- return {ok:false,reason:"invalid public key"}}let l=false;try{l=ga.verify(Fo(i),Hd.encode(`${r}.${o}`),c);}catch{return {ok:false,reason:"signature verification error"}}return l?{ok:true,header:s,payloadBytes:Fo(o)}:
255
- {ok:false,reason:"bad signature"}}function Vo(e,t){let n=gn(e,t);if(!n.ok||!n.payloadBytes)return {signatureValid:false,...n.reason?{reason:n.reason}:{}};try{let r=JSON.parse(va.decode(n.payloadBytes));return {
256
- signatureValid:!0,payload:pr(r)}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function fr(e,t,n){if(n?.has(e.jti))return "revoked";let r=e.expires_at+e.grace_days*86400;return t<=
257
- e.expires_at?"active":t<=r?"grace":"expired"}var ka="BVSALA-REVOC",Wd=300,Kd=new TextDecoder;function wa(e,t,n={}){let r=l=>({ok:false,seq:-1,asOf:0,revoked:new Set,reason:l}),o=gn(e,t);if(!o.ok||!o.payloadBytes)return r(o.reason??"bad signature");
258
- if(o.header?.typ!==ka)return r(`unexpected token type "${String(o.header?.typ??"")}" (want ${ka})`);let i;try{i=JSON.parse(Kd.decode(o.payloadBytes));}catch{return r("payload is not valid JSON")}if(typeof i.
249
+ -----END PUBLIC KEY-----`;function Ea(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 Ko(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.
250
+ length%4?"=".repeat(4-t.length%4):"";return Ea(t+n)}function Xd(e){let t=e.replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=Ea(t);return n.subarray(n.length-32)}var Qd=new TextEncoder,_a=new TextDecoder;
251
+ function Jo(e){return typeof e=="object"&&e!==null&&"keys"in e}function Jt(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 ep=/^[A-Za-z0-9_-]+$/;
252
+ function Ca(e){let t=e.split(".");return t.length===3&&t.every(n=>ep.test(n))}function yn(e){return e===""?"empty":Ca(e)?"token":"malformed"}function kn(e,t){if(!Ca(e))return {ok:false,reason:"malformed t\
253
+ oken"};let n=e.split("."),r=n[0],o=n[1],i=n[2],s;try{s=JSON.parse(_a.decode(Ko(r)));}catch{return {ok:false,reason:"header is not valid JSON"}}let a;if(Jo(t)){let d=typeof s.kid=="string"?s.kid:t.defaultKid,
254
+ u=t.keys[d];if(!u)return {ok:false,reason:`unknown key id "${d}"`};a=u;}else {if(!t)return {ok:false,reason:"no verification key"};a=t;}let c;try{if(c=Xd(a),c.length!==32)return {ok:!1,reason:"invalid public key"}}catch{
255
+ return {ok:false,reason:"invalid public key"}}let l=false;try{l=Sa.verify(Ko(i),Qd.encode(`${r}.${o}`),c);}catch{return {ok:false,reason:"signature verification error"}}return l?{ok:true,header:s,payloadBytes:Ko(o)}:
256
+ {ok:false,reason:"bad signature"}}function Yo(e,t){let n=kn(e,t);if(!n.ok||!n.payloadBytes)return {signatureValid:false,...n.reason?{reason:n.reason}:{}};try{let r=JSON.parse(_a.decode(n.payloadBytes));return {
257
+ signatureValid:!0,payload:hr(r)}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function gr(e,t,n){if(n?.has(e.jti))return "revoked";let r=e.expires_at+e.grace_days*86400;return t<=
258
+ e.expires_at?"active":t<=r?"grace":"expired"}var Ta="BVSALA-REVOC",tp=300,np=new TextDecoder;function Ra(e,t,n={}){let r=l=>({ok:false,seq:-1,asOf:0,revoked:new Set,reason:l}),o=kn(e,t);if(!o.ok||!o.payloadBytes)return r(o.reason??"bad signature");
259
+ if(o.header?.typ!==Ta)return r(`unexpected token type "${String(o.header?.typ??"")}" (want ${Ta})`);let i;try{i=JSON.parse(np.decode(o.payloadBytes));}catch{return r("payload is not valid JSON")}if(typeof i.
259
260
  seq!="number"||typeof i.asOf!="number"||!Array.isArray(i.revoked))return r("malformed revocation payload");let s=n.minSeq??0;if(i.seq<s)return r(`stale/rolled-back list (seq ${i.seq} < ${s})`);let a=n.
260
- nowSeconds??Math.floor(Date.now()/1e3),c=n.maxSkewSeconds??Wd;return i.asOf>a+c?r(`asOf too far in the future (${i.asOf} > ${a+c})`):{ok:true,seq:i.seq,asOf:i.asOf,revoked:new Set(i.revoked)}}var qt=class{_seq=-1;_asOf=0;_lastContactAt=0;set=new Set;get seq(){
261
+ nowSeconds??Math.floor(Date.now()/1e3),c=n.maxSkewSeconds??tp;return i.asOf>a+c?r(`asOf too far in the future (${i.asOf} > ${a+c})`):{ok:true,seq:i.seq,asOf:i.asOf,revoked:new Set(i.revoked)}}var Yt=class{_seq=-1;_asOf=0;_lastContactAt=0;set=new Set;get seq(){
261
262
  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.
262
263
  set}apply(t){if(t.seq<this._seq)return false;let n=this.set.size;for(let i of t.revoked)this.set.add(i);let r=this.set.size>n,o=t.seq>this._seq;return t.seq>this._seq&&(this._seq=t.seq),t.asOf>this._asOf&&
263
- (this._asOf=t.asOf),r||o}};function mr(e,t,n){let r=()=>Math.floor((n.now?n.now():Date.now())/1e3),o=n.startedAt??r(),i=Vt(e),s=hn(i),a=s==="token"?Vo(i,t):{signatureValid:false,reason:s},c=a.signatureValid?a.payload:void 0,l=new Set(
264
- c?.plan==="measure"?[]:c?.features??[]),p=()=>{if(s==="empty")return "none";if(!c)return "invalid";let f=fr(c,r(),n.revocation.snapshot());if(n.maxStalenessSeconds!=null&&(f==="active"||f==="grace")){let m=c.
265
- expires_at+c.grace_days*86400,b=Math.min(o,m),k=Math.max(n.revocation.lastContactAt,b);if(r()-k>n.maxStalenessSeconds)return "stale"}return f},u=()=>{let f=p();return f==="active"||f==="grace"};return {
266
- isEntitled:f=>u()&&l.has(f),isActive:()=>u(),status:p,reason:()=>c?void 0:a.reason,plan:()=>c&&u()?c.plan:void 0,refreshAfter:()=>{if(c)return Math.min(c.expires_at,r()+86400)}}}var Ht={pollIntervalSeconds:900,floorSeconds:300,maxIntervalSeconds:3600,jitterRatio:.1,maxSkewSeconds:300,requestTimeoutMs:3e4},xa=3,Jd=12;function Yd(e){let t=e.random??Math.random,n;if(e.consecutiveFailures>
264
+ (this._asOf=t.asOf),r||o}};function br(e,t,n){let r=()=>Math.floor((n.now?n.now():Date.now())/1e3),o=n.startedAt??r(),i=Jt(e),s=yn(i),a=s==="token"?Yo(i,t):{signatureValid:false,reason:s},c=a.signatureValid?a.payload:void 0,l=new Set(
265
+ c?.plan==="measure"?[]:c?.features??[]),d=()=>{if(s==="empty")return "none";if(!c)return "invalid";let f=gr(c,r(),n.revocation.snapshot());if(n.maxStalenessSeconds!=null&&(f==="active"||f==="grace")){let m=c.
266
+ expires_at+c.grace_days*86400,b=Math.min(o,m),y=Math.max(n.revocation.lastContactAt,b);if(r()-y>n.maxStalenessSeconds)return "stale"}return f},u=()=>{let f=d();return f==="active"||f==="grace"};return {
267
+ isEntitled:f=>u()&&l.has(f),isActive:()=>u(),status:d,reason:()=>c?void 0:a.reason,plan:()=>c&&u()?c.plan:void 0,refreshAfter:()=>{if(c)return Math.min(c.expires_at,r()+86400)}}}var Zt={pollIntervalSeconds:900,floorSeconds:300,maxIntervalSeconds:3600,jitterRatio:.1,maxSkewSeconds:300,requestTimeoutMs:3e4},Aa=3,rp=12;function op(e){let t=e.random??Math.random,n;if(e.consecutiveFailures>
267
268
  0){let o=Math.pow(2,Math.min(e.consecutiveFailures,4));n=Math.min(e.maxIntervalSeconds,e.floorSeconds*o);}else {let o=e.refreshAfter!=null?e.refreshAfter-e.nowSeconds:e.pollIntervalSeconds,i=o<0?e.pollIntervalSeconds:
268
- o;n=Math.min(e.pollIntervalSeconds,Math.max(e.floorSeconds,i));}let r=1+(t()*2-1)*e.jitterRatio;return Math.max(e.floorSeconds,n*r)}var Zd=10,bn=class{constructor(t){this.opts=t;}opts;timer=null;controller=null;consecutiveFailures=0;stopped=false;started=false;lastEtag=null;consecutive304=0;now(){
269
+ o;n=Math.min(e.pollIntervalSeconds,Math.max(e.floorSeconds,i));}let r=1+(t()*2-1)*e.jitterRatio;return Math.max(e.floorSeconds,n*r)}var ip=10,wn=class{constructor(t){this.opts=t;}opts;timer=null;controller=null;consecutiveFailures=0;stopped=false;started=false;lastEtag=null;consecutive304=0;now(){
269
270
  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();
270
271
  if(!t){this.avisar("sin-fetch","[bv-sala] no global fetch available; revocation call-home disabled (offline). License expiry is still enforced from the token."),this.opts.onEvent?.({type:"no-fetch"});
271
- return}let n=new AbortController;this.controller=n;let r=this.opts.requestTimeoutMs??Ht.requestTimeoutMs,o=setTimeout(()=>n.abort(),r);o.unref?.();let i={accept:"application/json"};this.lastEtag&&(i["\
272
+ return}let n=new AbortController;this.controller=n;let r=this.opts.requestTimeoutMs??Zt.requestTimeoutMs,o=setTimeout(()=>n.abort(),r);o.unref?.();let i={accept:"application/json"};this.lastEtag&&(i["\
272
273
  if-none-match"]=this.lastEtag);try{let s=await t(this.opts.url,{signal:n.signal,headers:i});if(s.status===304){this.consecutiveFailures=0,this.opts.snapshot.markContact(this.now()),this.opts.onEvent?.(
273
- {type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=Zd&&(this.consecutive304=0,this.lastEtag=null);return}if(this.consecutive304=0,!s.ok)throw new Error(`revocat\
274
- ions HTTP ${s.status}`);let a=s.headers.get("etag"),c=await s.json();if(!c.list)throw new Error("response missing `list`");this.consecutiveFailures=0;let l=wa(c.list,this.opts.publicKeyPem,{minSeq:this.
275
- opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??Ht.maxSkewSeconds});if(!l.ok){let u=l.reason??"rejected";this.opts.onEvent?.({type:"rejected",reason:u}),this.avisar(`r\
274
+ {type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=ip&&(this.consecutive304=0,this.lastEtag=null);return}if(this.consecutive304=0,!s.ok)throw new Error(`revocat\
275
+ ions HTTP ${s.status}`);let a=s.headers.get("etag"),c=await s.json();if(!c.list)throw new Error("response missing `list`");this.consecutiveFailures=0;let l=Ra(c.list,this.opts.publicKeyPem,{minSeq:this.
276
+ opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??Zt.maxSkewSeconds});if(!l.ok){let u=l.reason??"rejected";this.opts.onEvent?.({type:"rejected",reason:u}),this.avisar(`r\
276
277
  echazada:${u}`,`[bv-sala] the revocation list does NOT verify (${u}). The last known-good list is kept, so revocations ALREADY known still apply, but new ones are not arriving. Check ${this.opts.url}.`);
277
- return}a&&(this.lastEtag=a),this.opts.snapshot.markContact(this.now());let p=this.opts.snapshot.apply(l);this.opts.onEvent?.(p?{type:"applied",seq:l.seq,size:this.opts.snapshot.snapshot().size}:{type:"\
278
+ return}a&&(this.lastEtag=a),this.opts.snapshot.markContact(this.now());let d=this.opts.snapshot.apply(l);this.opts.onEvent?.(d?{type:"applied",seq:l.seq,size:this.opts.snapshot.snapshot().size}:{type:"\
278
279
  unchanged",seq:l.seq});}catch(s){this.consecutiveFailures++,this.opts.onEvent?.({type:"error",error:s}),this.avisarFalloDeRed(s);}finally{clearTimeout(o),this.controller=null;}}callado(){return !!this.opts.
279
- silenceWarnings}avisar(t,n){this.callado()||ee(`poller:${this.opts.url}:${t}`,n);}avisarFalloDeRed(t){if(this.callado())return;let n=this.consecutiveFailures;if(n<xa||(n-xa)%Jd!==0)return;let r=t instanceof
280
+ silenceWarnings}avisar(t,n){this.callado()||Q(`poller:${this.opts.url}:${t}`,n);}avisarFalloDeRed(t){if(this.callado())return;let n=this.consecutiveFailures;if(n<Aa||(n-Aa)%rp!==0)return;let r=t instanceof
280
281
  Error?t.message:String(t);console.warn(`[bv-sala] could not reach the revocation server ${n} times in a row (${r}). The license KEEPS working and known revocations still apply, but NEW ones are not ar\
281
- riving. Check egress to ${this.opts.url}.`);}start(){this.started||this.stopped||(this.started=true,this.pollOnce().finally(()=>this.schedule()));}schedule(){if(this.stopped)return;let t=Yd({refreshAfter:this.
282
- opts.getRefreshAfter?.(),nowSeconds:this.now(),consecutiveFailures:this.consecutiveFailures,floorSeconds:this.opts.floorSeconds??Ht.floorSeconds,pollIntervalSeconds:this.opts.pollIntervalSeconds??Ht.pollIntervalSeconds,
283
- maxIntervalSeconds:this.opts.maxIntervalSeconds??Ht.maxIntervalSeconds,jitterRatio:this.opts.jitterRatio??Ht.jitterRatio,...this.opts.random?{random:this.opts.random}:{}});this.timer=setTimeout(()=>{this.
284
- pollOnce().finally(()=>this.schedule());},t*1e3),this.timer.unref?.();}stop(){this.stopped=true,this.timer&&(clearTimeout(this.timer),this.timer=null),this.controller?.abort();}};var Xd="https://developers.openai.com/api/docs/pricing",Qd="https://ai.google.dev/gemini-api/docs/pricing",qo="2026-09-27",$=e=>({...e,fuente:Xd,consultado:qo}),He=e=>({...e,fuente:Qd,consultado:qo}),
285
- ep="https://platform.claude.com/docs/en/about-claude/pricing",le=e=>({...e,fuente:ep,consultado:qo});({openai:{flex:{"gpt-5":$({inputPer1k:625e-6,cachedInputPer1k:625e-7,outputPer1k:.005}),"gpt-5-mi\
286
- ni":$({inputPer1k:125e-6,cachedInputPer1k:125e-7,outputPer1k:.001}),"gpt-5-nano":$({inputPer1k:25e-6,cachedInputPer1k:25e-7,outputPer1k:2e-4}),"gpt-5.2":$({inputPer1k:875e-6,cachedInputPer1k:875e-7,outputPer1k:.007}),
287
- "gpt-5.4":$({inputPer1k:.00125,cachedInputPer1k:13e-5,outputPer1k:.0075,largo:{estandar:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225},tier:{inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.01125}}}),
288
- "gpt-5.4-mini":$({inputPer1k:375e-6,cachedInputPer1k:375e-7,outputPer1k:.00225}),"gpt-5.4-nano":$({inputPer1k:1e-4,cachedInputPer1k:1e-5,outputPer1k:625e-6}),"gpt-5.5":$({inputPer1k:.0025,cachedInputPer1k:25e-5,
289
- outputPer1k:.015,largo:{estandar:{inputPer1k:.01,cachedInputPer1k:.001,outputPer1k:.045},tier:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225}}}),"gpt-5.6-luna":$({inputPer1k:1e-4,cachedInputPer1k:1e-5,
282
+ riving. Check egress to ${this.opts.url}.`);}start(){this.started||this.stopped||(this.started=true,this.pollOnce().finally(()=>this.schedule()));}schedule(){if(this.stopped)return;let t=op({refreshAfter:this.
283
+ opts.getRefreshAfter?.(),nowSeconds:this.now(),consecutiveFailures:this.consecutiveFailures,floorSeconds:this.opts.floorSeconds??Zt.floorSeconds,pollIntervalSeconds:this.opts.pollIntervalSeconds??Zt.pollIntervalSeconds,
284
+ maxIntervalSeconds:this.opts.maxIntervalSeconds??Zt.maxIntervalSeconds,jitterRatio:this.opts.jitterRatio??Zt.jitterRatio,...this.opts.random?{random:this.opts.random}:{}});this.timer=setTimeout(()=>{this.
285
+ pollOnce().finally(()=>this.schedule());},t*1e3),this.timer.unref?.();}stop(){this.stopped=true,this.timer&&(clearTimeout(this.timer),this.timer=null),this.controller?.abort();}};var sp="https://developers.openai.com/api/docs/pricing",ap="https://ai.google.dev/gemini-api/docs/pricing",Zo="2026-09-27",M=e=>({...e,fuente:sp,consultado:Zo}),Ge=e=>({...e,fuente:ap,consultado:Zo}),
286
+ cp="https://platform.claude.com/docs/en/about-claude/pricing",ue=e=>({...e,fuente:cp,consultado:Zo});({openai:{flex:{"gpt-5":M({inputPer1k:625e-6,cachedInputPer1k:625e-7,outputPer1k:.005}),"gpt-5-mi\
287
+ ni":M({inputPer1k:125e-6,cachedInputPer1k:125e-7,outputPer1k:.001}),"gpt-5-nano":M({inputPer1k:25e-6,cachedInputPer1k:25e-7,outputPer1k:2e-4}),"gpt-5.2":M({inputPer1k:875e-6,cachedInputPer1k:875e-7,outputPer1k:.007}),
288
+ "gpt-5.4":M({inputPer1k:.00125,cachedInputPer1k:13e-5,outputPer1k:.0075,largo:{estandar:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225},tier:{inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.01125}}}),
289
+ "gpt-5.4-mini":M({inputPer1k:375e-6,cachedInputPer1k:375e-7,outputPer1k:.00225}),"gpt-5.4-nano":M({inputPer1k:1e-4,cachedInputPer1k:1e-5,outputPer1k:625e-6}),"gpt-5.5":M({inputPer1k:.0025,cachedInputPer1k:25e-5,
290
+ outputPer1k:.015,largo:{estandar:{inputPer1k:.01,cachedInputPer1k:.001,outputPer1k:.045},tier:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225}}}),"gpt-5.6-luna":M({inputPer1k:1e-4,cachedInputPer1k:1e-5,
290
291
  cacheWritePer1k:125e-6,outputPer1k:6e-4,largo:{estandar:{inputPer1k:4e-4,cachedInputPer1k:4e-5,cacheWritePer1k:5e-4,outputPer1k:.0018},tier:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,
291
- outputPer1k:9e-4}}}),"gpt-5.6-sol":$({inputPer1k:.002,cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.01,largo:{estandar:{inputPer1k:.008,cachedInputPer1k:8e-4,cacheWritePer1k:.01,outputPer1k:.03},
292
- tier:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.015}},vigenteHasta:"2026-11-21"}),"gpt-5.6-terra":$({inputPer1k:.001,cachedInputPer1k:1e-4,cacheWritePer1k:.00125,outputPer1k:.006,
293
- largo:{estandar:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.018},tier:{inputPer1k:.002,cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.009}}}),o3:$({inputPer1k:.001,
294
- cachedInputPer1k:25e-5,outputPer1k:.004}),"o4-mini":$({inputPer1k:55e-5,cachedInputPer1k:138e-6,outputPer1k:.0022}),"gpt-6-astra":$({inputPer1k:.005,cachedInputPer1k:5e-4,cacheWritePer1k:.00625,outputPer1k:.025,
295
- largo:{estandar:{inputPer1k:.02,cachedInputPer1k:.002,cacheWritePer1k:.025,outputPer1k:.075},tier:{inputPer1k:.01,cachedInputPer1k:.001,cacheWritePer1k:.0125,outputPer1k:.0375}}}),"gpt-6-sol":$({inputPer1k:.001,
292
+ outputPer1k:9e-4}}}),"gpt-5.6-sol":M({inputPer1k:.002,cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.01,largo:{estandar:{inputPer1k:.008,cachedInputPer1k:8e-4,cacheWritePer1k:.01,outputPer1k:.03},
293
+ tier:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.015}},vigenteHasta:"2026-11-21"}),"gpt-5.6-terra":M({inputPer1k:.001,cachedInputPer1k:1e-4,cacheWritePer1k:.00125,outputPer1k:.006,
294
+ largo:{estandar:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.018},tier:{inputPer1k:.002,cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.009}}}),o3:M({inputPer1k:.001,
295
+ cachedInputPer1k:25e-5,outputPer1k:.004}),"o4-mini":M({inputPer1k:55e-5,cachedInputPer1k:138e-6,outputPer1k:.0022}),"gpt-6-astra":M({inputPer1k:.005,cachedInputPer1k:5e-4,cacheWritePer1k:.00625,outputPer1k:.025,
296
+ largo:{estandar:{inputPer1k:.02,cachedInputPer1k:.002,cacheWritePer1k:.025,outputPer1k:.075},tier:{inputPer1k:.01,cachedInputPer1k:.001,cacheWritePer1k:.0125,outputPer1k:.0375}}}),"gpt-6-sol":M({inputPer1k:.001,
296
297
  cachedInputPer1k:1e-4,cacheWritePer1k:.00125,outputPer1k:.005,largo:{estandar:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.015},tier:{inputPer1k:.002,cachedInputPer1k:2e-4,
297
- cacheWritePer1k:.0025,outputPer1k:.0075}}}),"gpt-6-luna":$({inputPer1k:5e-5,cachedInputPer1k:5e-6,cacheWritePer1k:625e-7,outputPer1k:25e-5,largo:{estandar:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,
298
- outputPer1k:75e-5},tier:{inputPer1k:1e-4,cachedInputPer1k:1e-5,cacheWritePer1k:125e-6,outputPer1k:375e-6}}})},batch:{"gpt-6-astra":$({inputPer1k:.005,cachedInputPer1k:5e-4,cacheWritePer1k:.00625,outputPer1k:.025,
299
- largo:{estandar:{inputPer1k:.02,cachedInputPer1k:.002,cacheWritePer1k:.025,outputPer1k:.075},tier:{inputPer1k:.01,cachedInputPer1k:.001,cacheWritePer1k:.0125,outputPer1k:.0375}}}),"gpt-6-sol":$({inputPer1k:.001,
298
+ cacheWritePer1k:.0025,outputPer1k:.0075}}}),"gpt-6-luna":M({inputPer1k:5e-5,cachedInputPer1k:5e-6,cacheWritePer1k:625e-7,outputPer1k:25e-5,largo:{estandar:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,
299
+ outputPer1k:75e-5},tier:{inputPer1k:1e-4,cachedInputPer1k:1e-5,cacheWritePer1k:125e-6,outputPer1k:375e-6}}})},batch:{"gpt-6-astra":M({inputPer1k:.005,cachedInputPer1k:5e-4,cacheWritePer1k:.00625,outputPer1k:.025,
300
+ largo:{estandar:{inputPer1k:.02,cachedInputPer1k:.002,cacheWritePer1k:.025,outputPer1k:.075},tier:{inputPer1k:.01,cachedInputPer1k:.001,cacheWritePer1k:.0125,outputPer1k:.0375}}}),"gpt-6-sol":M({inputPer1k:.001,
300
301
  cachedInputPer1k:1e-4,cacheWritePer1k:.00125,outputPer1k:.005,largo:{estandar:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.015},tier:{inputPer1k:.002,cachedInputPer1k:2e-4,
301
- cacheWritePer1k:.0025,outputPer1k:.0075}}}),"gpt-6-luna":$({inputPer1k:5e-5,cachedInputPer1k:5e-6,cacheWritePer1k:625e-7,outputPer1k:25e-5,largo:{estandar:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,
302
- outputPer1k:75e-5},tier:{inputPer1k:1e-4,cachedInputPer1k:1e-5,cacheWritePer1k:125e-6,outputPer1k:375e-6}}}),"gpt-5.6-sol":$({inputPer1k:.002,cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.01,
302
+ cacheWritePer1k:.0025,outputPer1k:.0075}}}),"gpt-6-luna":M({inputPer1k:5e-5,cachedInputPer1k:5e-6,cacheWritePer1k:625e-7,outputPer1k:25e-5,largo:{estandar:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,
303
+ outputPer1k:75e-5},tier:{inputPer1k:1e-4,cachedInputPer1k:1e-5,cacheWritePer1k:125e-6,outputPer1k:375e-6}}}),"gpt-5.6-sol":M({inputPer1k:.002,cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.01,
303
304
  largo:{estandar:{inputPer1k:.008,cachedInputPer1k:8e-4,cacheWritePer1k:.01,outputPer1k:.03},tier:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.015}},vigenteHasta:"2026-11-21"}),
304
- "gpt-5.6-terra":$({inputPer1k:.001,cachedInputPer1k:1e-4,cacheWritePer1k:.00125,outputPer1k:.006,largo:{estandar:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.018},tier:{inputPer1k:.002,
305
- cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.009}}}),"gpt-5.6-luna":$({inputPer1k:1e-4,cachedInputPer1k:1e-5,cacheWritePer1k:125e-6,outputPer1k:6e-4,largo:{estandar:{inputPer1k:4e-4,cachedInputPer1k:4e-5,
306
- cacheWritePer1k:5e-4,outputPer1k:.0018},tier:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,outputPer1k:9e-4}}}),"gpt-5.5":$({inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.015,largo:{
307
- estandar:{inputPer1k:.01,cachedInputPer1k:.001,outputPer1k:.045},tier:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225}}}),"gpt-5.4":$({inputPer1k:.00125,cachedInputPer1k:13e-5,outputPer1k:.0075,
308
- largo:{estandar:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225},tier:{inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.01125}}}),"gpt-5.4-mini":$({inputPer1k:375e-6,cachedInputPer1k:375e-7,
309
- outputPer1k:.00225}),"gpt-5.4-nano":$({inputPer1k:1e-4,cachedInputPer1k:1e-5,outputPer1k:625e-6}),"gpt-5.2":$({inputPer1k:875e-6,cachedInputPer1k:875e-7,outputPer1k:.007}),"gpt-5":$({inputPer1k:625e-6,
310
- cachedInputPer1k:625e-7,outputPer1k:.005}),"gpt-5-mini":$({inputPer1k:125e-6,cachedInputPer1k:125e-7,outputPer1k:.001}),"gpt-5-nano":$({inputPer1k:25e-6,cachedInputPer1k:25e-7,outputPer1k:2e-4}),"gpt-\
311
- 4.1":$({inputPer1k:.001,outputPer1k:.004}),"gpt-4.1-mini":$({inputPer1k:2e-4,outputPer1k:8e-4}),"gpt-4.1-nano":$({inputPer1k:5e-5,outputPer1k:2e-4}),"gpt-4o":$({inputPer1k:.00125,outputPer1k:.005}),"g\
312
- pt-4o-mini":$({inputPer1k:75e-6,outputPer1k:3e-4}),o3:$({inputPer1k:.001,outputPer1k:.004}),"o4-mini":$({inputPer1k:55e-5,outputPer1k:.0022}),"o3-mini":$({inputPer1k:55e-5,outputPer1k:.0022}),"o3-pro":$(
313
- {inputPer1k:.01,outputPer1k:.04})}},anthropic:{batch:{"claude-fable-5-1":le({inputPer1k:.005,cachedInputPer1k:125e-6,cacheWritePer1k:.00625,outputPer1k:.025}),"claude-mythos-5-1":le({inputPer1k:.005,cachedInputPer1k:125e-6,
314
- cacheWritePer1k:.00625,outputPer1k:.025}),"claude-fable-5":le({inputPer1k:.005,cachedInputPer1k:5e-4,cacheWritePer1k:.00625,outputPer1k:.025}),"claude-mythos-5":le({inputPer1k:.005,cachedInputPer1k:5e-4,
315
- cacheWritePer1k:.00625,outputPer1k:.025}),"claude-opus-5-5":le({inputPer1k:.002,cachedInputPer1k:1e-4,cacheWritePer1k:.0025,outputPer1k:.01}),"claude-opus-5":le({inputPer1k:.0025,cachedInputPer1k:25e-5,
316
- cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-8":le({inputPer1k:.0025,cachedInputPer1k:25e-5,cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-7":le({inputPer1k:.0025,cachedInputPer1k:25e-5,
317
- cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-6":le({inputPer1k:.0025,cachedInputPer1k:25e-5,cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-5":le({inputPer1k:.0025,cachedInputPer1k:25e-5,
318
- cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4":le({inputPer1k:.0075,cachedInputPer1k:75e-5,cacheWritePer1k:.009375,outputPer1k:.0375}),"claude-sonnet-5":le({inputPer1k:.001,cachedInputPer1k:1e-4,
319
- cacheWritePer1k:.00125,outputPer1k:.005}),"claude-sonnet-5-5":{...le({inputPer1k:.001,cachedInputPer1k:1e-4,cacheWritePer1k:.00125,outputPer1k:.005})},"claude-sonnet-4-6":le({inputPer1k:.0015,
320
- cachedInputPer1k:15e-5,cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-sonnet-4-5":le({inputPer1k:.0015,cachedInputPer1k:15e-5,cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-sonnet-4":le({inputPer1k:.0015,
321
- cachedInputPer1k:15e-5,cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-haiku-4-5":le({inputPer1k:5e-4,cachedInputPer1k:5e-5,cacheWritePer1k:625e-6,outputPer1k:.0025}),"claude-3-5-haiku":le({inputPer1k:4e-4,
322
- cachedInputPer1k:4e-5,cacheWritePer1k:5e-4,outputPer1k:.002})}},google:{flex:{"gemini-3.7-flash":He({inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3\
323
- .5-flash":He({inputPer1k:75e-5,outputPer1k:.0045,cachedInputPer1k:8e-5}),"gemini-3.5-flash-lite":He({inputPer1k:15e-5,outputPer1k:.00125,cachedInputPer1k:2e-5}),"gemini-3.1-pro-preview":He({inputPer1k:.001,
324
- outputPer1k:.006,cachedInputPer1k:2e-4,largo:{estandar:{inputPer1k:.004,outputPer1k:.018,cachedInputPer1k:4e-4},tier:{inputPer1k:.002,outputPer1k:.009,cachedInputPer1k:4e-4}}}),"gemini-2.5-pro":He({inputPer1k:625e-6,
305
+ "gpt-5.6-terra":M({inputPer1k:.001,cachedInputPer1k:1e-4,cacheWritePer1k:.00125,outputPer1k:.006,largo:{estandar:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.018},tier:{inputPer1k:.002,
306
+ cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.009}}}),"gpt-5.6-luna":M({inputPer1k:1e-4,cachedInputPer1k:1e-5,cacheWritePer1k:125e-6,outputPer1k:6e-4,largo:{estandar:{inputPer1k:4e-4,cachedInputPer1k:4e-5,
307
+ cacheWritePer1k:5e-4,outputPer1k:.0018},tier:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,outputPer1k:9e-4}}}),"gpt-5.5":M({inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.015,largo:{
308
+ estandar:{inputPer1k:.01,cachedInputPer1k:.001,outputPer1k:.045},tier:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225}}}),"gpt-5.4":M({inputPer1k:.00125,cachedInputPer1k:13e-5,outputPer1k:.0075,
309
+ largo:{estandar:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225},tier:{inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.01125}}}),"gpt-5.4-mini":M({inputPer1k:375e-6,cachedInputPer1k:375e-7,
310
+ outputPer1k:.00225}),"gpt-5.4-nano":M({inputPer1k:1e-4,cachedInputPer1k:1e-5,outputPer1k:625e-6}),"gpt-5.2":M({inputPer1k:875e-6,cachedInputPer1k:875e-7,outputPer1k:.007}),"gpt-5":M({inputPer1k:625e-6,
311
+ cachedInputPer1k:625e-7,outputPer1k:.005}),"gpt-5-mini":M({inputPer1k:125e-6,cachedInputPer1k:125e-7,outputPer1k:.001}),"gpt-5-nano":M({inputPer1k:25e-6,cachedInputPer1k:25e-7,outputPer1k:2e-4}),"gpt-\
312
+ 4.1":M({inputPer1k:.001,outputPer1k:.004}),"gpt-4.1-mini":M({inputPer1k:2e-4,outputPer1k:8e-4}),"gpt-4.1-nano":M({inputPer1k:5e-5,outputPer1k:2e-4}),"gpt-4o":M({inputPer1k:.00125,outputPer1k:.005}),"g\
313
+ pt-4o-mini":M({inputPer1k:75e-6,outputPer1k:3e-4}),o3:M({inputPer1k:.001,outputPer1k:.004}),"o4-mini":M({inputPer1k:55e-5,outputPer1k:.0022}),"o3-mini":M({inputPer1k:55e-5,outputPer1k:.0022}),"o3-pro":M(
314
+ {inputPer1k:.01,outputPer1k:.04})}},anthropic:{batch:{"claude-fable-5-1":ue({inputPer1k:.005,cachedInputPer1k:125e-6,cacheWritePer1k:.00625,outputPer1k:.025}),"claude-mythos-5-1":ue({inputPer1k:.005,cachedInputPer1k:125e-6,
315
+ cacheWritePer1k:.00625,outputPer1k:.025}),"claude-fable-5":ue({inputPer1k:.005,cachedInputPer1k:5e-4,cacheWritePer1k:.00625,outputPer1k:.025}),"claude-mythos-5":ue({inputPer1k:.005,cachedInputPer1k:5e-4,
316
+ cacheWritePer1k:.00625,outputPer1k:.025}),"claude-opus-5-5":ue({inputPer1k:.002,cachedInputPer1k:1e-4,cacheWritePer1k:.0025,outputPer1k:.01}),"claude-opus-5":ue({inputPer1k:.0025,cachedInputPer1k:25e-5,
317
+ cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-8":ue({inputPer1k:.0025,cachedInputPer1k:25e-5,cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-7":ue({inputPer1k:.0025,cachedInputPer1k:25e-5,
318
+ cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-6":ue({inputPer1k:.0025,cachedInputPer1k:25e-5,cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-5":ue({inputPer1k:.0025,cachedInputPer1k:25e-5,
319
+ cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4":ue({inputPer1k:.0075,cachedInputPer1k:75e-5,cacheWritePer1k:.009375,outputPer1k:.0375}),"claude-sonnet-5":ue({inputPer1k:.001,cachedInputPer1k:1e-4,
320
+ cacheWritePer1k:.00125,outputPer1k:.005}),"claude-sonnet-5-5":{...ue({inputPer1k:.001,cachedInputPer1k:1e-4,cacheWritePer1k:.00125,outputPer1k:.005})},"claude-sonnet-4-6":ue({inputPer1k:.0015,
321
+ cachedInputPer1k:15e-5,cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-sonnet-4-5":ue({inputPer1k:.0015,cachedInputPer1k:15e-5,cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-sonnet-4":ue({inputPer1k:.0015,
322
+ cachedInputPer1k:15e-5,cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-haiku-4-5":ue({inputPer1k:5e-4,cachedInputPer1k:5e-5,cacheWritePer1k:625e-6,outputPer1k:.0025}),"claude-3-5-haiku":ue({inputPer1k:4e-4,
323
+ cachedInputPer1k:4e-5,cacheWritePer1k:5e-4,outputPer1k:.002})}},google:{flex:{"gemini-3.7-flash":Ge({inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3\
324
+ .5-flash":Ge({inputPer1k:75e-5,outputPer1k:.0045,cachedInputPer1k:8e-5}),"gemini-3.5-flash-lite":Ge({inputPer1k:15e-5,outputPer1k:.00125,cachedInputPer1k:2e-5}),"gemini-3.1-pro-preview":Ge({inputPer1k:.001,
325
+ outputPer1k:.006,cachedInputPer1k:2e-4,largo:{estandar:{inputPer1k:.004,outputPer1k:.018,cachedInputPer1k:4e-4},tier:{inputPer1k:.002,outputPer1k:.009,cachedInputPer1k:4e-4}}}),"gemini-2.5-pro":Ge({inputPer1k:625e-6,
325
326
  outputPer1k:.005,cachedInputPer1k:125e-6,largo:{estandar:{inputPer1k:.0025,outputPer1k:.015,cachedInputPer1k:25e-5},tier:{inputPer1k:.00125,outputPer1k:.0075,cachedInputPer1k:25e-5}}}),"gemini-2.5-fla\
326
- sh":He({inputPer1k:15e-5,outputPer1k:.00125,cachedInputPer1k:3e-5}),"gemini-3.8-flash":He({inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.6-flash":He(
327
- {inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.1-flash-lite":He({inputPer1k:125e-6,outputPer1k:75e-5,cachedInputPer1k:125e-7}),"gemini-3-flash-pre\
328
- view":He({inputPer1k:25e-5,outputPer1k:.0015,cachedInputPer1k:5e-5})}}});function Ho(e){let t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}function hr(e){let t=e.toLowerCase(),n=t.indexOf("/"),r=n>0?t.
329
- slice(0,n):"",o=Ho(t);return r==="openai"||r==="azure-openai"?"openai":r==="google"||r==="google-vertex"?"google":r==="anthropic"?"anthropic":/^(gpt-|o[1-9](-|$))/.test(o)?"openai":o.startsWith("gemin\
330
- i")?"google":o.startsWith("claude-")?"anthropic":null}var Sa={flex:.5,default:1,auto:1,priority:1,fast:1,scale:1,standard:1,batch:.5};Math.min(...Object.values(Sa).filter(e=>e<1));function gr(e){if(e==null||e==="")return null;let t=Sa[e];return t==null?{servido:e,factor:null,conDescuento:false}:{servido:e,factor:t,conDescuento:t<1}}var op={"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.\
327
+ sh":Ge({inputPer1k:15e-5,outputPer1k:.00125,cachedInputPer1k:3e-5}),"gemini-3.8-flash":Ge({inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.6-flash":Ge(
328
+ {inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.1-flash-lite":Ge({inputPer1k:125e-6,outputPer1k:75e-5,cachedInputPer1k:125e-7}),"gemini-3-flash-pre\
329
+ view":Ge({inputPer1k:25e-5,outputPer1k:.0015,cachedInputPer1k:5e-5})}}});function Xo(e){let t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}function vr(e){let t=e.toLowerCase(),n=t.indexOf("/"),r=n>0?t.
330
+ slice(0,n):"",o=Xo(t);return r==="openai"||r==="azure-openai"?"openai":r==="google"||r==="google-vertex"?"google":r==="anthropic"?"anthropic":/^(gpt-|o[1-9](-|$))/.test(o)?"openai":o.startsWith("gemin\
331
+ i")?"google":o.startsWith("claude-")?"anthropic":null}var Ia={flex:.5,default:1,auto:1,priority:1,fast:1,scale:1,standard:1,batch:.5};Math.min(...Object.values(Ia).filter(e=>e<1));function yr(e){if(e==null||e==="")return null;let t=Ia[e];return t==null?{servido:e,factor:null,conDescuento:false}:{servido:e,factor:t,conDescuento:t<1}}var pp={"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.\
331
332
  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\
332
333
  .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,
333
334
  "claude-opus-4-8":false,"claude-opus-5":true,"claude-opus-5-5":true,"claude-opus-4":false,"claude-sonnet-4-5":false,"claude-sonnet-4-6":false,"claude-sonnet-5":true,"claude-sonnet-5-5":true,"claude-fable-5":true,"claude-fa\
334
335
  ble-5-1":true,"claude-mythos-5-1":true,"claude-mythos-5":true,"claude-sonnet-4":false,"claude-haiku-4-5":false,"claude-3-5-sonnet":false,"claude-3-5-haiku":false,"claude-3-opus":false,"gemini-3.8-flash":true,"gemini-3.7-fla\
335
336
  sh":true,"gemini-3.6-flash":true,"gemini-3.1-flash-lite":true,"gemini-3-flash-preview":true,"gemini-3.5-flash":true,"gemini-3.5-flash-lite":true,"gemini-3.1-pro-preview":true,"gemini-2.5-pro":true,"gemini-2.5-flash":true},
336
- ip=new Set(["claude-opus-4-7","claude-opus-4-8"]),sp=[/^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($|[-_.])/,
337
- /^qwq/,/^qwen3/,/^glm-(4\.[5-9]|[5-9])/,/magistral/];function Go(e){let t=e.lastIndexOf("/"),n=(t>=0?e.slice(t+1):e).toLowerCase();if(sp.some(i=>i.test(n)))return "reasoning-model";let r=vt(e);if(r===void 0)
338
- return "unclassified-model";let o=op[r];if(o===true)return "reasoning-model";if(o!==false)return "unclassified-model";if(ip.has(r))return "temperature-ignored"}var Gt=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0;function Wo(e){if(!Array.isArray(e))return null;let t={input:0,output:0,cacheRead:0,cacheWrite:0,cacheWrite1h:0,iteraciones:0};for(let n of e){
339
- if(n===null||typeof n!="object")continue;let r=n;if(r.type!=="compaction")continue;t.iteraciones++,t.input+=Gt(r.input_tokens),t.output+=Gt(r.output_tokens),t.cacheRead+=Gt(r.cache_read_input_tokens);
340
- let o=r.cache_creation,i=Gt(o?.ephemeral_5m_input_tokens),s=Gt(o?.ephemeral_1h_input_tokens),a=typeof r.cache_creation_input_tokens=="number"?Gt(r.cache_creation_input_tokens):i+s;t.cacheWrite+=a,t.cacheWrite1h+=
341
- Math.min(s,a);}return t.iteraciones>0?t:null}var ap={anthropic:"explicit",openai:"automatic",google:"implicit",unknown:"unknown"};function Ko(e){return Math.round(e*1e10)/1e10}function Jo(e,t,n){let r=Math.max(0,n.leidos),o=Math.max(0,n.escritos),
342
- i=Math.min(o,Math.max(0,n.escritos1h));if(r===0&&o===0)return;let a=hr(e)??"unknown",c=ve(e),l=jt(e),p=t.cachedInputPer1k,u=p!==void 0&&Number.isFinite(p),f=p??t.inputPer1k,m=u?r/1e3*
343
- Math.max(0,t.inputPer1k-f):0,b=u?(o-i)/1e3*t.inputPer1k*Math.max(0,c-1)+i/1e3*t.inputPer1k*Math.max(0,l-1):0;return {provider:a,mechanism:ap[a],...n.marcadoPorLaCapa!==void 0?{layerMarked:n.marcadoPorLaCapa}:
344
- {},cacheReadTokens:r,cacheWriteTokens:o,cacheWrite1hTokens:i,inputPer1k:t.inputPer1k,cachedInputPer1k:f,writeMultiplier:c,write1hMultiplier:l,readDiscountUsd:Ko(m),writePremiumUsd:Ko(b),netUsd:Ko(m-b),
345
- basis:u?"measured":"unmeasured"}}var cp=new Set([null,"cyber","general_harms"]);function vr(e){if(e.stopReason!=="refusal")return false;let t=e.stopDetails;if(t===null||typeof t!="object"||Array.isArray(t))return false;let n=t;if(n.type!=="r\
346
- efusal"||!("category"in n))return false;let r=n.category;return !(r!==null&&typeof r!="string"||!cp.has(r)||e.bloques!==0||e.outputTokens!==0||Array.isArray(e.iterations)&&e.iterations.length>1)}var Xo="i(?:'m| am)? ?(?:"+["can't","cannot","can not","won't","will not","shouldn't","should not","unable to","not able to","not going to","not in a position to","not comfortable","don't feel comfort\
347
- able","do not feel comfortable","'d rather not","would rather not","don't think i can","do not think i can"].join("|")+")",Yo="(?:much|many times|happy|glad|grateful|excited|thankful|proud|sorry|impor\
348
- tant|good|great|amazing|nice|relieved|pleased|delighted|impressed|helpful|useful|valuable|lucky|blessed|thrilled|fun|cool|beautiful|wonderful)",lp=`(?:help(?! but| feeling| thinking| noticing| wonderi\
337
+ fp=new Set(["claude-opus-4-7","claude-opus-4-8"]),mp=[/^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($|[-_.])/,
338
+ /^qwq/,/^qwen3/,/^glm-(4\.[5-9]|[5-9])/,/magistral/];function Qo(e){let t=e.lastIndexOf("/"),n=(t>=0?e.slice(t+1):e).toLowerCase();if(mp.some(i=>i.test(n)))return "reasoning-model";let r=Ct(e);if(r===void 0)
339
+ return "unclassified-model";let o=pp[r];if(o===true)return "reasoning-model";if(o!==false)return "unclassified-model";if(fp.has(r))return "temperature-ignored"}var Xt=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0;function ei(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){
340
+ if(n===null||typeof n!="object")continue;let r=n;if(r.type!=="compaction")continue;t.iteraciones++,t.input+=Xt(r.input_tokens),t.output+=Xt(r.output_tokens),t.cacheRead+=Xt(r.cache_read_input_tokens);
341
+ let o=r.cache_creation,i=Xt(o?.ephemeral_5m_input_tokens),s=Xt(o?.ephemeral_1h_input_tokens),a=typeof r.cache_creation_input_tokens=="number"?Xt(r.cache_creation_input_tokens):i+s;t.cacheWrite+=a,t.cacheWrite1h+=
342
+ Math.min(s,a);}return t.iteraciones>0?t:null}var hp={anthropic:"explicit",openai:"automatic",google:"implicit",unknown:"unknown"};function ti(e){return Math.round(e*1e10)/1e10}function ni(e,t,n){let r=Math.max(0,n.leidos),o=Math.max(0,n.escritos),
343
+ i=Math.min(o,Math.max(0,n.escritos1h));if(r===0&&o===0)return;let a=vr(e)??"unknown",c=xe(e),l=qt(e),d=t.cachedInputPer1k,u=d!==void 0&&Number.isFinite(d),f=d??t.inputPer1k,m=u?r/1e3*
344
+ Math.max(0,t.inputPer1k-f):0,b=u?(o-i)/1e3*t.inputPer1k*Math.max(0,c-1)+i/1e3*t.inputPer1k*Math.max(0,l-1):0;return {provider:a,mechanism:hp[a],...n.marcadoPorLaCapa!==void 0?{layerMarked:n.marcadoPorLaCapa}:
345
+ {},cacheReadTokens:r,cacheWriteTokens:o,cacheWrite1hTokens:i,inputPer1k:t.inputPer1k,cachedInputPer1k:f,writeMultiplier:c,write1hMultiplier:l,readDiscountUsd:ti(m),writePremiumUsd:ti(b),netUsd:ti(m-b),
346
+ basis:u?"measured":"unmeasured"}}var gp=new Set([null,"cyber","general_harms"]);function wr(e){if(e.stopReason!=="refusal")return false;let t=e.stopDetails;if(t===null||typeof t!="object"||Array.isArray(t))return false;let n=t;if(n.type!=="r\
347
+ efusal"||!("category"in n))return false;let r=n.category;return !(r!==null&&typeof r!="string"||!gp.has(r)||e.bloques!==0||e.outputTokens!==0||Array.isArray(e.iterations)&&e.iterations.length>1)}var ii="i(?:'m| am)? ?(?:"+["can't","cannot","can not","won't","will not","shouldn't","should not","unable to","not able to","not going to","not in a position to","not comfortable","don't feel comfort\
348
+ able","do not feel comfortable","'d rather not","would rather not","don't think i can","do not think i can"].join("|")+")",ri="(?:much|many times|happy|glad|grateful|excited|thankful|proud|sorry|impor\
349
+ tant|good|great|amazing|nice|relieved|pleased|delighted|impressed|helpful|useful|valuable|lucky|blessed|thrilled|fun|cool|beautiful|wonderful)",bp=`(?:help(?! but| feeling| thinking| noticing| wonderi\
349
350
  ng| laughing| smiling| myself| it(?![\\p{L}]))|assist|provide|comply|fulfil|fulfill|create|write|generate|produce|give|share|support|engage|participate|answer|respond|discuss|offer|continue|draft|facil\
350
- itate|contribute|go along|go into|walk you through|explain how|describe how(?! ${Yo})|tell you how(?! ${Yo})|teach|instruct|encourage|condone|endorse|promote|role-?play|pretend|do that|do this|do so|w\
351
+ itate|contribute|go along|go into|walk you through|explain how|describe how(?! ${ri})|tell you how(?! ${ri})|teach|instruct|encourage|condone|endorse|promote|role-?play|pretend|do that|do this|do so|w\
351
352
  ith that|with this|with your request|with this request|that request|this request|determine|identify(?! any| anything| a single| no )|know|access|disclose|reveal|divulge|verify|confirm|locate|find(?! a\
352
353
  ny| anything| a single| no | nothing| it in me)|find out|track|trace|guess|predict|diagnose|recommend(?![^.!?]{0,60}enough)|prescribe|advise|look up|retrieve|obtain|browse|search|speculate|infer|asses\
353
- s|evaluate|comment on|speak to|give out|dox|tell (?:you )?(?:whether|if))`,up="i(?:'ll| will| must| need to|'d| would)?(?: have to)? ?(?:respectfully |politely )?decline",dp="(?:(?:that|this|it)(?:'s|\
354
+ s|evaluate|comment on|speak to|give out|dox|tell (?:you )?(?:whether|if))`,vp="i(?:'ll| will| must| need to|'d| would)?(?: have to)? ?(?:respectfully |politely )?decline",yp="(?:(?:that|this|it)(?:'s|\
354
355
  is) not something i(?:'m| am)? ?(?:can|will|able to|comfortable)|(?:it|that|this)(?:'s| is| would be| would not be| wouldn't be) (?:not )?(?:appropriate|ethical|responsible) for me to|i(?:'m| am) not\
355
356
  sure (?:that )?it(?:'s| is| would be) appropriate|(?:this|that|the|your) request (?:cannot|can't|can not|will not|won't) be (?:fulfilled|completed|processed|honou?red|accommodated|carried out|answere\
356
- d)|(?:this|that|your) request (?:is|would be) (?:considered )?(?:inappropriate|illegal|unlawful|unethical|harmful|dangerous|against|not appropriate|a violation))",pp="(?:(?:i'm |i am |i'm really |i am\
357
+ d)|(?:this|that|your) request (?:is|would be) (?:considered )?(?:inappropriate|illegal|unlawful|unethical|harmful|dangerous|against|not appropriate|a violation))",kp="(?:(?:i'm |i am |i'm really |i am\
357
358
  really |i'm so |really |so )?sorry|i apologi[sz]e|my apologies|apologies|unfortunately|regrettably|i'm afraid|i am afraid|as an ai|as a language model|as an assistant|i understand|i appreciate|thank \
358
- you for|thanks for|while i understand|while i appreciate)",d="\\p{L}*",Ta="no (?:puedo|voy a|me es posible|estoy en condiciones de|me siento c\xF3mod[oa])",fp=`(?:ayudar${d}|asistir${d}|proporcionar${d}\
359
- |facilitar${d}|dar${d}|ofrecer${d}|crear${d}|escribir${d}|generar${d}|compartir${d}|cumplir|responder${d}|colaborar|participar|atender${d}|hacer eso|hacerlo|con eso|con esto|con esa|con esta|con tu|de\
360
- terminar${d}|identificar${d}|saber${d}|acceder|revelar${d}|divulgar${d}|verificar${d}|confirmar${d}|localizar${d}|rastrear${d}|adivinar${d}|predecir${d}|diagnosticar${d}|recomendar${d}(?![^.!?]{0,60}s\
361
- uficiente)|recetar${d}|aconsejar${d})`,mp="(?:lo siento|lo lamento|siento|lamento|disculpa|disculpe|perd\xF3n|perdona|lamentablemente|desafortunadamente|me temo que|como (?:una )?(?:ia|inteligencia artif\
362
- icial|modelo de lenguaje|asistente)|entiendo)",Ra="no (?:puc|et puc|us puc|em sento c\xF2mod[ea]|estic en condicions de)",hp=`(?:ajudar${d}|assistir${d}|proporcionar${d}|facilitar${d}|donar${d}|oferir${d}\
363
- |crear${d}|escriure${d}|generar${d}|compartir${d}|complir|respondre${d}|col\xB7laborar|participar|fer aix\xF2|fer-ho|amb aix\xF2|amb aquesta|amb la teva|determinar${d}|identificar${d}|saber${d}|accedi\
364
- r|revelar${d}|divulgar${d}|verificar${d}|confirmar${d}|localitzar${d}|rastrejar${d}|endevinar${d}|predir${d}|diagnosticar${d}|recomanar${d}(?![^.!?]{0,60}prou)|receptar${d}|aconsellar${d})`,gp="(?:ho \
365
- sento|ho lamento|em sap greu|disculpa|disculpeu|perdona|malauradament|lamentablement|dissortadament|com a (?:ia|intel\xB7lig\xE8ncia artificial|model de llenguatge|assistent)|entenc)",Aa="(?:je ne (?:\
366
- peux|pourrai|pourrais|vais|souhaite)(?: malheureusement)? pas|je ne suis pas en mesure d[e']|je refuse d[e'])",bp="(?:aider|assister|fournir|r\xE9pondre|cr\xE9er|\xE9crire|g\xE9n\xE9rer|partager|donner|proposer|part\
359
+ you for|thanks for|while i understand|while i appreciate)",p="\\p{L}*",La="no (?:puedo|voy a|me es posible|estoy en condiciones de|me siento c\xF3mod[oa])",wp=`(?:ayudar${p}|asistir${p}|proporcionar${p}\
360
+ |facilitar${p}|dar${p}|ofrecer${p}|crear${p}|escribir${p}|generar${p}|compartir${p}|cumplir|responder${p}|colaborar|participar|atender${p}|hacer eso|hacerlo|con eso|con esto|con esa|con esta|con tu|de\
361
+ terminar${p}|identificar${p}|saber${p}|acceder|revelar${p}|divulgar${p}|verificar${p}|confirmar${p}|localizar${p}|rastrear${p}|adivinar${p}|predecir${p}|diagnosticar${p}|recomendar${p}(?![^.!?]{0,60}s\
362
+ uficiente)|recetar${p}|aconsejar${p})`,xp="(?:lo siento|lo lamento|siento|lamento|disculpa|disculpe|perd\xF3n|perdona|lamentablemente|desafortunadamente|me temo que|como (?:una )?(?:ia|inteligencia artif\
363
+ icial|modelo de lenguaje|asistente)|entiendo)",$a="no (?:puc|et puc|us puc|em sento c\xF2mod[ea]|estic en condicions de)",Sp=`(?:ajudar${p}|assistir${p}|proporcionar${p}|facilitar${p}|donar${p}|oferir${p}\
364
+ |crear${p}|escriure${p}|generar${p}|compartir${p}|complir|respondre${p}|col\xB7laborar|participar|fer aix\xF2|fer-ho|amb aix\xF2|amb aquesta|amb la teva|determinar${p}|identificar${p}|saber${p}|accedi\
365
+ r|revelar${p}|divulgar${p}|verificar${p}|confirmar${p}|localitzar${p}|rastrejar${p}|endevinar${p}|predir${p}|diagnosticar${p}|recomanar${p}(?![^.!?]{0,60}prou)|receptar${p}|aconsellar${p})`,Ep="(?:ho \
366
+ sento|ho lamento|em sap greu|disculpa|disculpeu|perdona|malauradament|lamentablement|dissortadament|com a (?:ia|intel\xB7lig\xE8ncia artificial|model de llenguatge|assistent)|entenc)",Ma="(?:je ne (?:\
367
+ peux|pourrai|pourrais|vais|souhaite)(?: malheureusement)? pas|je ne suis pas en mesure d[e']|je refuse d[e'])",_p="(?:aider|assister|fournir|r\xE9pondre|cr\xE9er|\xE9crire|g\xE9n\xE9rer|partager|donner|proposer|part\
367
368
  iciper|expliquer comment|acc\xE9der \xE0|satisfaire|faire cela|faire \xE7a|le faire|d\xE9terminer|identifier|savoir|divulguer|r\xE9v\xE9ler|v\xE9rifier|confirmer|localiser|retrouver|deviner|pr\xE9dire|diagnostiquer|prescrire\
368
- |conseiller|recommander(?![^.!?]{0,60}assez))",vp="(?:d\xE9sol\xE9e?|je suis d\xE9sol\xE9e?|je regrette|malheureusement|h\xE9las|je comprends|en tant qu'(?:ia|intelligence artificielle|mod\xE8le de langage|assistant))",
369
- Ia="(?:ich (?:kann|werde|darf|m\xF6chte)|(?:kann|werde|darf|m\xF6chte) ich)(?: \\p{L}+){0,4}? (?:nicht|keine\\p{L}*)(?: \\p{L}+){0,3}?",yp="(?:helfen|unterst\xFCtzen|bereitstellen|geben|erstellen|schreib\
369
+ |conseiller|recommander(?![^.!?]{0,60}assez))",Cp="(?:d\xE9sol\xE9e?|je suis d\xE9sol\xE9e?|je regrette|malheureusement|h\xE9las|je comprends|en tant qu'(?:ia|intelligence artificielle|mod\xE8le de langage|assistant))",
370
+ Na="(?:ich (?:kann|werde|darf|m\xF6chte)|(?:kann|werde|darf|m\xF6chte) ich)(?: \\p{L}+){0,4}? (?:nicht|keine\\p{L}*)(?: \\p{L}+){0,3}?",Tp="(?:helfen|unterst\xFCtzen|bereitstellen|geben|erstellen|schreib\
370
371
  en|generieren|beantworten|liefern|nachkommen|teilen|anbieten|erkl\xE4ren|behilflich sein|bestimmen|feststellen|identifizieren|wissen|zugreifen|preisgeben|offenlegen|verraten|\xFCberpr\xFCfen|best\xE4tigen|ausfind\
371
- ig machen|orten|verfolgen|erraten|vorhersagen|diagnostizieren|verschreiben|raten|sagen, ob)",kp="(?:es tut mir leid|tut mir leid|entschuldigung|entschuldige|leider|bedauerlicherweise|ich verstehe|als \
372
- (?:eine )?(?:ki|k\xFCnstliche intelligenz|sprachmodell|assistent))",Pa="non (?:posso|sono in grado di|riesco a|mi sento a mio agio (?:a|nel))",wp=`(?:aiutar${d}|assister${d}|fornir${d}|crear${d}|scriv\
373
- er${d}|generar${d}|condivider${d}|risponder${d}|dar${d}|offrir${d}|soddisfare|partecipare|farlo|fare questo|con questo|con questa|determinar${d}|identificar${d}|saper${d}|accedere|rivelar${d}|divulgar${d}\
374
- |verificar${d}|confermar${d}|localizzar${d}|rintracciar${d}|indovinar${d}|prevedere|diagnosticar${d}|prescriver${d}|consigliar${d}(?![^.!?]{0,60}abbastanza))`,xp="(?:mi dispiace|spiacente|purtroppo|sf\
375
- ortunatamente|capisco|come (?:un'?\\s?)?(?:ia|intelligenza artificiale|modello linguistico|assistente))",Da="n\xE3o (?:posso|consigo|vou|sou capaz de|estou em condi\xE7\xF5es de|me sinto confort\xE1vel (?:em|a))",
376
- Sp=`(?:ajudar${d}|auxiliar${d}|assistir${d}|fornecer${d}|criar${d}|escrever${d}|gerar${d}|compartilhar${d}|partilhar${d}|dar${d}|oferecer${d}|responder${d}|atender${d}|cumprir|participar|fazer isso|co\
377
- m isso|com esse|com essa|determinar${d}|identificar${d}|saber${d}|acessar|aceder|revelar${d}|divulgar${d}|verificar${d}|confirmar${d}|localizar${d}|rastrear${d}|adivinhar${d}|prever${d}|diagnosticar${d}\
378
- |receitar${d}|aconselhar${d}|recomendar${d}(?![^.!?]{0,60}o suficiente))`,Ep="(?:desculpe|desculpa|sinto muito|lamento|infelizmente|entendo|compreendo|como (?:uma? )?(?:ia|intelig\xEAncia artificial|mode\
379
- lo de linguagem|assistente))",Ct="(?:[\\s,]+[\\p{L}'\u2019-]+){0,4}?[\\s,]+",Qo=[`${Xo}${Ct}${lp}`,up,dp,`${Ta}${Ct}${fp}`,"lamento no poder","(?:esta|esa|la|tu) (?:solicitud|petici\xF3n) no (?:se )?pued\
380
- e (?:ser )?(?:atender|atendida|cumplir|cumplida|completar|completada|procesar|procesada)",`${Ra}${Ct}${hp}`,`${Aa}${Ct}${bp}`,`${Ia} ${yp}`,`${Pa}${Ct}${wp}`,`${Da}${Ct}${Sp}`].join("|"),_p=[pp,mp,gp,
381
- vp,kp,xp,Ep].join("|"),Cp=new RegExp(`^(?:${Qo})(?![\\p{L}])`,"u"),Tp=new RegExp(`^(?:${_p})(?![\\p{L}])`,"u"),Oa=new RegExp(`(?:^|[^\\p{L}'])(?:${Qo})(?![\\p{L}])`,"u"),Rp="(?:really|even|honestly|qu\
382
- ite|possibly|truly|personally|actually|simply|just|ever|always)",ei="i(?:'m| am)? ?(?:can't|cannot|can not|won't|will not|not going to|not able to|unable to)",Ap=["wait","believe","imagine (?:how|what\
372
+ ig machen|orten|verfolgen|erraten|vorhersagen|diagnostizieren|verschreiben|raten|sagen, ob)",Rp="(?:es tut mir leid|tut mir leid|entschuldigung|entschuldige|leider|bedauerlicherweise|ich verstehe|als \
373
+ (?:eine )?(?:ki|k\xFCnstliche intelligenz|sprachmodell|assistent))",ja="non (?:posso|sono in grado di|riesco a|mi sento a mio agio (?:a|nel))",Ap=`(?:aiutar${p}|assister${p}|fornir${p}|crear${p}|scriv\
374
+ er${p}|generar${p}|condivider${p}|risponder${p}|dar${p}|offrir${p}|soddisfare|partecipare|farlo|fare questo|con questo|con questa|determinar${p}|identificar${p}|saper${p}|accedere|rivelar${p}|divulgar${p}\
375
+ |verificar${p}|confermar${p}|localizzar${p}|rintracciar${p}|indovinar${p}|prevedere|diagnosticar${p}|prescriver${p}|consigliar${p}(?![^.!?]{0,60}abbastanza))`,Ip="(?:mi dispiace|spiacente|purtroppo|sf\
376
+ ortunatamente|capisco|come (?:un'?\\s?)?(?:ia|intelligenza artificiale|modello linguistico|assistente))",Ba="n\xE3o (?:posso|consigo|vou|sou capaz de|estou em condi\xE7\xF5es de|me sinto confort\xE1vel (?:em|a))",
377
+ Pp=`(?:ajudar${p}|auxiliar${p}|assistir${p}|fornecer${p}|criar${p}|escrever${p}|gerar${p}|compartilhar${p}|partilhar${p}|dar${p}|oferecer${p}|responder${p}|atender${p}|cumprir|participar|fazer isso|co\
378
+ m isso|com esse|com essa|determinar${p}|identificar${p}|saber${p}|acessar|aceder|revelar${p}|divulgar${p}|verificar${p}|confirmar${p}|localizar${p}|rastrear${p}|adivinhar${p}|prever${p}|diagnosticar${p}\
379
+ |receitar${p}|aconselhar${p}|recomendar${p}(?![^.!?]{0,60}o suficiente))`,Dp="(?:desculpe|desculpa|sinto muito|lamento|infelizmente|entendo|compreendo|como (?:uma? )?(?:ia|intelig\xEAncia artificial|mode\
380
+ lo de linguagem|assistente))",Lt="(?:[\\s,]+[\\p{L}'\u2019-]+){0,4}?[\\s,]+",si=[`${ii}${Lt}${bp}`,vp,yp,`${La}${Lt}${wp}`,"lamento no poder","(?:esta|esa|la|tu) (?:solicitud|petici\xF3n) no (?:se )?pued\
381
+ e (?:ser )?(?:atender|atendida|cumplir|cumplida|completar|completada|procesar|procesada)",`${$a}${Lt}${Sp}`,`${Ma}${Lt}${_p}`,`${Na} ${Tp}`,`${ja}${Lt}${Ap}`,`${Ba}${Lt}${Pp}`].join("|"),Op=[kp,xp,Ep,
382
+ Cp,Rp,Ip,Dp].join("|"),Lp=new RegExp(`^(?:${si})(?![\\p{L}])`,"u"),$p=new RegExp(`^(?:${Op})(?![\\p{L}])`,"u"),Ua=new RegExp(`(?:^|[^\\p{L}'])(?:${si})(?![\\p{L}])`,"u"),Mp="(?:really|even|honestly|qu\
383
+ ite|possibly|truly|personally|actually|simply|just|ever|always)",ai="i(?:'m| am)? ?(?:can't|cannot|can not|won't|will not|not going to|not able to|unable to)",Np=["wait","believe","imagine (?:how|what\
383
384
  |why|anything|anyone|anybody|life|living|being|a (?:better|world|life|time|single))","thank","stress","(?:over|under)?emphasi[sz]e","overstate","understate","exaggerate","(?:recommend|praise|rave abou\
384
385
  t|speak highly of|say enough good)[^.!?]{0,60}enough","say enough","get enough","help (?:but|feeling|thinking|noticing|wondering|laughing|smiling|myself|it)",`(?:tell you|say|express|describe|explain|\
385
- put into words) (?:how|what a) ${Yo}`,"express (?:my|our) (?:gratitude|thanks|appreciation)","begin to (?:describe|imagine|tell|express|thank|understand|fathom|comprehend|count)","agree (?:more|with y\
386
+ put into words) (?:how|what a) ${ri}`,"express (?:my|our) (?:gratitude|thanks|appreciation)","begin to (?:describe|imagine|tell|express|thank|understand|fathom|comprehend|count)","agree (?:more|with y\
386
387
  ou more)","complain","disagree","deny (?:that|it|this|the)","fault (?:you|it|that|this|the)","argue with (?:that|this|you|those|these|the (?:logic|results|data|numbers|math|facts))","find (?:any|anyth\
387
388
  ing|a single|no|nothing)","identify (?:any|anything|a single)","spot (?:any|anything|a single)","see (?:any|anything|a single|why not|a (?:reason|problem|downside|issue|bug))","think of (?:any|anythin\
388
389
  g|a (?:reason|better|single|downside))","lie","sugar-?coat(?: it| this| that)?","bore you","belabou?r","rehash","judge you","keep you","get over","resist","top (?:that|this)","go wrong","say (?:that )\
389
390
  ?i","pretend (?:otherwise|(?:that )?(?:i'm|i am|it's|it is|this is|everything|there's|there is|we|you))","remember (?:a time|the last time|when i)","stop (?:thinking|smiling|laughing|listening|reading\
390
- |talking about)"],Ip="(?:be (?:100% |completely |entirely |absolutely |totally |fully |one hundred percent )?(?:sure|certain)|say (?:for (?:sure|certain)|with (?:certainty|confidence)|definitively|exa\
391
+ |talking about)"],jp="(?:be (?:100% |completely |entirely |absolutely |totally |fully |one hundred percent )?(?:sure|certain)|say (?:for (?:sure|certain)|with (?:certainty|confidence)|definitively|exa\
391
392
  ctly|precisely|for a fact)|know (?:for (?:sure|certain)|exactly|precisely)|guarantee|promise|speak for|vouch for|recall|remember|run|test|execute|see (?:your|the) (?:screen|code|file|image|output|logs\
392
- ?))[^.!?]{0,160}?(?:,|\\s)(?:but|however)(?![\\p{L}])",yr=`(?:${Rp} ){0,2}(?:(?:${Ap.join("|")})(?![\\p{L}])|${Ip})`,La="no (?:(?:te|le|les|os|lo|la|me|se) )?(?:puedo|voy a)",Pp=["esperar",`creer${d}`,
393
- `imaginar${d}`,"dejar de",`evitar${d}`,`agradecer${d}`,`negar${d}`,`mentir${d}`,`quejar${d}`,"estar m\xE1s",`(?:encontrar|ver|detectar|identificar|notar)${d} (?:ning\xFAn|ninguna|ningun|nada|ni un|motivo\
394
- para no|raz\xF3n para no)`,`recomendar${d}[^.!?]{0,60}(?:suficiente|bastante)`,`(?:enfatizar|recalcar|subrayar|insistir|exagerar|ponderar)${d}`,`(?:decir|expresar)${d} (?:lo|cu\xE1nto|cuanto|c\xF3mo de|com\
395
- o de)`,`resistir${d}`,"m\xE1s que","sino","pedir m\xE1s"],Dp=`(?:estar (?:100 ?% |completamente |totalmente |del todo )?segur[oa]|asegurar${d}|garantizar${d}|prometer${d}|(?:decir|saber|afirmar)${d} c\
396
- on (?:certeza|seguridad|exactitud)|ejecutar${d}|probar${d}|recordar${d}|ver (?:tu|la|el) (?:pantalla|c\xF3digo|archivo))[^.!?]{0,160}?(?:,|\\s)(?:pero|aunque|sin embargo)(?![\\p{L}])`,ti=`(?:(?:${Pp.join(
397
- "|")})(?![\\p{L}])|${Dp})`,$a="no (?:(?:et|us|el|la|ho|em|li|els|les) )?(?:puc|penso|podr\xE9)",Op=[`esperar${d}`,`creure${d}`,`imaginar${d}`,"deixar de",`evitar${d}`,`agrair${d}`,`negar${d}`,`mentir${d}`,
398
- `queixar${d}`,"estar m\xE9s",`(?:trobar|veure|detectar|identificar)${d} (?:cap|res|ni un|ni una)`,`recomanar${d}[^.!?]{0,60}prou`,`(?:emfatitzar|remarcar|subratllar|insistir|exagerar)${d}`,`dir${d} (?\
399
- :com de|quant|prou)`,`resistir${d}`,"m\xE9s que","sin\xF3","fer altra cosa que"],Lp=`(?:estar (?:100 ?% |completament |del tot )?segura?|assegurar${d}|garantir${d}|prometre${d}|(?:dir|saber|afirmar)${d}\
400
- amb (?:certesa|seguretat)|executar${d}|provar${d}|recordar${d})[^.!?]{0,160}?(?:,|\\s)(?:per\xF2|pero|tot i que)(?![\\p{L}])`,ni=`(?:(?:${Op.join("|")})(?![\\p{L}])|${Lp})`,Ma="je ne (?:peux|pourrai|\
401
- pourrais|vais)(?: malheureusement)? pas",$p="(?:vous |te |t'|me |m'|le |la |les |l'|lui |leur |y |en |se |s')",Mp=["attendre","croire","imaginer","emp\xEAcher","remercier","(?:trop |assez )?(?:insiste\
393
+ ?))[^.!?]{0,160}?(?:,|\\s)(?:but|however)(?![\\p{L}])",xr=`(?:${Mp} ){0,2}(?:(?:${Np.join("|")})(?![\\p{L}])|${jp})`,Fa="no (?:(?:te|le|les|os|lo|la|me|se) )?(?:puedo|voy a)",Bp=["esperar",`creer${p}`,
394
+ `imaginar${p}`,"dejar de",`evitar${p}`,`agradecer${p}`,`negar${p}`,`mentir${p}`,`quejar${p}`,"estar m\xE1s",`(?:encontrar|ver|detectar|identificar|notar)${p} (?:ning\xFAn|ninguna|ningun|nada|ni un|motivo\
395
+ para no|raz\xF3n para no)`,`recomendar${p}[^.!?]{0,60}(?:suficiente|bastante)`,`(?:enfatizar|recalcar|subrayar|insistir|exagerar|ponderar)${p}`,`(?:decir|expresar)${p} (?:lo|cu\xE1nto|cuanto|c\xF3mo de|com\
396
+ o de)`,`resistir${p}`,"m\xE1s que","sino","pedir m\xE1s"],Up=`(?:estar (?:100 ?% |completamente |totalmente |del todo )?segur[oa]|asegurar${p}|garantizar${p}|prometer${p}|(?:decir|saber|afirmar)${p} c\
397
+ on (?:certeza|seguridad|exactitud)|ejecutar${p}|probar${p}|recordar${p}|ver (?:tu|la|el) (?:pantalla|c\xF3digo|archivo))[^.!?]{0,160}?(?:,|\\s)(?:pero|aunque|sin embargo)(?![\\p{L}])`,ci=`(?:(?:${Bp.join(
398
+ "|")})(?![\\p{L}])|${Up})`,za="no (?:(?:et|us|el|la|ho|em|li|els|les) )?(?:puc|penso|podr\xE9)",Fp=[`esperar${p}`,`creure${p}`,`imaginar${p}`,"deixar de",`evitar${p}`,`agrair${p}`,`negar${p}`,`mentir${p}`,
399
+ `queixar${p}`,"estar m\xE9s",`(?:trobar|veure|detectar|identificar)${p} (?:cap|res|ni un|ni una)`,`recomanar${p}[^.!?]{0,60}prou`,`(?:emfatitzar|remarcar|subratllar|insistir|exagerar)${p}`,`dir${p} (?\
400
+ :com de|quant|prou)`,`resistir${p}`,"m\xE9s que","sin\xF3","fer altra cosa que"],zp=`(?:estar (?:100 ?% |completament |del tot )?segura?|assegurar${p}|garantir${p}|prometre${p}|(?:dir|saber|afirmar)${p}\
401
+ amb (?:certesa|seguretat)|executar${p}|provar${p}|recordar${p})[^.!?]{0,160}?(?:,|\\s)(?:per\xF2|pero|tot i que)(?![\\p{L}])`,li=`(?:(?:${Fp.join("|")})(?![\\p{L}])|${zp})`,Va="je ne (?:peux|pourrai|\
402
+ pourrais|vais)(?: malheureusement)? pas",Vp="(?:vous |te |t'|me |m'|le |la |les |l'|lui |leur |y |en |se |s')",qp=["attendre","croire","imaginer","emp\xEAcher","remercier","(?:trop |assez )?(?:insiste\
402
403
  r|souligner|exag\xE9rer)","mentir","nier","plaindre","\xEAtre plus","(?:trouver|voir|d\xE9tecter|identifier|rep\xE9rer) (?:aucun|aucune|rien|de (?:probl\xE8me|raison|souci))","dire (?:\xE0 quel point|com\
403
- bien|assez)","recommander[^.!?]{0,60}assez","r\xE9sister","faire autrement que"],Np="(?:\xEAtre (?:(?:tout \xE0 fait|absolument|enti\xE8rement|100 ?%) )?(?:s\xFBre?|certaine?)|garantir|promettre|affirmer|dire ave\
404
- c certitude|ex\xE9cuter|tester|souvenir|rappeler|voir (?:votre|ton|ta|le|la) (?:\xE9cran|code|fichier))[^.!?]{0,160}?(?:,|\\s)(?:mais|cependant|toutefois)(?![\\p{L}])",ri=`${$p}*(?:(?:${Mp.join("|")})\
405
- (?![\\p{L}])|${Np})`,Na="non (?:(?:ti|vi|la|lo|le|gli|ne|mi|ci) )?(?:posso|riesco a|sono in grado di|ho intenzione di)",jp=[`aspettar${d}`,`creder${d}`,`immaginar${d}`,"fare a meno",`ringraziar${d}`,"\
406
- che","non",`negar${d}`,`mentir${d}`,`lamentar${d}`,"(?:essere|esser) pi\xF9",`(?:trovare|vedere|notare|individuare|rilevare) (?:nessun${d}|niente|alcun${d}|un solo)`,`consigliar${d}[^.!?]{0,60}abbasta\
407
- nza`,`(?:sottolinear|enfatizzar|insister|esagerar)${d}`,`dir${d} (?:quanto|abbastanza)`,`resister${d}`],Bp=`(?:(?:esserne|essere) (?:del tutto |completamente |al 100 ?% )?(?:sicur[oa]|cert[oa])|garant\
408
- ir${d}|prometter${d}|(?:dir|affermar)${d} con certezza|eseguir${d}|testar${d}|ricordar${d})[^.!?]{0,160}?(?:,|\\s)(?:ma|per\xF2|tuttavia)(?![\\p{L}])`,oi=`(?:(?:${jp.join("|")})(?![\\p{L}])|${Bp})`,ja="\
409
- n\xE3o (?:(?:te|lhe|lhes|vos|o|a|me) )?(?:posso|consigo|vou|sou capaz de)",Up=["esperar","acreditar",`imaginar${d}`,"deixar de",`evitar${d}`,`agradecer${d}`,`negar${d}`,`mentir${d}`,`(?:me )?(?:queixa\
410
- r|reclamar)${d}`,"concordar mais","estar mais","sen\xE3o","(?:fazer )?mais (?:do )?que",`(?:encontrar|ver|identificar|detetar|detectar|notar) (?:nenhum${d}|nada|um \xFAnico|uma \xFAnica)`,`recomendar${d}\
411
- [^.!?]{0,60}(?:o )?suficiente`,`(?:enfatizar|sublinhar|ressaltar|insistir|exagerar)${d}`,`dizer${d} (?:o quanto|quanto|como|o suficiente)`,`resistir${d}`],Fp=`(?:ter (?:a )?certeza|estar (?:100 ?% |co\
412
- mpletamente |totalmente )?(?:segur[oa]|cert[oa])|garantir${d}|prometer${d}|(?:dizer|afirmar|saber)${d} com (?:certeza|seguran\xE7a)|executar${d}|testar${d}|lembrar${d})[^.!?]{0,160}?(?:,|\\s)(?:mas|por\
413
- \xE9m|contudo)(?![\\p{L}])`,ii=`(?:(?:${Up.join("|")})(?![\\p{L}])|${Fp})`,Ba="(?:ich (?:kann|werde|darf)|kann ich|werde ich)",zp=["(?:kaum|nicht) erwarten","glauben","vorstellen","genug (?:danken|bet\
404
+ bien|assez)","recommander[^.!?]{0,60}assez","r\xE9sister","faire autrement que"],Hp="(?:\xEAtre (?:(?:tout \xE0 fait|absolument|enti\xE8rement|100 ?%) )?(?:s\xFBre?|certaine?)|garantir|promettre|affirmer|dire ave\
405
+ c certitude|ex\xE9cuter|tester|souvenir|rappeler|voir (?:votre|ton|ta|le|la) (?:\xE9cran|code|fichier))[^.!?]{0,160}?(?:,|\\s)(?:mais|cependant|toutefois)(?![\\p{L}])",ui=`${Vp}*(?:(?:${qp.join("|")})\
406
+ (?![\\p{L}])|${Hp})`,qa="non (?:(?:ti|vi|la|lo|le|gli|ne|mi|ci) )?(?:posso|riesco a|sono in grado di|ho intenzione di)",Gp=[`aspettar${p}`,`creder${p}`,`immaginar${p}`,"fare a meno",`ringraziar${p}`,"\
407
+ che","non",`negar${p}`,`mentir${p}`,`lamentar${p}`,"(?:essere|esser) pi\xF9",`(?:trovare|vedere|notare|individuare|rilevare) (?:nessun${p}|niente|alcun${p}|un solo)`,`consigliar${p}[^.!?]{0,60}abbasta\
408
+ nza`,`(?:sottolinear|enfatizzar|insister|esagerar)${p}`,`dir${p} (?:quanto|abbastanza)`,`resister${p}`],Wp=`(?:(?:esserne|essere) (?:del tutto |completamente |al 100 ?% )?(?:sicur[oa]|cert[oa])|garant\
409
+ ir${p}|prometter${p}|(?:dir|affermar)${p} con certezza|eseguir${p}|testar${p}|ricordar${p})[^.!?]{0,160}?(?:,|\\s)(?:ma|per\xF2|tuttavia)(?![\\p{L}])`,di=`(?:(?:${Gp.join("|")})(?![\\p{L}])|${Wp})`,Ha="\
410
+ n\xE3o (?:(?:te|lhe|lhes|vos|o|a|me) )?(?:posso|consigo|vou|sou capaz de)",Kp=["esperar","acreditar",`imaginar${p}`,"deixar de",`evitar${p}`,`agradecer${p}`,`negar${p}`,`mentir${p}`,`(?:me )?(?:queixa\
411
+ r|reclamar)${p}`,"concordar mais","estar mais","sen\xE3o","(?:fazer )?mais (?:do )?que",`(?:encontrar|ver|identificar|detetar|detectar|notar) (?:nenhum${p}|nada|um \xFAnico|uma \xFAnica)`,`recomendar${p}\
412
+ [^.!?]{0,60}(?:o )?suficiente`,`(?:enfatizar|sublinhar|ressaltar|insistir|exagerar)${p}`,`dizer${p} (?:o quanto|quanto|como|o suficiente)`,`resistir${p}`],Jp=`(?:ter (?:a )?certeza|estar (?:100 ?% |co\
413
+ mpletamente |totalmente )?(?:segur[oa]|cert[oa])|garantir${p}|prometer${p}|(?:dizer|afirmar|saber)${p} com (?:certeza|seguran\xE7a)|executar${p}|testar${p}|lembrar${p})[^.!?]{0,160}?(?:,|\\s)(?:mas|por\
414
+ \xE9m|contudo)(?![\\p{L}])`,pi=`(?:(?:${Kp.join("|")})(?![\\p{L}])|${Jp})`,Ga="(?:ich (?:kann|werde|darf)|kann ich|werde ich)",Yp=["(?:kaum|nicht) erwarten","glauben","vorstellen","genug (?:danken|bet\
414
415
  onen|empfehlen|loben|sagen|hervorheben)","oft genug","\\p{L}*l\xFCgen","leugnen","bestreiten","beschweren","beklagen","(?:mehr|besser) zustimmen","widerstehen","keine?n? (?:fehler|probleme?|grund|hake\
415
- n|m\xE4ngel|bugs?|nachteile?|einw\xE4nde?)","sagen, wie (?:sehr|froh|dankbar|gl\xFCcklich)"],Vp="(?:(?:mit )?sicherheit|genau|garantieren|versprechen|100 ?%|ausf\xFChren|testen|erinnern)[^.!?]{0,160}?(?:\
416
- ,|\\s)(?:aber|jedoch|allerdings)(?![\\p{L}])",Ua=`[^.!?]*?(?<![\\p{L}])(?:(?:${zp.join("|")})(?![\\p{L}])|${Vp})`,Fa="(?:no[,.!]? |non[,.!]? |n\xE3o[,.!]? |nein[,.!]? )?",qp=new RegExp("^"+Fa+"(?:"+[`${ei}\
417
- \\s(?!${yr})\\p{L}`,`${La}\\s(?!${ti})\\p{L}`,`${$a}\\s(?!${ni})\\p{L}`,`${Ma}\\s?(?!${ri})\\p{L}`,`${Na}\\s(?!${oi})\\p{L}`,`${ja}\\s(?!${ii})\\p{L}`,`${Ba}(?!${Ua})(?:\\s[\\p{L}\\p{N}'-]+){0,6}?\\s(?:ni\
418
- cht|keine?\\p{L}*)(?![\\p{L}])(?!\\s(?:nur|mehr als|anders|umhin))`].join("|")+")","u"),Hp=new RegExp("^"+Fa+"(?:"+[`${ei}\\s(?=${yr})`,`${La}\\s(?=${ti})`,`${$a}\\s(?=${ni})`,`${Ma}\\s?(?=${ri})`,`${Na}\
419
- \\s(?=${oi})`,`${ja}\\s(?=${ii})`,`${Ba}(?=${Ua})`].join("|")+")","u"),Gp="(?:(?:i'm |i am )?(?:really |so |very |truly |terribly )?sorry|i apologi[sz]e|my apologies|apologies|unfortunately|regrettabl\
420
- y|i'm afraid|i am afraid)",Wp="(?:lo siento(?: mucho)?|lo lamento|disculpa|disculpe|perd\xF3n|perdona|lamentablemente|desafortunadamente|me temo que)",Kp="(?:ho sento(?: molt)?|em sap greu|disculpa|di\
421
- sculpeu|perdona|malauradament|lamentablement|dissortadament)",Jp="(?:(?:je suis )?(?:vraiment )?d\xE9sol\xE9e?|je regrette|pardon|malheureusement|h\xE9las)",Yp="(?:es tut mir (?:sehr |wirklich )?leid|\
422
- tut mir leid|entschuldigung|leider|bedauerlicherweise)",Zp="(?:mi dispiace(?: molto)?|spiacente|scusa|scusami|mi scuso|purtroppo|sfortunatamente)",Xp="(?:desculpe|desculpa|sinto muito|lamento|pe\xE7o des\
423
- culpa|infelizmente)",Qp=yr,ef=ti,tf=ni,nf=ri,rf=oi,of=ii,Et=e=>`[,.!:;]?\\s(?:(?:${e})\\s)?`,sf="\\s\\p{L}",af=[`${Gp}${Et("but|however,?")}(?:as an ai(?: language model| assistant)?,?\\s)?${Xo}\\s(?!${Qp}\
424
- )\\p{L}`,`${Wp}${Et("pero")}${Ta}(?:\\s(?:te|le|les|os))?\\s(?!${ef})\\p{L}`,`${Kp}${Et("per\xF2|pero")}${Ra}\\s(?!${tf})\\p{L}`,`${Jp}${Et("mais")}${Aa}(?:\\s(?:vous|te))?\\s?(?!${nf})\\p{L}`,`${Yp}${Et(
425
- "aber")}${Ia}${sf}`,`${Zp}${Et("ma")}${Pa}\\s(?!${rf})\\p{L}`,`${Xp}${Et("mas")}${Da}\\s(?!${of})\\p{L}`].join("|"),cf="(?:(?:i'm |i am )?(?:really |so |very |truly |terribly )?sorry|i apologi[sz]e|my\
426
- apologies|apologies)",lf="(?:(?:is|are|was|would be|could be|may be|might be|it's|that's|this is|it is|that is)(?: considered| generally| strictly| both)? (?:illegal|unlawful|unethical|against|a viol\
416
+ n|m\xE4ngel|bugs?|nachteile?|einw\xE4nde?)","sagen, wie (?:sehr|froh|dankbar|gl\xFCcklich)"],Zp="(?:(?:mit )?sicherheit|genau|garantieren|versprechen|100 ?%|ausf\xFChren|testen|erinnern)[^.!?]{0,160}?(?:\
417
+ ,|\\s)(?:aber|jedoch|allerdings)(?![\\p{L}])",Wa=`[^.!?]*?(?<![\\p{L}])(?:(?:${Yp.join("|")})(?![\\p{L}])|${Zp})`,Ka="(?:no[,.!]? |non[,.!]? |n\xE3o[,.!]? |nein[,.!]? )?",Xp=new RegExp("^"+Ka+"(?:"+[`${ai}\
418
+ \\s(?!${xr})\\p{L}`,`${Fa}\\s(?!${ci})\\p{L}`,`${za}\\s(?!${li})\\p{L}`,`${Va}\\s?(?!${ui})\\p{L}`,`${qa}\\s(?!${di})\\p{L}`,`${Ha}\\s(?!${pi})\\p{L}`,`${Ga}(?!${Wa})(?:\\s[\\p{L}\\p{N}'-]+){0,6}?\\s(?:ni\
419
+ cht|keine?\\p{L}*)(?![\\p{L}])(?!\\s(?:nur|mehr als|anders|umhin))`].join("|")+")","u"),Qp=new RegExp("^"+Ka+"(?:"+[`${ai}\\s(?=${xr})`,`${Fa}\\s(?=${ci})`,`${za}\\s(?=${li})`,`${Va}\\s?(?=${ui})`,`${qa}\
420
+ \\s(?=${di})`,`${Ha}\\s(?=${pi})`,`${Ga}(?=${Wa})`].join("|")+")","u"),ef="(?:(?:i'm |i am )?(?:really |so |very |truly |terribly )?sorry|i apologi[sz]e|my apologies|apologies|unfortunately|regrettabl\
421
+ y|i'm afraid|i am afraid)",tf="(?:lo siento(?: mucho)?|lo lamento|disculpa|disculpe|perd\xF3n|perdona|lamentablemente|desafortunadamente|me temo que)",nf="(?:ho sento(?: molt)?|em sap greu|disculpa|di\
422
+ sculpeu|perdona|malauradament|lamentablement|dissortadament)",rf="(?:(?:je suis )?(?:vraiment )?d\xE9sol\xE9e?|je regrette|pardon|malheureusement|h\xE9las)",of="(?:es tut mir (?:sehr |wirklich )?leid|\
423
+ tut mir leid|entschuldigung|leider|bedauerlicherweise)",sf="(?:mi dispiace(?: molto)?|spiacente|scusa|scusami|mi scuso|purtroppo|sfortunatamente)",af="(?:desculpe|desculpa|sinto muito|lamento|pe\xE7o des\
424
+ culpa|infelizmente)",cf=xr,lf=ci,uf=li,df=ui,pf=di,ff=pi,Dt=e=>`[,.!:;]?\\s(?:(?:${e})\\s)?`,mf="\\s\\p{L}",hf=[`${ef}${Dt("but|however,?")}(?:as an ai(?: language model| assistant)?,?\\s)?${ii}\\s(?!${cf}\
425
+ )\\p{L}`,`${tf}${Dt("pero")}${La}(?:\\s(?:te|le|les|os))?\\s(?!${lf})\\p{L}`,`${nf}${Dt("per\xF2|pero")}${$a}\\s(?!${uf})\\p{L}`,`${rf}${Dt("mais")}${Ma}(?:\\s(?:vous|te))?\\s?(?!${df})\\p{L}`,`${of}${Dt(
426
+ "aber")}${Na}${mf}`,`${sf}${Dt("ma")}${ja}\\s(?!${pf})\\p{L}`,`${af}${Dt("mas")}${Ba}\\s(?!${ff})\\p{L}`].join("|"),gf="(?:(?:i'm |i am )?(?:really |so |very |truly |terribly )?sorry|i apologi[sz]e|my\
427
+ apologies|apologies)",bf="(?:(?:is|are|was|would be|could be|may be|might be|it's|that's|this is|it is|that is)(?: considered| generally| strictly| both)? (?:illegal|unlawful|unethical|against|a viol\
427
428
  ation|a serious violation|a breach|an invasion|prohibited|not (?:something|appropriate|possible|allowed|permitted|legal|ethical|safe|advisable|ok|okay))|violates?|goes against|go against|infringes?|i \
428
- (?:don't|do not) have (?:access|the ability|the means|the capability|any way|a way|information about|any information about|personal (?:information|data)))",uf="(?:(?:es|son|ser\xEDa|ser\xEDan|est\xE1|estar\xEDa|r\
429
+ (?:don't|do not) have (?:access|the ability|the means|the capability|any way|a way|information about|any information about|personal (?:information|data)))",vf="(?:(?:es|son|ser\xEDa|ser\xEDan|est\xE1|estar\xEDa|r\
429
430
  esulta)(?: considerado)? (?:ilegal|poco \xE9tic[oa]|inapropiad[oa]|contrari[oa] a|una violaci\xF3n|una infracci\xF3n|una invasi\xF3n|prohibid[oa])|no (?:es|ser\xEDa|est\xE1) (?:apropiado|posible|\xE9tico|legal|permitido|a\
430
- lgo)|viola|violar\xEDa|infringe|va en contra|no tengo (?:acceso|la capacidad|forma de|manera de|informaci\xF3n (?:sobre|personal)|datos personales))",df="(?:(?:\xE9s|s\xF3n|seria|serien) (?:il\xB7legal|ilegal|\
431
- poc \xE8tic|inadequat|inapropiat|contrari a|una violaci\xF3|una infracci\xF3|prohibit)|no (?:\xE9s|seria) (?:apropiat|adequat|possible|\xE8tic|legal|perm\xE8s)|viola|infringeix|va en contra)",pf="(?:(\
431
+ lgo)|viola|violar\xEDa|infringe|va en contra|no tengo (?:acceso|la capacidad|forma de|manera de|informaci\xF3n (?:sobre|personal)|datos personales))",yf="(?:(?:\xE9s|s\xF3n|seria|serien) (?:il\xB7legal|ilegal|\
432
+ poc \xE8tic|inadequat|inapropiat|contrari a|una violaci\xF3|una infracci\xF3|prohibit)|no (?:\xE9s|seria) (?:apropiat|adequat|possible|\xE8tic|legal|perm\xE8s)|viola|infringeix|va en contra)",kf="(?:(\
432
433
  ?:c'est|est|sont|serait|seraient) (?:ill\xE9gale?|contraire \xE0|une violation|une atteinte|interdite?|inappropri\xE9)|(?:ce )?n'est pas (?:appropri\xE9|possible|\xE9thique|l\xE9gal|autoris\xE9)|viole|enfreint|va \xE0 l'enco\
433
- ntre)",ff="(?:(?:ist|sind|w\xE4re|w\xE4ren)(?: \\p{L}+)? (?:illegal|rechtswidrig|unethisch|verboten|unangemessen|unzul\xE4ssig|ein versto\xDF|nicht (?:angemessen|m\xF6glich|erlaubt|zul\xE4ssig|legal|ethisch))|verst\xF6\xDFt|v\
434
- erletzt)",mf="(?:(?:\xE8|sono|sarebbe|sarebbero) (?:illegale|illecito|non etico|contrario a|una violazione|vietato|inappropriato)|non (?:\xE8|sarebbe) (?:appropriato|possibile|etico|legale|consentito)|viola\
435
- |va contro)",hf="(?:(?:\xE9|s\xE3o|seria|seriam) (?:ilegal|anti\xE9tic[oa]|contr\xE1ri[oa] a|uma viola\xE7\xE3o|proibid[oa]|inapropriad[oa])|n\xE3o (?:\xE9|seria) (?:apropriado|poss\xEDvel|\xE9tico|legal|permitido)|viola|vai contr\
436
- a)",_t="(?:[\\p{L}\\p{N}'\u2019-]+[\\s,]+){0,14}?",gf=[`${cf},?\\sbut\\s${_t}${lf}`,`(?:lo siento(?: mucho)?|lo lamento|disculpa|disculpe|perd\xF3n|perdona),?\\spero\\s${_t}${uf}`,`(?:ho sento(?: molt\
437
- )?|em sap greu|disculpa|perdona),?\\s(?:per\xF2|pero)\\s${_t}${df}`,`(?:(?:je suis )?(?:vraiment )?d\xE9sol\xE9e?|pardon),?\\smais\\s${_t}${pf}`,`(?:es tut mir (?:sehr |wirklich )?leid|tut mir leid|en\
438
- tschuldigung),?\\saber\\s${_t}${ff}`,`(?:mi dispiace(?: molto)?|spiacente|scusa|scusami|mi scuso),?\\sma\\s${_t}${mf}`,`(?:desculpe|desculpa|sinto muito|lamento|pe\xE7o desculpa),?\\smas\\s${_t}${hf}`].
439
- join("|"),bf=new RegExp(`^(?:${af}|(?:${gf})(?![\\p{L}]))`,"u"),vf="(?:(?:i'm |i am )?(?:really |so |very |truly |deeply |terribly )?sorry (?:to hear|to read|that you|you(?:'re| are)|you feel|for what\
434
+ ntre)",wf="(?:(?:ist|sind|w\xE4re|w\xE4ren)(?: \\p{L}+)? (?:illegal|rechtswidrig|unethisch|verboten|unangemessen|unzul\xE4ssig|ein versto\xDF|nicht (?:angemessen|m\xF6glich|erlaubt|zul\xE4ssig|legal|ethisch))|verst\xF6\xDFt|v\
435
+ erletzt)",xf="(?:(?:\xE8|sono|sarebbe|sarebbero) (?:illegale|illecito|non etico|contrario a|una violazione|vietato|inappropriato)|non (?:\xE8|sarebbe) (?:appropriato|possibile|etico|legale|consentito)|viola\
436
+ |va contro)",Sf="(?:(?:\xE9|s\xE3o|seria|seriam) (?:ilegal|anti\xE9tic[oa]|contr\xE1ri[oa] a|uma viola\xE7\xE3o|proibid[oa]|inapropriad[oa])|n\xE3o (?:\xE9|seria) (?:apropriado|poss\xEDvel|\xE9tico|legal|permitido)|viola|vai contr\
437
+ a)",Ot="(?:[\\p{L}\\p{N}'\u2019-]+[\\s,]+){0,14}?",Ef=[`${gf},?\\sbut\\s${Ot}${bf}`,`(?:lo siento(?: mucho)?|lo lamento|disculpa|disculpe|perd\xF3n|perdona),?\\spero\\s${Ot}${vf}`,`(?:ho sento(?: molt\
438
+ )?|em sap greu|disculpa|perdona),?\\s(?:per\xF2|pero)\\s${Ot}${yf}`,`(?:(?:je suis )?(?:vraiment )?d\xE9sol\xE9e?|pardon),?\\smais\\s${Ot}${kf}`,`(?:es tut mir (?:sehr |wirklich )?leid|tut mir leid|en\
439
+ tschuldigung),?\\saber\\s${Ot}${wf}`,`(?:mi dispiace(?: molto)?|spiacente|scusa|scusami|mi scuso),?\\sma\\s${Ot}${xf}`,`(?:desculpe|desculpa|sinto muito|lamento|pe\xE7o desculpa),?\\smas\\s${Ot}${Sf}`].
440
+ join("|"),_f=new RegExp(`^(?:${hf}|(?:${Ef})(?![\\p{L}]))`,"u"),Cf="(?:(?:i'm |i am )?(?:really |so |very |truly |deeply |terribly )?sorry (?:to hear|to read|that you|you(?:'re| are)|you feel|for what\
440
441
  you|about what you)|it sounds like you(?:'re| are)|that sounds (?:really |so |very |incredibly )?(?:hard|difficult|painful|overwhelming|tough|awful)|i(?:'m| am) (?:really |so |very )?(?:concerned|wor\
441
- ried) (?:about|for|by|to hear)|i hear (?:you|how|that you)|you(?:'re| are) not alone|i(?:'m| am) (?:so |really )?glad you reached out)",yf="(?:mental health (?:professional|provider|expert|specialist|\
442
+ ried) (?:about|for|by|to hear)|i hear (?:you|how|that you)|you(?:'re| are) not alone|i(?:'m| am) (?:so |really )?glad you reached out)",Tf="(?:mental health (?:professional|provider|expert|specialist|\
442
443
  service|services|support|crisis|line)|therapist|counsel(?:l)?or|psychologist|psychiatrist|crisis (?:line|hotline|helpline|center|centre|text line|counsel(?:l)?or|team|service|services)|(?:suicide|cris\
443
444
  is) (?:prevention|hotline|helpline|lifeline)|hotline|helpline|lifeline|samaritans|emergency services|emergency number|call (?:911|988|999|112|000|emergency)|988|someone you trust|people you trust|(?:a\
444
445
  )?trusted (?:person|friend|adult|family member|individual|someone|loved one)|someone who can (?:help|support|provide support)|reach out to (?:someone|a friend|friends|family|a loved one|loved ones)|p\
445
- rofessional (?:help|support)|seek (?:immediate|urgent|professional) (?:help|support))",kf="(?:(?:lo )?(?:siento|lamento) (?:mucho |much\xEDsimo )?(?:que (?:te sientas|est\xE9s|estes|te encuentres|pases|est\xE9\
446
- s pasando)|escuchar|o\xEDr|leer|saber)|parece que (?:est\xE1s|estas) (?:pasando|atravesando)|me preocupa)",wf="(?:profesional(?:es)? de (?:la )?salud mental|psic\xF3log[oa]|psiquiatra|terapeuta|l\xEDnea (?:\
446
+ rofessional (?:help|support)|seek (?:immediate|urgent|professional) (?:help|support))",Rf="(?:(?:lo )?(?:siento|lamento) (?:mucho |much\xEDsimo )?(?:que (?:te sientas|est\xE9s|estes|te encuentres|pases|est\xE9\
447
+ s pasando)|escuchar|o\xEDr|leer|saber)|parece que (?:est\xE1s|estas) (?:pasando|atravesando)|me preocupa)",Af="(?:profesional(?:es)? de (?:la )?salud mental|psic\xF3log[oa]|psiquiatra|terapeuta|l\xEDnea (?:\
447
448
  de )?(?:crisis|ayuda|prevenci\xF3n|atenci\xF3n)|tel\xE9fono de la esperanza|024|servicios de emergencia|(?:llama|llamar|llames) al (?:112|911|024)|alguien de (?:tu )?confianza|(?:una )?persona de (?:tu )?confi\
448
- anza|ayuda profesional)",xf="(?:em sap (?:molt )?greu (?:que (?:et sentis|estiguis|passis)|sentir|llegir|saber)|ho sento (?:molt|molt\xEDssim)|sembla que (?:est\xE0s|passes) (?:passant|travessant)?)",
449
- Sf="(?:professional(?:s)? de (?:la )?salut mental|psic\xF2leg|psic\xF2loga|psiquiatre|terapeuta|l\xEDnia (?:d'ajuda|d'atenci\xF3|de crisi|de prevenci\xF3)|tel\xE8fon de l'esperan\xE7a|024|serveis d'emerg\xE8ncia|(?:truca|tru\
450
- car|truquis) al (?:112|024)|alg\xFA de (?:la teva )?confian\xE7a|(?:una )?persona de confian\xE7a|ajuda professional)",Ef="(?:(?:je suis )?(?:vraiment |sinc\xE8rement |tellement |profond\xE9ment )?d\xE9sol\xE9e? \
451
- (?:d'apprendre|de lire|d'entendre|que tu|que vous)|il semble que (?:tu traverses|vous traversez)|\xE7a a l'air (?:tr\xE8s |vraiment )?(?:difficile|dur))",_f="(?:professionnel(?:le)?s? de (?:la )?sant\xE9\
449
+ anza|ayuda profesional)",If="(?:em sap (?:molt )?greu (?:que (?:et sentis|estiguis|passis)|sentir|llegir|saber)|ho sento (?:molt|molt\xEDssim)|sembla que (?:est\xE0s|passes) (?:passant|travessant)?)",
450
+ Pf="(?:professional(?:s)? de (?:la )?salut mental|psic\xF2leg|psic\xF2loga|psiquiatre|terapeuta|l\xEDnia (?:d'ajuda|d'atenci\xF3|de crisi|de prevenci\xF3)|tel\xE8fon de l'esperan\xE7a|024|serveis d'emerg\xE8ncia|(?:truca|tru\
451
+ car|truquis) al (?:112|024)|alg\xFA de (?:la teva )?confian\xE7a|(?:una )?persona de confian\xE7a|ajuda professional)",Df="(?:(?:je suis )?(?:vraiment |sinc\xE8rement |tellement |profond\xE9ment )?d\xE9sol\xE9e? \
452
+ (?:d'apprendre|de lire|d'entendre|que tu|que vous)|il semble que (?:tu traverses|vous traversez)|\xE7a a l'air (?:tr\xE8s |vraiment )?(?:difficile|dur))",Of="(?:professionnel(?:le)?s? de (?:la )?sant\xE9\
452
453
  mentale|psychologue|psychiatre|th\xE9rapeute|ligne d'\xE9coute|ligne de crise|ligne d'assistance|num\xE9ro d'urgence|services d'urgence|(?:appelle|appelez|composez|compose) le (?:3114|15|112|911)|3114|personn\
453
- e de confiance|quelqu'un en qui (?:tu as|vous avez) confiance|aide professionnelle|sos amiti\xE9)",Cf="(?:es tut mir (?:sehr |wirklich |so )?leid,? (?:dass|zu h\xF6ren|das zu h\xF6ren|zu lesen|das zu lesen)\
454
- |das klingt (?:sehr |wirklich )?(?:schwer|belastend|schmerzhaft)|ich mache mir sorgen)",Tf="(?:psychotherapeut\\p{L}*|psycholog\\p{L}*|psychiater\\p{L}*|therapeut\\p{L}*|fachkraft f\xFCr psychische|telefonse\
455
- elsorge|krisendienst|krisentelefon|notruf\\p{L}*|notdienst|rettungsdienst|vertrauensperson|jemandem,? dem (?:du|sie) vertrau\\p{L}*|professionelle hilfe|professionelle unterst\xFCtzung)",Rf="(?:mi dis\
456
- piace (?:molto |davvero |tanto )?(?:sentire|leggere|sapere|che tu|che ti|che stia)|sembra che (?:tu stia|stai) (?:passando|attraversando))",Af="(?:professionista della salute mentale|psicolog[oa]|psic\
454
+ e de confiance|quelqu'un en qui (?:tu as|vous avez) confiance|aide professionnelle|sos amiti\xE9)",Lf="(?:es tut mir (?:sehr |wirklich |so )?leid,? (?:dass|zu h\xF6ren|das zu h\xF6ren|zu lesen|das zu lesen)\
455
+ |das klingt (?:sehr |wirklich )?(?:schwer|belastend|schmerzhaft)|ich mache mir sorgen)",$f="(?:psychotherapeut\\p{L}*|psycholog\\p{L}*|psychiater\\p{L}*|therapeut\\p{L}*|fachkraft f\xFCr psychische|telefonse\
456
+ elsorge|krisendienst|krisentelefon|notruf\\p{L}*|notdienst|rettungsdienst|vertrauensperson|jemandem,? dem (?:du|sie) vertrau\\p{L}*|professionelle hilfe|professionelle unterst\xFCtzung)",Mf="(?:mi dis\
457
+ piace (?:molto |davvero |tanto )?(?:sentire|leggere|sapere|che tu|che ti|che stia)|sembra che (?:tu stia|stai) (?:passando|attraversando))",Nf="(?:professionista della salute mentale|psicolog[oa]|psic\
457
458
  hiatra|terapeuta|linea (?:di crisi|di ascolto|di supporto|d'ascolto)|telefono amico|telefono azzurro|numero di emergenza|servizi di emergenza|(?:chiama|chiamare) (?:il )?(?:112|118)|persona di fiducia\
458
- |qualcuno di cui ti fidi|aiuto professionale)",If="(?:sinto muito (?:que voc\xEA|por voc\xEA estar|em saber|ouvir|que esteja|que estejas)|lamento (?:muito )?(?:que voc\xEA|saber|ouvir)|parece que voc\xEA (?:est\xE1|\
459
- esteja) (?:passando|a passar))",Pf="(?:profissional de sa\xFAde mental|profissionais de sa\xFAde mental|psic\xF3log[oa]|psiquiatra|terapeuta|cvv|linha de (?:apoio|crise|ajuda)|servi\xE7os de emerg\xEAncia|(?:ligue|l\
460
- iga|ligar) (?:para )?(?:o )?(?:188|192|112|190)|188|pessoa de confian\xE7a|algu\xE9m (?:de confian\xE7a|em quem (?:voc\xEA )?confie)|ajuda profissional|sns 24)",Df=new RegExp(`^(?:${[vf,kf,xf,Ef,Cf,Rf,
461
- If].join("|")})(?![\\p{L}])`,"u"),Of=new RegExp(`(?<![\\p{L}\\p{N}])(?:${[yf,wf,Sf,_f,Tf,Af,Pf].join("|")})(?![\\p{L}\\p{N}])`,"u"),Lf=2e4,$f="(?:explain|detail|describe|elaborate)",Mf=new RegExp(`(?:\
462
- ^|[^\\p{L}'])(?:${Qo}|${Xo}${Ct}${$f})(?![\\p{L}])`,"gu"),Nf=new RegExp(`^[^\\p{L}]*${ei}\\s${yr}`,"u");function Ea(e,t){for(let n of e.matchAll(t))if(!Nf.test(e.slice(n.index)))return true;return false}var jf=new RegExp(
463
- Oa.source,"gu");function Bf(e){return e.slice(0,4*300).replace(/[‘’ʼ`´]/g,"'").toLowerCase().replace(/\s+/g," ").trim().replace(/^[\s*#>_"'«“¿¡(\[-]+/u,"").trim()}function Uf(e){let t=[...e.
464
- matchAll(/[.!?。](?:\s|$)/g)],n=t.length>=2?t[1].index+1:e.length;return e.slice(0,Math.min(n,240))}function Zo(e){let t=/[.!?。:;](?:\s|$)/.exec(e);return t?e.slice(t.index+1).trim():""}function si(e){
465
- if(typeof e!="string"||e==="")return null;let t=_a(e);if(t)return t;for(let n of Vf(e))if(_a(n))return "refusal-in-structured-output";return null}var Ff=200,zf=4e4;function Vf(e){let t=e.trim();if(!(t.
466
- startsWith("{")||t.startsWith("["))||t.length>zf)return [];let n;try{n=JSON.parse(t);}catch{return []}let r=[],o=[n];for(;o.length>0&&r.length<Ff;){let i=o.pop();if(typeof i=="string")i.trim()!==""&&r.push(
467
- i);else if(Array.isArray(i))for(let s=i.length-1;s>=0;s--)o.push(i[s]);else if(i!==null&&typeof i=="object"){let s=Object.values(i);for(let a=s.length-1;a>=0;a--)o.push(s[a]);}}return r}function _a(e){
468
- let t=Bf(e);if(t==="")return null;let n=Uf(t),r=Hp.test(n);if(!r&&(Cp.test(n)||qp.test(n)))return "opens-with-refusal";let o=r?Zo(n):n;return Tp.test(n)&&Oa.test(o)||bf.test(n)?"apology-then-refusal":t.
469
- length<=300&&Ea(r?Zo(t):t,jf)?"short-refusal":Df.test(n)&&Of.test(Ca(e,false))?"redirection":Ea(Ca(e,r),Mf)?"partial-refusal":null}function Ca(e,t){let n=e.slice(0,Lf).replace(/[‘’ʼ`´]/g,"'").toLowerCase().
470
- replace(/\s+/g," ").trim().replace(/^[\s*#>_"'«“¿¡(\[-]+/u,"").trim();return t?Zo(n):n}var qf=/^content_filter(?:\s*:\s*(.*?))?\s*$/;function ai(e){return typeof e=="string"&&qf.test(e)}function ci(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function li(e){if(!e)return 0;let{prompt_tokens:t,completion_tokens:n,total_tokens:r}=e;return !ci(t)||!ci(n)||!ci(r)?0:Math.max(0,r-
471
- t-n)}var H="\\p{L}*",Hf=[`suicid${H}`,`self[- ]?harm${H}`,`self[- ]?injur${H}`,`self[- ]?mutilat${H}`,"(?:kill|killing|hang|hanging|drown|drowning|cut|cutting|hurt|hurting|harm|harming|shoot|poison|stab|st\
459
+ |qualcuno di cui ti fidi|aiuto professionale)",jf="(?:sinto muito (?:que voc\xEA|por voc\xEA estar|em saber|ouvir|que esteja|que estejas)|lamento (?:muito )?(?:que voc\xEA|saber|ouvir)|parece que voc\xEA (?:est\xE1|\
460
+ esteja) (?:passando|a passar))",Bf="(?:profissional de sa\xFAde mental|profissionais de sa\xFAde mental|psic\xF3log[oa]|psiquiatra|terapeuta|cvv|linha de (?:apoio|crise|ajuda)|servi\xE7os de emerg\xEAncia|(?:ligue|l\
461
+ iga|ligar) (?:para )?(?:o )?(?:188|192|112|190)|188|pessoa de confian\xE7a|algu\xE9m (?:de confian\xE7a|em quem (?:voc\xEA )?confie)|ajuda profissional|sns 24)",Uf=new RegExp(`^(?:${[Cf,Rf,If,Df,Lf,Mf,
462
+ jf].join("|")})(?![\\p{L}])`,"u"),Ff=new RegExp(`(?<![\\p{L}\\p{N}])(?:${[Tf,Af,Pf,Of,$f,Nf,Bf].join("|")})(?![\\p{L}\\p{N}])`,"u"),zf=2e4,Vf="(?:explain|detail|describe|elaborate)",qf=new RegExp(`(?:\
463
+ ^|[^\\p{L}'])(?:${si}|${ii}${Lt}${Vf})(?![\\p{L}])`,"gu"),Hf=new RegExp(`^[^\\p{L}]*${ai}\\s${xr}`,"u");function Pa(e,t){for(let n of e.matchAll(t))if(!Hf.test(e.slice(n.index)))return true;return false}var Gf=new RegExp(
464
+ Ua.source,"gu");function Wf(e){return e.slice(0,4*300).replace(/[‘’ʼ`´]/g,"'").toLowerCase().replace(/\s+/g," ").trim().replace(/^[\s*#>_"'«“¿¡(\[-]+/u,"").trim()}function Kf(e){let t=[...e.
465
+ matchAll(/[.!?。](?:\s|$)/g)],n=t.length>=2?t[1].index+1:e.length;return e.slice(0,Math.min(n,240))}function oi(e){let t=/[.!?。:;](?:\s|$)/.exec(e);return t?e.slice(t.index+1).trim():""}function fi(e){
466
+ if(typeof e!="string"||e==="")return null;let t=Da(e);if(t)return t;for(let n of Zf(e))if(Da(n))return "refusal-in-structured-output";return null}var Jf=200,Yf=4e4;function Zf(e){let t=e.trim();if(!(t.
467
+ startsWith("{")||t.startsWith("["))||t.length>Yf)return [];let n;try{n=JSON.parse(t);}catch{return []}let r=[],o=[n];for(;o.length>0&&r.length<Jf;){let i=o.pop();if(typeof i=="string")i.trim()!==""&&r.push(
468
+ i);else if(Array.isArray(i))for(let s=i.length-1;s>=0;s--)o.push(i[s]);else if(i!==null&&typeof i=="object"){let s=Object.values(i);for(let a=s.length-1;a>=0;a--)o.push(s[a]);}}return r}function Da(e){
469
+ let t=Wf(e);if(t==="")return null;let n=Kf(t),r=Qp.test(n);if(!r&&(Lp.test(n)||Xp.test(n)))return "opens-with-refusal";let o=r?oi(n):n;return $p.test(n)&&Ua.test(o)||_f.test(n)?"apology-then-refusal":t.
470
+ length<=300&&Pa(r?oi(t):t,Gf)?"short-refusal":Uf.test(n)&&Ff.test(Oa(e,false))?"redirection":Pa(Oa(e,r),qf)?"partial-refusal":null}function Oa(e,t){let n=e.slice(0,zf).replace(/[‘’ʼ`´]/g,"'").toLowerCase().
471
+ replace(/\s+/g," ").trim().replace(/^[\s*#>_"'«“¿¡(\[-]+/u,"").trim();return t?oi(n):n}var Xf=/^content_filter(?:\s*:\s*(.*?))?\s*$/;function mi(e){return typeof e=="string"&&Xf.test(e)}function hi(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function gi(e){if(!e)return 0;let{prompt_tokens:t,completion_tokens:n,total_tokens:r}=e;return !hi(t)||!hi(n)||!hi(r)?0:Math.max(0,r-
472
+ t-n)}var q="\\p{L}*",Qf=[`suicid${q}`,`self[- ]?harm${q}`,`self[- ]?injur${q}`,`self[- ]?mutilat${q}`,"(?:kill|killing|hang|hanging|drown|drowning|cut|cutting|hurt|hurting|harm|harming|shoot|poison|stab|st\
472
473
  arve|suffocate|strangle|electrocute|overdose) myself","end (?:my|my own) life","(?:want to|going to|gonna|just|i'll|i will) end it all","take my (?:own )?life","i (?:really |just )?(?:want|wanna) to d\
473
474
  ie","i(?:'m| am) (?:going|planning|trying|ready) to die","wish i (?:was|were) dead","better off dead","(?:don't|do not) want to (?:live|be alive|wake up) any ?more","(?:don't|do not) want to be alive",
474
475
  "no reason to (?:live|keep living)","take to die","(?:cut|sever|slit|pierce|open) (?:my|my own) (?:\\p{L}+ )?(?:artery|arteries|wrists?|veins?|throat)","(?:carve|cut) (?:\\p{L}+ ){0,3}into my (?:arm|ar\
475
- ms|skin|leg|legs|wrist|wrists)",`overdos${H}`,"autolesi\\p{L}*","(?:matarme|ahorcarme|ahogarme|envenenarme|lastimarme|hacerme da\xF1o|quitarme la vida)","cortarme (?:las venas|los brazos|las mu\xF1ecas)",
476
- "acabar con mi vida","quiero morir(?:me)?","no quiero (?:seguir viviendo|vivir m\xE1s)","sobredosis",`su\xEFcid${H}`,"(?:matar-me|penjar-me|ofegar-me|fer-me mal|treure'm la vida)","acabar amb la meva \
476
+ ms|skin|leg|legs|wrist|wrists)",`overdos${q}`,"autolesi\\p{L}*","(?:matarme|ahorcarme|ahogarme|envenenarme|lastimarme|hacerme da\xF1o|quitarme la vida)","cortarme (?:las venas|los brazos|las mu\xF1ecas)",
477
+ "acabar con mi vida","quiero morir(?:me)?","no quiero (?:seguir viviendo|vivir m\xE1s)","sobredosis",`su\xEFcid${q}`,"(?:matar-me|penjar-me|ofegar-me|fer-me mal|treure'm la vida)","acabar amb la meva \
477
478
  vida","vull morir","no vull (?:seguir vivint|viure m\xE9s)","sobredosi","automutil\\p{L}*","(?:me tuer|me pendre|me noyer|me faire du mal|me mutiler|m'ouvrir les veines|me couper les veines)","mettre \
478
- fin \xE0 (?:mes jours|ma vie)","en finir avec la vie","(?:je veux|j'ai envie de) mourir","surdose",`suizid${H}`,`selbstmord${H}`,"freitod",`selbstverletz${H}`,"mich (?:umbringen|t\xF6ten|erh\xE4ngen|ertr\xE4nk\
479
- en|ritzen|verletzen)","mir das leben nehmen","mein leben beenden","(?:ich will|ich m\xF6chte) (?:nicht mehr leben|sterben)","\xFCberdosis",`autolesion${H}`,"(?:uccidermi|ammazzarmi|impiccarmi|annegarm\
480
- i|tagliarmi le vene|farmi del male|togliermi la vita)","(?:voglio|vorrei) morire","non voglio pi\xF9 vivere",`suic\xEDd${H}`,`automutila${H}`,"autoles\xE3o|autoles\xF5es","(?:me matar|matar-me|me enfo\
481
- rcar|enforcar-me|me afogar|me machucar)","tirar a (?:minha )?(?:pr\xF3pria )?vida","acabar com a minha vida","quero morrer","n\xE3o quero mais viver",`zelfmoord${H}`,`zelfbeschadig${H}`,"mezelf (?:dod\
482
- en|ophangen|verdrinken|snijden|iets aandoen|van kant maken)","ik wil dood","overdosis",`samob\xF3j${H}`,`samookalecz${H}`,"(?:zabi\u0107 si\u0119|powiesi\u0107 si\u0119|utopi\u0107 si\u0119|poci\u0105\u0107 si\u0119|skrzywdzi\u0107 si\u0119|odebra\u0107 sobie \
483
- \u017Cycie)","chc\u0119 umrze\u0107","nie chc\u0119 ju\u017C \u017Cy\u0107",`przedawkowa${H}`,`intihar${H}`,"kendime zarar",`kendimi \xF6ld\xFCr${H}`,"\xF6lmek istiyorum","art\u0131k ya\u015Famak istemiyorum",
484
- "a\u015F\u0131r\u0131 doz","bunuh diri",`menyakiti diri${H}`,"(?:ingin|mau) mati","tidak ingin hidup lagi","t\u1EF1 t\u1EED|t\u1EF1 s\xE1t|t\u1EF1 l\xE0m h\u1EA1i|t\u1EF1 h\u1EA1i|mu\u1ED1n ch\u1EBFt|kh\xF4ng mu\u1ED1n s\u1ED1ng n\u1EEFa|qu\xE1 li\u1EC1u"],
485
- Gf=["panic attacks?","(?:mental|nervous) breakdown","psychotic (?:episode|break)","hearing voices","mental health crisis","feel(?:ing)? (?:so |really |very |completely )?(?:hopeless|worthless|suicidal\
486
- |empty inside)","i(?:'m| am) (?:so |really |very )?(?:depressed|hopeless|worthless)","eating disorder",`anorexi${H}`,`bulimi${H}`,"ataques? de (?:p\xE1nico|panico|ansiedad)","crisis de (?:p\xE1nico|panic\
479
+ fin \xE0 (?:mes jours|ma vie)","en finir avec la vie","(?:je veux|j'ai envie de) mourir","surdose",`suizid${q}`,`selbstmord${q}`,"freitod",`selbstverletz${q}`,"mich (?:umbringen|t\xF6ten|erh\xE4ngen|ertr\xE4nk\
480
+ en|ritzen|verletzen)","mir das leben nehmen","mein leben beenden","(?:ich will|ich m\xF6chte) (?:nicht mehr leben|sterben)","\xFCberdosis",`autolesion${q}`,"(?:uccidermi|ammazzarmi|impiccarmi|annegarm\
481
+ i|tagliarmi le vene|farmi del male|togliermi la vita)","(?:voglio|vorrei) morire","non voglio pi\xF9 vivere",`suic\xEDd${q}`,`automutila${q}`,"autoles\xE3o|autoles\xF5es","(?:me matar|matar-me|me enfo\
482
+ rcar|enforcar-me|me afogar|me machucar)","tirar a (?:minha )?(?:pr\xF3pria )?vida","acabar com a minha vida","quero morrer","n\xE3o quero mais viver",`zelfmoord${q}`,`zelfbeschadig${q}`,"mezelf (?:dod\
483
+ en|ophangen|verdrinken|snijden|iets aandoen|van kant maken)","ik wil dood","overdosis",`samob\xF3j${q}`,`samookalecz${q}`,"(?:zabi\u0107 si\u0119|powiesi\u0107 si\u0119|utopi\u0107 si\u0119|poci\u0105\u0107 si\u0119|skrzywdzi\u0107 si\u0119|odebra\u0107 sobie \
484
+ \u017Cycie)","chc\u0119 umrze\u0107","nie chc\u0119 ju\u017C \u017Cy\u0107",`przedawkowa${q}`,`intihar${q}`,"kendime zarar",`kendimi \xF6ld\xFCr${q}`,"\xF6lmek istiyorum","art\u0131k ya\u015Famak istemiyorum",
485
+ "a\u015F\u0131r\u0131 doz","bunuh diri",`menyakiti diri${q}`,"(?:ingin|mau) mati","tidak ingin hidup lagi","t\u1EF1 t\u1EED|t\u1EF1 s\xE1t|t\u1EF1 l\xE0m h\u1EA1i|t\u1EF1 h\u1EA1i|mu\u1ED1n ch\u1EBFt|kh\xF4ng mu\u1ED1n s\u1ED1ng n\u1EEFa|qu\xE1 li\u1EC1u"],
486
+ em=["panic attacks?","(?:mental|nervous) breakdown","psychotic (?:episode|break)","hearing voices","mental health crisis","feel(?:ing)? (?:so |really |very |completely )?(?:hopeless|worthless|suicidal\
487
+ |empty inside)","i(?:'m| am) (?:so |really |very )?(?:depressed|hopeless|worthless)","eating disorder",`anorexi${q}`,`bulimi${q}`,"ataques? de (?:p\xE1nico|panico|ansiedad)","crisis de (?:p\xE1nico|panic\
487
488
  o|ansiedad)","(?:me siento|estoy) (?:muy )?(?:deprimid[oa]|desesperad[oa]|sin esperanza)","atacs? de (?:p\xE0nic|p\xE1nico|ansietat)","(?:em sento|estic) (?:molt )?(?:deprimit|deprimida|desesperat|des\
488
- esperada)","crises? (?:de panique|d'angoisse)","attaques? de panique","je suis (?:tr\xE8s )?d\xE9prim\xE9e?",`panikattacke${H}`,"ich bin (?:so |sehr )?(?:depressiv|verzweifelt)","attacc(?:o|hi) di pan\
489
- ico","(?:sono|mi sento) (?:molto )?(?:depress[oa]|disperat[oa])","(?:ataques?|crises?) de (?:p\xE2nico|ansiedade)","(?:estou|me sinto) (?:muito )?(?:deprimid[oa]|desesperad[oa])",`paniekaanval${H}`,"a\
490
- tak(?:i)? paniki",`panik atak${H}`,"serangan panik","c\u01A1n ho\u1EA3ng lo\u1EA1n"],Wf=["heart attack","having a stroke","(?:can't|cannot|can not) breathe","(?:not|stopped) breathing","chest pains?",
491
- `anaphyla${H}`,"(?:is |was |went |gone )unconscious","(?:having|had|is having) a seizure","(?:severe|heavy) bleeding|bleeding (?:heavily|profusely|a lot|won't stop)","swallowed (?:bleach|poison|a batt\
489
+ esperada)","crises? (?:de panique|d'angoisse)","attaques? de panique","je suis (?:tr\xE8s )?d\xE9prim\xE9e?",`panikattacke${q}`,"ich bin (?:so |sehr )?(?:depressiv|verzweifelt)","attacc(?:o|hi) di pan\
490
+ ico","(?:sono|mi sento) (?:molto )?(?:depress[oa]|disperat[oa])","(?:ataques?|crises?) de (?:p\xE2nico|ansiedade)","(?:estou|me sinto) (?:muito )?(?:deprimid[oa]|desesperad[oa])",`paniekaanval${q}`,"a\
491
+ tak(?:i)? paniki",`panik atak${q}`,"serangan panik","c\u01A1n ho\u1EA3ng lo\u1EA1n"],tm=["heart attack","having a stroke","(?:can't|cannot|can not) breathe","(?:not|stopped) breathing","chest pains?",
492
+ `anaphyla${q}`,"(?:is |was |went |gone )unconscious","(?:having|had|is having) a seizure","(?:severe|heavy) bleeding|bleeding (?:heavily|profusely|a lot|won't stop)","swallowed (?:bleach|poison|a batt\
492
493
  ery|batteries|pills)","call (?:911|999|112|an ambulance)","medical emergency","infarto","no (?:puedo|puede) respirar","(?:dolor|dolores) (?:en el|de) pecho","(?:est\xE1|esta) inconsciente","emergencia\
493
494
  m\xE9dica","infart","no (?:puc|pot) respirar","emerg\xE8ncia m\xE8dica","crise cardiaque","(?:je n'arrive pas \xE0|je ne peux pas|il ne peut pas|elle ne peut pas) respirer","urgence m\xE9dicale","her\
494
495
  zinfarkt","(?:kann|bekomme) (?:nicht|keine) (?:atmen|luft)","medizinischer notfall","non riesc[oe] a respirare","emergenza medica","ataque card\xEDaco","n\xE3o consig[oa] respirar","emerg\xEAncia m\xE9dica",
495
496
  "hartaanval","zawa\u0142 serca","nie mog\u0119 oddycha\u0107","kalp krizi","nefes alam\u0131yorum","serangan jantung","tidak bisa bernapas","nh\u1ED3i m\xE1u c\u01A1 tim|\u0111\u1ED9t qu\u1EF5|kh\xF4ng th\u1EDF \u0111\u01B0\u1EE3c"],
496
- Kf=/(?<![\p{L}\p{N}])(?:suicide (?:squad|doors?|burn|king|linux|slide|bid)|shoot myself in the foot)(?![\p{L}\p{N}])/gu,ui=e=>new RegExp(`(?<![\\p{L}\\p{N}])(?:${e.join("|")})(?![\\p{L}\\p{N}])`,"u"),
497
- Jf=ui(Hf),Yf=ui(Gf),Zf=ui(Wf);function Xf(e){return e.normalize("NFC").replace(/[‘’ʼ`´]/g,"'").toLowerCase().replace(/\s+/g," ").replace(Kf," ")}function Qf(e){if(typeof e!="string"||e==="")return null;
498
- let t=Xf(e);return Jf.test(t)?"self-harm":Yf.test(t)?"mental-health-crisis":Zf.test(t)?"medical-emergency":null}function di(e){for(let t of e){let n=Qf(t);if(n!==null)return n}return null}var kr=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(
497
+ nm=/(?<![\p{L}\p{N}])(?:suicide (?:squad|doors?|burn|king|linux|slide|bid)|shoot myself in the foot)(?![\p{L}\p{N}])/gu,bi=e=>new RegExp(`(?<![\\p{L}\\p{N}])(?:${e.join("|")})(?![\\p{L}\\p{N}])`,"u"),
498
+ rm=bi(Qf),om=bi(em),im=bi(tm);function sm(e){return e.normalize("NFC").replace(/[‘’ʼ`´]/g,"'").toLowerCase().replace(/\s+/g," ").replace(nm," ")}function am(e){if(typeof e!="string"||e==="")return null;
499
+ let t=sm(e);return rm.test(t)?"self-harm":om.test(t)?"mental-health-crisis":im.test(t)?"medical-emergency":null}function vi(e){for(let t of e){let n=am(t);if(n!==null)return n}return null}var Sr=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(
499
500
  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,
500
501
  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(
501
502
  0)===10&&(o=1));let i=o;for(;o<r.length;){let s=r.charCodeAt(o);if(s!==10&&s!==13){o++;continue}this.linea(this.resto+r.slice(i,o),n),this.resto="",s===13&&(o+1<r.length?r.charCodeAt(o+1)===10&&o++:this.
502
503
  crPendiente=true),o++,i=o;}return this.resto+=r.slice(i),n}linea(t,n){if(t===""){this.despachar(n);return}if(t.charCodeAt(0)===58)return;let r=t.indexOf(":"),o,i;switch(r===-1?(o=t,i=""):(o=t.slice(0,r),
503
504
  i=t.slice(r+1),i.charCodeAt(0)===32&&(i=i.slice(1))),o){case "data":this.datos+=i+`
504
505
  `;break;case "event":this.evento=i;break;case "id":i.includes("\0")||(this.ultimoId=i);break;}}despachar(t){if(this.datos===""){this.evento="";return}t.push({event:this.evento===""?"message":
505
- this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};var Ge=class{resto="";uso=null;elisionObservada=null;paradaFinal=null;detallesDeParada=void 0;texto=new yn;eventos={};observar(t){this.resto+=typeof t=="string"?t:t.toString("utf8");let n;for(;(n=this.
506
+ this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};function cm(e,t){if(e.system!==t.system||e.tools!==t.tools)return 0;let n=e.bytesFijos;for(let i of e.bytes)n+=i;if(n<=0)return 0;let r=0;for(;r<e.mensajes.length&&r<t.mensajes.length&&e.mensajes[r]===
507
+ t.mensajes[r];)r++;let o=e.bytesFijos;for(let i=0;i<r;i++)o+=e.bytes[i]??0;return Math.min(1,o/n)}var Ja=e=>e.previo!==null&&e.previo.rebajado&&e.huecoMs>3e5&&e.huecoMs<=36e5;function Ya(e,t){if(!Ja(e)||
508
+ e.previo===null||!e.previo.atribuible)return 0;let n=e.previo.cubierto*e.compartido,r=Math.min(n-t.cacheLeida,e.previo.enRiesgo,t.cacheEscrita);return r>0?Math.floor(r):0}function Za(e,t){if(!Ja(e)||e.
509
+ previo===null)return 0;let n=Math.min(t.cacheLeida,e.previo.cubierto)-e.previo.base1h;return n>0?n:0}function _r(e){let{perdidos:t,inputPer1k:n,primaEscritura:r}=e;if(t<=0||n<=0)return 0;let o=e.cachedInputPer1k??
510
+ n*.1;return Math.max(0,t/1e3*(n*r-o))}var Er=class{constructor(t=512){this.maxEntradas=t;}maxEntradas;hilos=new Map;abrir(t,n,r,o){let i=this.hilos.get(t),s=i===void 0?1/0:r-i.inicioMs,a=i!==void 0&&i.
511
+ cierre!==null&&s<=36e5?i:null,c={inicioMs:r,huella:n,rebajado:o,previo:a!==null&&a.cierre!==null?{...a.cierre,rebajado:a.rebajado}:null,huecoMs:s,compartido:a!==null?cm(a.huella,n):0,cierre:null};for(this.
512
+ hilos.delete(t),this.hilos.set(t,c);this.hilos.size>this.maxEntradas;){let l=this.hilos.keys().next();if(l.done===true)break;this.hilos.delete(l.value);}return c}get tamano(){return this.hilos.size}};function Xa(e,t,n){
513
+ let r=t.cacheLeida+t.cacheEscrita;if(!n.sombra){let s=Math.max(0,t.cacheEscrita-t.cacheEscrita1h),a=e.rebajado?s:0;e.cierre={cubierto:r,enRiesgo:a,base1h:r-a,atribuible:n.atribuible};return}let o=Math.
514
+ max(0,t.cacheLeida-n.perdidos),i;e.rebajado?e.previo!==null&&e.previo.rebajado&&e.huecoMs<=3e5?i=Math.min(o,e.previo.base1h):i=o:i=r,e.cierre={cubierto:r,enRiesgo:r-i,base1h:i,atribuible:true};}var We=class{resto="";uso=null;elisionObservada=null;paradaFinal=null;detallesDeParada=void 0;texto=new Sn;eventos={};observar(t){this.resto+=typeof t=="string"?t:t.toString("utf8");let n;for(;(n=this.
506
515
  resto.indexOf(`
507
516
 
508
517
  `))>=0;){let r=this.resto.slice(0,n);this.resto=this.resto.slice(n+2);let o=/^event: (.+)$/m.exec(r)?.[1];if(o&&(this.eventos[o]=(this.eventos[o]??0)+1),o==="content_block_delta"&&!this.texto.lleno()){
509
518
  let s=/^data: (.+)$/m.exec(r)?.[1];try{let a=s?JSON.parse(s):null;a?.delta?.type==="text_delta"&&this.texto.sumar(a.delta.text);}catch{}continue}if(o!=="message_start"&&o!=="message_delta")continue;let i=/^data: (.+)$/m.
510
519
  exec(r)?.[1];if(i)try{let s=JSON.parse(i);o==="message_delta"&&typeof s.delta?.stop_reason=="string"&&(this.paradaFinal=s.delta.stop_reason),o==="message_delta"&&s.delta&&"stop_details"in s.delta&&(this.
511
- detallesDeParada=s.delta.stop_details);let a=qa(s.context_management);a&&(this.elisionObservada=a);let c=s.usage??s.message?.usage;if(c){let l=c.cache_creation||this.uso?.cache_creation?{...this.uso?.
520
+ detallesDeParada=s.delta.stop_details);let a=tc(s.context_management);a&&(this.elisionObservada=a);let c=s.usage??s.message?.usage;if(c){let l=c.cache_creation||this.uso?.cache_creation?{...this.uso?.
512
521
  cache_creation,...c.cache_creation}:void 0;this.uso={...this.uso,...c,...l?{cache_creation:l}:{}};}}catch{}}}usage(){return this.uso}usageFinal(){return (this.eventos.message_delta??0)>0?this.uso:null}elision(){
513
- return this.elisionObservada}negativa(){return this.paradaFinal==="refusal"}textoInicial(){return this.texto.valor()}negativaNoCobrada(){let t=this.usageFinal();return t!==null&&vr({stopReason:this.paradaFinal,
514
- stopDetails:this.detallesDeParada,bloques:this.eventos.content_block_start??0,outputTokens:t.output_tokens,iterations:t.iterations})}};function em(e,t){if(!t||t.atribuible!==true||!(t.tokensLimpiadosToolUses>
515
- 0))return 0;let n=e.cachedInputPer1k;return typeof n!="number"||!Number.isFinite(n)||n<=0?0:t.tokensLimpiadosToolUses/1e3*n}function qa(e){if(e===null||typeof e!="object")return null;let t=e.applied_edits;
522
+ return this.elisionObservada}negativa(){return this.paradaFinal==="refusal"}textoInicial(){return this.texto.valor()}negativaNoCobrada(){let t=this.usageFinal();return t!==null&&wr({stopReason:this.paradaFinal,
523
+ stopDetails:this.detallesDeParada,bloques:this.eventos.content_block_start??0,outputTokens:t.output_tokens,iterations:t.iterations})}};function lm(e,t){if(!t||t.atribuible!==true||!(t.tokensLimpiadosToolUses>
524
+ 0))return 0;let n=e.cachedInputPer1k;return typeof n!="number"||!Number.isFinite(n)||n<=0?0:t.tokensLimpiadosToolUses/1e3*n}function tc(e){if(e===null||typeof e!="object")return null;let t=e.applied_edits;
516
525
  if(!Array.isArray(t)||t.length===0)return null;let n=0,r=0;for(let o of t){let i=o.cleared_input_tokens;typeof i=="number"&&Number.isFinite(i)&&i>0&&(n+=i,o.type==="clear_tool_uses_20250919"&&(r+=i));}
517
- return {borrados:t.length,tokensLimpiados:n,tokensLimpiadosToolUses:r}}function Ha(e){try{let t=JSON.parse(typeof e=="string"?e:e.toString("utf8"));return qa(t.context_management)}catch{return null}}var Wt=class{resto="";uso=null;final=null;negada=false;texto=new yn;eventos={};observar(t){
526
+ return {borrados:t.length,tokensLimpiados:n,tokensLimpiadosToolUses:r}}function nc(e){try{let t=JSON.parse(typeof e=="string"?e:e.toString("utf8"));return tc(t.context_management)}catch{return null}}var Qt=class{resto="";uso=null;final=null;negada=false;texto=new Sn;eventos={};observar(t){
518
527
  this.resto+=typeof t=="string"?t:t.toString("utf8");let n;for(;(n=this.resto.indexOf(`
519
528
 
520
529
  `))>=0;){let r=this.resto.slice(0,n);this.resto=this.resto.slice(n+2);let o=/^event: (.+)$/m.exec(r)?.[1];o&&(this.eventos[o]=(this.eventos[o]??0)+1);let i=/^data: (.+)$/m.exec(r)?.[1];if(i)try{let s=JSON.
521
- parse(i),a=o??s.type;tm(a,s)&&(this.negada=!0),a==="response.output_text.delta"&&this.texto.sumar(s.delta);let c=a!==void 0&&Object.hasOwn(za,a)?za[a]:void 0;if(c===void 0)continue;this.final=c;let l=s.
522
- response?.usage;if(!l)continue;c==="completed"?this.uso=wr(l):typeof l.input_tokens=="number"&&typeof l.output_tokens=="number"&&(this.uso=wr(l));}catch{}}}usage(){return this.uso}usageFinal(){return this.
523
- uso}estadoFinal(){return this.final}negativa(){return this.negada}textoInicial(){return this.texto.valor()}};function tm(e,t){if(e==="response.refusal.delta"||e==="response.refusal.done")return true;if(t===
524
- null||typeof t!="object")return false;let n=t;return Ga(n.part)||fi([n.item])?true:n.response!==null&&typeof n.response=="object"&&fi(n.response.output)}function Ga(e){return e!==null&&typeof e=="object"&&e.
525
- type==="refusal"}function fi(e){return Array.isArray(e)&&e.some(t=>{if(t===null||typeof t!="object")return false;let n=t.content;return Array.isArray(n)&&n.some(Ga)})}var za={"response.completed":"complet\
526
- ed","response.incomplete":"incomplete","response.failed":"failed"};function wr(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.
527
- max(0,e.input_tokens_details?.cache_write_tokens??0),t-n);return {input_tokens:t-n-r,output_tokens:Math.max(0,e.output_tokens??0),cache_read_input_tokens:n,cache_creation_input_tokens:r}}function Wa(e){
528
- return !e||typeof e.prompt_tokens!="number"||typeof e.completion_tokens!="number"?null:wr({input_tokens:e.prompt_tokens,output_tokens:e.completion_tokens+li(e),input_tokens_details:{...e.prompt_tokens_details?.
530
+ parse(i),a=o??s.type;um(a,s)&&(this.negada=!0),a==="response.output_text.delta"&&this.texto.sumar(s.delta);let c=a!==void 0&&Object.hasOwn(Qa,a)?Qa[a]:void 0;if(c===void 0)continue;this.final=c;let l=s.
531
+ response?.usage;if(!l)continue;c==="completed"?this.uso=Cr(l):typeof l.input_tokens=="number"&&typeof l.output_tokens=="number"&&(this.uso=Cr(l));}catch{}}}usage(){return this.uso}usageFinal(){return this.
532
+ uso}estadoFinal(){return this.final}negativa(){return this.negada}textoInicial(){return this.texto.valor()}};function um(e,t){if(e==="response.refusal.delta"||e==="response.refusal.done")return true;if(t===
533
+ null||typeof t!="object")return false;let n=t;return rc(n.part)||ki([n.item])?true:n.response!==null&&typeof n.response=="object"&&ki(n.response.output)}function rc(e){return e!==null&&typeof e=="object"&&e.
534
+ type==="refusal"}function ki(e){return Array.isArray(e)&&e.some(t=>{if(t===null||typeof t!="object")return false;let n=t.content;return Array.isArray(n)&&n.some(rc)})}var Qa={"response.completed":"complet\
535
+ ed","response.incomplete":"incomplete","response.failed":"failed"};function Cr(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.
536
+ max(0,e.input_tokens_details?.cache_write_tokens??0),t-n);return {input_tokens:t-n-r,output_tokens:Math.max(0,e.output_tokens??0),cache_read_input_tokens:n,cache_creation_input_tokens:r}}function oc(e){
537
+ return !e||typeof e.prompt_tokens!="number"||typeof e.completion_tokens!="number"?null:Cr({input_tokens:e.prompt_tokens,output_tokens:e.completion_tokens+gi(e),input_tokens_details:{...e.prompt_tokens_details?.
529
538
  cached_tokens!==void 0?{cached_tokens:e.prompt_tokens_details.cached_tokens}:{},...e.prompt_tokens_details?.cache_write_tokens!==void 0?{cache_write_tokens:e.prompt_tokens_details.cache_write_tokens}:
530
- {}}})}var vn=class{parser=new kr;ultimoUso=null;vioUsoFinal=false;vioDone=false;filtrada=false;texto=new yn;eventos={};observar(t){for(let n of this.parser.push(t))this.mensaje(n);}textoInicial(){for(let t of this.
539
+ {}}})}var xn=class{parser=new Sr;ultimoUso=null;vioUsoFinal=false;vioDone=false;filtrada=false;texto=new Sn;eventos={};observar(t){for(let n of this.parser.push(t))this.mensaje(n);}textoInicial(){for(let t of this.
531
540
  parser.end())this.mensaje(t);return this.texto.valor()}negativa(){return this.filtrada}usage(){return this.vioUsoFinal||this.vioDone?this.ultimoUso:null}usageFinal(){for(let t of this.parser.end())this.
532
541
  mensaje(t);return this.usage()}mensaje(t){if(t.data==="[DONE]"){this.vioDone=true,this.eventos.done=(this.eventos.done??0)+1;return}let n;try{n=JSON.parse(t.data);}catch{return}if(n===null||typeof n!="ob\
533
- ject")return;if(this.eventos.chunk=(this.eventos.chunk??0)+1,Xa(n.choices)&&(this.filtrada=true),Array.isArray(n.choices)&&!this.texto.lleno()){let o=n.choices[0];this.texto.sumar(o?.delta?.content);}if(n.
534
- usage===null||typeof n.usage!="object")return;let r=Wa(n.usage);r!==null&&(this.ultimoUso=r,Array.isArray(n.choices)&&n.choices.length===0&&(this.vioUsoFinal=true));}};function Ka(e,t,n){let r=e.cachedInputPer1k??
535
- e.inputPer1k;return t.entrada/1e3*e.inputPer1k+t.cacheLeida/1e3*r+(t.cacheEscrita-t.cacheEscrita1h)/1e3*e.inputPer1k*ve(n)+t.cacheEscrita1h/1e3*e.inputPer1k*2+t.salida/1e3*e.outputPer1k}function mi(e,t,n){
536
- let r=n??Date.now(),o=Le(e,r);if(!o)return null;let i=Wo(t.iterations),s=(t.input_tokens??0)+(i?.input??0),a=(t.output_tokens??0)+(i?.output??0),c=(t.cache_read_input_tokens??0)+(i?.cacheRead??0),l=t.
537
- cache_creation,p=t.cache_creation_input_tokens??(l?.ephemeral_5m_input_tokens??0)+(l?.ephemeral_1h_input_tokens??0),u=p+(i?.cacheWrite??0),f=Math.min(Math.min(l?.ephemeral_1h_input_tokens??0,p)+(i?.cacheWrite1h??
538
- 0),u),m={entrada:s,salida:a,cacheLeida:c,cacheEscrita:u,cacheEscrita1h:f};return {costeUsd:Ka(o,m,e),precio:o,tokens:m,instante:r}}function Ja(e,t){let r=Kt(e,t)?.model;return typeof r=="string"?r:""}function Kt(e,t){
539
- try{let n=e,r={maxOutputLength:nm};switch((t??"").trim().toLowerCase()){case "gzip":case "x-gzip":n=st.gunzipSync(e,r);break;case "deflate":n=st.inflateSync(e,r);break;case "br":n=st.brotliDecompressSync(
540
- e,r);break;case "zstd":{let o=st.zstdDecompressSync;if(typeof o!="function")return null;n=o(e,r);break}default:break}return JSON.parse(n.toString("utf8"))}catch{return null}}var nm=5*1024*1024;function Ya(){
541
- return typeof st.zstdDecompressSync=="function"}function rm(e){try{return JSON.parse(typeof e=="string"?e:e.toString("utf8")).usage??null}catch{return null}}function xr(e,t){if(e==="/v1/messages")return rm(
542
- t);if(!Tt(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 Wa(n.usage);let r=n.usage;return r&&
543
- typeof r.input_tokens=="number"&&typeof r.output_tokens=="number"?wr(r):null}catch{return null}}function Za(e,t){if(!e.endsWith("/responses"))return false;try{let n=JSON.parse(typeof t=="string"?t:t.toString(
544
- "utf8"));return n!==null&&typeof n=="object"&&n.status==="failed"}catch{return false}}function Xa(e){let t=n=>{let r=n!==null&&typeof n=="object"?n.refusal:void 0;return typeof r=="string"&&r!==""};return Array.
545
- isArray(e)&&e.some(n=>{if(n===null||typeof n!="object")return false;let r=n;return ai(r.finish_reason)||t(r.message)||t(r.delta)})}function Qa(e,t){if(e!=="/v1/messages"&&!e.endsWith("/chat/completions")&&
542
+ ject")return;if(this.eventos.chunk=(this.eventos.chunk??0)+1,lc(n.choices)&&(this.filtrada=true),Array.isArray(n.choices)&&!this.texto.lleno()){let o=n.choices[0];this.texto.sumar(o?.delta?.content);}if(n.
543
+ usage===null||typeof n.usage!="object")return;let r=oc(n.usage);r!==null&&(this.ultimoUso=r,Array.isArray(n.choices)&&n.choices.length===0&&(this.vioUsoFinal=true));}};function ic(e,t,n){let r=e.cachedInputPer1k??
544
+ e.inputPer1k;return t.entrada/1e3*e.inputPer1k+t.cacheLeida/1e3*r+(t.cacheEscrita-t.cacheEscrita1h)/1e3*e.inputPer1k*xe(n)+t.cacheEscrita1h/1e3*e.inputPer1k*2+t.salida/1e3*e.outputPer1k}function wi(e,t,n){
545
+ let r=n??Date.now(),o=Ne(e,r);if(!o)return null;let i=ei(t.iterations),s=(t.input_tokens??0)+(i?.input??0),a=(t.output_tokens??0)+(i?.output??0),c=(t.cache_read_input_tokens??0)+(i?.cacheRead??0),l=t.
546
+ cache_creation,d=t.cache_creation_input_tokens??(l?.ephemeral_5m_input_tokens??0)+(l?.ephemeral_1h_input_tokens??0),u=d+(i?.cacheWrite??0),f=Math.min(Math.min(l?.ephemeral_1h_input_tokens??0,d)+(i?.cacheWrite1h??
547
+ 0),u),m={entrada:s,salida:a,cacheLeida:c,cacheEscrita:u,cacheEscrita1h:f};return {costeUsd:ic(o,m,e),precio:o,tokens:m,instante:r}}function sc(e,t){let r=en(e,t)?.model;return typeof r=="string"?r:""}function en(e,t){
548
+ try{let n=e,r={maxOutputLength:dm};switch((t??"").trim().toLowerCase()){case "gzip":case "x-gzip":n=ct.gunzipSync(e,r);break;case "deflate":n=ct.inflateSync(e,r);break;case "br":n=ct.brotliDecompressSync(
549
+ e,r);break;case "zstd":{let o=ct.zstdDecompressSync;if(typeof o!="function")return null;n=o(e,r);break}default:break}return JSON.parse(n.toString("utf8"))}catch{return null}}var dm=5*1024*1024;function ac(){
550
+ return typeof ct.zstdDecompressSync=="function"}function pm(e){try{return JSON.parse(typeof e=="string"?e:e.toString("utf8")).usage??null}catch{return null}}function Tr(e,t){if(e==="/v1/messages")return pm(
551
+ t);if(!$t(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 oc(n.usage);let r=n.usage;return r&&
552
+ typeof r.input_tokens=="number"&&typeof r.output_tokens=="number"?Cr(r):null}catch{return null}}function cc(e,t){if(!e.endsWith("/responses"))return false;try{let n=JSON.parse(typeof t=="string"?t:t.toString(
553
+ "utf8"));return n!==null&&typeof n=="object"&&n.status==="failed"}catch{return false}}function lc(e){let t=n=>{let r=n!==null&&typeof n=="object"?n.refusal:void 0;return typeof r=="string"&&r!==""};return Array.
554
+ isArray(e)&&e.some(n=>{if(n===null||typeof n!="object")return false;let r=n;return mi(r.finish_reason)||t(r.message)||t(r.delta)})}function uc(e,t){if(e!=="/v1/messages"&&!e.endsWith("/chat/completions")&&
546
555
  !e.endsWith("/responses"))return false;try{let n=JSON.parse(typeof t=="string"?t:t.toString("utf8"));return n===null||typeof n!="object"?!1:e==="/v1/messages"?n.stop_reason==="refusal":e.endsWith("/chat/c\
547
- ompletions")?Xa(n.choices):fi(n.output)}catch{return false}}var pi=1200,yn=class{t="";sumar(t){typeof t=="string"&&this.t.length<pi&&(this.t=(this.t+t).slice(0,pi));}lleno(){return this.t.length>=pi}valor(){
548
- return this.t}};function ec(e,t){try{let n=JSON.parse(typeof t=="string"?t:t.toString("utf8"));if(n===null||typeof n!="object")return "";let r=(o,i,s)=>Array.isArray(o)?o.filter(a=>a!==null&&typeof a==
556
+ ompletions")?lc(n.choices):ki(n.output)}catch{return false}}var yi=1200,Sn=class{t="";sumar(t){typeof t=="string"&&this.t.length<yi&&(this.t=(this.t+t).slice(0,yi));}lleno(){return this.t.length>=yi}valor(){
557
+ return this.t}};function dc(e,t){try{let n=JSON.parse(typeof t=="string"?t:t.toString("utf8"));if(n===null||typeof n!="object")return "";let r=(o,i,s)=>Array.isArray(o)?o.filter(a=>a!==null&&typeof a==
549
558
  "object"&&a.type===i).map(a=>a[s]).filter(a=>typeof a=="string").join(""):"";if(e==="/v1/messages")return r(n.content,"text","text");if(e.endsWith("/chat/completions")){let i=(Array.isArray(n.choices)?
550
559
  n.choices[0]:void 0)?.message?.content;return typeof i=="string"?i:r(i,"text","text")}return e.endsWith("/responses")&&Array.isArray(n.output)?n.output.map(o=>o!==null&&typeof o=="object"?r(o.content,
551
- "output_text","text"):"").join(""):""}catch{return ""}}function tc(e){return si(e)!==null}function hi(e,t){if(e!=="/v1/messages")return false;try{let n=JSON.parse(typeof t=="string"?t:t.toString("utf8"));return n===
552
- null||typeof n!="object"?!1:vr({stopReason:n.stop_reason,stopDetails:n.stop_details,bloques:Array.isArray(n.content)?n.content.length:-1,outputTokens:n.usage?.output_tokens,iterations:n.usage?.iterations})}catch{
553
- return false}}function nc(e,t){let n=typeof t=="string"?t:t.toString("utf8"),r=i=>{if(i===null||typeof i!="object")return;let s=i,a=l=>l!==null&&typeof l=="object"?l.service_tier:void 0,c;return e==="/v1/\
560
+ "output_text","text"):"").join(""):""}catch{return ""}}function pc(e){return fi(e)!==null}function xi(e,t){if(e!=="/v1/messages")return false;try{let n=JSON.parse(typeof t=="string"?t:t.toString("utf8"));return n===
561
+ null||typeof n!="object"?!1:wr({stopReason:n.stop_reason,stopDetails:n.stop_details,bloques:Array.isArray(n.content)?n.content.length:-1,outputTokens:n.usage?.output_tokens,iterations:n.usage?.iterations})}catch{
562
+ return false}}function fc(e,t){let n=typeof t=="string"?t:t.toString("utf8"),r=i=>{if(i===null||typeof i!="object")return;let s=i,a=l=>l!==null&&typeof l=="object"?l.service_tier:void 0,c;return e==="/v1/\
554
563
  messages"?(c=a(s.usage),c===void 0&&s.message!==null&&typeof s.message=="object"&&(c=a(s.message.usage))):e.endsWith("/chat/completions")?c=s.service_tier:e.endsWith("/responses")&&(c=s.service_tier,c===
555
564
  void 0&&s.response!==null&&typeof s.response=="object"&&(c=s.response.service_tier)),typeof c=="string"&&c!==""?c:void 0};try{return r(JSON.parse(n))}catch{}let o;for(let i of n.split(`
556
- `)){if(!i.startsWith("data:"))continue;let s=i.slice(5).trim();if(!(s===""||s==="[DONE]"))try{o=r(JSON.parse(s))??o;}catch{}}return o}function Tt(e){return e==="/v1/messages"||e.endsWith("/chat/complet\
557
- ions")||e.endsWith("/responses")}var om=Buffer.from('"stream_options":{"include_usage":true},',"utf8");function rc(e,t){let n=(t??"").trim().toLowerCase();if(n!==""&&n!=="identity")return {cuerpo:null,
565
+ `)){if(!i.startsWith("data:"))continue;let s=i.slice(5).trim();if(!(s===""||s==="[DONE]"))try{o=r(JSON.parse(s))??o;}catch{}}return o}function $t(e){return e==="/v1/messages"||e.endsWith("/chat/complet\
566
+ ions")||e.endsWith("/responses")}var fm=Buffer.from('"stream_options":{"include_usage":true},',"utf8");function mc(e,t){let n=(t??"").trim().toLowerCase();if(n!==""&&n!=="identity")return {cuerpo:null,
558
567
  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:"\
559
568
  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,
560
569
  motivo:"cliente-decide"};let i=0;for(;i<e.length;){let s=e[i];if(s===32||s===9||s===10||s===13){i++;continue}if(s===239&&e[i+1]===187&&e[i+2]===191){i+=3;continue}break}return e[i]!==123?{cuerpo:null,
561
- motivo:"ilegible"}:{cuerpo:Buffer.concat([e.subarray(0,i+1),om,e.subarray(i+1)]),motivo:"inyectado"}}function oc(e,t){let n=Kt(e,t);if(n===null||typeof n!="object")return null;let r=n;return r.stream!==
562
- true?null:r.stream_options?.include_usage===true}function gi(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();
563
- return r==="chatgpt.com"||r.endsWith(".chatgpt.com")}catch{return false}}function ic(e,t,n,r,o,i,s,a,c,l){return cc(e,t,n,false,r,o,i,s,a,c,l===true)}function im(e){if(e===null||typeof e!="object"||Array.isArray(
564
- e))return [];let t=e,n=o=>typeof o=="string"?[o]:Array.isArray(o)?o.filter(i=>i!==null&&typeof i=="object").filter(i=>i.type==="text"||i.type==="input_text").map(i=>i.text).filter(i=>typeof i=="string"):
565
- [],r=o=>Array.isArray(o)?o.filter(i=>i!==null&&typeof i=="object").filter(i=>i.role==="user").flatMap(i=>n(i.content)):[];return [...r(t.messages),...typeof t.input=="string"?[t.input]:r(t.input)]}function sm(e){
566
- return di(im(e))}var am=new Set(["auto","default","priority","standard_only"]);function cm(e){if(e==null)return 1;if(typeof e!="string")return null;if(am.has(e))return 1;let t=gr(e);return t!==null&&t.
567
- conDescuento&&t.factor!==null?t.factor:null}function lm(e){if(e===void 0)return 1;if(e==="scale")return null;let t=gr(e);return t!==null&&t.factor!==null?t.factor:null}function sc(e,t,n,r,o){if(!n||!n.
568
- conContador)return {ok:false,reason:"no-primary-record"};if(n.suscripcion||o.suscripcion)return {ok:false,reason:"subscription"};if(!n.proveedorOficial)return {ok:false,reason:"unofficial-upstream"};if(!n.intacta)
570
+ motivo:"ilegible"}:{cuerpo:Buffer.concat([e.subarray(0,i+1),fm,e.subarray(i+1)]),motivo:"inyectado"}}function hc(e,t){let n=en(e,t);if(n===null||typeof n!="object")return null;let r=n;return r.stream!==
571
+ true?null:r.stream_options?.include_usage===true}function Si(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();
572
+ return r==="chatgpt.com"||r.endsWith(".chatgpt.com")}catch{return false}}function gc(e,t,n,r,o,i,s,a,c,l,d){return yc(e,t,n,false,r,o,i,s,a,c,l===true,d??null)}function mm(e){if(e===null||typeof e!="object"||Array.
573
+ isArray(e))return [];let t=e,n=o=>typeof o=="string"?[o]:Array.isArray(o)?o.filter(i=>i!==null&&typeof i=="object").filter(i=>i.type==="text"||i.type==="input_text").map(i=>i.text).filter(i=>typeof i==
574
+ "string"):[],r=o=>Array.isArray(o)?o.filter(i=>i!==null&&typeof i=="object").filter(i=>i.role==="user").flatMap(i=>n(i.content)):[];return [...r(t.messages),...typeof t.input=="string"?[t.input]:r(t.input)]}
575
+ function hm(e){return vi(mm(e))}var gm=new Set(["auto","default","priority","standard_only"]);function bm(e){if(e==null)return 1;if(typeof e!="string")return null;if(gm.has(e))return 1;let t=yr(e);return t!==
576
+ null&&t.conDescuento&&t.factor!==null?t.factor:null}function vm(e){if(e===void 0)return 1;if(e==="scale")return null;let t=yr(e);return t!==null&&t.factor!==null?t.factor:null}function bc(e,t,n,r,o){if(!n||
577
+ !n.conContador)return {ok:false,reason:"no-primary-record"};if(n.suscripcion||o.suscripcion)return {ok:false,reason:"subscription"};if(!n.proveedorOficial)return {ok:false,reason:"unofficial-upstream"};if(!n.intacta)
569
578
  return {ok:false,reason:"layer-changed-request"};if(n.fallida)return {ok:false,reason:"primary-failed"};if(n.negativa===true)return {ok:false,reason:"primary-refused"};if(n.negativaEnTexto===true)return {ok:false,reason:"\
570
- primary-text-refusal"};if(sm(r)!==null)return {ok:false,reason:"sensitive-topic"};if(!o.entregada)return {ok:false,reason:"client-disconnected"};let i=r!==null&&typeof r=="object"&&!Array.isArray(r)?r:{},s=cm(
571
- i.service_tier),a=lm(o.tierServido);if(s===null||a===null)return {ok:false,reason:"service-tier"};let c=Math.min(s,a),l=Bt(e,t.instante),p=l?.cachedInputPer1k;if(!l||typeof p!="number"||!Number.isFinite(p)||
572
- !(p>0)||!Number.isFinite(l.inputPer1k)||p>l.inputPer1k||!Number.isFinite(l.outputPer1k)||l.outputPer1k<0)return {ok:false,reason:"no-cached-price"};let u=t.tokens,f=u.entrada+u.cacheLeida+u.cacheEscrita,m=k=>Number.
573
- isInteger(k)&&k>=0;if(!m(u.entrada)||!m(u.cacheLeida)||!m(u.cacheEscrita)||!m(u.salida)||!(f>0))return {ok:false,reason:"no-credit"};let b=i.temperature===0&&Go(e)===void 0;return {ok:true,credit:{requestId:n.
574
- requestId,at:n.at,inputTokens:f,outputTokens:u.salida,creditedInputTokens:f,creditedOutputTokens:b?Math.floor(.95*u.salida):0,cachedInputPer1k:p,outputPer1k:l.outputPer1k,tierFactor:c}}}function bi(e){
575
- return e.tierFactor*(e.creditedInputTokens/1e3*e.cachedInputPer1k+e.creditedOutputTokens/1e3*e.outputPer1k)}function ac(e,t,n,r,o,i){let s=o?bi(o):0;return i===true||!o||!(s>0)||!Number.isFinite(s)?cc(e,
579
+ primary-text-refusal"};if(hm(r)!==null)return {ok:false,reason:"sensitive-topic"};if(!o.entregada)return {ok:false,reason:"client-disconnected"};let i=r!==null&&typeof r=="object"&&!Array.isArray(r)?r:{},s=bm(
580
+ i.service_tier),a=vm(o.tierServido);if(s===null||a===null)return {ok:false,reason:"service-tier"};let c=Math.min(s,a),l=Ht(e,t.instante),d=l?.cachedInputPer1k;if(!l||typeof d!="number"||!Number.isFinite(d)||
581
+ !(d>0)||!Number.isFinite(l.inputPer1k)||d>l.inputPer1k||!Number.isFinite(l.outputPer1k)||l.outputPer1k<0)return {ok:false,reason:"no-cached-price"};let u=t.tokens,f=u.entrada+u.cacheLeida+u.cacheEscrita,m=y=>Number.
582
+ isInteger(y)&&y>=0;if(!m(u.entrada)||!m(u.cacheLeida)||!m(u.cacheEscrita)||!m(u.salida)||!(f>0))return {ok:false,reason:"no-credit"};let b=i.temperature===0&&Qo(e)===void 0;return {ok:true,credit:{requestId:n.
583
+ requestId,at:n.at,inputTokens:f,outputTokens:u.salida,creditedInputTokens:f,creditedOutputTokens:b?Math.floor(.95*u.salida):0,cachedInputPer1k:d,outputPer1k:l.outputPer1k,tierFactor:c}}}function Ei(e){
584
+ return e.tierFactor*(e.creditedInputTokens/1e3*e.cachedInputPer1k+e.creditedOutputTokens/1e3*e.outputPer1k)}function vc(e,t,n,r,o,i){let s=o?Ei(o):0;return i===true||!o||!(s>0)||!Number.isFinite(s)?yc(e,
576
585
  t,n,true,r,void 0,void 0,void 0,false,false,i===true):{requestId:e,model:t,...r&&(r.sessionId||r.agentId)?{attribution:r}:{},calls:{avoidedLlm:1,actualLlm:0},tokens:{baselineInput:o.creditedInputTokens,actualInput:0,
577
586
  eliminatedInput:0,compressedInput:0,baselineOutput:o.creditedOutputTokens,actualOutput:0,providerCachedInput:0},cache:{result:"singleflight",reference:o},cost:{baselineEstimate:s,actual:0,netSavingsRatio:1,
578
- netSavingsUsd:s,basis:"reference"}}}function vi(e,t,n,r,o){return {requestId:e,model:t,...o&&(o.sessionId||o.agentId)?{attribution:o}:{},calls:{avoidedLlm:0,actualLlm:0},tokens:{baselineInput:0,actualInput:0,
587
+ netSavingsUsd:s,basis:"reference"}}}function _i(e,t,n,r,o){return {requestId:e,model:t,...o&&(o.sessionId||o.agentId)?{attribution:o}:{},calls:{avoidedLlm:0,actualLlm:0},tokens:{baselineInput:0,actualInput:0,
579
588
  eliminatedInput:0,compressedInput:0,baselineOutput:0,actualOutput:0,providerCachedInput:0},cache:{result:"miss"},cost:{baselineEstimate:n,actual:r,netSavingsRatio:n>0?Math.max(-100,Math.min(1,(n-r)/n)):
580
- 0,netSavingsUsd:n-r,basis:"shadow"}}}function um(e,t){let n=Le(e.solicitado,t.instante);return n===void 0?0:Math.max(0,Ka(n,t.tokens,e.solicitado)-t.costeUsd)}function cc(e,t,n,r,o,i,s,a,c=false,l=false,p=false){
581
- p&&(n={...n,costeUsd:0});let u=n.tokens.entrada+n.tokens.cacheLeida+n.tokens.cacheEscrita,m=!r&&!c&&!l&&!p,b=n.tokens.cacheEscrita-n.tokens.cacheEscrita1h,k=m&&s&&s.rebajadas>0&&s.yaEran5m===0&&!s.herramientaDeServidor&&
582
- b>0?b/1e3*n.precio.inputPer1k*(2-1.25):0,g=m&&a?um(a,n):0,v=n.costeUsd+k+g,x=k+g,E=r||l||p?0:em(n.precio,i),y=m?Jo(t,n.precio,{leidos:n.tokens.cacheLeida,escritos:n.tokens.cacheEscrita,escritos1h:n.tokens.
583
- cacheEscrita1h}):void 0;return {requestId:e,model:t,...o&&(o.sessionId||o.agentId)?{attribution:o}:{},calls:r?{avoidedLlm:1,actualLlm:0}:{avoidedLlm:0,actualLlm:1},tokens:{baselineInput:u,
584
- actualInput:r?0:u,eliminatedInput:r?0:i?.tokensLimpiados??0,compressedInput:0,baselineOutput:n.tokens.salida,actualOutput:r?0:n.tokens.salida,providerCachedInput:r?0:n.tokens.cacheLeida},cache:{result:r?
585
- "singleflight":"miss"},...y?{nativeSavings:y}:{},cost:r?{baselineEstimate:n.costeUsd,actual:0,netSavingsRatio:p?0:1,netSavingsUsd:n.costeUsd,basis:"estimated"}:{baselineEstimate:v,actual:n.costeUsd,netSavingsRatio:v>
586
- 0?Math.max(-100,Math.min(1,x/v)):0,netSavingsUsd:v-n.costeUsd,basis:"measured",...E>0?{eliminatedInputFloorCost:E}:{}}}}var dm=1024,kn=120,pm=8,fm=256*1024,mm=/error|exception|traceback|warn|fatal|fail|panic|assert|denied|refused|timeout|\bat\s+\S+:\d+/i,dc=/^\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)/;
587
- function hm(e){return Buffer.byteLength(typeof e=="string"?e:JSON.stringify(e??""))}function gm(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t&&typeof t=="object"&&typeof t.text=="string"?
589
+ 0,netSavingsUsd:n-r,basis:"shadow"}}}function ym(e,t){let n=Ne(e.solicitado,t.instante);return n===void 0?0:Math.max(0,ic(n,t.tokens,e.solicitado)-t.costeUsd)}function yc(e,t,n,r,o,i,s,a,c=false,l=false,d=false,u=null){
590
+ d&&(n={...n,costeUsd:0});let f=n.tokens.entrada+n.tokens.cacheLeida+n.tokens.cacheEscrita,b=!r&&!c&&!l&&!d,y=n.tokens.cacheEscrita-n.tokens.cacheEscrita1h,g=b&&u?Math.max(0,Math.min(u.perdidos,n.tokens.
591
+ cacheEscrita)):0,x=b&&s&&s.rebajadas>0&&s.yaEran5m===0&&!s.herramientaDeServidor&&y-g>0?(y-g)/1e3*n.precio.inputPer1k*(2-1.25):0,C=n.tokens.cacheEscrita>0?(Math.max(0,y)*1.25+n.tokens.cacheEscrita1h*2)/
592
+ n.tokens.cacheEscrita:2,k=Math.min(n.costeUsd,_r({perdidos:g,inputPer1k:n.precio.inputPer1k,cachedInputPer1k:n.precio.cachedInputPer1k,primaEscritura:C})),R=b&&a?ym(a,n):0,A=Math.max(0,n.costeUsd+x+R-
593
+ k),D=A-n.costeUsd,$=r||l||d?0:lm(n.precio,i),j=b?ni(t,n.precio,{leidos:n.tokens.cacheLeida,escritos:n.tokens.cacheEscrita,escritos1h:n.tokens.cacheEscrita1h}):void 0;return {requestId:e,
594
+ model:t,...o&&(o.sessionId||o.agentId)?{attribution:o}:{},calls:r?{avoidedLlm:1,actualLlm:0}:{avoidedLlm:0,actualLlm:1},tokens:{baselineInput:f,actualInput:r?0:f,eliminatedInput:r?0:i?.tokensLimpiados??
595
+ 0,compressedInput:0,baselineOutput:n.tokens.salida,actualOutput:r?0:n.tokens.salida,providerCachedInput:r?0:n.tokens.cacheLeida},cache:{result:r?"singleflight":"miss"},...j?{nativeSavings:j}:{},cost:r?
596
+ {baselineEstimate:n.costeUsd,actual:0,netSavingsRatio:d?0:1,netSavingsUsd:n.costeUsd,basis:"estimated"}:{baselineEstimate:A,actual:n.costeUsd,netSavingsRatio:A>0?Math.max(-100,Math.min(1,D/A)):0,netSavingsUsd:A-
597
+ n.costeUsd,basis:"measured",...$>0?{eliminatedInputFloorCost:$}:{}}}}var km=1024,En=120,wm=8,xm=256*1024,Sm=/error|exception|traceback|warn|fatal|fail|panic|assert|denied|refused|timeout|\bat\s+\S+:\d+/i,xc=/^\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)/;
598
+ function Em(e){return Buffer.byteLength(typeof e=="string"?e:JSON.stringify(e??""))}function _m(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t&&typeof t=="object"&&typeof t.text=="string"?
588
599
  t.text:"").join(`
589
- `):""}var bm=/^\s*\d+[\t→]/;function pc(e){return e.replace(bm,"")}function vm(e){if(!e)return "otro";let t=e.split(`
590
- `),n=Math.max(1,t.length),r=0,o=0,i=0;for(let s of t){let a=pc(s);(/^[+-](?![+-])/.test(a)||a.startsWith("@@")||a.startsWith("diff --git"))&&(r+=1),dc.test(a)&&(o+=1),(/^\s*(\d{4}-\d{2}-\d{2}|\[\d|\d{2}:\d{2}:\d{2})/.
591
- test(a)||/\b(INFO|DEBUG|TRACE|WARN|ERROR)\b/.test(a))&&(i+=1);}return r/n>.25?"diff":i/n>.3?"log":o/n>.08?"codigo":"otro"}function ym(e,t){if(t==="diff"||t==="otro")return Buffer.byteLength(e);let n=e.
600
+ `):""}var Cm=/^\s*\d+[\t→]/;function Sc(e){return e.replace(Cm,"")}function Tm(e){if(!e)return "otro";let t=e.split(`
601
+ `),n=Math.max(1,t.length),r=0,o=0,i=0;for(let s of t){let a=Sc(s);(/^[+-](?![+-])/.test(a)||a.startsWith("@@")||a.startsWith("diff --git"))&&(r+=1),xc.test(a)&&(o+=1),(/^\s*(\d{4}-\d{2}-\d{2}|\[\d|\d{2}:\d{2}:\d{2})/.
602
+ test(a)||/\b(INFO|DEBUG|TRACE|WARN|ERROR)\b/.test(a))&&(i+=1);}return r/n>.25?"diff":i/n>.3?"log":o/n>.08?"codigo":"otro"}function Rm(e,t){if(t==="diff"||t==="otro")return Buffer.byteLength(e);let n=e.
592
603
  split(`
593
- `),r=new Set;for(let i=0;i<n.length;i++){let s=pc(n[i]);(t==="log"?mm.test(s):dc.test(s))&&(r.add(i),t==="log"&&(i>0&&r.add(i-1),i<n.length-1&&r.add(i+1)));}let o=kn;for(let i of r)o+=Buffer.byteLength(
594
- n[i])+1;return Math.min(o,Buffer.byteLength(e))}var km=(e,t)=>e==="cache_control"?void 0:t;function wm(e){if(typeof e=="string")return `text:${e}`;if(!e||typeof e!="object"||Array.isArray(e))return `jso\
595
- 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,km)}`}
596
- function xm(e){return createHash("sha256").update(wm(e)).digest("hex").slice(0,16)}function Sm(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.cache_control;return !t||typeof t!="object"?null:
597
- t.ttl==="1h"?"1h":"5m"}function fc(e){let t=[],n=(r,o)=>{let i=hm(o),s={clave:xm(o),tipo:r,marca:Sm(o),bytes:i,bytesV1:i,clase:"otro",esError:false};if(r.endsWith(":tool_result")&&o&&typeof o=="object"){
598
- let a=o;s.esError=a.is_error===true;let c=gm(a.content);s.clase=vm(c);let l=i-Buffer.byteLength(c);s.bytesV1=Math.min(i,Math.max(0,l)+ym(c,s.clase));}t.push(s);};if(Array.isArray(e.tools))for(let r of e.tools)
604
+ `),r=new Set;for(let i=0;i<n.length;i++){let s=Sc(n[i]);(t==="log"?Sm.test(s):xc.test(s))&&(r.add(i),t==="log"&&(i>0&&r.add(i-1),i<n.length-1&&r.add(i+1)));}let o=En;for(let i of r)o+=Buffer.byteLength(
605
+ n[i])+1;return Math.min(o,Buffer.byteLength(e))}var Am=(e,t)=>e==="cache_control"?void 0:t;function Im(e){if(typeof e=="string")return `text:${e}`;if(!e||typeof e!="object"||Array.isArray(e))return `jso\
606
+ 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,Am)}`}
607
+ function Pm(e){return createHash("sha256").update(Im(e)).digest("hex").slice(0,16)}function Dm(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.cache_control;return !t||typeof t!="object"?null:
608
+ t.ttl==="1h"?"1h":"5m"}function Ec(e){let t=[],n=(r,o)=>{let i=Em(o),s={clave:Pm(o),tipo:r,marca:Dm(o),bytes:i,bytesV1:i,clase:"otro",esError:false};if(r.endsWith(":tool_result")&&o&&typeof o=="object"){
609
+ let a=o;s.esError=a.is_error===true;let c=_m(a.content);s.clase=Tm(c);let l=i-Buffer.byteLength(c);s.bytesV1=Math.min(i,Math.max(0,l)+Rm(c,s.clase));}t.push(s);};if(Array.isArray(e.tools))for(let r of e.tools)
599
610
  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!=
600
611
  "object"){n("?:invalido",r);continue}let o=r,i=typeof o.role=="string"?o.role:"?";if(typeof o.content=="string")n(`${i}:text`,o.content);else if(Array.isArray(o.content))for(let s of o.content)n(`${i}\
601
- :${s?.type??"?"}`,s);}return t}function Em(){return {nacimiento:new Map,turno:0,elididosV2m:new Set}}function _m(e,t){let n=e.turno++;for(let r of t)e.nacimiento.has(r.clave)||e.nacimiento.set(r.clave,n);
602
- return n}function mc(e,t,n,r,o=fm){let i=t.reduce((u,f,m)=>f.tipo.endsWith(":tool_result")?m:u,-1),s=(u,f)=>u.tipo.endsWith(":tool_result")&&u.bytes>=dm&&f!==i;return t.map((u,f)=>{if(!s(u,
603
- f))return {clave:u.clave,bytes:u.bytes};let m=r-(n.nacimiento.get(u.clave)??r);return m>=2&&m*u.bytes/1024>=pm?{clave:`${u.clave}:e`,bytes:kn}:{clave:u.clave,bytes:u.bytes}});}function Cm(e,t){let n=Le(e,t);return n?{inputPer1k:n.inputPer1k,lecturaPer1k:n.cachedInputPer1k??n.inputPer1k,escrituraPer1k:n.inputPer1k*
604
- ve(e),escritura1hPer1k:n.inputPer1k*jt(e)}:null}function lc(){return {lecturaUsd:0,escrituraUsd:0,entradaUsd:0,totalUsd:0,tokensLeidos:0,tokensEscritos:0,tokensEntrada:0,tokensInvalidados:0,invalidacionUsd:0}}
605
- var ki={"1h":36e5,"5m":3e5},Tm=20,Rm=6e3,Am=2e4,Jt=class{constructor(t=Am){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?
606
- r:null}escribir(t,n,r){this.entradas.delete(t),this.entradas.set(t,{expira:n+ki[r],ttl:r}),this.entradas.size>this.tope&&this.podar(n);}refrescar(t,n){let r=this.entradas.get(t);r&&(this.entradas.delete(
607
- t),this.entradas.set(t,{expira:n+ki[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().
608
- value;if(n===void 0)break;this.entradas.delete(n);}}};function Im(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(
609
- "|").update(t[o]).digest("hex").slice(0,32),n[o]=r;return n}function Pm(e){let t=new Array(e.length),n=-1,r="";for(let o=0;o<e.length;o++){let i=e[o],s=i.endsWith(":tool_use")||i.endsWith(":tool_resul\
610
- t");s&&i===r||(n+=1),r=s?i:"",t[o]=n;}return t}function uc(e,t){return e.endsWith(":image")?Math.min(t,Rm):t}var wn=class{constructor(t,n){this.transformar=t;this.cache=n??new Jt;}transformar;estado=Em();cache;previo=[];previoUltimoBp=-1;previoTtl="\
611
- 5m";hayPrevio=false;atPrevio=0;acumulado=lc();paso(t){let n=lc(),r=_m(this.estado,t.bloques),o=Cm(t.model,t.at),i=this.transformar(t.bloques,this.estado,r);if(!o||t.entradaReal<=0||i.length===0)return this.
612
- previo=i,this.previoUltimoBp=-1,this.previoTtl="5m",this.hayPrevio=true,this.atPrevio=t.at,n;let s=i.map((y,R)=>t.bloques[R]?.tipo??""),a=i.map((y,R)=>t.bloques[R]?.marca??null),c=t.bloques.reduce((y,R)=>y+
613
- uc(R.tipo,R.bytes),0),l=c>0?t.entradaReal/c:0,p=i.map((y,R)=>uc(s[R],y.bytes)*l),u=Im(t.model,i.map(y=>y.clave)),f=Pm(s),m=a.map((y,R)=>y?R:-1).filter(y=>y>=0);if(m.length===0){for(let y=0;y<i.length;y++)
614
- n.tokensEntrada+=p[y],n.entradaUsd+=p[y]/1e3*o.inputPer1k;return n.totalUsd=n.entradaUsd,this.previo=i,this.previoUltimoBp=-1,this.previoTtl="5m",this.hayPrevio=true,this.atPrevio=t.at,this.acumulado.tokensEntrada+=
615
- n.tokensEntrada,this.acumulado.entradaUsd+=n.entradaUsd,this.acumulado.totalUsd+=n.totalUsd,n}let b=-1;for(let y of m){let R=f[y]-(Tm-1);for(let P=y;P>=0&&f[P]>=R;P--)if(this.cache.viva(u[P],t.at)){P>
616
- b&&(b=P);break}}for(let y=0;y<=b;y++)this.cache.refrescar(u[y],t.at);let k=m[m.length-1];for(let y of m)y>b&&this.cache.escribir(u[y],t.at,a[y]);let g=0,x=this.hayPrevio&&t.at-this.atPrevio>ki[this.previoTtl]?
617
- []:this.previo.slice(b+1,this.previoUltimoBp+1),E=0;for(let y=0;y<i.length;y++){let R=i[y],P=p[y];if(y<=b){n.tokensLeidos+=P,n.lecturaUsd+=P/1e3*o.lecturaPer1k;continue}if(y>k){n.tokensEntrada+=P,n.entradaUsd+=
618
- P/1e3*o.inputPer1k;continue}for(;m[g]<y;)g+=1;let L=a[m[g]]==="1h"?o.escritura1hPer1k:o.escrituraPer1k;n.tokensEscritos+=P,n.escrituraUsd+=P/1e3*L;let M=E;for(;M<x.length&&x[M].clave!==R.clave;)M+=1;M<
619
- x.length&&(x[M].bytes===R.bytes&&(n.tokensInvalidados+=P,n.invalidacionUsd+=P/1e3*(L-o.lecturaPer1k)),E=M+1);}return this.previo=i,this.previoUltimoBp=k,this.previoTtl=a[k]??"5m",this.hayPrevio=true,this.
612
+ :${s?.type??"?"}`,s);}return t}function Om(){return {nacimiento:new Map,turno:0,elididosV2m:new Set}}function Lm(e,t){let n=e.turno++;for(let r of t)e.nacimiento.has(r.clave)||e.nacimiento.set(r.clave,n);
613
+ return n}function _c(e,t,n,r,o=xm){let i=t.reduce((u,f,m)=>f.tipo.endsWith(":tool_result")?m:u,-1),s=(u,f)=>u.tipo.endsWith(":tool_result")&&u.bytes>=km&&f!==i;return t.map((u,f)=>{if(!s(u,
614
+ f))return {clave:u.clave,bytes:u.bytes};let m=r-(n.nacimiento.get(u.clave)??r);return m>=2&&m*u.bytes/1024>=wm?{clave:`${u.clave}:e`,bytes:En}:{clave:u.clave,bytes:u.bytes}});}function $m(e,t){let n=Ne(e,t);return n?{inputPer1k:n.inputPer1k,lecturaPer1k:n.cachedInputPer1k??n.inputPer1k,escrituraPer1k:n.inputPer1k*
615
+ xe(e),escritura1hPer1k:n.inputPer1k*qt(e)}:null}function kc(){return {lecturaUsd:0,escrituraUsd:0,entradaUsd:0,totalUsd:0,tokensLeidos:0,tokensEscritos:0,tokensEntrada:0,tokensInvalidados:0,invalidacionUsd:0}}
616
+ var Ti={"1h":36e5,"5m":3e5},Mm=20,Nm=6e3,jm=2e4,tn=class{constructor(t=jm){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?
617
+ r:null}escribir(t,n,r){this.entradas.delete(t),this.entradas.set(t,{expira:n+Ti[r],ttl:r}),this.entradas.size>this.tope&&this.podar(n);}refrescar(t,n){let r=this.entradas.get(t);r&&(this.entradas.delete(
618
+ t),this.entradas.set(t,{expira:n+Ti[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().
619
+ value;if(n===void 0)break;this.entradas.delete(n);}}};function Bm(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(
620
+ "|").update(t[o]).digest("hex").slice(0,32),n[o]=r;return n}function Um(e){let t=new Array(e.length),n=-1,r="";for(let o=0;o<e.length;o++){let i=e[o],s=i.endsWith(":tool_use")||i.endsWith(":tool_resul\
621
+ t");s&&i===r||(n+=1),r=s?i:"",t[o]=n;}return t}function wc(e,t){return e.endsWith(":image")?Math.min(t,Nm):t}var _n=class{constructor(t,n){this.transformar=t;this.cache=n??new tn;}transformar;estado=Om();cache;previo=[];previoUltimoBp=-1;previoTtl="\
622
+ 5m";hayPrevio=false;atPrevio=0;acumulado=kc();paso(t){let n=kc(),r=Lm(this.estado,t.bloques),o=$m(t.model,t.at),i=this.transformar(t.bloques,this.estado,r);if(!o||t.entradaReal<=0||i.length===0)return this.
623
+ previo=i,this.previoUltimoBp=-1,this.previoTtl="5m",this.hayPrevio=true,this.atPrevio=t.at,n;let s=i.map((k,R)=>t.bloques[R]?.tipo??""),a=i.map((k,R)=>t.bloques[R]?.marca??null),c=t.bloques.reduce((k,R)=>k+
624
+ wc(R.tipo,R.bytes),0),l=c>0?t.entradaReal/c:0,d=i.map((k,R)=>wc(s[R],k.bytes)*l),u=Bm(t.model,i.map(k=>k.clave)),f=Um(s),m=a.map((k,R)=>k?R:-1).filter(k=>k>=0);if(m.length===0){for(let k=0;k<i.length;k++)
625
+ n.tokensEntrada+=d[k],n.entradaUsd+=d[k]/1e3*o.inputPer1k;return n.totalUsd=n.entradaUsd,this.previo=i,this.previoUltimoBp=-1,this.previoTtl="5m",this.hayPrevio=true,this.atPrevio=t.at,this.acumulado.tokensEntrada+=
626
+ n.tokensEntrada,this.acumulado.entradaUsd+=n.entradaUsd,this.acumulado.totalUsd+=n.totalUsd,n}let b=-1;for(let k of m){let R=f[k]-(Mm-1);for(let A=k;A>=0&&f[A]>=R;A--)if(this.cache.viva(u[A],t.at)){A>
627
+ b&&(b=A);break}}for(let k=0;k<=b;k++)this.cache.refrescar(u[k],t.at);let y=m[m.length-1];for(let k of m)k>b&&this.cache.escribir(u[k],t.at,a[k]);let g=0,x=this.hayPrevio&&t.at-this.atPrevio>Ti[this.previoTtl]?
628
+ []:this.previo.slice(b+1,this.previoUltimoBp+1),C=0;for(let k=0;k<i.length;k++){let R=i[k],A=d[k];if(k<=b){n.tokensLeidos+=A,n.lecturaUsd+=A/1e3*o.lecturaPer1k;continue}if(k>y){n.tokensEntrada+=A,n.entradaUsd+=
629
+ A/1e3*o.inputPer1k;continue}for(;m[g]<k;)g+=1;let D=a[m[g]]==="1h"?o.escritura1hPer1k:o.escrituraPer1k;n.tokensEscritos+=A,n.escrituraUsd+=A/1e3*D;let $=C;for(;$<x.length&&x[$].clave!==R.clave;)$+=1;$<
630
+ x.length&&(x[$].bytes===R.bytes&&(n.tokensInvalidados+=A,n.invalidacionUsd+=A/1e3*(D-o.lecturaPer1k)),C=$+1);}return this.previo=i,this.previoUltimoBp=y,this.previoTtl=a[y]??"5m",this.hayPrevio=true,this.
620
631
  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.
621
632
  totalUsd+=n.totalUsd,this.acumulado.tokensLeidos+=n.tokensLeidos,this.acumulado.tokensEscritos+=n.tokensEscritos,this.acumulado.tokensEntrada+=n.tokensEntrada,this.acumulado.tokensInvalidados+=n.tokensInvalidados,
622
- this.acumulado.invalidacionUsd+=n.invalidacionUsd,n}};function hc(e){return e.map(t=>({clave:t.clave,bytes:t.bytes}))}var Om=64,Sr=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??
623
- 0),r=(t.uso.input_tokens??0)+(t.uso.cache_read_input_tokens??0)+n;if(r<=0)return null;let o={bloques:fc(t.cuerpo),at:t.at,model:t.model,entradaReal:r,escritura1h:(t.uso.cache_creation?.ephemeral_1h_input_tokens??
633
+ this.acumulado.invalidacionUsd+=n.invalidacionUsd,n}};function Cc(e){return e.map(t=>({clave:t.clave,bytes:t.bytes}))}var zm=64,Rr=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??
634
+ 0),r=(t.uso.input_tokens??0)+(t.uso.cache_read_input_tokens??0)+n;if(r<=0)return null;let o={bloques:Ec(t.cuerpo),at:t.at,model:t.model,entradaReal:r,escritura1h:(t.uso.cache_creation?.ephemeral_1h_input_tokens??
624
635
  0)>0};if(o.bloques.length===0)return null;let i=this.cadenaPara(this.clave(t),t.model),s=i.base.paso(o),a=i.v0.paso(o);return s.totalUsd<=0&&a.totalUsd<=0?null:{baselineUsd:s.totalUsd,politicaUsd:a.totalUsd}}clave(t){
625
636
  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(
626
- "hex").slice(0,16)}\xB7${t.model}`}cachesDe(t){let n=this.cachesPorModelo.get(t);return n||(n={base:new Jt,v0:new Jt},this.cachesPorModelo.set(t,n)),n}cadenaPara(t,n){let r=this.cadenas.get(t);if(!r){
627
- let o=this.cachesDe(n);if(r={base:new wn(i=>hc(i),o.base),v0:new wn((i,s,a)=>mc("v0",i,s,a),o.v0),ultimoUso:0},this.cadenas.set(t,r),this.cadenas.size>Om){let i=null,s=1/0;for(let[a,c]of this.cadenas)
628
- c.ultimoUso<s&&(s=c.ultimoUso,i=a);i!==null&&this.cadenas.delete(i);}}return r.ultimoUso=Date.now(),r}};var Lm="[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\
629
- oard/install and relaunch",Er=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,
637
+ "hex").slice(0,16)}\xB7${t.model}`}cachesDe(t){let n=this.cachesPorModelo.get(t);return n||(n={base:new tn,v0:new tn},this.cachesPorModelo.set(t,n)),n}cadenaPara(t,n){let r=this.cadenas.get(t);if(!r){
638
+ let o=this.cachesDe(n);if(r={base:new _n(i=>Cc(i),o.base),v0:new _n((i,s,a)=>_c("v0",i,s,a),o.v0),ultimoUso:0},this.cadenas.set(t,r),this.cadenas.size>zm){let i=null,s=1/0;for(let[a,c]of this.cadenas)
639
+ c.ultimoUso<s&&(s=c.ultimoUso,i=a);i!==null&&this.cadenas.delete(i);}}return r.ultimoUso=Date.now(),r}};var Vm="[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\
640
+ oard/install and relaunch",Ar=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,
630
641
  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(),
631
642
  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===
632
643
  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(
633
- "entitlements HTTP 401",Lm);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(
644
+ "entitlements HTTP 401",Vm);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(
634
645
  "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==
635
646
  "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,
636
647
  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\
637
- ing`));}};var xi="https://savings.bivelio.com",ge="https://savings.bivelio.com/dashboard/account",ht="https://savings.bivelio.com/dashboard/install",$m=1e4,Mm=3e3,bc=6e4,Nm=36e5,jm=7*86400,Bm=3e4,Um=86400,Fm="B\
638
- VL";function Si(e){return St}function zm(e){return zo(e)?Object.keys(e.keys??{}).length===0:e.trim()===""}var wi=e=>typeof e=="string"&&e.trim()!=="",_r=e=>typeof e=="number"&&Number.
639
- isFinite(e);function Vm(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let t=e;return wi(t.jti)&&wi(t.org_id)&&wi(t.plan)&&_r(t.seats)&&_r(t.issued_at)&&_r(t.expires_at)&&_r(t.grace_days)&&
640
- t.grace_days>=0&&Array.isArray(t.features)&&t.features.every(n=>typeof n=="string")}function Tr(e,t){try{let n=Vt(typeof e=="string"?e:""),r=hn(n);if(r==="empty")return {ok:!1,shape:"empty",reason:"emp\
641
- ty"};if(r==="malformed")return {ok:!1,shape:"malformed",reason:"malformed"};let o=gn(n,t);if(!o.ok||!o.payloadBytes)return {ok:!1,shape:"token",reason:Sn(o.reason??"bad signature")};let i=o.header?.typ;
642
- if(i!==Fm)return {ok:!1,shape:"token",reason:`not a license token (typ ${Sn(String(i??"none"))})`};let s;try{s=JSON.parse(new TextDecoder().decode(o.payloadBytes));}catch{return {ok:!1,shape:"token",reason:"\
643
- payload is not valid JSON"}}return Vm(s)?{ok:!0,license:{token:n,payload:pr(s)}}:{ok:!1,shape:"token",reason:"license payload has the wrong field types"}}catch(n){return {ok:false,shape:"token",reason:`ve\
644
- rification error: ${Sn(String(n))}`}}}function Yt(e,t,n){return fr(e,Math.floor(t/1e3),n)}var Zt=e=>e==="active"||e==="grace";function Sn(e,t=200){let n=e.replace(/[^\x20-\x7E]/g,"?");return n.length>
645
- t?`${n.slice(0,t)}...`:n}function qm(e){return `${Number((e/1e3).toFixed(3))} s`}function Hm(e){let t=e,n=typeof t?.message=="string"&&t.message!==""?t.message:String(e),r=t?.cause,o=r&&typeof r.code==
646
- "string"?r.code:r&&typeof r.message=="string"?r.message:void 0;return o?`${n} (${o})`:n}async function vc(e){let t=`${e.licenseServerUrl.replace(/\/+$/,"")}/api/license/current`,n=c=>e.serviceAccountKey?
648
+ ing`));}};var Ai="https://savings.bivelio.com",ke="https://savings.bivelio.com/dashboard/account",xt="https://savings.bivelio.com/dashboard/install",qm=1e4,Hm=3e3,Rc=6e4,Gm=36e5,Wm=7*86400,Km=3e4,Jm=86400,Ym="B\
649
+ VL";function Ii(e){return Pt}function Zm(e){return Jo(e)?Object.keys(e.keys??{}).length===0:e.trim()===""}var Ri=e=>typeof e=="string"&&e.trim()!=="",Ir=e=>typeof e=="number"&&Number.
650
+ isFinite(e);function Xm(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let t=e;return Ri(t.jti)&&Ri(t.org_id)&&Ri(t.plan)&&Ir(t.seats)&&Ir(t.issued_at)&&Ir(t.expires_at)&&Ir(t.grace_days)&&
651
+ t.grace_days>=0&&Array.isArray(t.features)&&t.features.every(n=>typeof n=="string")}function Dr(e,t){try{let n=Jt(typeof e=="string"?e:""),r=yn(n);if(r==="empty")return {ok:!1,shape:"empty",reason:"emp\
652
+ ty"};if(r==="malformed")return {ok:!1,shape:"malformed",reason:"malformed"};let o=kn(n,t);if(!o.ok||!o.payloadBytes)return {ok:!1,shape:"token",reason:Tn(o.reason??"bad signature")};let i=o.header?.typ;
653
+ if(i!==Ym)return {ok:!1,shape:"token",reason:`not a license token (typ ${Tn(String(i??"none"))})`};let s;try{s=JSON.parse(new TextDecoder().decode(o.payloadBytes));}catch{return {ok:!1,shape:"token",reason:"\
654
+ payload is not valid JSON"}}return Xm(s)?{ok:!0,license:{token:n,payload:hr(s)}}:{ok:!1,shape:"token",reason:"license payload has the wrong field types"}}catch(n){return {ok:false,shape:"token",reason:`ve\
655
+ rification error: ${Tn(String(n))}`}}}function nn(e,t,n){return gr(e,Math.floor(t/1e3),n)}var rn=e=>e==="active"||e==="grace";function Tn(e,t=200){let n=e.replace(/[^\x20-\x7E]/g,"?");return n.length>
656
+ t?`${n.slice(0,t)}...`:n}function Qm(e){return `${Number((e/1e3).toFixed(3))} s`}function eh(e){let t=e,n=typeof t?.message=="string"&&t.message!==""?t.message:String(e),r=t?.cause,o=r&&typeof r.code==
657
+ "string"?r.code:r&&typeof r.message=="string"?r.message:void 0;return o?`${n} (${o})`:n}async function Ac(e){let t=`${e.licenseServerUrl.replace(/\/+$/,"")}/api/license/current`,n=c=>e.serviceAccountKey?
647
658
  c.split(e.serviceAccountKey).join("[service key]"):c,r=new AbortController,o=false,i=setTimeout(()=>{o=true,r.abort();},e.timeoutMs);i.unref?.();let s=()=>r.abort();e.signal&&(e.signal.aborted?r.abort():e.signal.
648
- addEventListener("abort",s,{once:true}));let a=c=>o?{kind:"unreachable",cause:`timed out after ${qm(e.timeoutMs)}`}:{kind:"unreachable",cause:Sn(n(`network error: ${Hm(c)}`))};try{let c=e.fetchImpl??globalThis.
659
+ addEventListener("abort",s,{once:true}));let a=c=>o?{kind:"unreachable",cause:`timed out after ${Qm(e.timeoutMs)}`}:{kind:"unreachable",cause:Tn(n(`network error: ${eh(c)}`))};try{let c=e.fetchImpl??globalThis.
649
660
  fetch,l;try{l=await c(t,{method:"GET",headers:{authorization:`Bearer ${e.serviceAccountKey}`,accept:"application/json"},signal:r.signal});}catch(m){return a(m)}if(l.status===401)return {kind:"key-unknow\
650
- n"};if(l.status===404)return {kind:"no-license"};if(!l.ok)return {kind:"unreachable",cause:`HTTP ${l.status}`};let p;try{p=await l.json();}catch(m){return o||r.signal.aborted?a(m):{kind:"unreachable",cause:"\
651
- unexpected response (no license token)"}}let u=p?.token;if(typeof u!="string"||u.trim()==="")return {kind:"unreachable",cause:"unexpected response (no license token)"};let f=Tr(u,e.publicKey);return f.
652
- ok?{kind:"token",license:f.license}:{kind:"not-verifying",reason:Sn(f.reason)}}catch(c){return a(c)}finally{clearTimeout(i),e.signal?.removeEventListener("abort",s);}}function Ne(e){try{return new Date(
653
- e*1e3).toISOString().slice(0,10)}catch{return "an unknown date"}}var En=(e,t)=>e+t*Um,Gm="WARNING: BIVELIO_LICENSE_KEY belongs to a different organization than BIVELIO_SERVICE_KEY and is ignored; the l\
654
- icense of the service key's organization is used. Unset BIVELIO_LICENSE_KEY or replace it with this organization's license key.",Wm=e=>`WARNING: the license served by savings.bivelio.com does not veri\
655
- fy against this build's BiVelio key (${e}); starting with BIVELIO_LICENSE_KEY. Update @bivelio/savings-layer (npm i -g @bivelio/savings-layer).`;function Km(e,t={}){switch(e){case "no-public-key":return "\
661
+ n"};if(l.status===404)return {kind:"no-license"};if(!l.ok)return {kind:"unreachable",cause:`HTTP ${l.status}`};let d;try{d=await l.json();}catch(m){return o||r.signal.aborted?a(m):{kind:"unreachable",cause:"\
662
+ unexpected response (no license token)"}}let u=d?.token;if(typeof u!="string"||u.trim()==="")return {kind:"unreachable",cause:"unexpected response (no license token)"};let f=Dr(u,e.publicKey);return f.
663
+ ok?{kind:"token",license:f.license}:{kind:"not-verifying",reason:Tn(f.reason)}}catch(c){return a(c)}finally{clearTimeout(i),e.signal?.removeEventListener("abort",s);}}function Ue(e){try{return new Date(
664
+ e*1e3).toISOString().slice(0,10)}catch{return "an unknown date"}}var Rn=(e,t)=>e+t*Jm,th="WARNING: BIVELIO_LICENSE_KEY belongs to a different organization than BIVELIO_SERVICE_KEY and is ignored; the l\
665
+ icense of the service key's organization is used. Unset BIVELIO_LICENSE_KEY or replace it with this organization's license key.",nh=e=>`WARNING: the license served by savings.bivelio.com does not veri\
666
+ fy against this build's BiVelio key (${e}); starting with BIVELIO_LICENSE_KEY. Update @bivelio/savings-layer (npm i -g @bivelio/savings-layer).`;function rh(e,t={}){switch(e){case "no-public-key":return "\
656
667
  this build has no embedded 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 `\
657
- BIVELIO_SERVICE_KEY is not set. The gateway needs two things and does not start without them: an active BiVelio subscription (${ge}) and its service key (bvk_..., created at ${ht}, step 2). Export the\
668
+ BIVELIO_SERVICE_KEY is not set. The gateway needs two things and does not start without them: an active BiVelio subscription (${ke}) and its service key (bvk_..., created at ${xt}, step 2). Export the\
658
669
  key and relaunch: 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?
659
- " It looks like a license key: that one goes in BIVELIO_LICENSE_KEY.":"")+` Create a service key at ${ht} (step 2), export it and relaunch.`;case "service-key-not-recognised":return `BIVELIO_SERVICE_KEY\
660
- is not recognised by savings.bivelio.com (HTTP 401): it was deleted or rotated, or it was copied incompletely. Create a new one at ${ht} (step 2), export it and relaunch.`;case "no-license":return `you\
661
- r organization has no active BiVelio license, and the gateway does not start without one. Get the free Measure license (no card; shadow mode: it measures and applies no lever) at ${ht}, or subscribe a\
662
- t ${ge}, and relaunch; the license is collected automatically with your service key.`;case "license-expired":{let n=t.expiresAt??0;return `your BiVelio license expired on ${Ne(n)} and its grace period e\
663
- nded on ${Ne(En(n,t.graceDays??0))}. Renew at ${ge} and relaunch.`+(t.cause?` (savings.bivelio.com could not be reached to look for a renewed license: ${t.cause})`:"")}case "license-invalid":{let n=t.reason??
670
+ " It looks like a license key: that one goes in BIVELIO_LICENSE_KEY.":"")+` Create a service key at ${xt} (step 2), export it and relaunch.`;case "service-key-not-recognised":return `BIVELIO_SERVICE_KEY\
671
+ is not recognised by savings.bivelio.com (HTTP 401): it was deleted or rotated, or it was copied incompletely. Create a new one at ${xt} (step 2), export it and relaunch.`;case "no-license":return `you\
672
+ r organization has no active BiVelio license, and the gateway does not start without one. Get the free Measure license (no card; shadow mode: it measures and applies no lever) at ${xt}, or subscribe a\
673
+ t ${ke}, and relaunch; the license is collected automatically with your service key.`;case "license-expired":{let n=t.expiresAt??0;return `your BiVelio license expired on ${Ue(n)} and its grace period e\
674
+ nded on ${Ue(Rn(n,t.graceDays??0))}. Renew at ${ke} and relaunch.`+(t.cause?` (savings.bivelio.com could not be reached to look for a renewed license: ${t.cause})`:"")}case "license-invalid":{let n=t.reason??
664
675
  "bad signature";return t.tokenSource==="savings.bivelio.com"?`the license served by savings.bivelio.com does not verify against this build's BiVelio key (${n}). Update @bivelio/savings-layer (npm i -g\
665
676
  @bivelio/savings-layer); if it persists, write to support@bivelio.com.`:t.shape==="malformed"?`BIVELIO_LICENSE_KEY is not a license key: a license key has three dot-separated parts and several hundre\
666
- d characters. Did you paste the bvk_ service key by mistake? That one goes in BIVELIO_SERVICE_KEY; the license key is the other value on ${ht}. Or unset BIVELIO_LICENSE_KEY: the gateway collects the l\
667
- icense online by itself.`:`BIVELIO_LICENSE_KEY does not verify against this build's BiVelio key (${n}). Copy the WHOLE key again from ${ht}, or unset BIVELIO_LICENSE_KEY to collect it online; if it pe\
677
+ d characters. Did you paste the bvk_ service key by mistake? That one goes in BIVELIO_SERVICE_KEY; the license key is the other value on ${xt}. Or unset BIVELIO_LICENSE_KEY: the gateway collects the l\
678
+ icense online by itself.`:`BIVELIO_LICENSE_KEY does not verify against this build's BiVelio key (${n}). Copy the WHOLE key again from ${xt}, or unset BIVELIO_LICENSE_KEY to collect it online; if it pe\
668
679
  rsists, update @bivelio/savings-layer or write to support@bivelio.com.`}case "unreachable":return `could not collect your license from savings.bivelio.com (${t.cause??"unknown cause"}). The gateway does\
669
- not start without a verified license. Check your connection and relaunch. If savings.bivelio.com is down, export BIVELIO_LICENSE_KEY=<your license key> (from ${ht}) as a fallback: it is verified on t\
670
- his machine and used only when savings.bivelio.com cannot be reached, and it must be replaced by hand every billing period.`}}function gc(e,t,n,r){let o=e.plan.toUpperCase(),i=e.grace_days,s=Ne(e.expires_at),
680
+ not start without a verified license. Check your connection and relaunch. If savings.bivelio.com is down, export BIVELIO_LICENSE_KEY=<your license key> (from ${xt}) as a fallback: it is verified on t\
681
+ his machine and used only when savings.bivelio.com cannot be reached, and it must be replaced by hand every billing period.`}}function Tc(e,t,n,r){let o=e.plan.toUpperCase(),i=e.grace_days,s=Ue(e.expires_at),
671
682
  a=t==="online"?"collected with your service key and verified on this machine":r?`from BIVELIO_LICENSE_KEY, verified on this machine (savings.bivelio.com unreachable: ${r})`:"from BIVELIO_LICENSE_KEY, \
672
- verified on this machine";if(n==="grace"){let c=Ne(En(e.expires_at,i));return `license: ${o}, IN GRACE: expired on ${s}, keeps working until ${c}. Renew at ${ge} (${a})`}return `license: ${o}, active un\
673
- til ${s} (+${i} ${i===1?"day":"days"} grace), ${a}`}var We=(e,t)=>({ok:false,code:e,message:Km(e,t)});async function yc(e){let t=e.now??Date.now,n=Si();if(zm(n))return We("no-public-key");let r=e.
674
- serviceAccountKey?.trim();if(!r)return We("service-key-missing");if(!r.startsWith("bvk_"))return We("service-key-malformed",{keyLooksLikeLicense:hn(Vt(r))==="token"});let o=null;if(e.licenseKey!==void 0){
675
- let c=Tr(e.licenseKey,n);if(c.ok)o=c.license;else if(c.shape!=="empty")return We("license-invalid",{tokenSource:"BIVELIO_LICENSE_KEY",shape:c.shape,reason:c.reason})}let i=o!==null&&Zt(Yt(o.payload,t())),
676
- s=await vc({licenseServerUrl:e.licenseServerUrl,serviceAccountKey:r,publicKey:n,timeoutMs:e.timeoutMs??(i?Mm:$m),...e.fetchImpl?{fetchImpl:e.fetchImpl}:{}}),a=(c,l)=>{let p=Yt(o.payload,t());return Zt(
677
- p)?{ok:true,license:o,source:"offline",status:p,line:gc(o.payload,"offline",p,c),lineIsWarning:true,warnings:l}:We("license-expired",{expiresAt:o.payload.expires_at,graceDays:o.payload.grace_days,...c?{cause:c}:
678
- {}})};switch(s.kind){case "key-unknown":return We("service-key-not-recognised");case "no-license":return We("no-license");case "token":{let c=s.license,l=Yt(c.payload,t()),p=o&&o.payload.org_id!==c.payload.
679
- org_id?[Gm]:[];return Zt(l)?{ok:true,license:c,source:"online",status:l,line:gc(c.payload,"online",l),lineIsWarning:l==="grace",warnings:p}:We("license-expired",{expiresAt:c.payload.expires_at,graceDays:c.
680
- payload.grace_days})}case "not-verifying":return i?a(void 0,[Wm(s.reason)]):We("license-invalid",{tokenSource:"savings.bivelio.com",reason:s.reason});case "unreachable":return o?a(s.cause,[]):We("unreac\
681
- hable",{cause:s.cause})}}var Jm=new Set(["expired","revoked","no-license","blocked","invalid"]);function Ei(e,t,n){let r=typeof t=="string"?t.trim():"";if(r!==""){let i="reported by savings.bivelio.co\
683
+ verified on this machine";if(n==="grace"){let c=Ue(Rn(e.expires_at,i));return `license: ${o}, IN GRACE: expired on ${s}, keeps working until ${c}. Renew at ${ke} (${a})`}return `license: ${o}, active un\
684
+ til ${s} (+${i} ${i===1?"day":"days"} grace), ${a}`}var Ke=(e,t)=>({ok:false,code:e,message:rh(e,t)});async function Ic(e){let t=e.now??Date.now,n=Ii();if(Zm(n))return Ke("no-public-key");let r=e.
685
+ serviceAccountKey?.trim();if(!r)return Ke("service-key-missing");if(!r.startsWith("bvk_"))return Ke("service-key-malformed",{keyLooksLikeLicense:yn(Jt(r))==="token"});let o=null;if(e.licenseKey!==void 0){
686
+ let c=Dr(e.licenseKey,n);if(c.ok)o=c.license;else if(c.shape!=="empty")return Ke("license-invalid",{tokenSource:"BIVELIO_LICENSE_KEY",shape:c.shape,reason:c.reason})}let i=o!==null&&rn(nn(o.payload,t())),
687
+ s=await Ac({licenseServerUrl:e.licenseServerUrl,serviceAccountKey:r,publicKey:n,timeoutMs:e.timeoutMs??(i?Hm:qm),...e.fetchImpl?{fetchImpl:e.fetchImpl}:{}}),a=(c,l)=>{let d=nn(o.payload,t());return rn(
688
+ d)?{ok:true,license:o,source:"offline",status:d,line:Tc(o.payload,"offline",d,c),lineIsWarning:true,warnings:l}:Ke("license-expired",{expiresAt:o.payload.expires_at,graceDays:o.payload.grace_days,...c?{cause:c}:
689
+ {}})};switch(s.kind){case "key-unknown":return Ke("service-key-not-recognised");case "no-license":return Ke("no-license");case "token":{let c=s.license,l=nn(c.payload,t()),d=o&&o.payload.org_id!==c.payload.
690
+ org_id?[th]:[];return rn(l)?{ok:true,license:c,source:"online",status:l,line:Tc(c.payload,"online",l),lineIsWarning:l==="grace",warnings:d}:Ke("license-expired",{expiresAt:c.payload.expires_at,graceDays:c.
691
+ payload.grace_days})}case "not-verifying":return i?a(void 0,[nh(s.reason)]):Ke("license-invalid",{tokenSource:"savings.bivelio.com",reason:s.reason});case "unreachable":return o?a(s.cause,[]):Ke("unreac\
692
+ hable",{cause:s.cause})}}var oh=new Set(["expired","revoked","no-license","blocked","invalid"]);function Pi(e,t,n){let r=typeof t=="string"?t.trim():"";if(r!==""){let i="reported by savings.bivelio.co\
682
693
  m";return r==="license-revoked"?{serve:false,state:"revoked",detail:i}:r==="license-expired"?{serve:false,state:"expired",detail:i}:r==="no-license"?{serve:false,state:"no-license",detail:i}:{serve:false,state:"b\
683
- locked",detail:i}}let o=e.status();return o==="active"||o==="grace"?{serve:true,state:o}:o==="expired"?{serve:false,state:"expired",detail:n?`grace period ended ${Ne(En(n.expires_at,n.grace_days))}`:"grace\
684
- period ended"}:o==="revoked"?{serve:false,state:"revoked",detail:"license id revoked"}:{serve:false,state:"invalid",detail:"license no longer verifies"}}var xn="requests already in flight were not interrup\
685
- ted";function Ym(e){switch(e){case "expired":return `bvsala gateway: the BiVelio license for this organization has expired. New requests are refused until it is renewed at ${ge}; ${xn}.`;case "revoked":return `\
686
- bvsala gateway: the BiVelio license for this organization is no longer active (revoked or cancelled). New requests are refused; ${xn}. Check ${ge} or write to support@bivelio.com.`;case "no-license":return `\
687
- bvsala gateway: this organization has no active BiVelio license. New requests are refused until you subscribe at ${ge}; ${xn}.`;case "blocked":return `bvsala gateway: savings.bivelio.com reports the BiV\
688
- elio license for this organization as not active. New requests are refused; ${xn}. Check ${ge}.`;case "invalid":return `bvsala gateway: the license loaded by this gateway no longer verifies. New request\
689
- s are refused; ${xn}. Relaunch the terminal; if it persists, write to support@bivelio.com.`}}function kc(e){return JSON.stringify({type:"error",error:{type:"license_error",status:e,message:Ym(e)}})}var Zm={
690
- expired:`Renew at ${ge}`,revoked:`Check ${ge} or write to support@bivelio.com`,"no-license":`Subscribe at ${ge}`,blocked:`Check ${ge}`,invalid:"Relaunch the terminal; if it persists, write to support@\
691
- bivelio.com"};function wc(e,t,n){if(!t.serve)return e===t.state?null:`[bvsala gateway] license ${t.state} (${t.detail}): new requests are refused with HTTP 402; requests in flight are not touched. ${Zm[t.
692
- state]}`;let r=Ne(n.expires_at),o=Ne(En(n.expires_at,n.grace_days));return e!==null&&Jm.has(e)?t.state==="grace"?`[bvsala gateway] license in grace again (it expired on ${r} and keeps working until ${o}\
693
- ): serving new requests. Renew at ${ge}`:`[bvsala gateway] license ${t.state} again (expires ${r}): serving new requests`:t.state==="grace"&&e!=="grace"?`[bvsala gateway] license in grace: it expired \
694
- on ${r} and keeps working until ${o}. Renew at ${ge}`:null}function _i(e,t,n,r){return {license:e,gate:mr(e.token,t,{revocation:n,...r?{now:r}:{}})}}var Cr=class{constructor(t){this.o=t;}o;timer=null;enVuelo=false;parado=false;ctrl=null;avisados=new Set;ahora(){
695
- return this.o.now?this.o.now():Date.now()}start(t={}){this.parado||this.timer!==null||(this.timer=setInterval(()=>{this.check();},this.o.intervalMs??Nm),this.timer.unref?.(),t.checkNow&&this.check({force:true}));}stop(){
694
+ locked",detail:i}}let o=e.status();return o==="active"||o==="grace"?{serve:true,state:o}:o==="expired"?{serve:false,state:"expired",detail:n?`grace period ended ${Ue(Rn(n.expires_at,n.grace_days))}`:"grace\
695
+ period ended"}:o==="revoked"?{serve:false,state:"revoked",detail:"license id revoked"}:{serve:false,state:"invalid",detail:"license no longer verifies"}}var Cn="requests already in flight were not interrup\
696
+ ted";function ih(e){switch(e){case "expired":return `bvsala gateway: the BiVelio license for this organization has expired. New requests are refused until it is renewed at ${ke}; ${Cn}.`;case "revoked":return `\
697
+ bvsala gateway: the BiVelio license for this organization is no longer active (revoked or cancelled). New requests are refused; ${Cn}. Check ${ke} or write to support@bivelio.com.`;case "no-license":return `\
698
+ bvsala gateway: this organization has no active BiVelio license. New requests are refused until you subscribe at ${ke}; ${Cn}.`;case "blocked":return `bvsala gateway: savings.bivelio.com reports the BiV\
699
+ elio license for this organization as not active. New requests are refused; ${Cn}. Check ${ke}.`;case "invalid":return `bvsala gateway: the license loaded by this gateway no longer verifies. New request\
700
+ s are refused; ${Cn}. Relaunch the terminal; if it persists, write to support@bivelio.com.`}}function Pc(e){return JSON.stringify({type:"error",error:{type:"license_error",status:e,message:ih(e)}})}var sh={
701
+ expired:`Renew at ${ke}`,revoked:`Check ${ke} or write to support@bivelio.com`,"no-license":`Subscribe at ${ke}`,blocked:`Check ${ke}`,invalid:"Relaunch the terminal; if it persists, write to support@\
702
+ bivelio.com"};function Dc(e,t,n){if(!t.serve)return e===t.state?null:`[bvsala gateway] license ${t.state} (${t.detail}): new requests are refused with HTTP 402; requests in flight are not touched. ${sh[t.
703
+ state]}`;let r=Ue(n.expires_at),o=Ue(Rn(n.expires_at,n.grace_days));return e!==null&&oh.has(e)?t.state==="grace"?`[bvsala gateway] license in grace again (it expired on ${r} and keeps working until ${o}\
704
+ ): serving new requests. Renew at ${ke}`:`[bvsala gateway] license ${t.state} again (expires ${r}): serving new requests`:t.state==="grace"&&e!=="grace"?`[bvsala gateway] license in grace: it expired \
705
+ on ${r} and keeps working until ${o}. Renew at ${ke}`:null}function Di(e,t,n,r){return {license:e,gate:br(e.token,t,{revocation:n,...r?{now:r}:{}})}}var Pr=class{constructor(t){this.o=t;}o;timer=null;enVuelo=false;parado=false;ctrl=null;avisados=new Set;ahora(){
706
+ return this.o.now?this.o.now():Date.now()}start(t={}){this.parado||this.timer!==null||(this.timer=setInterval(()=>{this.check();},this.o.intervalMs??Gm),this.timer.unref?.(),t.checkNow&&this.check({force:true}));}stop(){
696
707
  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.
697
- enVuelo||this.parado)return false;let n=this.o.current(),r=Zt(Yt(n.payload,this.ahora(),this.o.revocation.snapshot())),o=n.payload.expires_at-Math.floor(this.ahora()/1e3),i=n.payload.plan==="measure";if(!t.
698
- force&&!i&&r&&o>(this.o.leadSeconds??jm))return false;this.enVuelo=true;let s=new AbortController;this.ctrl=s;try{let a=await vc({licenseServerUrl:this.o.licenseServerUrl,serviceAccountKey:this.o.serviceAccountKey,
699
- publicKey:this.o.publicKey,timeoutMs:this.o.timeoutMs??Bm,signal:s.signal,...this.o.fetchImpl?{fetchImpl:this.o.fetchImpl}:{}});if(this.parado)return !1;let c=Ne(En(n.payload.expires_at,n.payload.grace_days));
700
- switch(a.kind){case "token":{let l=a.license.payload,p=this.o.revocation.snapshot();if(l.jti===n.payload.jti||this.o.revocation.has(l.jti)||!Zt(Yt(l,this.ahora(),p)))return !1;let u=Zt(Yt(n.payload,this.
701
- ahora(),p)),f=l.org_id!==n.payload.org_id,m=l.expires_at>n.payload.expires_at||i&&l.plan!=="measure";return !f&&!m&&u?!1:(this.o.onAdopt(a.license),!0)}case "key-unknown":return this.avisar("key-unknown",
702
- `[bvsala gateway] license renewal: BIVELIO_SERVICE_KEY is no longer recognised (HTTP 401). This session keeps its current license until ${c}; create a new key at ${ht} and relaunch.`),!1;case "no-licen\
708
+ enVuelo||this.parado)return false;let n=this.o.current(),r=rn(nn(n.payload,this.ahora(),this.o.revocation.snapshot())),o=n.payload.expires_at-Math.floor(this.ahora()/1e3),i=n.payload.plan==="measure";if(!t.
709
+ force&&!i&&r&&o>(this.o.leadSeconds??Wm))return false;this.enVuelo=true;let s=new AbortController;this.ctrl=s;try{let a=await Ac({licenseServerUrl:this.o.licenseServerUrl,serviceAccountKey:this.o.serviceAccountKey,
710
+ publicKey:this.o.publicKey,timeoutMs:this.o.timeoutMs??Km,signal:s.signal,...this.o.fetchImpl?{fetchImpl:this.o.fetchImpl}:{}});if(this.parado)return !1;let c=Ue(Rn(n.payload.expires_at,n.payload.grace_days));
711
+ switch(a.kind){case "token":{let l=a.license.payload,d=this.o.revocation.snapshot();if(l.jti===n.payload.jti||this.o.revocation.has(l.jti)||!rn(nn(l,this.ahora(),d)))return !1;let u=rn(nn(n.payload,this.
712
+ ahora(),d)),f=l.org_id!==n.payload.org_id,m=l.expires_at>n.payload.expires_at||i&&l.plan!=="measure";return !f&&!m&&u?!1:(this.o.onAdopt(a.license),!0)}case "key-unknown":return this.avisar("key-unknown",
713
+ `[bvsala gateway] license renewal: BIVELIO_SERVICE_KEY is no longer recognised (HTTP 401). This session keeps its current license until ${c}; create a new key at ${xt} and relaunch.`),!1;case "no-licen\
703
714
  se":return this.avisar("no-license",`[bvsala gateway] license renewal: savings.bivelio.com reports no active license for this organization (HTTP 404). This session keeps its current license until ${c}\
704
- ; subscribe or renew at ${ge}.`),!1;case "not-verifying":return this.avisar(`not-verifying:${a.reason}`,`[bvsala gateway] license renewal: the license served by savings.bivelio.com does not verify agai\
705
- nst this build's BiVelio key (${a.reason}); update @bivelio/savings-layer.`),!1;case "unreachable":return !1}return !1}catch{return false}finally{this.ctrl===s&&(this.ctrl=null),this.enVuelo=false;}}};function xc(e){let t=0,n=0;for(;;){let i=e.indexOf('"input_schema"',n);if(i<0)break;t+=1,n=i+14;}let r=0;for(n=0;;){let i=e.indexOf('"tool_reference"',n);if(i<0)break;r+=1,n=i+16;}let o=e.match(/"defer_loading"\s*:\s*true/g)?.
706
- length??0;return {definiciones:t,referencias:r,diferidas:o}}var Xm=40;function Sc(e){return e.referencias>0||(e.diferidas??0)>0||e.definiciones<Xm?null:`[bvsala gateway] your client sends ${e.definiciones}\
715
+ ; subscribe or renew at ${ke}.`),!1;case "not-verifying":return this.avisar(`not-verifying:${a.reason}`,`[bvsala gateway] license renewal: the license served by savings.bivelio.com does not verify agai\
716
+ nst this build's BiVelio key (${a.reason}); update @bivelio/savings-layer.`),!1;case "unreachable":return !1}return !1}catch{return false}finally{this.ctrl===s&&(this.ctrl=null),this.enVuelo=false;}}};function Oc(e){let t=0,n=0;for(;;){let i=e.indexOf('"input_schema"',n);if(i<0)break;t+=1,n=i+14;}let r=0;for(n=0;;){let i=e.indexOf('"tool_reference"',n);if(i<0)break;r+=1,n=i+16;}let o=e.match(/"defer_loading"\s*:\s*true/g)?.
717
+ length??0;return {definiciones:t,referencias:r,diferidas:o}}var ah=40;function Lc(e){return e.referencias>0||(e.diferidas??0)>0||e.definiciones<ah?null:`[bvsala gateway] your client sends ${e.definiciones}\
707
718
  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\
708
- 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 Ci=5*1024*1024,eh=["authorization","x-api-key","anthropic-version","anthropic-beta","api-key","openai-organization","openai-project"];function Ec(e,t,n,r=""){return createHash(
719
+ 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 Oi=5*1024*1024,lh=["authorization","x-api-key","anthropic-version","anthropic-beta","api-key","openai-organization","openai-project"];function $c(e,t,n,r=""){return createHash(
709
720
  "sha256").update(e).update(`
710
721
  `).update(t).update(`
711
722
  `).update(r).update(`
712
- `).update(n).digest("hex")}function _c(e){return eh.map(t=>`${t}=${e(t)??""}`).join(`
713
- `)}var Rr=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=[],
714
- i=0,s=false;return {capturar:a=>{if(!s){if(i+=a.length,i>Ci){s=true,o.length=0;return}o.push(a);}},terminar:(a,c,l)=>{let p=!s&&a>=200&&a<300;this.enVuelo.get(t)?.resolver(p?{status:a,headers:c,chunks:o,...l?
723
+ `).update(n).digest("hex")}function Mc(e){return lh.map(t=>`${t}=${e(t)??""}`).join(`
724
+ `)}var Or=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=[],
725
+ i=0,s=false;return {capturar:a=>{if(!s){if(i+=a.length,i>Oi){s=true,o.length=0;return}o.push(a);}},terminar:(a,c,l)=>{let d=!s&&a>=200&&a<300;this.enVuelo.get(t)?.resolver(d?{status:a,headers:c,chunks:o,...l?
715
726
  {primaria:l}:{}}:null),this.enVuelo.delete(t);},abortar:()=>{this.enVuelo.get(t)?.resolver(null),this.enVuelo.delete(t);}}}async esperar(t){let n=this.enVuelo.get(t);if(!n)return null;let r=await n.promesa;
716
- return r&&(this.gemelas+=1),r}tieneEnVuelo(t){return this.enVuelo.has(t)}};var Cc={openai:"https://api.openai.com",anthropic:"https://api.anthropic.com"};function Tc(e){let t;try{t=new URL(e).origin;}catch{return false}return Object.values(Cc).includes(t)}function Rc(e){for(let t=0;t<
717
- 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 th(e){
718
- 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 Ac(e){if(e.flag===
727
+ return r&&(this.gemelas+=1),r}tieneEnVuelo(t){return this.enVuelo.has(t)}};var Nc={openai:"https://api.openai.com",anthropic:"https://api.anthropic.com"};function jc(e){let t;try{t=new URL(e).origin;}catch{return false}return Object.values(Nc).includes(t)}function Bc(e){for(let t=0;t<
728
+ 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 uh(e){
729
+ 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 Uc(e){if(e.flag===
719
730
  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&&
720
- e.env.trim()!=="")t=e.env,n="env";else return {ok:true,upstream:void 0,origen:"none"};let r=Cc[t.trim().toLowerCase()];if(r!==void 0)return {ok:true,upstream:r,origen:n};let o={ok:false,error:`[bvsala gateway]\
721
- invalid upstream ${th(t)}: use openai, anthropic or an http(s) origin URL`},i;try{i=new URL(t.trim());}catch{return o}return i.protocol!=="http:"&&i.protocol!=="https:"?o:i.pathname!=="/"||i.search!==
731
+ e.env.trim()!=="")t=e.env,n="env";else return {ok:true,upstream:void 0,origen:"none"};let r=Nc[t.trim().toLowerCase()];if(r!==void 0)return {ok:true,upstream:r,origen:n};let o={ok:false,error:`[bvsala gateway]\
732
+ invalid upstream ${uh(t)}: use openai, anthropic or an http(s) origin URL`},i;try{i=new URL(t.trim());}catch{return o}return i.protocol!=="http:"&&i.protocol!=="https:"?o:i.pathname!=="/"||i.search!==
722
733
  ""||i.hash!==""?{ok:true,upstream:i.origin,origen:n,aviso:`[bvsala gateway] WARNING: the upstream path "${i.pathname}" is ignored: requests keep the path the client sends (for example /v1/chat/completio\
723
- ns), so put that prefix in the client's base URL instead.`}:{ok:true,upstream:i.origin,origen:n}}var nh="other reasons",Ar=class{medidas=0;replicas=0;noMedidas=new Map;medida(){this.medidas++;}replica(){this.replicas++;}noMedida(t){let n=this.noMedidas.has(t)||this.noMedidas.size<50?t:nh;this.noMedidas.
724
- set(n,(this.noMedidas.get(n)??0)+1);}estado(){return {medidas:this.medidas,replicas:this.replicas,noMedidas:Object.fromEntries(this.noMedidas)}}};function Ic(e,t){let n=`[bvsala ${t}] metering in this r\
734
+ ns), so put that prefix in the client's base URL instead.`}:{ok:true,upstream:i.origin,origen:n}}var dh="other reasons",Lr=class{medidas=0;replicas=0;noMedidas=new Map;medida(){this.medidas++;}replica(){this.replicas++;}noMedida(t){let n=this.noMedidas.has(t)||this.noMedidas.size<50?t:dh;this.noMedidas.
735
+ set(n,(this.noMedidas.get(n)??0)+1);}estado(){return {medidas:this.medidas,replicas:this.replicas,noMedidas:Object.fromEntries(this.noMedidas)}}};function Fc(e,t){let n=`[bvsala ${t}] metering in this r\
725
736
  un:`,r=Object.entries(e.noMedidas).sort((a,c)=>c[1]-a[1]||a[0].localeCompare(c[0])),o=r.reduce((a,[,c])=>a+c,0);if(e.medidas===0&&e.replicas===0&&o===0)return `${n} no inference request went through th\
726
737
  e gateway. If the terminal did call a model, those calls went straight to the provider and were not metered: check its guide in docs/terminales/.`;let i=`${e.medidas} request(s) metered with the provi\
727
738
  der's usage`+(e.replicas>0?` \xB7 ${e.replicas} duplicate(s) answered with a replica, valued from the request that travelled`:"");if(o===0)return `${n} ${i}.`;let s=r.map(([a,c])=>`${c} \xD7 ${a}`).join(
728
- "; ");return `${n} ${i} \xB7 ${o} forwarded but NOT metered (nothing is estimated in their place): ${s}. What each reason means and what to do: docs/terminales/README.md.`}var _n="x-bvsala-report",Ri="x-bvsala-request-id",rh="/_bvsala/",oh="bvsala.gateway.report/1",Pc="bvsala.gateway.status/1";var Ir=/^[A-Za-z0-9._:-]{1,200}$/;function Dc(e){let t=(Array.isArray(e)?e[0]:e)?.trim().toLowerCase();return t==="1"||t==="true"}var Pr=class{entradas=new Map;porRespuestaId=new Map;oyentes=new Set;capacidad;now;constructor(t={}){
739
+ "; ");return `${n} ${i} \xB7 ${o} forwarded but NOT metered (nothing is estimated in their place): ${s}. What each reason means and what to do: docs/terminales/README.md.`}var An="x-bvsala-report",$i="x-bvsala-request-id",ph="/_bvsala/",fh="bvsala.gateway.report/1",zc="bvsala.gateway.status/1";var $r=/^[A-Za-z0-9._:-]{1,200}$/;function Vc(e){let t=(Array.isArray(e)?e[0]:e)?.trim().toLowerCase();return t==="1"||t==="true"}var Mr=class{entradas=new Map;porRespuestaId=new Map;oyentes=new Set;capacidad;now;constructor(t={}){
729
740
  this.capacidad=Math.max(1,Math.floor(t.capacidad??1e3)),this.now=t.now??Date.now;}get tamano(){return this.entradas.size}get limite(){return this.capacidad}abrir(t,n){for(this.purgar();this.entradas.size>=
730
- this.capacidad;){let r=this.entradas.keys().next().value;if(r===void 0)break;this.quitar(r);}this.entradas.set(t,{informe:{schema:oh,requestId:t,responseId:null,path:n,status:"pending",reason:null,report:null},
731
- abiertaMs:this.now()}),this.avisar();}anotarRespuesta(t,n){let r=this.entradas.get(t);!r||r.informe.responseId!==null||!n||!Ir.test(n)||(r.informe.responseId=n,this.porRespuestaId.set(n,t),this.avisar());}medido(t,n){
741
+ this.capacidad;){let r=this.entradas.keys().next().value;if(r===void 0)break;this.quitar(r);}this.entradas.set(t,{informe:{schema:fh,requestId:t,responseId:null,path:n,status:"pending",reason:null,report:null},
742
+ abiertaMs:this.now()}),this.avisar();}anotarRespuesta(t,n){let r=this.entradas.get(t);!r||r.informe.responseId!==null||!n||!$r.test(n)||(r.informe.responseId=n,this.porRespuestaId.set(n,t),this.avisar());}medido(t,n){
732
743
  this.cerrar(t,"metered",null,n);}noMedido(t,n){this.cerrar(t,"not_metered",n,null);}porPeticion(t){return this.purgar(),this.entradas.get(t)?.informe}porRespuesta(t){this.purgar();let n=this.porRespuestaId.
733
744
  get(t);return n===void 0?void 0:this.entradas.get(n)?.informe}esperar(t,n,r){let o=s=>s!==void 0&&s.status!=="pending",i=t();return o(i)||n<=0||r?.aborted?Promise.resolve(i):new Promise(s=>{let a=false,c=()=>{
734
- a||(a=true,clearTimeout(p),this.oyentes.delete(l),r?.removeEventListener("abort",c),s(t()));},l=()=>{o(t())&&c();},p=setTimeout(c,Math.min(n,3e4));this.oyentes.add(l),r?.addEventListener("abort",c);})}cerrar(t,n,r,o){
745
+ a||(a=true,clearTimeout(d),this.oyentes.delete(l),r?.removeEventListener("abort",c),s(t()));},l=()=>{o(t())&&c();},d=setTimeout(c,Math.min(n,3e4));this.oyentes.add(l),r?.addEventListener("abort",c);})}cerrar(t,n,r,o){
735
746
  let i=this.entradas.get(t);!i||i.informe.status!=="pending"||(i.informe.status=n,i.informe.reason=r,i.informe.report=o===null?null:structuredClone(o),this.avisar());}quitar(t){let n=this.entradas.get(t);
736
747
  this.entradas.delete(t);let r=n?.informe.responseId;r&&this.porRespuestaId.get(r)===t&&this.porRespuestaId.delete(r);}purgar(){let t=this.now()-36e5;for(let[n,r]of this.entradas){if(r.abiertaMs>=t)break;
737
- this.quitar(n);}}avisar(){for(let t of [...this.oyentes])t();}};function Oc(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e;for(let n of [t.message?.id,t.response?.id,t.id])if(typeof n==
738
- "string"&&Ir.test(n))return n;return null}function Ai(e){try{return Oc(JSON.parse(e.toString("utf8")))}catch{return null}}var Dr=class{resto="";leidos=0;id=null;observar(t){if(this.id!==null||this.leidos>
748
+ this.quitar(n);}}avisar(){for(let t of [...this.oyentes])t();}};function qc(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e;for(let n of [t.message?.id,t.response?.id,t.id])if(typeof n==
749
+ "string"&&$r.test(n))return n;return null}function Mi(e){try{return qc(JSON.parse(e.toString("utf8")))}catch{return null}}var Nr=class{resto="";leidos=0;id=null;observar(t){if(this.id!==null||this.leidos>
739
750
  262144)return;let n=typeof t=="string"?t:t.toString("utf8");this.leidos+=n.length,this.resto+=n;let r;for(;(r=this.resto.indexOf(`
740
- `))>=0;){let o=this.resto.slice(0,r).replace(/\r$/,"");if(this.resto=this.resto.slice(r+1),!o.startsWith("data:"))continue;let i=o.slice(5).trim();if(!(i===""||i==="[DONE]"))try{let s=Oc(JSON.parse(i));
741
- if(s!==null){this.id=s,this.resto="";return}}catch{}}this.leidos>262144&&(this.resto="");}valor(){return this.id}};function Lc(e){try{return new URL(e).origin}catch{return "unknown"}}function $c(e){let t;
742
- try{t=new URL(e??"/","http://127.0.0.1");}catch{return null}return t.pathname.startsWith(rh)?t:null}var ih=new Set(["127.0.0.1","localhost","[::1]"]);function sh(e){if(e===void 0||e==="")return true;let t;
743
- try{t=new URL(`http://${e}`).hostname.toLowerCase();}catch{return false}return ih.has(t)}function Ti(e,t,n){e.writeHead(t,{"content-type":"application/json","cache-control":"no-store"}),e.end(JSON.stringify(
744
- n));}function Rt(e,t,n,r){Ti(e,t,{type:"error",error:{type:n,message:r}});}async function Mc(e,t,n,r){if(e.resume(),!sh(e.headers.host)){Rt(t,403,"forbidden","bvsala gateway: local routes answer only to\
745
- 127.0.0.1 or localhost");return}if(e.method!=="GET"){t.setHeader("allow","GET"),Rt(t,405,"method_not_allowed","bvsala gateway: local routes only answer GET");return}if(n.pathname==="/_bvsala/v1/statu\
746
- s"){Ti(t,200,r.estado());return}let o=Number(n.searchParams.get("wait_ms")??"0");if(!Number.isFinite(o)||o<0){Rt(t,400,"invalid_request","bvsala gateway: wait_ms must be a non-negative number of milli\
751
+ `))>=0;){let o=this.resto.slice(0,r).replace(/\r$/,"");if(this.resto=this.resto.slice(r+1),!o.startsWith("data:"))continue;let i=o.slice(5).trim();if(!(i===""||i==="[DONE]"))try{let s=qc(JSON.parse(i));
752
+ if(s!==null){this.id=s,this.resto="";return}}catch{}}this.leidos>262144&&(this.resto="");}valor(){return this.id}};function Hc(e){try{return new URL(e).origin}catch{return "unknown"}}function Gc(e){let t;
753
+ try{t=new URL(e??"/","http://127.0.0.1");}catch{return null}return t.pathname.startsWith(ph)?t:null}var mh=new Set(["127.0.0.1","localhost","[::1]"]);function hh(e){if(e===void 0||e==="")return true;let t;
754
+ try{t=new URL(`http://${e}`).hostname.toLowerCase();}catch{return false}return mh.has(t)}function Li(e,t,n){e.writeHead(t,{"content-type":"application/json","cache-control":"no-store"}),e.end(JSON.stringify(
755
+ n));}function Mt(e,t,n,r){Li(e,t,{type:"error",error:{type:n,message:r}});}async function Wc(e,t,n,r){if(e.resume(),!hh(e.headers.host)){Mt(t,403,"forbidden","bvsala gateway: local routes answer only to\
756
+ 127.0.0.1 or localhost");return}if(e.method!=="GET"){t.setHeader("allow","GET"),Mt(t,405,"method_not_allowed","bvsala gateway: local routes only answer GET");return}if(n.pathname==="/_bvsala/v1/statu\
757
+ s"){Li(t,200,r.estado());return}let o=Number(n.searchParams.get("wait_ms")??"0");if(!Number.isFinite(o)||o<0){Mt(t,400,"invalid_request","bvsala gateway: wait_ms must be a non-negative number of milli\
747
758
  seconds");return}let i=Math.min(Math.floor(o),3e4),s=new AbortController;t.on("close",()=>s.abort());let a=null,c="",l=/^\/_bvsala\/v1\/reports\/([^/]+)$/.exec(n.pathname);if(l){let u="";try{u=decodeURIComponent(
748
- l[1]);}catch{u="";}if(!Ir.test(u)){Rt(t,400,"invalid_request","bvsala gateway: malformed request id");return}a=()=>r.buzon.porPeticion(u),c=`request id ${u}`;}else if(n.pathname==="/_bvsala/v1/reports"){
749
- let u=n.searchParams.get("response_id")??"";if(!Ir.test(u)){Rt(t,400,"invalid_request","bvsala gateway: pass ?response_id=<the id of the provider's response>");return}a=()=>r.buzon.porRespuesta(u),c=`\
750
- response id ${u}`;}if(a===null){Rt(t,404,"not_found",`bvsala gateway: no local route ${n.pathname}`);return}let p=await r.buzon.esperar(a,i,s.signal);if(!t.destroyed){if(p===void 0){Rt(t,404,"not_found",
751
- `bvsala gateway: no report for ${c}. Reports exist only for requests sent with the header "${_n}: 1", while this gateway process keeps them (the last ${r.buzon.limite}, one hour at most).`);return}Ti(
752
- t,200,p);}}var Nc=4096;function jc(e){let t={marcas:0,de1h:0,deOtroTtl:0,enLaCola:false,herramientaDeServidor:false};return io(e,(n,r)=>{t.marcas++,n.ttl==="1h"?t.de1h++:t.deOtroTtl++,(r==="raiz"||r==="ultimoMensaje")&&
753
- (t.enLaCola=true);}),t.herramientaDeServidor=to(e),t}function Bc(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==
754
- "string"&&n.startsWith("claude-cli/")}var Uc=e=>e.cache_creation_input_tokens??(e.cache_creation?.ephemeral_5m_input_tokens??0)+(e.cache_creation?.ephemeral_1h_input_tokens??0);function Fc(e){if((e.cache_read_input_tokens??
755
- 0)===0&&Uc(e)===0&&(e.input_tokens??0)>=Nc)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 zc(e){let{vista:t,uso:n,
756
- ttlReescritoPorLaCapa:r}=e;if(t.marcas===0)return null;if((n.cache_read_input_tokens??0)===0&&Uc(n)===0&&t.enLaCola&&(n.input_tokens??0)>=Nc)return "cacheIgnorada";let i=n.cache_creation;return !r&&t.de1h>
757
- 0&&t.deOtroTtl===0&&!t.herramientaDeServidor&&i!==void 0&&(i.ephemeral_1h_input_tokens??0)===0&&(i.ephemeral_5m_input_tokens??0)>0?"ttlAcortado":null}function Ii(e,t){let n=`[gateway] degraded traffic${t.
759
+ l[1]);}catch{u="";}if(!$r.test(u)){Mt(t,400,"invalid_request","bvsala gateway: malformed request id");return}a=()=>r.buzon.porPeticion(u),c=`request id ${u}`;}else if(n.pathname==="/_bvsala/v1/reports"){
760
+ let u=n.searchParams.get("response_id")??"";if(!$r.test(u)){Mt(t,400,"invalid_request","bvsala gateway: pass ?response_id=<the id of the provider's response>");return}a=()=>r.buzon.porRespuesta(u),c=`\
761
+ response id ${u}`;}if(a===null){Mt(t,404,"not_found",`bvsala gateway: no local route ${n.pathname}`);return}let d=await r.buzon.esperar(a,i,s.signal);if(!t.destroyed){if(d===void 0){Mt(t,404,"not_found",
762
+ `bvsala gateway: no report for ${c}. Reports exist only for requests sent with the header "${An}: 1", while this gateway process keeps them (the last ${r.buzon.limite}, one hour at most).`);return}Li(
763
+ t,200,d);}}var Kc=4096;function Jc(e){let t={marcas:0,de1h:0,deOtroTtl:0,enLaCola:false,herramientaDeServidor:false};return fo(e,(n,r)=>{t.marcas++,n.ttl==="1h"?t.de1h++:t.deOtroTtl++,(r==="raiz"||r==="ultimoMensaje")&&
764
+ (t.enLaCola=true);}),t.herramientaDeServidor=co(e),t}function Yc(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==
765
+ "string"&&n.startsWith("claude-cli/")}var Zc=e=>e.cache_creation_input_tokens??(e.cache_creation?.ephemeral_5m_input_tokens??0)+(e.cache_creation?.ephemeral_1h_input_tokens??0);function Xc(e){if((e.cache_read_input_tokens??
766
+ 0)===0&&Zc(e)===0&&(e.input_tokens??0)>=Kc)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 Qc(e){let{vista:t,uso:n,
767
+ ttlReescritoPorLaCapa:r}=e;if(t.marcas===0)return null;if((n.cache_read_input_tokens??0)===0&&Zc(n)===0&&t.enLaCola&&(n.input_tokens??0)>=Kc)return "cacheIgnorada";let i=n.cache_creation;return !r&&t.de1h>
768
+ 0&&t.deOtroTtl===0&&!t.herramientaDeServidor&&i!==void 0&&(i.ephemeral_1h_input_tokens??0)===0&&(i.ephemeral_5m_input_tokens??0)>0?"ttlAcortado":null}function Ni(e,t){let n=`[gateway] degraded traffic${t.
758
769
  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 \
759
770
  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\
760
771
  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 \
761
772
  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\
762
773
  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 \
763
774
  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\
764
- y hand.`+r}var Or=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??""}`;
775
+ y hand.`+r}var jr=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??""}`;
765
776
  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.
766
- cuentas}}};function Vc(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) \
777
+ cuentas}}};function el(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) \
767
778
  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\
768
- 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 lh="[bvsala gateway] Measure license: SHADOW mode. Requests are forwarded to the provider byte for byte (no levers, no coalescing, no usage injection) and your usage is measured; what a lever woul\
769
- d have saved shows on your dashboard as an estimate, never billed. To turn the levers on, upgrade at https://savings.bivelio.com/dashboard/account - the gateway picks up the new license by itself.",Gc='\
779
+ 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 vh="[bvsala gateway] Measure license: SHADOW mode. Requests are forwarded to the provider byte for byte (no levers, no coalescing, no usage injection) and your usage is measured; what a lever woul\
780
+ d have saved shows on your dashboard as an estimate, never billed. To turn the levers on, upgrade at https://savings.bivelio.com/dashboard/account - the gateway picks up the new license by itself.",rl='\
770
781
  [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} to the ca\
771
- ll (Node: stream_options: { include_usage: true }); its last chunk then has an empty choices list.',uh=Gc+" Or start the gateway with BVSALA_GATEWAY_USAGE_INJECT=1 to add it for clients you cannot cha\
772
- nge.",dh=Gc+" 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.",ph=e=>`[bvsala gateway] POST ${e} answered with\
773
- out the provider's final usage, so it was forwarded but NOT metered. Nothing is estimated in its place.`,fh=e=>`[bvsala gateway] POST ${e} is forwarded but NOT metered: the gateway reads usage from /v\
774
- 1/messages, \u2026/chat/completions and \u2026/responses only.`,qc=/\/(count_tokens|input_tokens)$/,mh=["content-encoding","content-length","transfer-encoding"],hh=new Set(["connection","keep-alive","\
775
- proxy-connection","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"]);function gh(e){let t=new Set((e.connection??"").split(",").map(r=>r.trim().toLowerCase()).filter(
776
- r=>r!=="")),n={};for(let[r,o]of Object.entries(e)){let i=r.toLowerCase();hh.has(i)||t.has(i)||(n[r]=o);}return n}var bh=5e3,vh=new Set(["connection","keep-alive","proxy-connection","proxy-authenticate",
777
- "proxy-authorization","te","trailer","transfer-encoding","upgrade","expect"]);function Xt(e){let t=e?.cause;if(t==null)return String(e);let n=t instanceof AggregateError&&t.errors.length>0?t.errors.map(
778
- r=>String(r)).join("; "):String(t);return `${String(e)} \xB7 cause: ${n}`}var Pi=class extends Error{code;puerto;constructor(t,n,r){super(t==="EADDRINUSE"?`port ${n} is already in use: the gateway coul\
779
- d 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",this.code=t,this.puerto=n;}};function Hc(e,t){
780
- 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 yh(e){return e.writableFinished?Promise.resolve(true):e.destroyed?Promise.
781
- resolve(false):new Promise(t=>{let n=()=>o(true),r=()=>o(e.writableFinished),o=i=>{e.off("finish",n),e.off("close",r),t(i);};e.once("finish",n),e.once("close",r);})}async function Wc(e){if(!e?.license)throw new Error(
782
- "arrancarGateway: a verified BiVelio license is required (LICENSE section 2)");let t=Si(e.license.publicKey),n=Tr(e.license.token,t);if(!n.ok)throw new Error(`arrancarGateway: the license token does n\
783
- ot verify (${n.reason})`);let r=(e.upstream??"https://api.anthropic.com").replace(/\/+$/,""),o=Tc(r),i=e.fetchImpl??fetch,s=e.log??(h=>console.log(h)),a=e.warn??(h=>console.error(h)),c=e.license.now??
784
- Date.now,l=e.license.licenseServerUrl?.replace(/\/+$/,""),p=new qt,u=_i(n.license,t,p,c),f;if(e.serviceAccountKey){f=new Ut({url:e.meteringUrl??"https://savings.bivelio.com/api/metering/usage",serviceAccountKey:e.
785
- serviceAccountKey,surface:"gateway",...e.fetchImpl?{fetchImpl:e.fetchImpl}:{},onAuthError:S=>ee("gateway-ingest-auth",`[bvsala gateway] the usage ingest is rejecting the credential (${S}). Traffic kee\
786
- ps flowing (warn, never break), but this usage is not reaching your dashboard. Check BIVELIO_SERVICE_KEY and your subscription status at savings.bivelio.com.`)});let h=Wn();e.seatId?f.setSeat(e.seatId,
787
- h):Kn(e.serviceAccountKey).then(S=>f?.setSeat(S,h)).catch(()=>{}),f.start();}else ee("gateway-sin-clave","[bvsala gateway] no BIVELIO_SERVICE_KEY: this in-process gateway forwards traffic but does not \
788
- meter it (the bvsala CLI refuses to start without the key).");let m=e.coalescer?new Rr:null,b=new Set,k=()=>{let h,S=new Promise(O=>h=O);return b.add(S),()=>{b.delete(S),h();}},g=e.sombra&&f?new Sr:null,
789
- v=new Pr,x=new zn,E=new Or,y=new Ar,R=e.serviceAccountKey?new Er({url:l?`${l}/api/org/entitlements`:new URL("/api/org/entitlements",e.meteringUrl??"https://savings.bivelio.com/api/metering/usage").toString(),
790
- serviceAccountKey:e.serviceAccountKey,...e.fetchImpl?{fetchImpl:e.fetchImpl}:{},...e.entitlementsTtlMs!==void 0?{ttlMs:e.entitlementsTtlMs}:{},log:s}):null,P=R!==null&&e.elision!==false,L=()=>Ei(u.gate,R?.
791
- blockReason()??null,u.license.payload),M=null;{let h=Ei(u.gate,null,u.license.payload);h.serve&&(M=h.state);}let B=h=>{let S=wc(M,h,u.license.payload);M=h.state,S&&a(S);},K,J,C=Number.NEGATIVE_INFINITY,
792
- I=new Set,N=(h,S)=>{I.has(h)||(I.add(h),s(S));},U=false,oe=h=>h==="/v1/messages"?new Ge:h.endsWith("/responses")?new Wt:h.endsWith("/chat/completions")?new vn:null,Q=(h,S,O,j,G,V,Y)=>{v.noMedido(h,V),s(`[\
793
- gateway] ${S} ${O} \u2192 ${j}${G?" (stream)":""} \xB7 not metered: ${V}`),(Tt(O)||O.startsWith("/v1/"))&&y.noMedida(V),e.avisosDeNoMedido!==false&&(Y==="chat"&&ee("gateway-chat-sin-include-usage",uh),Y===
794
- "chat-con-inyeccion"&&ee("gateway-chat-sin-include-usage-con-inyeccion",dh),Y==="uso"&&ee(`gateway-sin-usage:${O}`,ph(O)),Y==="dialecto"&&ee(`gateway-sin-dialecto:${O}`,fh(O)));},Te=(h,S,O,j)=>{let G=h instanceof
795
- Wt?h.estadoFinal():null;if(G!==null&&G!=="completed")return {motivo:`the response ended as response.${G} without usage`,aviso:"uso"};if(!(h instanceof vn&&j!=="inyectado"&&oc(S,O)!==true))return {motivo:"\
796
- the stream ended without the provider's final usage event",aviso:"uso"};let Y="the request did not ask for usage (stream_options.include_usage)";return j==="rechazada-por-el-upstream"?{motivo:`${Y}, a\
797
- nd the upstream rejects that option`,aviso:null}:j==="comprimido"?{motivo:`${Y}; usage injection skips compressed request bodies`,aviso:"chat-con-inyeccion"}:j!==null?{motivo:Y,aviso:"chat-con-inyecci\
798
- on"}:{motivo:Y,aviso:"chat"}},Re=(h,S,O,j,G,V,Y,te,be,Dt,Ue,Se,Ye,_,F,Ot)=>{if(!f||!O){v.noMedido(h,f?"the provider reported no usage":"metering is off: the gateway has no BIVELIO_SERVICE_KEY");return}
799
- let Lt=f,tn=O,Z=Ja(S,V),Pe=`[gateway] POST ${G}${j?" \xB7 COALESCED (call avoided)":""}`;if(!Z){let he=`could not read the model from the request body${V?` (content-encoding: ${V})`:""}`;s(`${Pe} \xB7 no\
800
- t metered: ${he}`),y.noMedida(he),v.noMedido(h,"could not read the model from the request body"),ee(`gateway-sin-modelo:${G}`,`[bvsala gateway] could not read the model from the ${G} request body (con\
801
- tent-encoding: ${V??"none"}); its usage is forwarded but not metered.`);return}let me=!j&&Ue?Ue.servido:Z,X=mi(me,O,Dt);if(X){let he=j?sc(Z,X,Ye,Kt(S,V),{suscripcion:Se===true,entregada:_?.entregada===true,
802
- tierServido:_?.tierServido}):null,bt=j?ac(h,Z,X,Y,he?.ok?he.credit:null,F===true):ic(h,me,X,Y,te,be,Ue,Se===true,!o,F===true);f.record(bt),j?y.replica():y.medida(),v.medido(h,bt);let ie=bt.cost.eliminatedInputFloorCost;
803
- s(`[gateway] POST ${G} ${j?"\xB7 COALESCED (call avoided)":""} \xB7 ${me!==Z?`${Z}\u2192${me} (sibling model)`:Z} \xB7 $${(F?0:X.costeUsd).toFixed(6)} (in ${X.tokens.entrada}, cache\u2191${X.tokens.cacheEscrita}${X.
804
- tokens.cacheEscrita1h?` (1h ${X.tokens.cacheEscrita1h})`:""} cache\u2193${X.tokens.cacheLeida}, out ${X.tokens.salida})`+(te?` \xB7 elision: ${te.borrados} clear(s), ${te.tokensLimpiados} tok cleared \
805
- by the provider`+(ie!==void 0?` \xB7 floor $${ie.toFixed(6)} (cache read price)`:te.tokensLimpiadosToolUses>0?te.atribuible?" \xB7 no cache read price in the catalog: no floor":" \xB7 your own context_ma\
806
- nagement settings: counted, not credited":te.tokensLimpiados>0?" \xB7 thinking only (your config): counted, not credited":""):"")+(F?" \xB7 refusal the provider does not bill: measured at $0, no saving c\
807
- redited":"")+(Se&&!j&&(be||Ue)?" \xB7 subscription traffic: lever applied, saving not credited (no per-token invoice)":"")+(!o&&!Se&&!j&&(be||Ue||te?.atribuible)?" \xB7 unofficial upstream: lever applied\
808
- , saving not credited (list prices only hold at the provider's own API)":"")+(he?he.ok?` \xB7 by reference: floor $${bi(he.credit).toFixed(6)} (cache read price${he.credit.creditedOutputTokens>0?`, ${he.
809
- credit.creditedOutputTokens} output tok at temperature 0`:", no output credited"})`:` \xB7 estimated, not by reference: ${he.reason}`:""));let Ln=te?.atribuible===true&&te.tokensLimpiadosToolUses>0,De=u.
810
- license.payload.plan==="measure";if(De&&!j&&G==="/v1/messages"&&!Se&&o&&F!==true)try{let Ee=po(S,V),pe=Ee?mi(Ee.cambio.servido,tn,Dt):null,q=Ee&&pe&&pe.costeUsd<X.costeUsd?pe:null,D=q??X,Fe=Ot?us(Ot,D.tokens.
811
- cacheEscrita1h,D.precio.inputPer1k):0,Ze=D.costeUsd-Fe;Ze<X.costeUsd&&(Lt.record(vi(`${h}:shadow`,Z,X.costeUsd,Ze,Y)),s(`[gateway] measure (shadow) \xB7 ${Z} \xB7 `+[q&&Ee?`sibling model ${Ee.cambio.servido}`:
812
- null,Fe>0?`cache TTL 1h\u21925m on ${D.tokens.cacheEscrita1h} written tok`:null].filter(Boolean).join(" + ")+` \xB7 this call would have cost $${Ze.toFixed(6)} instead of $${X.costeUsd.toFixed(6)} (no\
813
- t applied)`));}catch{}g&&!De&&!j&&G==="/v1/messages"&&setImmediate(()=>{try{let Ee=Kt(S,V);if(!Ee||typeof Ee!="object")return;let pe=g.observar({cuerpo:Ee,uso:tn,model:Z,at:Dt??Date.now(),...Y?.sessionId!==
814
- void 0?{sessionId:Y.sessionId}:{},...Y?.agentId!==void 0?{agentId:Y.agentId}:{}});if(!pe)return;if(Ln){s(`[gateway] shadow estimate \xB7 ${Z} \xB7 the provider already cleared context via our settings: c\
815
- hain advances, nothing emitted`);return}Lt.record(vi(`${h}:shadow`,Z,pe.baselineUsd,pe.politicaUsd,Y)),s(`[gateway] shadow estimate \xB7 ${Z} \xB7 baseline $${pe.baselineUsd.toFixed(6)} \u2192 with elision\
816
- $${pe.politicaUsd.toFixed(6)}`);}catch{}});}else v.noMedido(h,`model "${me}" has no list price in the catalog`),s(`${Pe} \xB7 not metered: model "${me}" has no list price in the catalog`),y.noMedida(`m\
817
- odel "${me}" has no list price in the catalog`),ee(`gateway-sin-precio:${me}`,`[bvsala gateway] model "${me}" is not in the price catalog; its usage is forwarded but not metered.`);},je=(h,S,O,j,G,V)=>{
818
- if(!(h!=="/v1/messages"||j===null||!Fc(j)||(O===void 0||O===""||O==="identity")&&!S.includes('"cache_control"')))try{let te=Kt(S,O);if(te===null||typeof te!="object"||Array.isArray(te))return;let be=zc(
819
- {vista:jc(te),uso:j,ttlReescritoPorLaCapa:G});be!==null&&E.anotar(be,V)&&s(Ii(be,{sesion:V,entrada:j.input_tokens??0,escrita5m:j.cache_creation?.ephemeral_5m_input_tokens??0}));}catch{}},Ae=createServer(async(h,S)=>{
820
- let O=randomUUID(),j=Date.now(),G=L();if(B(G),!G.serve){let q=c();J&&q-C>=bc&&(C=q,J.check({force:true})),h.resume(),S.writeHead(402,{"content-type":"application/json","cache-control":"no-store","x-bvsala-licen\
821
- se-status":G.state}),S.end(h.method==="HEAD"?void 0:kc(G.state));let D="/";try{D=new URL(h.url??"/","http://x").pathname;}catch{}s(`[gateway] ${h.method} ${D} \u2192 402 (license ${G.state})`);return}let V=u.
822
- license.payload.plan==="measure";V&&ee("gateway-licencia-medir",lh);let Y=$c(h.url);if(Y!==null){await Mc(h,S,Y,{buzon:v,estado:()=>({schema:Pc,gateway:"bvsala",version:ye,upstream:Lc(r),license:{state:G.
823
- state,plan:u.license.payload.plan??null,expiresAt:Ne(u.license.payload.expires_at)},metering:f!==void 0,reports:{requestHeader:_n,responseHeader:Ri,capacity:v.limite}})});return}let te=Dc(h.headers[_n]),
824
- be=te?new Dr:null;if(te){let q="/";try{q=new URL(h.url??"/","http://x").pathname;}catch{}v.abrir(O,q);}let Dt=q=>te?{...q,[Ri]:O}:q,Ue=null,Se=new AbortController;S.on("close",()=>{S.writableEnded||Se.abort();});
825
- let Ye=null,_=new URL(h.url??"/",r),F=null,Ot=Buffer.alloc(0),Lt=false,tn=false,Z=null,Pe=null,me=false,X=false,he=(q,D)=>{if(q===null||Z===null||!Z.nuestros)return q;let Fe=D?.cache_creation,Ze=D?.cache_creation_input_tokens??
826
- (Fe?.ephemeral_5m_input_tokens??0)+(Fe?.ephemeral_1h_input_tokens??0),nn=(D?.input_tokens??0)+(D?.cache_read_input_tokens??0)+Ze+q.tokensLimpiados,rn=Z.triggerDelCliente!==null&&nn>=Z.triggerDelCliente;
827
- return {...q,atribuible:!rn}},bt=h.headers["content-encoding"],ie=Array.isArray(bt)?bt[0]:bt,Ln=q=>{let D=Array.isArray(q)?q[0]:q;return D!==void 0&&/^[A-Za-z0-9._:/-]{1,128}$/.test(D)?D:void 0},De=Ln(
828
- h.headers["x-claude-code-session-id"]),Ee=Ln(h.headers["x-claude-code-agent-id"]),pe=De!==void 0||Ee!==void 0?{...De!==void 0?{sessionId:De}:{},...Ee!==void 0?{agentId:Ee}:{}}:void 0;try{let q=[];for await(let w of h)
829
- q.push(w);let D=Buffer.concat(q);Ot=D,_=new URL(h.url??"/",r);let Fe=m!==null&&!V&&h.method==="POST"&&D.length>0,Ze=_c(w=>{let T=h.headers[w];return Array.isArray(T)?T.join(", "):T}),nn=Fe?Ec("POST",_.
830
- pathname+_.search,D,Ze):"";if(Fe)if(m.tieneEnVuelo(nn)){let w=await m.esperar(nn);if(w){let T=k();try{let ne=Se.signal.aborted||S.destroyed;ne||S.writeHead(w.status,Dt(w.headers)),Ue=w.status;let Ce=oe(
831
- _.pathname)??new Ge;for(let Nt of w.chunks)ne||S.write(Nt),Ce.observar(Nt),be?.observar(Nt);be&&v.anotarRespuesta(O,be.valor()??Ai(Buffer.concat(w.chunks))),ne||S.end();let ze=ne?!1:await yh(S),Oe=Ce.
832
- usageFinal()??xr(_.pathname,Buffer.concat(w.chunks));if(Oe===null){if(f&&!qc.test(_.pathname)){let Nt=String(w.headers["content-type"]??"").includes("text/event-stream");Q(O,h.method??"POST",_.pathname,
833
- w.status,Nt,Tt(_.pathname)?Nt?Te(Ce,D,ie,null).motivo:"the response carried no usage":"no usage dialect for this route",null);}return}let et=h.headers["anthropic-beta"],yu=gi(_.pathname,Array.isArray(et)?
834
- et.join(", "):et,r);Re(O,D,Oe,!0,_.pathname,ie,pe,null,null,j,null,yu,w.primaria??null,{entregada:ze,tierServido:nc(_.pathname,Buffer.concat(w.chunks))},_.pathname==="/v1/messages"&&(Ce instanceof Ge&&
835
- Ce.negativaNoCobrada()||hi(_.pathname,Buffer.concat(w.chunks))));return}finally{T();}}}else Ye=m.registrar(nn);let rn=h.headers.connection,vu=new Set((Array.isArray(rn)?rn.join(","):rn??"").split(",").
836
- map(w=>w.trim().toLowerCase()).filter(w=>w!=="")),Xe={};for(let[w,T]of Object.entries(h.headers))w==="host"||w==="content-length"||T===void 0||vh.has(w)||vu.has(w)||w!==_n&&(Xe[w]=Array.isArray(T)?T.join(
837
- ", "):T);let on={...Xe};me=gi(_.pathname,on["anthropic-beta"],r);let _e=D;if(P&&!V&&e.dialesElision===!0&&h.method==="POST"&&_.pathname==="/v1/messages"&&R.tiene("context_elision"))try{let w=ss(D,ie);
838
- w!==null&&(_e=w.cuerpo,Z={nuestros:w.nuestros,triggerDelCliente:w.triggerDelCliente},Xe["anthropic-beta"]=cs(Xe["anthropic-beta"]));}catch{}if(h.method==="POST"&&_.pathname==="/v1/messages"&&(ie??"")===
839
- "")try{let w=xc(D.toString("utf8")),T=Sc(w);T&&(ee("gateway-busqueda-herramientas",T),Bc(h.headers)&&E.anotar("busquedaApagada",De)&&s(Ii("busquedaApagada",{sesion:De,definiciones:w.definiciones})));}catch{}
840
- let ts=P&&!V&&e.modeloHermano===!0&&h.method==="POST"&&(_.pathname==="/v1/messages"||_.pathname==="/v1/messages/count_tokens");if(ts&&!R.tiene("sibling_model_routing")&&ee("gateway-hermano-sin-feature",
841
- "[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-closed)."),ts&&R.tiene("sibling_model_r\
842
- outing"))try{let T=po(_e,_e===D?ie:"identity",{betas:Xe["anthropic-beta"]});T!==null&&(_e=T.cuerpo,Pe=T.cambio);}catch{}let $n=!1;if(P&&!V&&co(e.esfuerzo)&&h.method==="POST"&&_.pathname==="/v1/messages"&&
843
- R.tiene("per_turn_effort"))try{let w=_e===D?ie:"identity",T=ms(_e,e.esfuerzo,w);T!==null&&(_e=T.cuerpo,Xe["anthropic-beta"]=hs(Xe["anthropic-beta"]),$n=!0);}catch{}let $t=null;if(P&&!V&&h.method==="POS\
844
- T"&&_.pathname==="/v1/messages"&&R.tiene("cache_ttl_tuning"))try{let T=ct(_e,_e===D?ie:"identity");if(T!==null){let ne=no(T),Ce=`${pe?.sessionId??"sin-sesion"}:${ne.system}`,ze=Date.now(),Oe=x.ultima(
845
- Ce,ze);if(x.anotar(Ce,ne,ze),oo({fraccionNueva:ro(Oe,ne)})){let et=so(T);et!==null&&(_e=et.cuerpo,$t={rebajadas:et.rebajadas,yaEran5m:et.yaEran5m,herramientaDeServidor:et.herramientaDeServidor},X=!0);}}}catch{}
846
- let Gr=null;if(V&&e.elision!==!1&&h.method==="POST"&&_.pathname==="/v1/messages")try{let w=ct(D,ie);if(w!==null){let T=no(w),ne=`${pe?.sessionId??"sin-sesion"}:${T.system}`,Ce=Date.now(),ze=x.ultima(ne,
847
- Ce);if(x.anotar(ne,T,Ce),oo({fraccionNueva:ro(ze,T)})){let Oe=so(w);Oe!==null&&(Gr={rebajadas:Oe.rebajadas,yaEran5m:Oe.yaEran5m,herramientaDeServidor:Oe.herramientaDeServidor});}}}catch{}let Mt=!1,Mn=null;
848
- if(h.method==="POST"&&_.pathname.endsWith("/chat/completions")&&f&&e.usageInject===!0&&!V)if(U)Mn="rechazada-por-el-upstream";else try{let w=rc(D,ie);Mn=w.motivo,w.cuerpo&&(_e=w.cuerpo,Mt=!0);}catch{}let z,
849
- Wr=_e,Kr=Xe;try{z=await i(_,{method:h.method,headers:Xe,body:["GET","HEAD"].includes(h.method??"")?void 0:_e,redirect:"manual",signal:Se.signal});}catch(w){Ye?.abortar(),S.headersSent||(S.writeHead(502,
850
- {"content-type":"application/json"}),S.end(JSON.stringify({error:"bvsala gateway: upstream unreachable",detail:Xt(w)}))),s(`[gateway] ${h.method} ${_.pathname} \u2192 upstream unreachable: ${Xt(w)}`);
851
- return}if(((Wr!==D||!Hc(Kr,on))&&z.status===400||Mt&&(z.status===400||z.status===422))&&!Se.signal.aborted){let w="";try{w=(await z.text()).slice(0,300).replace(/\s+/g," ");}catch{}let T=Mt;s(T?`[gatew\
852
- ay] the upstream rejected (${z.status}) the request with stream_options.include_usage added; forwarding it unchanged \xB7 ${w}`:`[gateway] the upstream rejected (400) the rewritten request${Pe?` to ${Pe.
853
- servido}`:""}${$n?" (per-turn effort)":""}${$t?" (cache TTL)":""}${Z?" (context editing dials)":""}; forwarding it unchanged \xB7 ${w}`),Pe=null,$n=!1,$t=null,X=!1,Z=null,Mt=!1,T&&(Mn="rechazada-por-e\
854
- l-upstream"),Wr=D,Kr=on;try{z=await i(_,{method:h.method,headers:on,body:D,redirect:"manual",signal:Se.signal});}catch(ne){Ye?.abortar(),S.headersSent||(S.writeHead(502,{"content-type":"application/jso\
855
- n"}),S.end(JSON.stringify({error:"bvsala gateway: upstream unreachable",detail:Xt(ne)}))),s(`[gateway] ${h.method} ${_.pathname} \u2192 upstream unreachable on retry: ${Xt(ne)}`);return}T&&z.ok&&(U=!0,
856
- ee("gateway-sin-stream-options","[bvsala gateway] the upstream rejects stream_options, so usage injection is off for the rest of this process: streamed /v1/chat/completions answers from it are forward\
857
- ed but NOT metered (stream=false answers still are)."));}let Jr=gh(Object.fromEntries(z.headers.entries()));for(let w of mh)delete Jr[w];S.writeHead(z.status,Dt(Jr)),Ue=z.status;let Nn=z.headers.get("c\
858
- ontent-type")??"",jn=Nn.includes("text/event-stream")||Nn===""&&z.ok&&oe(_.pathname)!==null&&!_.pathname.endsWith("/chat/completions");F=jn?oe(_.pathname):null,tn=z.ok;let Qe=!jn&&z.ok&&f!==void 0&&h.
859
- method==="POST"&&Tt(_.pathname)&&(z.headers.get("content-type")??"").includes("application/json")?[]:null,ns=0,rs=!1;if(z.body)for await(let w of z.body){let T=Buffer.from(w);S.write(T),F?.observar(T),
860
- be?.observar(T),Qe&&(ns+=T.length,ns>Ci?(Qe=null,rs=!0):Qe.push(T)),Ye?.capturar(T);}if(S.end(),be&&v.anotarRespuesta(O,be.valor()??(Qe?Ai(Buffer.concat(Qe)):null)),Ye){let w=Pe===null&&!$n&&Z===null&&
861
- !Mt&&$t===null&&Wr===D&&Hc(Kr,on),T=Qe?Buffer.concat(Qe):null,ne=z.ok&&(F?F.usageFinal()!==null:T!==null&&xr(_.pathname,T)!==null),Ce=F instanceof Wt&&F.estadoFinal()==="failed"||T!==null&&Za(_.pathname,
862
- T),ze=F!==null&&F.negativa()||T!==null&&Qa(_.pathname,T),Oe=!ze&&tc(F!==null?F.textoInicial():T!==null?ec(_.pathname,T):"");Ye.terminar(z.status,Jr,{requestId:O,at:Date.now(),intacta:w,proveedorOficial:o,
863
- conContador:ne,suscripcion:me,fallida:Ce,...ze?{negativa:ze}:{},...Oe?{negativaEnTexto:!0}:{}});}if(F&&z.ok){Lt=!0;let w=F.usageFinal();if(w===null&&f){let T=Te(F,D,ie,Mt?"inyectado":Mn);Q(O,h.method??
864
- "POST",_.pathname,z.status,!0,T.motivo,T.aviso);}else {let T=he(F instanceof Ge?F.elision():null,w),ne=_.pathname==="/v1/messages"&&F instanceof Ge&&F.negativaNoCobrada();Re(O,D,w,!1,_.pathname,ie,pe,T,
865
- $t,j,Pe,me,void 0,void 0,ne,Gr),je(_.pathname,D,ie,w,X,De);}f||s(`[gateway] ${h.method} ${_.pathname} \u2192 ${z.status} (stream) \xB7 not metered: no BIVELIO_SERVICE_KEY`);}else if(Qe){let w=Buffer.concat(
866
- Qe),T=xr(_.pathname,w);if(T===null)Q(O,h.method??"POST",_.pathname,z.status,!1,"the response carried no usage","uso");else {let ne=_.pathname==="/v1/messages"?Ha(w):null;Re(O,D,T,!1,_.pathname,ie,pe,he(
867
- ne,T),$t,j,Pe,me,void 0,void 0,hi(_.pathname,w),Gr),je(_.pathname,D,ie,T,X,De);}}else rs?Q(O,h.method??"POST",_.pathname,z.status,!1,"the response was too large to read its usage",null):f&&h.method==="\
868
- POST"&&z.ok&&Tt(_.pathname)?Q(O,h.method,_.pathname,z.status,!1,`the response is neither JSON nor an event stream (content-type: ${Nn===""?"none":Nn.slice(0,80)})`,null):f&&h.method==="POST"&&z.ok&&!Tt(
869
- _.pathname)&&!qc.test(_.pathname)?Q(O,h.method,_.pathname,z.status,jn,"no usage dialect for this route",_.pathname.startsWith("/v1/")?"dialecto":null):s(`[gateway] ${h.method} ${_.pathname} \u2192 ${z.
870
- status}${jn?" (stream)":""}`);}catch(q){if(Ye?.abortar(),Se.signal.aborted){let D=!Lt&&F?F.usageFinal():null;if(D){s(`[gateway] ${h.method} ${_.pathname} \u2192 client closed after the final usage; metered \
871
- anyway`);let Fe=he(F instanceof Ge?F.elision():null,D),Ze=_.pathname==="/v1/messages"&&F instanceof Ge&&F.negativaNoCobrada();Re(O,Ot,D,false,_.pathname,ie,pe,Fe,void 0,j,Pe,me,void 0,void 0,Ze),je(_.pathname,
872
- Ot,ie,D,X,De);}else s(`[gateway] ${h.method} ${_.pathname} \u2192 client aborted; upstream cancelled`),F&&tn&&!Lt&&y.noMedida("the client closed the stream before the provider's final usage");}else if(s(
873
- `[gateway] ${h.method} ${_.pathname} \u2192 error while serving: ${Xt(q)}`),!S.headersSent){S.writeHead(502,{"content-type":"application/json"}),S.end(JSON.stringify({error:"bvsala gateway: stream int\
874
- errupted",detail:Xt(q)}));return}S.writableEnded||S.end();}finally{te&&v.noMedido(O,Se.signal.aborted?"the client closed the connection before the provider's final usage":Ue===null?"the request did not\
875
- get an answer from the provider":`no usage was read from the provider's answer (HTTP ${Ue})`);}});Ae.on("upgrade",(h,S)=>{s(`[gateway] ${h.method} ${new URL(h.url??"/","http://x").pathname} \u2192 426 (Web\
876
- Socket not supported; the client falls back to HTTP)`),S.once("error",()=>{}),S.once("finish",()=>S.destroy()),S.end(`HTTP/1.1 426 Upgrade Required\r
782
+ ll (Node: stream_options: { include_usage: true }); its last chunk then has an empty choices list.',yh=rl+" Or start the gateway with BVSALA_GATEWAY_USAGE_INJECT=1 to add it for clients you cannot cha\
783
+ nge.",kh=rl+" 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.",wh=e=>`[bvsala gateway] POST ${e} answered with\
784
+ out the provider's final usage, so it was forwarded but NOT metered. Nothing is estimated in its place.`,xh=e=>`[bvsala gateway] POST ${e} is forwarded but NOT metered: the gateway reads usage from /v\
785
+ 1/messages, \u2026/chat/completions and \u2026/responses only.`,tl=/\/(count_tokens|input_tokens)$/,Sh=["content-encoding","content-length","transfer-encoding"],Eh=new Set(["connection","keep-alive","\
786
+ proxy-connection","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"]);function _h(e){let t=new Set((e.connection??"").split(",").map(r=>r.trim().toLowerCase()).filter(
787
+ r=>r!=="")),n={};for(let[r,o]of Object.entries(e)){let i=r.toLowerCase();Eh.has(i)||t.has(i)||(n[r]=o);}return n}var Ch=5e3,Th=new Set(["connection","keep-alive","proxy-connection","proxy-authenticate",
788
+ "proxy-authorization","te","trailer","transfer-encoding","upgrade","expect"]);function on(e){let t=e?.cause;if(t==null)return String(e);let n=t instanceof AggregateError&&t.errors.length>0?t.errors.map(
789
+ r=>String(r)).join("; "):String(t);return `${String(e)} \xB7 cause: ${n}`}var ji=class extends Error{code;puerto;constructor(t,n,r){super(t==="EADDRINUSE"?`port ${n} is already in use: the gateway coul\
790
+ d 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",this.code=t,this.puerto=n;}};function nl(e,t){
791
+ 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 Rh(e){return e.writableFinished?Promise.resolve(true):e.destroyed?Promise.
792
+ resolve(false):new Promise(t=>{let n=()=>o(true),r=()=>o(e.writableFinished),o=i=>{e.off("finish",n),e.off("close",r),t(i);};e.once("finish",n),e.once("close",r);})}async function ol(e){if(!e?.license)throw new Error(
793
+ "arrancarGateway: a verified BiVelio license is required (LICENSE section 2)");let t=Ii(e.license.publicKey),n=Dr(e.license.token,t);if(!n.ok)throw new Error(`arrancarGateway: the license token does n\
794
+ ot verify (${n.reason})`);let r=(e.upstream??"https://api.anthropic.com").replace(/\/+$/,""),o=jc(r),i=e.fetchImpl??fetch,s=e.log??(h=>console.log(h)),a=e.warn??(h=>console.error(h)),c=e.license.now??
795
+ Date.now,l=e.license.licenseServerUrl?.replace(/\/+$/,""),d=new Yt,u=Di(n.license,t,d,c),f;if(e.serviceAccountKey){f=new Gt({url:e.meteringUrl??"https://savings.bivelio.com/api/metering/usage",serviceAccountKey:e.
796
+ serviceAccountKey,surface:"gateway",...e.fetchImpl?{fetchImpl:e.fetchImpl}:{},onAuthError:E=>Q("gateway-ingest-auth",`[bvsala gateway] the usage ingest is rejecting the credential (${E}). Traffic keep\
797
+ s flowing (warn, never break), but this usage is not reaching your dashboard. Check BIVELIO_SERVICE_KEY and your subscription status at savings.bivelio.com.`)});let h=Yn();e.seatId?f.setSeat(e.seatId,
798
+ h):Zn(e.serviceAccountKey).then(E=>f?.setSeat(E,h)).catch(()=>{}),f.start();}else Q("gateway-sin-clave","[bvsala gateway] no BIVELIO_SERVICE_KEY: this in-process gateway forwards traffic but does not m\
799
+ eter it (the bvsala CLI refuses to start without the key).");let m=e.coalescer?new Or:null,b=new Set,y=()=>{let h,E=new Promise(O=>h=O);return b.add(E),()=>{b.delete(E),h();}},g=e.sombra&&f?new Rr:null,
800
+ v=new Mr,x=new Gn,C=new Er,k=new jr,R=new Lr,A=e.serviceAccountKey?new Ar({url:l?`${l}/api/org/entitlements`:new URL("/api/org/entitlements",e.meteringUrl??"https://savings.bivelio.com/api/metering/us\
801
+ age").toString(),serviceAccountKey:e.serviceAccountKey,...e.fetchImpl?{fetchImpl:e.fetchImpl}:{},...e.entitlementsTtlMs!==void 0?{ttlMs:e.entitlementsTtlMs}:{},log:s}):null,D=A!==null&&e.elision!==false,
802
+ $=()=>Pi(u.gate,A?.blockReason()??null,u.license.payload),j=null;{let h=Pi(u.gate,null,u.license.payload);h.serve&&(j=h.state);}let J=h=>{let E=Dc(j,h,u.license.payload);j=h.state,E&&a(E);},ee,S,P=Number.
803
+ NEGATIVE_INFINITY,N=new Set,z=(h,E)=>{N.has(h)||(N.add(h),s(E));},ie=false,se=h=>h==="/v1/messages"?new We:h.endsWith("/responses")?new Qt:h.endsWith("/chat/completions")?new xn:null,me=(h,E,O,B,G,V,Y)=>{
804
+ v.noMedido(h,V),s(`[gateway] ${E} ${O} \u2192 ${B}${G?" (stream)":""} \xB7 not metered: ${V}`),($t(O)||O.startsWith("/v1/"))&&R.noMedida(V),e.avisosDeNoMedido!==false&&(Y==="chat"&&Q("gateway-chat-sin-in\
805
+ clude-usage",yh),Y==="chat-con-inyeccion"&&Q("gateway-chat-sin-include-usage-con-inyeccion",kh),Y==="uso"&&Q(`gateway-sin-usage:${O}`,wh(O)),Y==="dialecto"&&Q(`gateway-sin-dialecto:${O}`,xh(O)));},Fe=(h,E,O,B)=>{
806
+ let G=h instanceof Qt?h.estadoFinal():null;if(G!==null&&G!=="completed")return {motivo:`the response ended as response.${G} without usage`,aviso:"uso"};if(!(h instanceof xn&&B!=="inyectado"&&hc(E,O)!==
807
+ true))return {motivo:"the stream ended without the provider's final usage event",aviso:"uso"};let Y="the request did not ask for usage (stream_options.include_usage)";return B==="rechazada-por-el-upstrea\
808
+ m"?{motivo:`${Y}, and the upstream rejects that option`,aviso:null}:B==="comprimido"?{motivo:`${Y}; usage injection skips compressed request bodies`,aviso:"chat-con-inyeccion"}:B!==null?{motivo:Y,aviso:"\
809
+ chat-con-inyeccion"}:{motivo:Y,aviso:"chat"}},Oe=(h,E,O,B,G,V,Y,te,ae,Ut,Ve,we,Ze,_,U,Et,ut)=>{if(!f||!O){v.noMedido(h,f?"the provider reported no usage":"metering is off: the gateway has no BIVELIO_S\
810
+ ERVICE_KEY");return}let ln=f,Le=O,Z=sc(E,V),dt=`[gateway] POST ${G}${B?" \xB7 COALESCED (call avoided)":""}`;if(!Z){let be=`could not read the model from the request body${V?` (content-encoding: ${V})`:
811
+ ""}`;s(`${dt} \xB7 not metered: ${be}`),R.noMedida(be),v.noMedido(h,"could not read the model from the request body"),Q(`gateway-sin-modelo:${G}`,`[bvsala gateway] could not read the model from the ${G}\
812
+ request body (content-encoding: ${V??"none"}); its usage is forwarded but not metered.`);return}let he=!B&&Ve?Ve.servido:Z,W=wi(he,O,Ut);if(W){let be=B?bc(Z,W,Ze,en(E,V),{suscripcion:we===true,entregada:_?.
813
+ entregada===true,tierServido:_?.tierServido}):null,ne=u.license.payload.plan==="measure",Xe=0;ut&&!B&&(Xe=ne?Za(ut,W.tokens):Ya(ut,W.tokens),Xa(ut,W.tokens,{sombra:ne,atribuible:!!ae&&ae.rebajadas>0&&ae.
814
+ yaEran5m===0&&!ae.herramientaDeServidor&&we!==true&&o&&U!==true,perdidos:Xe}));let Ie=!ne&&Xe>0?{perdidos:Xe}:null,pt=B?vc(h,Z,W,Y,be?.ok?be.credit:null,U===true):gc(h,he,W,Y,te,ae,Ve,we===true,!o,U===true,Ie);
815
+ f.record(pt),B?R.replica():R.medida(),v.medido(h,pt);let Qe=pt.cost.eliminatedInputFloorCost;s(`[gateway] POST ${G} ${B?"\xB7 COALESCED (call avoided)":""} \xB7 ${he!==Z?`${Z}\u2192${he} (sibling mode\
816
+ l)`:Z} \xB7 $${(U?0:W.costeUsd).toFixed(6)} (in ${W.tokens.entrada}, cache\u2191${W.tokens.cacheEscrita}${W.tokens.cacheEscrita1h?` (1h ${W.tokens.cacheEscrita1h})`:""} cache\u2193${W.tokens.cacheLeida}\
817
+ , out ${W.tokens.salida})`+(te?` \xB7 elision: ${te.borrados} clear(s), ${te.tokensLimpiados} tok cleared by the provider`+(Qe!==void 0?` \xB7 floor $${Qe.toFixed(6)} (cache read price)`:te.tokensLimpiadosToolUses>
818
+ 0?te.atribuible?" \xB7 no cache read price in the catalog: no floor":" \xB7 your own context_management settings: counted, not credited":te.tokensLimpiados>0?" \xB7 thinking only (your config): counted, \
819
+ not credited":""):"")+(Ie?` \xB7 cache TTL miss: ${Ie.perdidos} tok rewritten because the 5m entry expired (net $${pt.cost.netSavingsUsd.toFixed(6)} on this call)`:"")+(U?" \xB7 refusal the provider does\
820
+ not bill: measured at $0, no saving credited":"")+(we&&!B&&(ae||Ve)?" \xB7 subscription traffic: lever applied, saving not credited (no per-token invoice)":"")+(!o&&!we&&!B&&(ae||Ve||te?.atribuible)?
821
+ " \xB7 unofficial upstream: lever applied, saving not credited (list prices only hold at the provider's own API)":"")+(be?be.ok?` \xB7 by reference: floor $${Ei(be.credit).toFixed(6)} (cache read pric\
822
+ e${be.credit.creditedOutputTokens>0?`, ${be.credit.creditedOutputTokens} output tok at temperature 0`:", no output credited"})`:` \xB7 estimated, not by reference: ${be.reason}`:""));let H=te?.atribuible===
823
+ true&&te.tokensLimpiadosToolUses>0,L=u.license.payload.plan==="measure";if(L&&!B&&G==="/v1/messages"&&!we&&o&&U!==true)try{let de=yo(E,V),ve=de?wi(de.cambio.servido,Le,Ut):null,ft=de&&ve&&ve.costeUsd<W.costeUsd?
824
+ ve:null,Pe=ft??W,jn=Et?bs(Et,Pe.tokens.cacheEscrita1h,Pe.precio.inputPer1k):0,Re=_r({perdidos:Xe,inputPer1k:Pe.precio.inputPer1k,cachedInputPer1k:Pe.precio.cachedInputPer1k,primaEscritura:Et?so:ao}),et=Pe.
825
+ costeUsd-jn+Re;et!==W.costeUsd&&(ln.record(_i(`${h}:shadow`,Z,W.costeUsd,et,Y)),s(`[gateway] measure (shadow) \xB7 ${Z} \xB7 `+[ft&&de?`sibling model ${de.cambio.servido}`:null,jn>0?`cache TTL 1h\u21925m o\
826
+ n ${Pe.tokens.cacheEscrita1h} written tok`:null,Re>0?`cache miss the 5m TTL would have caused on ${Xe} tok (+$${Re.toFixed(6)})`:null].filter(Boolean).join(" + ")+` \xB7 this call would have cost $${et.
827
+ toFixed(6)} instead of $${W.costeUsd.toFixed(6)} (not applied)`));}catch{}g&&!L&&!B&&G==="/v1/messages"&&setImmediate(()=>{try{let de=en(E,V);if(!de||typeof de!="object")return;let ve=g.observar({cuerpo:de,
828
+ uso:Le,model:Z,at:Ut??Date.now(),...Y?.sessionId!==void 0?{sessionId:Y.sessionId}:{},...Y?.agentId!==void 0?{agentId:Y.agentId}:{}});if(!ve)return;if(H){s(`[gateway] shadow estimate \xB7 ${Z} \xB7 the pr\
829
+ ovider already cleared context via our settings: chain advances, nothing emitted`);return}ln.record(_i(`${h}:shadow`,Z,ve.baselineUsd,ve.politicaUsd,Y)),s(`[gateway] shadow estimate \xB7 ${Z} \xB7 baseli\
830
+ ne $${ve.baselineUsd.toFixed(6)} \u2192 with elision $${ve.politicaUsd.toFixed(6)}`);}catch{}});}else v.noMedido(h,`model "${he}" has no list price in the catalog`),s(`${dt} \xB7 not metered: model "${he}\
831
+ " has no list price in the catalog`),R.noMedida(`model "${he}" has no list price in the catalog`),Q(`gateway-sin-precio:${he}`,`[bvsala gateway] model "${he}" is not in the price catalog; its usage is\
832
+ forwarded but not metered.`);},ze=(h,E,O,B,G,V)=>{if(!(h!=="/v1/messages"||B===null||!Xc(B)||(O===void 0||O===""||O==="identity")&&!E.includes('"cache_control"')))try{let te=en(E,O);if(te===null||typeof te!=
833
+ "object"||Array.isArray(te))return;let ae=Qc({vista:Jc(te),uso:B,ttlReescritoPorLaCapa:G});ae!==null&&k.anotar(ae,V)&&s(Ni(ae,{sesion:V,entrada:B.input_tokens??0,escrita5m:B.cache_creation?.ephemeral_5m_input_tokens??
834
+ 0}));}catch{}},Te=createServer(async(h,E)=>{let O=randomUUID(),B=Date.now(),G=$();if(J(G),!G.serve){let H=c();S&&H-P>=Rc&&(P=H,S.check({force:true})),h.resume(),E.writeHead(402,{"content-type":"application/json","cache-co\
835
+ ntrol":"no-store","x-bvsala-license-status":G.state}),E.end(h.method==="HEAD"?void 0:Pc(G.state));let L="/";try{L=new URL(h.url??"/","http://x").pathname;}catch{}s(`[gateway] ${h.method} ${L} \u2192 402 (li\
836
+ cense ${G.state})`);return}let V=u.license.payload.plan==="measure";V&&Q("gateway-licencia-medir",vh);let Y=Gc(h.url);if(Y!==null){await Wc(h,E,Y,{buzon:v,estado:()=>({schema:zc,gateway:"bvsala",version:Se,
837
+ upstream:Hc(r),license:{state:G.state,plan:u.license.payload.plan??null,expiresAt:Ue(u.license.payload.expires_at)},metering:f!==void 0,reports:{requestHeader:An,responseHeader:$i,capacity:v.limite}})});
838
+ return}let te=Vc(h.headers[An]),ae=te?new Nr:null;if(te){let H="/";try{H=new URL(h.url??"/","http://x").pathname;}catch{}v.abrir(O,H);}let Ut=H=>te?{...H,[$i]:O}:H,Ve=null,we=new AbortController;E.on("c\
839
+ lose",()=>{E.writableEnded||we.abort();});let Ze=null,_=new URL(h.url??"/",r),U=null,Et=Buffer.alloc(0),ut=false,ln=false,Le=null,Z=null,dt=false,he=false,W=(H,L)=>{if(H===null||Le===null||!Le.nuestros)return H;let de=L?.
840
+ cache_creation,ve=L?.cache_creation_input_tokens??(de?.ephemeral_5m_input_tokens??0)+(de?.ephemeral_1h_input_tokens??0),ft=(L?.input_tokens??0)+(L?.cache_read_input_tokens??0)+ve+H.tokensLimpiados,Pe=Le.
841
+ triggerDelCliente!==null&&ft>=Le.triggerDelCliente;return {...H,atribuible:!Pe}},be=h.headers["content-encoding"],ne=Array.isArray(be)?be[0]:be,Xe=H=>{let L=Array.isArray(H)?H[0]:H;return L!==void 0&&/^[A-Za-z0-9._:/-]{1,128}$/.
842
+ test(L)?L:void 0},Ie=Xe(h.headers["x-claude-code-session-id"]),pt=Xe(h.headers["x-claude-code-agent-id"]),Qe=Ie!==void 0||pt!==void 0?{...Ie!==void 0?{sessionId:Ie}:{},...pt!==void 0?{agentId:pt}:{}}:
843
+ void 0;try{let H=[];for await(let w of h)H.push(w);let L=Buffer.concat(H);Et=L,_=new URL(h.url??"/",r);let de=m!==null&&!V&&h.method==="POST"&&L.length>0,ve=Mc(w=>{let T=h.headers[w];return Array.isArray(
844
+ T)?T.join(", "):T}),ft=de?$c("POST",_.pathname+_.search,L,ve):"";if(de)if(m.tieneEnVuelo(ft)){let w=await m.esperar(ft);if(w){let T=y();try{let X=we.signal.aborted||E.destroyed;X||E.writeHead(w.status,
845
+ Ut(w.headers)),Ve=w.status;let ye=se(_.pathname)??new We;for(let Vt of w.chunks)X||E.write(Vt),ye.observar(Vt),ae?.observar(Vt);ae&&v.anotarRespuesta(O,ae.valor()??Mi(Buffer.concat(w.chunks))),X||E.end();
846
+ let $e=X?!1:await Rh(E),Me=ye.usageFinal()??Tr(_.pathname,Buffer.concat(w.chunks));if(Me===null){if(f&&!tl.test(_.pathname)){let Vt=String(w.headers["content-type"]??"").includes("text/event-stream");
847
+ me(O,h.method??"POST",_.pathname,w.status,Vt,$t(_.pathname)?Vt?Fe(ye,L,ne,null).motivo:"the response carried no usage":"no usage dialect for this route",null);}return}let nt=h.headers["anthropic-beta"],
848
+ Au=Si(_.pathname,Array.isArray(nt)?nt.join(", "):nt,r);Oe(O,L,Me,!0,_.pathname,ne,Qe,null,null,B,null,Au,w.primaria??null,{entregada:$e,tierServido:fc(_.pathname,Buffer.concat(w.chunks))},_.pathname===
849
+ "/v1/messages"&&(ye instanceof We&&ye.negativaNoCobrada()||xi(_.pathname,Buffer.concat(w.chunks))));return}finally{T();}}}else Ze=m.registrar(ft);let Pe=h.headers.connection,jn=new Set((Array.isArray(Pe)?
850
+ Pe.join(","):Pe??"").split(",").map(w=>w.trim().toLowerCase()).filter(w=>w!=="")),Re={};for(let[w,T]of Object.entries(h.headers))w==="host"||w==="content-length"||T===void 0||Th.has(w)||jn.has(w)||w!==
851
+ An&&(Re[w]=Array.isArray(T)?T.join(", "):T);let et={...Re};dt=Si(_.pathname,et["anthropic-beta"],r);let Ae=L;if(D&&!V&&e.dialesElision===!0&&h.method==="POST"&&_.pathname==="/v1/messages"&&A.tiene("co\
852
+ ntext_elision"))try{let w=fs(L,ne);w!==null&&(Ae=w.cuerpo,Le={nuestros:w.nuestros,triggerDelCliente:w.triggerDelCliente},Re["anthropic-beta"]=hs(Re["anthropic-beta"]));}catch{}if(h.method==="POST"&&_.pathname===
853
+ "/v1/messages"&&(ne??"")==="")try{let w=Oc(L.toString("utf8")),T=Lc(w);T&&(Q("gateway-busqueda-herramientas",T),Yc(h.headers)&&k.anotar("busquedaApagada",Ie)&&s(Ni("busquedaApagada",{sesion:Ie,definiciones:w.
854
+ definiciones})));}catch{}let cs=D&&!V&&e.modeloHermano===!0&&h.method==="POST"&&(_.pathname==="/v1/messages"||_.pathname==="/v1/messages/count_tokens");if(cs&&!A.tiene("sibling_model_routing")&&Q("gate\
855
+ way-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-closed)."),cs&&
856
+ A.tiene("sibling_model_routing"))try{let T=yo(Ae,Ae===L?ne:"identity",{betas:Re["anthropic-beta"]});T!==null&&(Ae=T.cuerpo,Z=T.cambio);}catch{}let Bn=!1;if(D&&!V&&go(e.esfuerzo)&&h.method==="POST"&&_.pathname===
857
+ "/v1/messages"&&A.tiene("per_turn_effort"))try{let w=Ae===L?ne:"identity",T=ws(Ae,e.esfuerzo,w);T!==null&&(Ae=T.cuerpo,Re["anthropic-beta"]=xs(Re["anthropic-beta"]),Bn=!0);}catch{}let Ft=null,mt=null;if(D&&
858
+ !V&&h.method==="POST"&&_.pathname==="/v1/messages"&&A.tiene("cache_ttl_tuning"))try{let T=ht(Ae,Ae===L?ne:"identity");if(T!==null){let X=lo(T),ye=`${Qe?.sessionId??"sin-sesion"}:${X.system}`,$e=Date.now(),
859
+ Me=x.ultima(ye,$e);if(x.anotar(ye,X,$e),mt=C.abrir(ye,X,$e,!1),po({fraccionNueva:uo(Me,X)})){let nt=mo(T);nt!==null&&(mt.rebajado=!0,Ae=nt.cuerpo,Ft={rebajadas:nt.rebajadas,yaEran5m:nt.yaEran5m,herramientaDeServidor:nt.
860
+ herramientaDeServidor},he=!0);}}}catch{}let Zr=null;if(V&&e.elision!==!1&&h.method==="POST"&&_.pathname==="/v1/messages")try{let w=ht(L,ne);if(w!==null){let T=lo(w),X=`${Qe?.sessionId??"sin-sesion"}:${T.
861
+ system}`,ye=Date.now(),$e=x.ultima(X,ye);if(x.anotar(X,T,ye),mt=C.abrir(X,T,ye,!1),po({fraccionNueva:uo($e,T)})){let Me=mo(w);Me!==null&&(mt.rebajado=!0,Zr={rebajadas:Me.rebajadas,yaEran5m:Me.yaEran5m,
862
+ herramientaDeServidor:Me.herramientaDeServidor});}}}catch{}let zt=!1,Un=null;if(h.method==="POST"&&_.pathname.endsWith("/chat/completions")&&f&&e.usageInject===!0&&!V)if(ie)Un="rechazada-por-el-upstrea\
863
+ m";else try{let w=mc(L,ne);Un=w.motivo,w.cuerpo&&(Ae=w.cuerpo,zt=!0);}catch{}let F,Xr=Ae,Qr=Re;try{F=await i(_,{method:h.method,headers:Re,body:["GET","HEAD"].includes(h.method??"")?void 0:Ae,redirect:"\
864
+ manual",signal:we.signal});}catch(w){Ze?.abortar(),E.headersSent||(E.writeHead(502,{"content-type":"application/json"}),E.end(JSON.stringify({error:"bvsala gateway: upstream unreachable",detail:on(w)}))),
865
+ s(`[gateway] ${h.method} ${_.pathname} \u2192 upstream unreachable: ${on(w)}`);return}if(((Xr!==L||!nl(Qr,et))&&F.status===400||zt&&(F.status===400||F.status===422))&&!we.signal.aborted){let w="";try{
866
+ w=(await F.text()).slice(0,300).replace(/\s+/g," ");}catch{}let T=zt;s(T?`[gateway] the upstream rejected (${F.status}) the request with stream_options.include_usage added; forwarding it unchanged \xB7 ${w}`:
867
+ `[gateway] the upstream rejected (400) the rewritten request${Z?` to ${Z.servido}`:""}${Bn?" (per-turn effort)":""}${Ft?" (cache TTL)":""}${Le?" (context editing dials)":""}; forwarding it unchanged \xB7\
868
+ ${w}`),Z=null,Bn=!1,Ft=null,mt&&he&&(mt.rebajado=!1),he=!1,Le=null,zt=!1,T&&(Un="rechazada-por-el-upstream"),Xr=L,Qr=et;try{F=await i(_,{method:h.method,headers:et,body:L,redirect:"manual",signal:we.
869
+ signal});}catch(X){Ze?.abortar(),E.headersSent||(E.writeHead(502,{"content-type":"application/json"}),E.end(JSON.stringify({error:"bvsala gateway: upstream unreachable",detail:on(X)}))),s(`[gateway] ${h.
870
+ method} ${_.pathname} \u2192 upstream unreachable on retry: ${on(X)}`);return}T&&F.ok&&(ie=!0,Q("gateway-sin-stream-options","[bvsala gateway] the upstream rejects stream_options, so usage injection i\
871
+ s 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 eo=_h(Object.fromEntries(F.headers.entries()));
872
+ for(let w of Sh)delete eo[w];E.writeHead(F.status,Ut(eo)),Ve=F.status;let Fn=F.headers.get("content-type")??"",zn=Fn.includes("text/event-stream")||Fn===""&&F.ok&&se(_.pathname)!==null&&!_.pathname.endsWith(
873
+ "/chat/completions");U=zn?se(_.pathname):null,ln=F.ok;let tt=!zn&&F.ok&&f!==void 0&&h.method==="POST"&&$t(_.pathname)&&(F.headers.get("content-type")??"").includes("application/json")?[]:null,ls=0,us=!1;
874
+ if(F.body)for await(let w of F.body){let T=Buffer.from(w);E.write(T),U?.observar(T),ae?.observar(T),tt&&(ls+=T.length,ls>Oi?(tt=null,us=!0):tt.push(T)),Ze?.capturar(T);}if(E.end(),ae&&v.anotarRespuesta(
875
+ O,ae.valor()??(tt?Mi(Buffer.concat(tt)):null)),Ze){let w=Z===null&&!Bn&&Le===null&&!zt&&Ft===null&&Xr===L&&nl(Qr,et),T=tt?Buffer.concat(tt):null,X=F.ok&&(U?U.usageFinal()!==null:T!==null&&Tr(_.pathname,
876
+ T)!==null),ye=U instanceof Qt&&U.estadoFinal()==="failed"||T!==null&&cc(_.pathname,T),$e=U!==null&&U.negativa()||T!==null&&uc(_.pathname,T),Me=!$e&&pc(U!==null?U.textoInicial():T!==null?dc(_.pathname,
877
+ T):"");Ze.terminar(F.status,eo,{requestId:O,at:Date.now(),intacta:w,proveedorOficial:o,conContador:X,suscripcion:dt,fallida:ye,...$e?{negativa:$e}:{},...Me?{negativaEnTexto:!0}:{}});}if(U&&F.ok){ut=!0;
878
+ let w=U.usageFinal();if(w===null&&f){let T=Fe(U,L,ne,zt?"inyectado":Un);me(O,h.method??"POST",_.pathname,F.status,!0,T.motivo,T.aviso);}else {let T=W(U instanceof We?U.elision():null,w),X=_.pathname==="\
879
+ /v1/messages"&&U instanceof We&&U.negativaNoCobrada();Oe(O,L,w,!1,_.pathname,ne,Qe,T,Ft,B,Z,dt,void 0,void 0,X,Zr,mt),ze(_.pathname,L,ne,w,he,Ie);}f||s(`[gateway] ${h.method} ${_.pathname} \u2192 ${F.status}\
880
+ (stream) \xB7 not metered: no BIVELIO_SERVICE_KEY`);}else if(tt){let w=Buffer.concat(tt),T=Tr(_.pathname,w);if(T===null)me(O,h.method??"POST",_.pathname,F.status,!1,"the response carried no usage","us\
881
+ o");else {let X=_.pathname==="/v1/messages"?nc(w):null;Oe(O,L,T,!1,_.pathname,ne,Qe,W(X,T),Ft,B,Z,dt,void 0,void 0,xi(_.pathname,w),Zr,mt),ze(_.pathname,L,ne,T,he,Ie);}}else us?me(O,h.method??"POST",_.pathname,
882
+ F.status,!1,"the response was too large to read its usage",null):f&&h.method==="POST"&&F.ok&&$t(_.pathname)?me(O,h.method,_.pathname,F.status,!1,`the response is neither JSON nor an event stream (cont\
883
+ ent-type: ${Fn===""?"none":Fn.slice(0,80)})`,null):f&&h.method==="POST"&&F.ok&&!$t(_.pathname)&&!tl.test(_.pathname)?me(O,h.method,_.pathname,F.status,zn,"no usage dialect for this route",_.pathname.startsWith(
884
+ "/v1/")?"dialecto":null):s(`[gateway] ${h.method} ${_.pathname} \u2192 ${F.status}${zn?" (stream)":""}`);}catch(H){if(Ze?.abortar(),we.signal.aborted){let L=!ut&&U?U.usageFinal():null;if(L){s(`[gateway\
885
+ ] ${h.method} ${_.pathname} \u2192 client closed after the final usage; metered anyway`);let de=W(U instanceof We?U.elision():null,L),ve=_.pathname==="/v1/messages"&&U instanceof We&&U.negativaNoCobrada();
886
+ Oe(O,Et,L,false,_.pathname,ne,Qe,de,void 0,B,Z,dt,void 0,void 0,ve),ze(_.pathname,Et,ne,L,he,Ie);}else s(`[gateway] ${h.method} ${_.pathname} \u2192 client aborted; upstream cancelled`),U&&ln&&!ut&&R.noMedida(
887
+ "the client closed the stream before the provider's final usage");}else if(s(`[gateway] ${h.method} ${_.pathname} \u2192 error while serving: ${on(H)}`),!E.headersSent){E.writeHead(502,{"content-type":"\
888
+ application/json"}),E.end(JSON.stringify({error:"bvsala gateway: stream interrupted",detail:on(H)}));return}E.writableEnded||E.end();}finally{te&&v.noMedido(O,we.signal.aborted?"the client closed the c\
889
+ onnection before the provider's final usage":Ve===null?"the request did not get an answer from the provider":`no usage was read from the provider's answer (HTTP ${Ve})`);}});Te.on("upgrade",(h,E)=>{s(`\
890
+ [gateway] ${h.method} ${new URL(h.url??"/","http://x").pathname} \u2192 426 (WebSocket not supported; the client falls back to HTTP)`),E.once("error",()=>{}),E.once("finish",()=>E.destroy()),E.end(`HT\
891
+ TP/1.1 426 Upgrade Required\r
877
892
  connection: close\r
878
893
  content-length: 0\r
879
894
  \r
880
- `);});let Be=e.puerto??8402;try{await new Promise((h,S)=>{Ae.once("error",S),Ae.listen(Be,"127.0.0.1",()=>h());});}catch(h){f?.stop();let S=h?.code;throw new Pi(typeof S=="string"?S:"EUNKNOWN",Be,h)}let On=Ae.
881
- address().port;return l&&(K=new bn({url:`${l}/licenses/revocations`,publicKeyPem:t,snapshot:p,getRefreshAfter:()=>u.gate.refreshAfter?.(),nowSeconds:()=>Math.floor(c()/1e3),...e.fetchImpl?{fetchImpl:e.
882
- fetchImpl}:{},silenceWarnings:true,onEvent:h=>{h.type==="rejected"&&N(`poller:${h.reason}`,`[gateway] revocation list rejected (${h.reason}); known revocations still apply`);},...e.license.revocations??{}}),
883
- K.start(),e.serviceAccountKey&&(J=new Cr({licenseServerUrl:l,serviceAccountKey:e.serviceAccountKey,publicKey:t,revocation:p,current:()=>u.license,onAdopt:h=>{u=_i(h,t,p,c),s(`[gateway] renewed license\
884
- adopted (expires ${Ne(h.payload.expires_at)})`),B(L());},onWarning:a,...e.fetchImpl?{fetchImpl:e.fetchImpl}:{},now:c,...e.license.renewal??{}}),J.start({checkNow:e.license.checkOnStart===true}))),{puerto:On,
885
- cerrar:async()=>{if(J?.stop(),K?.stop(),b.size>0){let h=[...b];s(`[gateway] closing: waiting for ${h.length} in-flight measurement(s) before draining usage`);let S=e.topeMedicionesAlCerrarMs??bh,O,j=new Promise(
886
- V=>{O=setTimeout(()=>V("vencido"),S),O.unref?.();}),G=await Promise.race([Promise.all(h).then(()=>"ok"),j]);clearTimeout(O),G==="vencido"&&a(`[bvsala gateway] shutting down with ${b.size} measurement(s\
887
- ) still in flight after ${S} ms: that usage will not reach your dashboard.`);}await f?.stopAndDrain(),await new Promise(h=>Ae.close(()=>h()));},licenseStatus:()=>L().state,degradaciones:()=>E.contadores(),
888
- medicion:()=>y.estado()}}var Di=["claude","codex","goose","qwen","opencode","kilo","copilot","aider"];function Cn(e){return Di.includes(e??"")}function Oi(e,t={}){
895
+ `);});let cn=e.puerto??8402;try{await new Promise((h,E)=>{Te.once("error",E),Te.listen(cn,"127.0.0.1",()=>h());});}catch(h){f?.stop();let E=h?.code;throw new ji(typeof E=="string"?E:"EUNKNOWN",cn,h)}let Nn=Te.
896
+ address().port;return l&&(ee=new wn({url:`${l}/licenses/revocations`,publicKeyPem:t,snapshot:d,getRefreshAfter:()=>u.gate.refreshAfter?.(),nowSeconds:()=>Math.floor(c()/1e3),...e.fetchImpl?{fetchImpl:e.
897
+ fetchImpl}:{},silenceWarnings:true,onEvent:h=>{h.type==="rejected"&&z(`poller:${h.reason}`,`[gateway] revocation list rejected (${h.reason}); known revocations still apply`);},...e.license.revocations??{}}),
898
+ ee.start(),e.serviceAccountKey&&(S=new Pr({licenseServerUrl:l,serviceAccountKey:e.serviceAccountKey,publicKey:t,revocation:d,current:()=>u.license,onAdopt:h=>{u=Di(h,t,d,c),s(`[gateway] renewed licens\
899
+ e adopted (expires ${Ue(h.payload.expires_at)})`),J($());},onWarning:a,...e.fetchImpl?{fetchImpl:e.fetchImpl}:{},now:c,...e.license.renewal??{}}),S.start({checkNow:e.license.checkOnStart===true}))),{puerto:Nn,
900
+ cerrar:async()=>{if(S?.stop(),ee?.stop(),b.size>0){let h=[...b];s(`[gateway] closing: waiting for ${h.length} in-flight measurement(s) before draining usage`);let E=e.topeMedicionesAlCerrarMs??Ch,O,B=new Promise(
901
+ V=>{O=setTimeout(()=>V("vencido"),E),O.unref?.();}),G=await Promise.race([Promise.all(h).then(()=>"ok"),B]);clearTimeout(O),G==="vencido"&&a(`[bvsala gateway] shutting down with ${b.size} measurement(s\
902
+ ) still in flight after ${E} ms: that usage will not reach your dashboard.`);}await f?.stopAndDrain(),await new Promise(h=>Te.close(()=>h()));},licenseStatus:()=>$().state,degradaciones:()=>k.contadores(),
903
+ medicion:()=>R.estado()}}var Bi=["claude","codex","goose","qwen","opencode","kilo","copilot","aider"];function In(e){return Bi.includes(e??"")}function Ui(e,t={}){
889
904
  let n=t.path??process.env.PATH??"",r=t.existe??existsSync,o=null;for(let i of n.split(";").filter(s=>s.length>0)){for(let s of [".exe",".com"]){let a=join(i,e+s);if(r(a))return {tipo:"exe",ruta:a}}if(o===null)for(let s of [
890
- ".cmd",".bat"]){let a=join(i,e+s);if(r(a)){o=a;break}}}return o!==null?{tipo:"solo-shim",ruta:o}:{tipo:"no-encontrado"}}function Zc(e={}){let n=(e.env??process.env).BVSALA_CODEX_AUTH?.toLowerCase();if(n===
905
+ ".cmd",".bat"]){let a=join(i,e+s);if(r(a)){o=a;break}}}return o!==null?{tipo:"solo-shim",ruta:o}:{tipo:"no-encontrado"}}function cl(e={}){let n=(e.env??process.env).BVSALA_CODEX_AUTH?.toLowerCase();if(n===
891
906
  "api-key"||n==="apikey")return "api-key";if(n==="chatgpt")return "chatgpt";let r=null;try{r=e.leerAuth?e.leerAuth():null;}catch{r=null;}if(r===null)return "api-key";try{let o=JSON.parse(r);return typeof o.
892
- auth_mode=="string"?o.auth_mode.toLowerCase().replace(/[^a-z]/g,"")==="apikey"?"api-key":"chatgpt":o.tokens!==void 0&&o.tokens!==null?"chatgpt":"api-key"}catch{return "api-key"}}var wh={"api-key":{upstream:"\
893
- https://api.openai.com",prefijo:"/v1"},chatgpt:{upstream:"https://chatgpt.com",prefijo:"/backend-api/codex"}},Jc="https://api.anthropic.com",Yc="https://api.openai.com",Xc={opencode:"OPENCODE_CONFIG_C\
894
- ONTENT",kilo:"KILO_CONFIG_CONTENT"};function Qc(e,t){let n={};if(e!==void 0&&e.trim()!==""){let a;try{a=JSON.parse(e);}catch{return null}if(typeof a!="object"||a===null||Array.isArray(a))return null;n=
907
+ auth_mode=="string"?o.auth_mode.toLowerCase().replace(/[^a-z]/g,"")==="apikey"?"api-key":"chatgpt":o.tokens!==void 0&&o.tokens!==null?"chatgpt":"api-key"}catch{return "api-key"}}var Ih={"api-key":{upstream:"\
908
+ https://api.openai.com",prefijo:"/v1"},chatgpt:{upstream:"https://chatgpt.com",prefijo:"/backend-api/codex"}},sl="https://api.anthropic.com",al="https://api.openai.com",ll={opencode:"OPENCODE_CONFIG_C\
909
+ ONTENT",kilo:"KILO_CONFIG_CONTENT"};function ul(e,t){let n={};if(e!==void 0&&e.trim()!==""){let a;try{a=JSON.parse(e);}catch{return null}if(typeof a!="object"||a===null||Array.isArray(a))return null;n=
895
910
  a;}let r=(a,c)=>{let l=a[c];return l===void 0?{}:typeof l=="object"&&l!==null&&!Array.isArray(l)?l:null},o=r(n,"provider"),i=o&&r(o,"anthropic"),s=i&&r(i,"options");return !o||!i||!s?null:JSON.stringify(
896
- {...n,provider:{...o,anthropic:{...i,options:{...s,baseURL:t}}}})}function el(e){let t=e.COPILOT_PROVIDER_BASE_URL?.trim()??"";if(t==="")return {ok:false,error:"Copilot CLI goes through a base URL only wi\
911
+ {...n,provider:{...o,anthropic:{...i,options:{...s,baseURL:t}}}})}function dl(e){let t=e.COPILOT_PROVIDER_BASE_URL?.trim()??"";if(t==="")return {ok:false,error:"Copilot CLI goes through a base URL only wi\
897
912
  th your own provider key (BYOK). Without COPILOT_PROVIDER_BASE_URL it uses GitHub-hosted models, which never pass through the gateway: there is nothing to meter (its /usage shows those AI credits). To\
898
913
  meter BYOK with Anthropic, export COPILOT_PROVIDER_TYPE=anthropic, COPILOT_PROVIDER_BASE_URL=https://api.anthropic.com, COPILOT_PROVIDER_API_KEY and COPILOT_MODEL, and run `bvsala copilot` again."};let n=e.
899
914
  COPILOT_PROVIDER_TYPE?.trim().toLowerCase()||"openai";if(n==="openai")return {ok:false,error:"`bvsala copilot` wraps the anthropic provider type only for now. With the openai type (the default) Copilot CL\
900
915
  I can call the Responses API over WebSocket, which the gateway answers with 426, and its fallback to HTTP is not validated yet. To meter it by hand and check the log, see `bvsala doctor`."};if(n!=="an\
901
916
  thropic")return {ok:false,error:"COPILOT_PROVIDER_TYPE is neither anthropic nor openai: the gateway prices only the provider's own API at its list price (Azure, a local model or a reseller bills different\
902
917
  ly, or not at all), so `bvsala copilot` wraps the anthropic type only."};let r;try{r=new URL(t);}catch{return {ok:false,error:"COPILOT_PROVIDER_BASE_URL is not a URL: fix it so Copilot CLI works directly f\
903
- irst."}}return r.origin!==Jc?{ok:false,error:`COPILOT_PROVIDER_BASE_URL does not point at ${Jc}: the gateway prices only the provider's own API at its list price (a local model or a reseller bills differ\
904
- ently, or not at all), so it does not wrap it.`}:{ok:true,ruta:r.pathname.replace(/\/+$/,"")}}function tl(e,t=process.env){if(e==="opencode"||e==="kilo"){let n=Xc[e];return Qc(t[n],"http://127.0.0.1:1/v\
918
+ irst."}}return r.origin!==sl?{ok:false,error:`COPILOT_PROVIDER_BASE_URL does not point at ${sl}: the gateway prices only the provider's own API at its list price (a local model or a reseller bills differ\
919
+ ently, or not at all), so it does not wrap it.`}:{ok:true,ruta:r.pathname.replace(/\/+$/,"")}}function pl(e,t=process.env){if(e==="opencode"||e==="kilo"){let n=ll[e];return ul(t[n],"http://127.0.0.1:1/v\
905
920
  1")===null?`${n} is set but is not a JSON object with an object at provider.anthropic.options, so the wrapper cannot add the gateway's baseURL without guessing (its value is not shown). Unset it, or u\
906
- se the manual recipe in \`bvsala doctor\`.`:null}if(e==="copilot"){let n=el(t);return n.ok?null:n.error}return null}function Lr(e,t,n,r={},o=process.env){let i=`http://127.0.0.1:${t}`;switch(e){case "c\
921
+ se the manual recipe in \`bvsala doctor\`.`:null}if(e==="copilot"){let n=dl(t);return n.ok?null:n.error}return null}function Br(e,t,n,r={},o=process.env){let i=`http://127.0.0.1:${t}`;switch(e){case "c\
907
922
  laude":return {bin:"claude",args:n,env:{ANTHROPIC_BASE_URL:i,ENABLE_TOOL_SEARCH:o.ENABLE_TOOL_SEARCH??"true"}};case "goose":return {bin:"goose",args:n,env:{ANTHROPIC_HOST:i}};case "qwen":return {bin:"qwen",
908
- args:n,env:{ANTHROPIC_BASE_URL:i},nota:'Qwen Code only routes through here with `security.auth.selectedType: "anthropic"` in ~/.qwen/settings.json (see `bvsala doctor`).'};case "opencode":case "kilo":{let s=Xc[e],
909
- a=Qc(o[s],`${i}/v1`),c=e==="opencode"?"opencode":"Kilo";return {bin:e,args:n,env:a===null?{}:{[s]:a},nota:`routes ${c}'s \`anthropic\` provider (your Anthropic API key) through the gateway, with ${s}: \
910
- nothing is written to disk. Other providers`+(e==="kilo"?", the Kilo Gateway included,":"")+" go straight to their API and are not metered."}}case "copilot":{let s=el(o);return s.ok?{bin:"copilot",args:n,
923
+ args:n,env:{ANTHROPIC_BASE_URL:i},nota:'Qwen Code only routes through here with `security.auth.selectedType: "anthropic"` in ~/.qwen/settings.json (see `bvsala doctor`).'};case "opencode":case "kilo":{let s=ll[e],
924
+ a=ul(o[s],`${i}/v1`),c=e==="opencode"?"opencode":"Kilo";return {bin:e,args:n,env:a===null?{}:{[s]:a},nota:`routes ${c}'s \`anthropic\` provider (your Anthropic API key) through the gateway, with ${s}: \
925
+ nothing is written to disk. Other providers`+(e==="kilo"?", the Kilo Gateway included,":"")+" go straight to their API and are not metered."}}case "copilot":{let s=dl(o);return s.ok?{bin:"copilot",args:n,
911
926
  env:{COPILOT_PROVIDER_BASE_URL:`${i}${s.ruta}`},nota:"BYOK with Anthropic: the gateway routes to api.anthropic.com. Your key and model stay as you exported them."}:{bin:"copilot",args:n,env:{}}}case "a\
912
- ider":{if(r.upstreamElegido===Yc){let s=o.BVSALA_GATEWAY_USAGE_INJECT==="1";return {bin:"aider",args:n,env:{OPENAI_BASE_URL:`${i}/v1`,OPENAI_API_BASE:`${i}/v1`},upstream:Yc,nota:"OpenAI models through \
927
+ ider":{if(r.upstreamElegido===al){let s=o.BVSALA_GATEWAY_USAGE_INJECT==="1";return {bin:"aider",args:n,env:{OPENAI_BASE_URL:`${i}/v1`,OPENAI_API_BASE:`${i}/v1`},upstream:al,nota:"OpenAI models through \
913
928
  the gateway (Anthropic ones go direct in this run). "+(s?"Usage injection is on: streamed replies ask for their usage.":"litellm asks for streamed usage only when it talks to api.openai.com itself: st\
914
929
  reamed replies are forwarded but NOT metered unless you relaunch with BVSALA_GATEWAY_USAGE_INJECT=1 (or use --no-stream).")}}return {bin:"aider",args:n,env:{ANTHROPIC_API_BASE:i},nota:"Anthropic models\
915
- through the gateway; OpenAI and other providers go direct and are not metered (for OpenAI models: BVSALA_GATEWAY_UPSTREAM=openai bvsala aider)."}}case "codex":{let s=r.modoCodex??"api-key",a=wh[s];return {
930
+ through the gateway; OpenAI and other providers go direct and are not metered (for OpenAI models: BVSALA_GATEWAY_UPSTREAM=openai bvsala aider)."}}case "codex":{let s=r.modoCodex??"api-key",a=Ih[s];return {
916
931
  bin:"codex",args:["-c",`openai_base_url="${i}${a.prefijo}"`,...n],env:{},upstream:a.upstream,nota:s==="chatgpt"?"ChatGPT auth detected: the gateway routes to chatgpt.com/backend-api/codex. Subscriptio\
917
932
  n traffic is metered at list-price equivalent with no commission (there is no per-token invoice); the per-seat license applies as for any other use.":"API key auth: the gateway routes to api.openai.co\
918
- m/v1."}}}}var xh=["gateway","doctor","skill","init"],nl=new Set(["help","--help","-h"]),rl=new Set(["version","--version","-v"]);function ol(e){let[t,...n]=e;return t===void 0||nl.has(t)?{tipo:"ayuda",salida:0}:
919
- rl.has(t)?{tipo:"version"}:Cn(t)?{tipo:"arrancar",comando:t,resto:n}:xh.includes(t)?n.some(r=>nl.has(r))?{tipo:"ayuda",salida:0}:n.some(r=>rl.has(r))?{tipo:"version"}:{tipo:"arrancar",comando:t,resto:n}:
920
- {tipo:"ayuda",salida:1}}function il(e){return e.length===1&&(e[0]==="--help"||e[0]==="-h"||e[0]==="--version")}function sl(e,t,n){let r=e??{},o=typeof r.puerto=="number"?r.puerto:n;if(r.code==="EADDRI\
933
+ m/v1."}}}}var Ph=["gateway","doctor","skill","init"],fl=new Set(["help","--help","-h"]),ml=new Set(["version","--version","-v"]);function hl(e){let[t,...n]=e;return t===void 0||fl.has(t)?{tipo:"ayuda",salida:0}:
934
+ ml.has(t)?{tipo:"version"}:In(t)?{tipo:"arrancar",comando:t,resto:n}:Ph.includes(t)?n.some(r=>fl.has(r))?{tipo:"ayuda",salida:0}:n.some(r=>ml.has(r))?{tipo:"version"}:{tipo:"arrancar",comando:t,resto:n}:
935
+ {tipo:"ayuda",salida:1}}function gl(e){return e.length===1&&(e[0]==="--help"||e[0]==="-h"||e[0]==="--version")}function bl(e,t,n){let r=e??{},o=typeof r.puerto=="number"?r.puerto:n;if(r.code==="EADDRI\
921
936
  NUSE")return `port ${o} is already in use (another gateway, or a terminal launched earlier?): use --port ${o+1} or stop the other process`;if(r.code==="EACCES")return `port ${o} cannot be opened: permis\
922
937
  sion denied (EACCES; ports below 1024 need privileges): use --port ${Math.max(1024,o)} or higher`;let i=e instanceof Error?e.message:String(e);return `could not start the gateway for \`bvsala ${t}\`: ${i}`}
923
- var Sh={"--puerto":"--port","--proyecto":"--project","--forzar":"--force"},Eh={BVSALA_GATEWAY_ESFUERZO:"BVSALA_GATEWAY_EFFORT",BVSALA_GATEWAY_MODELO_HERMANO:"BVSALA_GATEWAY_SIBLING_MODEL"};function al(e,t,{
924
- checkEnv:n}){let r=[],o=new Set;for(let i of e){let s=i.split("=")[0],a=Sh[s];a===void 0||o.has(s)||(o.add(s),r.push(`[bvsala] ${s} was removed in 0.5: use ${a}.`));}if(n)for(let[i,s]of Object.entries(
925
- Eh))t[i]!==void 0&&r.push(`[bvsala] ${i} was removed in 0.5 and is no longer read: rename it to ${s} (same values), or unset it.`);return r}function _h(e){let t=Number.parseInt(e.slice(8,10),10);return Number.isFinite(t)&&t%2===0?"palanca":"control"}function cl(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.
926
- activo!==false,espia:r}}function ll(e){let{enrolamiento:t,espiaVivo:n,upstreamEnv:r,elisionEnv:o,hoyUtcIso:i}=e;if(!t)return {linea:"",aviso:false};if(!t.activo)return {linea:"A/B plan: enrolment paused (acti\
938
+ var Dh={"--puerto":"--port","--proyecto":"--project","--forzar":"--force"},Oh={BVSALA_GATEWAY_ESFUERZO:"BVSALA_GATEWAY_EFFORT",BVSALA_GATEWAY_MODELO_HERMANO:"BVSALA_GATEWAY_SIBLING_MODEL"};function vl(e,t,{
939
+ checkEnv:n}){let r=[],o=new Set;for(let i of e){let s=i.split("=")[0],a=Dh[s];a===void 0||o.has(s)||(o.add(s),r.push(`[bvsala] ${s} was removed in 0.5: use ${a}.`));}if(n)for(let[i,s]of Object.entries(
940
+ Oh))t[i]!==void 0&&r.push(`[bvsala] ${i} was removed in 0.5 and is no longer read: rename it to ${s} (same values), or unset it.`);return r}function Lh(e){let t=Number.parseInt(e.slice(8,10),10);return Number.isFinite(t)&&t%2===0?"palanca":"control"}function yl(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.
941
+ activo!==false,espia:r}}function kl(e){let{enrolamiento:t,espiaVivo:n,upstreamEnv:r,elisionEnv:o,hoyUtcIso:i}=e;if(!t)return {linea:"",aviso:false};if(!t.activo)return {linea:"A/B plan: enrolment paused (acti\
927
942
  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\
928
- 2:espia\`.`,aviso:true};let s=_h(i),a=`http://127.0.0.1:${t.espia}`,c=r!==void 0&&r!=="",l=o!==void 0&&o!=="",p=[];p.push(`A/B plan: ${i} UTC \u2192 arm ${s.toUpperCase()}`);let u=e.upstreamOrigen==="fl\
929
- ag"?"--upstream":"the environment";return p.push(c?`upstream kept from ${u} (${r})`:`chained to :${t.espia}`),l&&p.push(`elision flag kept from the environment (=${o})`),p.push("context elision dials \
930
- OFF (2026-09-09): the arm no longer turns them on"),p.push("assignment PER SESSION since 2026-09-10 (brazoDeSesion), not by day parity"),{...c?{}:{upstream:a},brazo:s,linea:p.join(", "),aviso:false}}var Ah="check: the gateway log must show `[gateway] POST /v1/messages \u2026`; if you see `/v1/v1\
931
- /messages`, there is one /v1 too many; if you see a bare `POST /messages`, one is missing.",Ih=[{id:"claude",nombre:"Claude Code",binario:"claude",configs:[],detectable:true,receta:({base:e})=>["use `bv\
943
+ 2:espia\`.`,aviso:true};let s=Lh(i),a=`http://127.0.0.1:${t.espia}`,c=r!==void 0&&r!=="",l=o!==void 0&&o!=="",d=[];d.push(`A/B plan: ${i} UTC \u2192 arm ${s.toUpperCase()}`);let u=e.upstreamOrigen==="fl\
944
+ ag"?"--upstream":"the environment";return d.push(c?`upstream kept from ${u} (${r})`:`chained to :${t.espia}`),l&&d.push(`elision flag kept from the environment (=${o})`),d.push("context elision dials \
945
+ OFF (2026-09-09): the arm no longer turns them on"),d.push("assignment PER SESSION since 2026-09-10 (brazoDeSesion), not by day parity"),{...c?{}:{upstream:a},brazo:s,linea:d.join(", "),aviso:false}}var jh="check: the gateway log must show `[gateway] POST /v1/messages \u2026`; if you see `/v1/v1\
946
+ /messages`, there is one /v1 too many; if you see a bare `POST /messages`, one is missing.",Bh=[{id:"claude",nombre:"Claude Code",binario:"claude",configs:[],detectable:true,receta:({base:e})=>["use `bv\
932
947
  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\
933
948
  ages)`]},{id:"codex",nombre:"Codex CLI",binario:"codex",configs:[join(".codex","config.toml"),join(".codex","auth.json")],detectable:true,comprobar:"check: the gateway log must show `[gateway] POST /v1/resp\
934
949
  onses \u2026` (API key) or `POST /backend-api/codex/responses \u2026` (ChatGPT); `/v1/v1/responses` means one /v1 too many.",receta:({base:e,rutas:t})=>["use `bvsala codex` \u2014 the base URL prefix depen\
@@ -975,200 +990,200 @@ he stream is forwarded but NOT metered; the last chunk then has an empty choices
975
990
  o is client.responses.create. Cost is priced at the model's list price;","a model without one is forwarded but not metered, and the gateway log says so on every such request."]},{id:"python-anthropic",
976
991
  nombre:"Python, or any Anthropic SDK (Messages)",configs:[],detectable:false,estadoSinDeteccion:"no detection: any language, through the SDK's base URL",receta:({base:e,puerto:t})=>[`start: bvsala gatewa\
977
992
  y --port ${t} (Anthropic is the default upstream)`,`python: client = Anthropic(base_url="${e}") (NO /v1: the SDK appends /v1/messages)`,`node: const client = new Anthropic({ baseURL: "${e}" })`,
978
- "streamed and stream=False requests are both metered."]}];function Ph(e,t){let n=e.split(delimiter).filter(o=>o.length>0),r=process.platform==="win32"?["",".exe",".cmd",".bat"]:[""];return o=>n.some(i=>r.some(
979
- s=>t(join(i,o+s))))}async function ul(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??Ph(t.
993
+ "streamed and stream=False requests are both metered."]}];function Uh(e,t){let n=e.split(delimiter).filter(o=>o.length>0),r=process.platform==="win32"?["",".exe",".cmd",".bat"]:[""];return o=>n.some(i=>r.some(
994
+ s=>t(join(i,o+s))))}async function wl(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??Uh(t.
980
995
  path??process.env.PATH??"",r),i=`http://127.0.0.1:${e}`,s=`${i}/v1`,a=[],c=[`bvsala doctor \u2014 local gateway at ${i}`,"Print only: it writes no configuration. Detection by existence (binaries on th\
981
996
  e PATH and","user configuration files); the contents of a file are never read.","The gateway needs BIVELIO_SERVICE_KEY and an active BiVelio license in every mode: it collects the license with that ke\
982
- y and does not start without one.",""];for(let l of Ih){let p=l.configs.map(k=>join(n,k)),u=l.binario!==void 0&&o(l.binario),f=p.filter(k=>r(k)),m=u||f.length>0;m&&a.push(l.id);let b;l.detectable?m?b=`d\
997
+ y and does not start without one.",""];for(let l of Bh){let d=l.configs.map(y=>join(n,y)),u=l.binario!==void 0&&o(l.binario),f=d.filter(y=>r(y)),m=u||f.length>0;m&&a.push(l.id);let b;l.detectable?m?b=`d\
983
998
  etected \u2014 ${[...u?[`binary \`${l.binario}\` on PATH`]:[],...f.map(g=>`config present: ${g}`)].join("; ")}`:b="not detected":b=l.estadoSinDeteccion??"no automatic detection (editor extension)",c.push(
984
- `\xBB ${l.id}: ${b}`),c.push(` ${l.nombre}`);for(let k of l.receta({base:i,baseV1:s,puerto:e,rutas:p}))c.push(` ${k}`);l.comprobar!==null&&c.push(` ${l.comprobar??Ah}`),c.push("");}return c.push("BY\
999
+ `\xBB ${l.id}: ${b}`),c.push(` ${l.nombre}`);for(let y of l.receta({base:i,baseV1:s,puerto:e,rutas:d}))c.push(` ${y}`);l.comprobar!==null&&c.push(` ${l.comprobar??jh}`),c.push("");}return c.push("BY\
985
1000
  OK rule: the recipes for the third-party terminals (opencode, Kilo, Copilot, Aider, Goose, Crush, Qwen Code, Droid,","Cline, Continue) are for API keys. Never route the OAuth of a Claude Pro/Max subsc\
986
1001
  ription through the gateway from a","third-party harness - Anthropic forbids it. Claude Code and Codex on a subscription are routed and metered at","list-price equivalent, with no commission (there is\
987
1002
  no per-token invoice); the per-seat license applies.","Any language through the gateway: it measures every request whose usage it can read (Anthropic Messages, OpenAI Chat","Completions and Responses\
988
1003
  ) for models with a list price, and its log line says when one is not metered. The saving","levers of the SDK (npm) are TypeScript; the gateway's own levers apply to Anthropic /v1/messages with a PRO \
989
1004
  license.","Per-terminal detail: docs/terminales/<terminal>.md"),{texto:c.join(`
990
- `),detectados:a}}var Li=["ai-sdk","mastra","langchain","anthropic-sdk","sdk"],Rn={"ai-sdk":["openai","anthropic"],mastra:["openai","anthropic"],langchain:["openai","anthropic"],"anthropic-sdk":["anthropic"],sdk:["open\
991
- ai","anthropic"]},An={"ai-sdk":"Vercel AI SDK",mastra:"Mastra",langchain:"LangChain.js","anthropic-sdk":"Anthropic TypeScript SDK",sdk:"the SDK directly (no framework)"},$i={"ai-sdk":"@bivelio/savings\
992
- -layer/ai-sdk",mastra:"@bivelio/savings-layer/mastra",langchain:"@bivelio/savings-layer/langchain","anthropic-sdk":"@bivelio/savings-layer/anthropic-sdk",sdk:"@bivelio/savings-layer"},Dh={openai:"gpt-\
993
- 4o-mini",anthropic:"claude-haiku-4-5"},dl="What is 2 + 2 * 3?",Tn=["licenseKey: process.env.BIVELIO_LICENSE_KEY,",'licenseServerUrl: "https://savings.bivelio.com",',"serviceAccountKey: process.env.BIV\
994
- ELIO_SERVICE_KEY,"],Oh=["onReport: (report) => {"," seen.calls += 1;"," seen.avoidedLlm = report.calls.avoidedLlm;"," seen.basis = report.cost.basis;","},"];function pl(e,t){switch(e){case "ai-sdk":
1005
+ `),detectados:a}}var Fi=["ai-sdk","mastra","langchain","anthropic-sdk","sdk"],Dn={"ai-sdk":["openai","anthropic"],mastra:["openai","anthropic"],langchain:["openai","anthropic"],"anthropic-sdk":["anthropic"],sdk:["open\
1006
+ ai","anthropic"]},On={"ai-sdk":"Vercel AI SDK",mastra:"Mastra",langchain:"LangChain.js","anthropic-sdk":"Anthropic TypeScript SDK",sdk:"the SDK directly (no framework)"},zi={"ai-sdk":"@bivelio/savings\
1007
+ -layer/ai-sdk",mastra:"@bivelio/savings-layer/mastra",langchain:"@bivelio/savings-layer/langchain","anthropic-sdk":"@bivelio/savings-layer/anthropic-sdk",sdk:"@bivelio/savings-layer"},Fh={openai:"gpt-\
1008
+ 4o-mini",anthropic:"claude-haiku-4-5"},xl="What is 2 + 2 * 3?",Pn=["licenseKey: process.env.BIVELIO_LICENSE_KEY,",'licenseServerUrl: "https://savings.bivelio.com",',"serviceAccountKey: process.env.BIV\
1009
+ ELIO_SERVICE_KEY,"],zh=["onReport: (report) => {"," seen.calls += 1;"," seen.avoidedLlm = report.calls.avoidedLlm;"," seen.basis = report.cost.basis;","},"];function Sl(e,t){switch(e){case "ai-sdk":
995
1010
  return ["ai",t==="openai"?"@ai-sdk/openai":"@ai-sdk/anthropic"];case "mastra":return ["@mastra/core"];case "langchain":return ["langchain","@langchain/core",t==="openai"?"@langchain/openai":"@langchain/ant\
996
- hropic"];case "anthropic-sdk":return ["@anthropic-ai/sdk"];case "sdk":return []}}function Ke(e,t){let n=" ".repeat(t);return e.map(r=>r===""?"":n+r)}function at(e){return e?"export ":""}function Qt(e,t){let n=Dh[t];
1011
+ hropic"];case "anthropic-sdk":return ["@anthropic-ai/sdk"];case "sdk":return []}}function Je(e,t){let n=" ".repeat(t);return e.map(r=>r===""?"":n+r)}function lt(e){return e?"export ":""}function sn(e,t){let n=Fh[t];
997
1012
  switch(e){case "ai-sdk":{let r=t==="openai"?"openai":"anthropic";return {imports:['import { wrapLanguageModel } from "ai";',`import { ${r} } from "@ai-sdk/${r}";`,'import { savingsMiddleware } from "@bi\
998
- velio/savings-layer/ai-sdk";'],adaptador:"savings",construir:(o,i)=>[`${at(i)}const savings = savingsMiddleware({`,...Ke([...Tn,...o],2),"});",...i?["","// Pass `model` wherever you pass a model today\
999
- (generateText, streamText\u2026).","// `savings` goes LAST in the middleware list: nothing between it and the model."]:[],`${at(i)}const model = wrapLanguageModel({ model: ${r}("${n}"), middleware: s\
1013
+ velio/savings-layer/ai-sdk";'],adaptador:"savings",construir:(o,i)=>[`${lt(i)}const savings = savingsMiddleware({`,...Je([...Pn,...o],2),"});",...i?["","// Pass `model` wherever you pass a model today\
1014
+ (generateText, streamText\u2026).","// `savings` goes LAST in the middleware list: nothing between it and the model."]:[],`${lt(i)}const model = wrapLanguageModel({ model: ${r}("${n}"), middleware: s\
1000
1015
  avings });`],exporta:["model"],importsDeUso:['import { generateText } from "ai";','import { getSavingsReport } from "@bivelio/savings-layer/ai-sdk";'],llamar:o=>[`const result = await generateText({ m\
1001
1016
  odel, ${o==="prompt"?"prompt":`prompt: ${o}`} });`,"const text = result.text;","const basis = getSavingsReport(result)?.cost.basis;"],daBasis:true,importsDeComprobacion:['import { generateText } from "a\
1002
1017
  i";'],preguntar:o=>[`const { text } = await generateText({ model, prompt: ${o} });`]}}case "mastra":return {imports:['import { Agent } from "@mastra/core/agent";','import { savingsProcessor } from "@biv\
1003
- elio/savings-layer/mastra";'],adaptador:"bivelio",construir:(r,o)=>[`${at(o)}const bivelio = savingsProcessor({`,...Ke([...Tn,...r],2),"});",...o?["","// Add `bivelio` LAST to the inputProcessors of e\
1004
- ach agent you already have;","// this one shows where. Its reports go to `onReport` if you pass one above."]:[],`${at(o)}const agent = new Agent({`,' id: "assistant",',' name: "Assistant",',' instr\
1018
+ elio/savings-layer/mastra";'],adaptador:"bivelio",construir:(r,o)=>[`${lt(o)}const bivelio = savingsProcessor({`,...Je([...Pn,...r],2),"});",...o?["","// Add `bivelio` LAST to the inputProcessors of e\
1019
+ ach agent you already have;","// this one shows where. Its reports go to `onReport` if you pass one above."]:[],`${lt(o)}const agent = new Agent({`,' id: "assistant",',' name: "Assistant",',' instr\
1005
1020
  uctions: "Answer briefly.",',` model: "${t}/${n}",`," inputProcessors: [bivelio],","});"],exporta:["agent"],importsDeUso:[],llamar:r=>[`const result = await agent.generate(${r});`,"const text = resu\
1006
1021
  lt.text;"],daBasis:false,importsDeComprobacion:[],preguntar:r=>[`const { text } = await agent.generate(${r});`]};case "langchain":return {imports:['import { createAgent } from "langchain";','import { savin\
1007
- gsAgentMiddleware } from "@bivelio/savings-layer/langchain";'],adaptador:"savings",construir:(r,o)=>[`${at(o)}const savings = savingsAgentMiddleware({`,...Ke([...Tn,...r],2),"});",...o?["","// Add `sa\
1008
- vings` LAST to the middleware of each agent you already have; this one shows where."]:[],`${at(o)}const agent = createAgent({ model: "${t}:${n}", tools: [], middleware: [savings] });`],exporta:["agent"],
1022
+ gsAgentMiddleware } from "@bivelio/savings-layer/langchain";'],adaptador:"savings",construir:(r,o)=>[`${lt(o)}const savings = savingsAgentMiddleware({`,...Je([...Pn,...r],2),"});",...o?["","// Add `sa\
1023
+ vings` LAST to the middleware of each agent you already have; this one shows where."]:[],`${lt(o)}const agent = createAgent({ model: "${t}:${n}", tools: [], middleware: [savings] });`],exporta:["agent"],
1009
1024
  importsDeUso:['import { getSavingsReportFromMessage } from "@bivelio/savings-layer/langchain";'],llamar:r=>[`const state = await agent.invoke({ messages: [{ role: "user", content: ${r} }] });`,"const \
1010
1025
  last = state.messages.at(-1);",'const text = last?.text ?? "";',"const basis = getSavingsReportFromMessage(last)?.cost.basis;"],daBasis:true,importsDeComprobacion:[],preguntar:r=>[`const state = await a\
1011
1026
  gent.invoke({ messages: [{ role: "user", content: ${r} }] });`,'const text = state.messages.at(-1)?.text ?? "";']};case "anthropic-sdk":{let r=i=>`const message = await client.messages.create({ model: \
1012
1027
  "${n}", max_tokens: 1024, messages: [{ role: "user", content: ${i} }] });`,o='const text = message.content.map((block) => (block.type === "text" ? block.text : "")).join("");';return {imports:['import \
1013
- Anthropic from "@anthropic-ai/sdk";','import { anthropicSavings } from "@bivelio/savings-layer/anthropic-sdk";'],adaptador:"claudeSavings",construir:(i,s)=>[`${at(s)}const claudeSavings = anthropicSav\
1014
- ings({`,...Ke([...Tn,...i],2),"});",...s?["","// Use `client` for messages.create(); `claudeSavings.middleware` goes LAST in the list."]:[],`${at(s)}const client = new Anthropic({ middleware: [claudeS\
1028
+ Anthropic from "@anthropic-ai/sdk";','import { anthropicSavings } from "@bivelio/savings-layer/anthropic-sdk";'],adaptador:"claudeSavings",construir:(i,s)=>[`${lt(s)}const claudeSavings = anthropicSav\
1029
+ ings({`,...Je([...Pn,...i],2),"});",...s?["","// Use `client` for messages.create(); `claudeSavings.middleware` goes LAST in the list."]:[],`${lt(s)}const client = new Anthropic({ middleware: [claudeS\
1015
1030
  avings.middleware] });`],exporta:["client","claudeSavings"],importsDeUso:[],llamar:i=>[r(i),o,"const basis = claudeSavings.reportFor(message)?.cost.basis;"],daBasis:true,importsDeComprobacion:[],preguntar:i=>[
1016
1031
  r(i),o]}}case "sdk":{let r=`${t}/${n}`,o=t==="openai"?'provider: new OpenAICompatibleProvider({ baseUrl: "https://api.openai.com/v1", apiKey: process.env.OPENAI_API_KEY }),':"provider: new AnthropicPro\
1017
1032
  vider({ apiKey: process.env.ANTHROPIC_API_KEY }),",i=t==="openai"?"OpenAICompatibleProvider":"AnthropicProvider";return {imports:[t==="openai"?`import { createSavingsLayer, ${i} } from "@bivelio/saving\
1018
1033
  s-layer";`:`import { ${i}, createSavingsLayer } from "@bivelio/savings-layer";`],adaptador:"layer",construir:(a,c)=>[...c?["// Your provider. LLM traffic goes straight to it: the layer is not a proxy."]:
1019
- [],`${at(c)}const layer = createSavingsLayer({`,...Ke([o,...Tn,...a],2),"});"],exporta:["layer"],importsDeUso:[],llamar:a=>[`const { text, report } = await layer.generate({ model: "${r}", messages: [{\
1034
+ [],`${lt(c)}const layer = createSavingsLayer({`,...Je([o,...Pn,...a],2),"});"],exporta:["layer"],importsDeUso:[],llamar:a=>[`const { text, report } = await layer.generate({ model: "${r}", messages: [{\
1020
1035
  role: "user", content: ${a} }] });`,"const basis = report.cost.basis;"],daBasis:true,importsDeComprobacion:[],preguntar:a=>[`const { text, report } = await layer.generate({ model: "${r}", messages: [{ \
1021
- role: "user", content: ${a} }] });`]}}}}function Mi(e,t){let n=Qt(e,t);return ["// BiVelio Savings Layer: created once, when this module loads, and reused by every","// request. The exact cache lives i\
1036
+ role: "user", content: ${a} }] });`]}}}}function Vi(e,t){let n=sn(e,t);return ["// BiVelio Savings Layer: created once, when this module loads, and reused by every","// request. The exact cache lives i\
1022
1037
  n this instance, so do not create one per request.",...n.imports,"",...n.construir([],true),""].join(`
1023
- `)}var fl=["// BiVelio Savings Layer: a free wiring check, generated by `bvsala init`.","// It asks a question the layer answers on this machine (2 + 2 * 3), so with the","// layer in place the model \
1038
+ `)}var El=["// BiVelio Savings Layer: a free wiring check, generated by `bvsala init`.","// It asks a question the layer answers on this machine (2 + 2 * 3), so with the","// layer in place the model \
1024
1039
  is not called and your provider bills nothing for it.","// The saving is `estimated`, and estimated savings are never billed. It needs","// BIVELIO_LICENSE_KEY: the layer is fail-closed. Delete this f\
1025
- ile once it says ok."];function ml(e){return e==="sdk"?['const ok = text.trim() === "8" && report.calls.avoidedLlm === 1;',"const line = ok",' ? `ok: the layer answered "8" on this machine without ca\
1040
+ ile once it says ok."];function _l(e){return e==="sdk"?['const ok = text.trim() === "8" && report.calls.avoidedLlm === 1;',"const line = ok",' ? `ok: the layer answered "8" on this machine without ca\
1026
1041
  lling the model (basis: ${report.cost.basis}).`'," : `not ok: the layer did not answer it (got ${JSON.stringify(text)}). Send this output to support@bivelio.com.`;"]:['const ok = text.trim() === "8" \
1027
1042
  && seen.avoidedLlm === 1;',"const line = ok",' ? `ok: the layer answered "8" on this machine without calling the model (basis: ${seen.basis}).`'," : seen.calls === 0",' ? "not ok: the layer did n\
1028
1043
  ot see the call. It has to go LAST in the list, next to the model."'," : `not ok: the layer saw the call but did not answer it (got ${JSON.stringify(text)}). Send this output to support@bivelio.com\
1029
- .`;"]}function hl(e,t){let n=Qt(e,t),r=Ni([...n.importsDeComprobacion,...n.imports]),o=e==="sdk"?n.construir([],false):['const seen = { calls: 0, avoidedLlm: 0, basis: "" };',...n.construir(Oh,false)];return {
1030
- imports:r,cuerpo:o}}function Ni(e){let t=new Map,n=[];for(let r of e){let o=/^import \{ ([^}]+) \} from "([^"]+)";$/.exec(r);if(!o){n.includes(r)||n.push(r);continue}let[,i="",s=""]=o,a=t.get(s);a||(a=
1031
- new Set,t.set(s,a),n.push({modulo:s}));for(let c of i.split(", "))a.add(c);}return n.map(r=>typeof r=="string"?r:`import { ${[...t.get(r.modulo)??[]].sort().join(", ")} } from "${r.modulo}";`)}function gl(e,t){
1032
- let n=Qt(e,t),{imports:r,cuerpo:o}=hl(e,t);return [...fl,...r,"",...o,"","try {",...Ke([...n.preguntar(JSON.stringify(dl)),...ml(e),"console.log(line);","if (!ok) process.exitCode = 1;"],2),"} catch (e\
1044
+ .`;"]}function Cl(e,t){let n=sn(e,t),r=qi([...n.importsDeComprobacion,...n.imports]),o=e==="sdk"?n.construir([],false):['const seen = { calls: 0, avoidedLlm: 0, basis: "" };',...n.construir(zh,false)];return {
1045
+ imports:r,cuerpo:o}}function qi(e){let t=new Map,n=[];for(let r of e){let o=/^import \{ ([^}]+) \} from "([^"]+)";$/.exec(r);if(!o){n.includes(r)||n.push(r);continue}let[,i="",s=""]=o,a=t.get(s);a||(a=
1046
+ new Set,t.set(s,a),n.push({modulo:s}));for(let c of i.split(", "))a.add(c);}return n.map(r=>typeof r=="string"?r:`import { ${[...t.get(r.modulo)??[]].sort().join(", ")} } from "${r.modulo}";`)}function Tl(e,t){
1047
+ let n=sn(e,t),{imports:r,cuerpo:o}=Cl(e,t);return [...El,...r,"",...o,"","try {",...Je([...n.preguntar(JSON.stringify(xl)),..._l(e),"console.log(line);","if (!ok) process.exitCode = 1;"],2),"} catch (e\
1033
1048
  rr) {"," console.log(`not ok: ${err instanceof Error ? err.message : String(err)}`);"," process.exitCode = 1;","} finally {",` ${n.adaptador}.close();`,"}",""].join(`
1034
- `)}function bl(e,t){let n=Qt(e,t),{imports:r,cuerpo:o}=hl(e,t);return [...fl,"// It answers only in development: in production it is a 404.",...r,"","// Run on each request, never at build time.",'expo\
1035
- rt const dynamic = "force-dynamic";',"","export async function GET() {",' if (process.env.NODE_ENV === "production") {',' return new Response("Not found", { status: 404 });'," }",...Ke(o,2)," tr\
1036
- y {",...Ke([...n.preguntar(JSON.stringify(dl)),...ml(e),"return Response.json({ ok, message: line }, { status: ok ? 200 : 500 });"],4)," } catch (err) {"," return Response.json({ ok: false, messag\
1049
+ `)}function Rl(e,t){let n=sn(e,t),{imports:r,cuerpo:o}=Cl(e,t);return [...El,"// It answers only in development: in production it is a 404.",...r,"","// Run on each request, never at build time.",'expo\
1050
+ rt const dynamic = "force-dynamic";',"","export async function GET() {",' if (process.env.NODE_ENV === "production") {',' return new Response("Not found", { status: 404 });'," }",...Je(o,2)," tr\
1051
+ y {",...Je([...n.preguntar(JSON.stringify(xl)),..._l(e),"return Response.json({ ok, message: line }, { status: ok ? 200 : 500 });"],4)," } catch (err) {"," return Response.json({ ok: false, messag\
1037
1052
  e: `not ok: ${err instanceof Error ? err.message : String(err)}` }, { status: 500 });"," } finally {",` ${n.adaptador}.close();`," }","}",""].join(`
1038
- `)}function vl(e,t,n){let r=Qt(e,t),o=r.daBasis?"{ text, basis }":"{ text }";return [...Ni(r.importsDeUso),`import { ${r.exporta.slice().sort().join(", ")} } from "${n.importeDelCableado}";`,"",`export\
1039
- async function POST(req${n.ts?": Request":""}) {`,` const { prompt } = ${n.ts?"(await req.json()) as { prompt: string }":"await req.json()"};`,...Ke(r.llamar("prompt"),2),` return Response.json(${o}\
1053
+ `)}function Al(e,t,n){let r=sn(e,t),o=r.daBasis?"{ text, basis }":"{ text }";return [...qi(r.importsDeUso),`import { ${r.exporta.slice().sort().join(", ")} } from "${n.importeDelCableado}";`,"",`export\
1054
+ async function POST(req${n.ts?": Request":""}) {`,` const { prompt } = ${n.ts?"(await req.json()) as { prompt: string }":"await req.json()"};`,...Je(r.llamar("prompt"),2),` return Response.json(${o}\
1040
1055
  );`,"}",""].join(`
1041
- `)}function yl(e,t){let n=Qt(e,t),r=n.daBasis?"{ text, basis }":"{ text }";return ['import express from "express";',...Ni([...n.imports,...n.importsDeUso]),"","// Created once, at startup, not inside t\
1042
- he handler: the exact cache lives in this instance.",...n.construir([],false),"","const app = express();","app.use(express.json());","",'app.post("/api/chat", async (req, res, next) => {'," try {",...Ke(
1056
+ `)}function Il(e,t){let n=sn(e,t),r=n.daBasis?"{ text, basis }":"{ text }";return ['import express from "express";',...qi([...n.imports,...n.importsDeUso]),"","// Created once, at startup, not inside t\
1057
+ he handler: the exact cache lives in this instance.",...n.construir([],false),"","const app = express();","app.use(express.json());","",'app.post("/api/chat", async (req, res, next) => {'," try {",...Je(
1043
1058
  n.llamar('String(req.body?.prompt ?? "")'),4),` res.json(${r});`," } catch (err) {"," next(err);"," }","});","","app.listen(Number(process.env.PORT ?? 3000));",""].join(`
1044
- `)}var $r="usage: bvsala init [--write [--yes]] [--json] [--stack ai-sdk|mastra|langchain|anthropic-sdk|sdk] [--provider openai|anthropic] [--cwd <dir>]";function El(e,t){let n={cwd:t,escribir:false,si:false,json:false};
1059
+ `)}var Ur="usage: bvsala init [--write [--yes]] [--json] [--stack ai-sdk|mastra|langchain|anthropic-sdk|sdk] [--provider openai|anthropic] [--cwd <dir>]";function $l(e,t){let n={cwd:t,escribir:false,si:false,json:false};
1045
1060
  for(let r=0;r<e.length;r++){let o=e[r],i=()=>{let s=e[r+1];if(!(s===void 0||s.startsWith("-")))return r++,s};if(o==="--write")n.escribir=true;else if(o==="--yes"||o==="-y")n.si=true;else if(o==="--json")n.
1046
- json=true;else if(o==="--stack"){let s=i();if(!s||!Li.includes(s))return {ok:false,mensaje:`--stack needs one of: ${Li.join(", ")}.
1047
- ${$r}`};n.capa=s;}else if(o==="--provider"){let s=i();if(s!=="openai"&&s!=="anthropic")return {ok:false,mensaje:`--provider needs openai or anthropic.
1048
- ${$r}`};n.proveedor=s;}else if(o==="--cwd"){let s=i();if(!s)return {ok:false,mensaje:`--cwd needs a directory.
1049
- ${$r}`};n.cwd=s.startsWith("/")||/^[A-Za-z]:[\\/]/.test(s)?s:join(t,s);}else return {ok:false,mensaje:`unknown option: ${o}
1050
- ${$r}`}}return n.json&&n.escribir?{ok:false,mensaje:"--json prints the plan and --write applies it: use one of them."}:n.si&&!n.escribir?{ok:false,mensaje:"--yes only confirms --write: add --write, or drop \
1051
- --yes."}:n.capa&&n.proveedor&&!Rn[n.capa].includes(n.proveedor)?{ok:false,mensaje:`--stack ${n.capa} only works with --provider ${Rn[n.capa].join(" or ")}.`}:{ok:true,valor:n}}var Lh=[["pnpm-lock.yaml","pn\
1052
- pm"],["yarn.lock","yarn"],["bun.lock","bun"],["bun.lockb","bun"],["package-lock.json","npm"]];function $h(e,t,n){if(typeof e.packageManager=="string"){let r=e.packageManager.split("@")[0];if(r==="pnpm"||
1053
- r==="yarn"||r==="bun"||r==="npm")return r}for(let r=t,o=0;o<20;o++){for(let[s,a]of Lh)if(n.existe(join(r,s)))return a;let i=dirname(r);if(i===r)break;r=i;}return "npm"}function Mh(e){let t={};for(let n of [e.devDependencies,
1054
- e.dependencies])if(n&&typeof n=="object")for(let[r,o]of Object.entries(n))typeof o=="string"&&(t[r]=o);return t}function Nh(e,t,n,r){let o=r.leer(join(n,"node_modules",...e.split("/"),"package.json"));if(o)
1061
+ json=true;else if(o==="--stack"){let s=i();if(!s||!Fi.includes(s))return {ok:false,mensaje:`--stack needs one of: ${Fi.join(", ")}.
1062
+ ${Ur}`};n.capa=s;}else if(o==="--provider"){let s=i();if(s!=="openai"&&s!=="anthropic")return {ok:false,mensaje:`--provider needs openai or anthropic.
1063
+ ${Ur}`};n.proveedor=s;}else if(o==="--cwd"){let s=i();if(!s)return {ok:false,mensaje:`--cwd needs a directory.
1064
+ ${Ur}`};n.cwd=s.startsWith("/")||/^[A-Za-z]:[\\/]/.test(s)?s:join(t,s);}else return {ok:false,mensaje:`unknown option: ${o}
1065
+ ${Ur}`}}return n.json&&n.escribir?{ok:false,mensaje:"--json prints the plan and --write applies it: use one of them."}:n.si&&!n.escribir?{ok:false,mensaje:"--yes only confirms --write: add --write, or drop \
1066
+ --yes."}:n.capa&&n.proveedor&&!Dn[n.capa].includes(n.proveedor)?{ok:false,mensaje:`--stack ${n.capa} only works with --provider ${Dn[n.capa].join(" or ")}.`}:{ok:true,valor:n}}var Vh=[["pnpm-lock.yaml","pn\
1067
+ pm"],["yarn.lock","yarn"],["bun.lock","bun"],["bun.lockb","bun"],["package-lock.json","npm"]];function qh(e,t,n){if(typeof e.packageManager=="string"){let r=e.packageManager.split("@")[0];if(r==="pnpm"||
1068
+ r==="yarn"||r==="bun"||r==="npm")return r}for(let r=t,o=0;o<20;o++){for(let[s,a]of Vh)if(n.existe(join(r,s)))return a;let i=dirname(r);if(i===r)break;r=i;}return "npm"}function Hh(e){let t={};for(let n of [e.devDependencies,
1069
+ e.dependencies])if(n&&typeof n=="object")for(let[r,o]of Object.entries(n))typeof o=="string"&&(t[r]=o);return t}function Gh(e,t,n,r){let o=r.leer(join(n,"node_modules",...e.split("/"),"package.json"));if(o)
1055
1070
  try{let s=JSON.parse(o).version;if(typeof s=="string")return s}catch{}let i=/(\d+)(?:\.(\d+))?(?:\.(\d+))?/.exec(t.replace(/^npm:[^@]+@/,""));if(!(!i||/^(workspace|catalog|link|file|git|github):/.test(
1056
- t)))return `${i[1]}.${i[2]??0}.${i[3]??0}`}function Ui(e){let[t=0,n=0,r=0]=e.split(/[.+-]/).map(o=>Number.parseInt(o,10)||0);return [t,n,r]}function Fi(e,t){let n=Ui(e),r=Ui(t);for(let o=0;o<3;o++)if(n[o]!==
1057
- r[o])return n[o]>r[o];return true}var _l=[{paquete:"ai",capa:"ai-sdk",desde:"6.0.0",hasta:"8.0.0",texto:"ai 6 or 7"},{paquete:"@mastra/core",capa:"mastra",desde:"1.68.0",hasta:"2.0.0",texto:"@mastra/core\
1071
+ t)))return `${i[1]}.${i[2]??0}.${i[3]??0}`}function Wi(e){let[t=0,n=0,r=0]=e.split(/[.+-]/).map(o=>Number.parseInt(o,10)||0);return [t,n,r]}function Ki(e,t){let n=Wi(e),r=Wi(t);for(let o=0;o<3;o++)if(n[o]!==
1072
+ r[o])return n[o]>r[o];return true}var Ml=[{paquete:"ai",capa:"ai-sdk",desde:"6.0.0",hasta:"8.0.0",texto:"ai 6 or 7"},{paquete:"@mastra/core",capa:"mastra",desde:"1.68.0",hasta:"2.0.0",texto:"@mastra/core\
1058
1073
  \u2265 1.68 < 2"},{paquete:"langchain",capa:"langchain",desde:"1.1.0",hasta:"2.0.0",texto:"langchain \u2265 1.1 < 2"},{paquete:"@langchain/core",capa:"langchain",desde:"1.1.0",hasta:"2.0.0",texto:"@l\
1059
- angchain/core \u2265 1.1 < 2"},{paquete:"@anthropic-ai/sdk",capa:"anthropic-sdk",desde:"0.103.0",hasta:"1.0.0",texto:"@anthropic-ai/sdk \u2265 0.103 < 1"}],Cl=[["@mastra/core","mastra"],["langchain","\
1060
- langchain"],["ai","ai-sdk"],["@anthropic-ai/sdk","anthropic-sdk"],["openai","sdk"]];function Tl(e,t){let n=t.leer(join(e,"package.json"));if(n===void 0){let u=["pyproject.toml","requirements.txt","setup\
1074
+ angchain/core \u2265 1.1 < 2"},{paquete:"@anthropic-ai/sdk",capa:"anthropic-sdk",desde:"0.103.0",hasta:"1.0.0",texto:"@anthropic-ai/sdk \u2265 0.103 < 1"}],Nl=[["@mastra/core","mastra"],["langchain","\
1075
+ langchain"],["ai","ai-sdk"],["@anthropic-ai/sdk","anthropic-sdk"],["openai","sdk"]];function jl(e,t){let n=t.leer(join(e,"package.json"));if(n===void 0){let u=["pyproject.toml","requirements.txt","setup\
1061
1076
  .py","Pipfile"].find(f=>t.existe(join(e,f)));return u?{ok:false,mensaje:`no package.json in ${e}, and ${u} says this is Python. The SDK is TypeScript; for Python (or any language), run the local gateway an\
1062
1077
  d point your client's base URL at it: \`bvsala gateway --upstream openai --port 8403\`, then OpenAI(base_url="http://127.0.0.1:8403/v1"). It measures; the saving levers are TypeScript. \`bvsala doctor\` p\
1063
1078
  rints the recipe for each SDK.`}:{ok:false,mensaje:`no package.json in ${e}. Run this from your project's root, or pass --cwd <dir>.`}}let r;try{r=JSON.parse(n);}catch(u){return {ok:false,mensaje:`${join(e,"pac\
1064
1079
  kage.json")} is not valid JSON (${u instanceof Error?u.message:String(u)}). Fix it and run init again.`}}if(!r||typeof r!="object"||Array.isArray(r))return {ok:false,mensaje:`${join(e,"package.json")} is no\
1065
- t a JSON object. Fix it and run init again.`};let o=Mh(r),i={};for(let[u,f]of Object.entries(o))i[u]=Nh(u,f,e,t);let s=["app","src/app"].find(u=>t.existe(join(e,...u.split("/")))),a="next"in i?"next":"e\
1066
- xpress"in i?"express":"node",c=Cl.filter(([u])=>u in i).map(([,u])=>u),l={dir:e,gestor:$h(r,e,t),ts:"typescript"in i||t.existe(join(e,"tsconfig.json")),esm:r.type==="module",anfitrion:a,src:t.existe(join(
1080
+ t a JSON object. Fix it and run init again.`};let o=Hh(r),i={};for(let[u,f]of Object.entries(o))i[u]=Gh(u,f,e,t);let s=["app","src/app"].find(u=>t.existe(join(e,...u.split("/")))),a="next"in i?"next":"e\
1081
+ xpress"in i?"express":"node",c=Nl.filter(([u])=>u in i).map(([,u])=>u),l={dir:e,gestor:qh(r,e,t),ts:"typescript"in i||t.existe(join(e,"tsconfig.json")),esm:r.type==="module",anfitrion:a,src:t.existe(join(
1067
1082
  e,"src")),capas:c,deps:i,monorepo:r.workspaces!==void 0||t.existe(join(e,"pnpm-workspace.yaml")),ficherosEnv:[".env",".env.local"].filter(u=>t.existe(join(e,u))),scriptDev:typeof r.scripts?.dev=="string"},
1068
- p=a==="node"?void 0:i[a];return p&&(l.versionDelAnfitrion=p),a==="next"&&s&&(l.appDir=s),"@bivelio/savings-layer"in o&&(l.yaInstalado=i["@bivelio/savings-layer"]??o["@bivelio/savings-layer"]),{ok:true,valor:l}}
1069
- var wl=(e,t)=>t.some(n=>n in e.deps),jh=["openai","@ai-sdk/openai","@langchain/openai"],Bh=["@anthropic-ai/sdk","@ai-sdk/anthropic","@langchain/anthropic"];function Uh(e,t){if(e==="anthropic-sdk")return "\
1083
+ d=a==="node"?void 0:i[a];return d&&(l.versionDelAnfitrion=d),a==="next"&&s&&(l.appDir=s),"@bivelio/savings-layer"in o&&(l.yaInstalado=i["@bivelio/savings-layer"]??o["@bivelio/savings-layer"]),{ok:true,valor:l}}
1084
+ var Dl=(e,t)=>t.some(n=>n in e.deps),Wh=["openai","@ai-sdk/openai","@langchain/openai"],Kh=["@anthropic-ai/sdk","@ai-sdk/anthropic","@langchain/anthropic"];function Jh(e,t){if(e==="anthropic-sdk")return "\
1070
1085
  anthropic";if(e==="ai-sdk"){if("@ai-sdk/openai"in t.deps)return "openai";if("@ai-sdk/anthropic"in t.deps)return "anthropic"}if(e==="langchain"){if("@langchain/openai"in t.deps)return "openai";if("@langch\
1071
- ain/anthropic"in t.deps)return "anthropic"}return wl(t,Bh)&&!wl(t,jh)?"anthropic":"openai"}function xl(e,t){for(let n of _l){if(n.capa!==e)continue;let r=t.deps[n.paquete];if(r!==void 0&&(!Fi(r,n.desde)||
1072
- Fi(r,n.hasta)))return `${n.paquete} ${r} is outside what the adapter supports (${n.texto})`}}var ji={npm:"npm i",pnpm:"pnpm add",yarn:"yarn add",bun:"bun add"};function Fh(e){let t=e.ficherosEnv[0];return t?
1073
- `node --env-file=${t} bivelio-check.mjs`:"node bivelio-check.mjs"}function Rl(e,t,n){let[r=0]=Ui(n.node);if(r<20)return {ok:false,mensaje:`Node ${n.node} is too old: @bivelio/savings-layer needs Node \u2265 20\
1074
- . Upgrade Node and run init again.`};let o=[],i=t.capa,s=[];if(i){let m=xl(i,e);m&&o.push(`${m}: the snippets below will not work until you upgrade it.`);}else for(let m of e.capas){let b=xl(m,e);if(!b){
1086
+ ain/anthropic"in t.deps)return "anthropic"}return Dl(t,Kh)&&!Dl(t,Wh)?"anthropic":"openai"}function Ol(e,t){for(let n of Ml){if(n.capa!==e)continue;let r=t.deps[n.paquete];if(r!==void 0&&(!Ki(r,n.desde)||
1087
+ Ki(r,n.hasta)))return `${n.paquete} ${r} is outside what the adapter supports (${n.texto})`}}var Hi={npm:"npm i",pnpm:"pnpm add",yarn:"yarn add",bun:"bun add"};function Yh(e){let t=e.ficherosEnv[0];return t?
1088
+ `node --env-file=${t} bivelio-check.mjs`:"node bivelio-check.mjs"}function Bl(e,t,n){let[r=0]=Wi(n.node);if(r<20)return {ok:false,mensaje:`Node ${n.node} is too old: @bivelio/savings-layer needs Node \u2265 20\
1089
+ . Upgrade Node and run init again.`};let o=[],i=t.capa,s=[];if(i){let m=Ol(i,e);m&&o.push(`${m}: the snippets below will not work until you upgrade it.`);}else for(let m of e.capas){let b=Ol(m,e);if(!b){
1075
1090
  i=m;break}s.push({capa:m,motivo:b});}i||(i="sdk",e.capas.length===0&&o.push(e.monorepo?"No LLM library in this package.json, and it looks like a monorepo root: run init inside the package that calls th\
1076
1091
  e LLM (--cwd <path>).":"No LLM library found (ai, @mastra/core, langchain, @anthropic-ai/sdk or openai): showing the SDK on its own. If you call the LLM from another language, see `bvsala doctor`."));
1077
- for(let m of s){let b=_l.find(k=>k.capa===m.capa&&m.motivo.startsWith(`${k.paquete} `))?.paquete??"";o.push(`${m.motivo}: showing ${An[i]} instead. To use the ${An[m.capa]} adapter, upgrade it: ${ji[e.
1078
- gestor]} ${b}@latest`);}let a=t.proveedor??Uh(i,e);if(!Rn[i].includes(a))return {ok:false,mensaje:`--stack ${i} only works with --provider ${Rn[i].join(" or ")}.`};let c=[];e.yaInstalado||c.push("@bivelio/\
1079
- savings-layer");for(let m of pl(i,a))m in e.deps||c.push(m);a==="openai"&&!("gpt-tokenizer"in e.deps)&&c.push("gpt-tokenizer");let l=e.deps["@bivelio/savings-layer"];e.yaInstalado&&i!=="sdk"&&l&&!Fi(l,
1080
- "0.4.25")&&o.push(`@bivelio/savings-layer ${l} has no framework adapters (they arrived in 0.4.25): ${ji[e.gestor]} @bivelio/savings-layer@latest`),r<22&&(i==="mastra"||i==="ai-sdk"&&(e.deps.ai??"7").startsWith(
1092
+ for(let m of s){let b=Ml.find(y=>y.capa===m.capa&&m.motivo.startsWith(`${y.paquete} `))?.paquete??"";o.push(`${m.motivo}: showing ${On[i]} instead. To use the ${On[m.capa]} adapter, upgrade it: ${Hi[e.
1093
+ gestor]} ${b}@latest`);}let a=t.proveedor??Jh(i,e);if(!Dn[i].includes(a))return {ok:false,mensaje:`--stack ${i} only works with --provider ${Dn[i].join(" or ")}.`};let c=[];e.yaInstalado||c.push("@bivelio/\
1094
+ savings-layer");for(let m of Sl(i,a))m in e.deps||c.push(m);a==="openai"&&!("gpt-tokenizer"in e.deps)&&c.push("gpt-tokenizer");let l=e.deps["@bivelio/savings-layer"];e.yaInstalado&&i!=="sdk"&&l&&!Ki(l,
1095
+ "0.4.25")&&o.push(`@bivelio/savings-layer ${l} has no framework adapters (they arrived in 0.4.25): ${Hi[e.gestor]} @bivelio/savings-layer@latest`),r<22&&(i==="mastra"||i==="ai-sdk"&&(e.deps.ai??"7").startsWith(
1081
1096
  "7"))&&o.push(`Node ${n.node}: ${i==="mastra"?"@mastra/core":"ai 7"} declares Node \u2265 22 in its own engines.`),!e.ts&&!e.esm&&e.anfitrion!=="next"&&o.push('Your package.json has no "type": "module\
1082
- " and the package is ESM-only. The check is a .mjs file and runs as is; from your own CommonJS files, load it with `await import(\u2026)`, or with require() on Node \u2265 22.');let p=[{nombre:"BIVELI\
1097
+ " and the package is ESM-only. The check is a .mjs file and runs as is; from your own CommonJS files, load it with `await import(\u2026)`, or with require() on Node \u2265 22.');let d=[{nombre:"BIVELI\
1083
1098
  O_LICENSE_KEY",puesta:n.env("BIVELIO_LICENSE_KEY"),para:"required: the layer is fail-closed"},{nombre:"BIVELIO_SERVICE_KEY",puesta:n.env("BIVELIO_SERVICE_KEY"),para:"seat metering and license auto-ren\
1084
- ewal"}];if(i==="anthropic-sdk")p.push({nombre:"ANTHROPIC_API_KEY",puesta:n.env("ANTHROPIC_API_KEY")||n.env("ANTHROPIC_AUTH_TOKEN"),para:"needed even by the free check: the Anthropic SDK builds no requ\
1099
+ ewal"}];if(i==="anthropic-sdk")d.push({nombre:"ANTHROPIC_API_KEY",puesta:n.env("ANTHROPIC_API_KEY")||n.env("ANTHROPIC_AUTH_TOKEN"),para:"needed even by the free check: the Anthropic SDK builds no requ\
1085
1100
  est without credentials"});else {let m=a==="openai"?"OPENAI_API_KEY":"ANTHROPIC_API_KEY",b=i==="mastra"?"your provider key; the free check works without it, but Mastra logs a warning with a stack trace":
1086
- "your provider key; the free check does not need it";p.push({nombre:m,puesta:n.env(m),para:b});}let u=e.anfitrion==="next"?"Put them in .env.local (Next.js loads it) or in your host's environment setti\
1101
+ "your provider key; the free check does not need it";d.push({nombre:m,puesta:n.env(m),para:b});}let u=e.anfitrion==="next"?"Put them in .env.local (Next.js loads it) or in your host's environment setti\
1087
1102
  ngs.":e.ficherosEnv.length>0?`Export them, or keep them in ${e.ficherosEnv[0]} and pass it to node with --env-file (Node \u2265 20.6).`:"Export them in your shell, or keep them in a .env file and pass\
1088
- it to node with --env-file (Node \u2265 20.6).",f={deteccion:e,capa:i,proveedor:a,alternativas:e.capas.filter(m=>m!==i),instalar:c,claves:p,dondeVanLasClaves:u,ficheros:[],usos:[],comoComprobar:[],avisos:o};
1089
- return c.length>0&&(f.comandoDeInstalacion=`${ji[e.gestor]} ${c.join(" ")}`),{ok:true,valor:f}}function Al(e,t){let n=e.deteccion,{capa:r,proveedor:o}=e,i=n.ts?"ts":n.esm||n.anfitrion==="next"?"js":"mjs",
1090
- s=f=>t.existe(join(n.dir,...f.split("/"))),a=[],c=[],l=[],p=n.anfitrion==="next"?`${n.appDir?.startsWith("src/")?"src/":""}lib/savings.${i}`:`${n.src?"src/":""}savings.${i}`;if(n.anfitrion==="next"&&n.appDir){
1091
- a.push({ruta:p,proposito:"wiring",contenido:Mi(r,o),existe:s(p)});let f=`${n.appDir}/api/chat/route.${i}`,m=posix.relative(posix.dirname(f),p.replace(/\.[^.]+$/,""));c.push({titulo:`Use it in a route handle\
1092
- r (example: ${f})`,ruta:f,contenido:vl(r,o,{ts:n.ts,importeDelCableado:m.startsWith(".")?m:`./${m}`})});let b=`${n.appDir}/api/bivelio-check/route.${i}`;a.push({ruta:b,proposito:"check",contenido:bl(r,
1093
- o),existe:s(b)});let k=n.scriptDev?n.gestor==="npm"?"npm run dev":`${n.gestor} dev`:"next dev";l.push(`Start your dev server (${k}) and open http://localhost:3000/api/bivelio-check (or your dev port).`,
1103
+ it to node with --env-file (Node \u2265 20.6).",f={deteccion:e,capa:i,proveedor:a,alternativas:e.capas.filter(m=>m!==i),instalar:c,claves:d,dondeVanLasClaves:u,ficheros:[],usos:[],comoComprobar:[],avisos:o};
1104
+ return c.length>0&&(f.comandoDeInstalacion=`${Hi[e.gestor]} ${c.join(" ")}`),{ok:true,valor:f}}function Ul(e,t){let n=e.deteccion,{capa:r,proveedor:o}=e,i=n.ts?"ts":n.esm||n.anfitrion==="next"?"js":"mjs",
1105
+ s=f=>t.existe(join(n.dir,...f.split("/"))),a=[],c=[],l=[],d=n.anfitrion==="next"?`${n.appDir?.startsWith("src/")?"src/":""}lib/savings.${i}`:`${n.src?"src/":""}savings.${i}`;if(n.anfitrion==="next"&&n.appDir){
1106
+ a.push({ruta:d,proposito:"wiring",contenido:Vi(r,o),existe:s(d)});let f=`${n.appDir}/api/chat/route.${i}`,m=posix.relative(posix.dirname(f),d.replace(/\.[^.]+$/,""));c.push({titulo:`Use it in a route handle\
1107
+ r (example: ${f})`,ruta:f,contenido:Al(r,o,{ts:n.ts,importeDelCableado:m.startsWith(".")?m:`./${m}`})});let b=`${n.appDir}/api/bivelio-check/route.${i}`;a.push({ruta:b,proposito:"check",contenido:Rl(r,
1108
+ o),existe:s(b)});let y=n.scriptDev?n.gestor==="npm"?"npm run dev":`${n.gestor} dev`:"next dev";l.push(`Start your dev server (${y}) and open http://localhost:3000/api/bivelio-check (or your dev port).`,
1094
1109
  'It answers {"ok":true,\u2026} when the layer is in place, and a message that says what to fix when it is not.');}else n.anfitrion==="express"?c.push({titulo:"In your Express server: the layer is creat\
1095
- ed once at startup, then used by the route",ruta:`server.${i}`,contenido:yl(r,o)}):a.push({ruta:p,proposito:"wiring",contenido:Mi(r,o),existe:s(p)}),a.push({ruta:"bivelio-check.mjs",proposito:"check",
1096
- contenido:gl(r,o),existe:s("bivelio-check.mjs")}),l.push(`Run it: ${Fh(n)}`,'It prints "ok: \u2026" and exits 0 when the layer is in place, or "not ok: \u2026" with what to fix and exits 1.');let u=[...e.
1110
+ ed once at startup, then used by the route",ruta:`server.${i}`,contenido:Il(r,o)}):a.push({ruta:d,proposito:"wiring",contenido:Vi(r,o),existe:s(d)}),a.push({ruta:"bivelio-check.mjs",proposito:"check",
1111
+ contenido:Tl(r,o),existe:s("bivelio-check.mjs")}),l.push(`Run it: ${Yh(n)}`,'It prints "ok: \u2026" and exits 0 when the layer is in place, or "not ok: \u2026" with what to fix and exits 1.');let u=[...e.
1097
1112
  avisos];return n.anfitrion==="next"&&!n.appDir&&u.push("No app/ directory (Pages Router?): the check is a script instead of a route. The wiring works the same from an API route."),l.push("The question\
1098
1113
  (2 + 2 * 3) is answered on your machine: with the layer in place the model is not called, so your provider bills nothing for it,","and the saving is `estimated`, which is never billed. Delete the che\
1099
- ck once it says ok."),{...e,ficheros:a,usos:c,comoComprobar:l,avisos:u}}function Bi(e,t){let n="-".repeat(Math.max(8,Math.min(72,e.length+12)));return `----- ${e} -----
1114
+ ck once it says ok."),{...e,ficheros:a,usos:c,comoComprobar:l,avisos:u}}function Gi(e,t){let n="-".repeat(Math.max(8,Math.min(72,e.length+12)));return `----- ${e} -----
1100
1115
  ${t.replace(/\n$/,"")}
1101
- ${n}`}function zh(e){let t=[];return e.anfitrion==="next"?t.push(`Next.js${e.versionDelAnfitrion?` ${e.versionDelAnfitrion}`:""}${e.appDir?`, App Router in ${e.appDir}`:""}`):e.anfitrion==="express"?t.
1102
- push(`Express${e.versionDelAnfitrion?` ${e.versionDelAnfitrion}`:""}`):t.push("Node.js"),t.push(e.ts?"TypeScript":e.esm?"JavaScript (ESM)":"JavaScript (CommonJS)"),t.push(e.gestor),t.join(", ")}function Vh(e){
1103
- let t=e.deteccion,n=Cl.find(([,s])=>s===e.capa)?.[0],r=n?t.deps[n]:void 0,o=t.capas.includes(e.capa);return `${`${An[e.capa]}${o&&r&&e.capa!=="sdk"?` ${r}`:""}`}${o||e.capa==="sdk"?"":" (not installed \
1104
- yet)"} with ${e.proveedor==="openai"?"OpenAI":"Anthropic"} models \u2192 ${$i[e.capa]}`}function Il(e,t,n,r={}){let o=e.deteccion,i=[t,"",`Detected in ${o.dir}`,` app: ${zh(o)}`,` LLM calls: \
1105
- ${Vh(e)}`];if(e.alternativas.length>0&&i.push(` also found: ${e.alternativas.map(u=>`${An[u]} (${n} --stack ${u})`).join(", ")}`),o.yaInstalado){let u=o.deps["@bivelio/savings-layer"];i.push(` inst\
1116
+ ${n}`}function Zh(e){let t=[];return e.anfitrion==="next"?t.push(`Next.js${e.versionDelAnfitrion?` ${e.versionDelAnfitrion}`:""}${e.appDir?`, App Router in ${e.appDir}`:""}`):e.anfitrion==="express"?t.
1117
+ push(`Express${e.versionDelAnfitrion?` ${e.versionDelAnfitrion}`:""}`):t.push("Node.js"),t.push(e.ts?"TypeScript":e.esm?"JavaScript (ESM)":"JavaScript (CommonJS)"),t.push(e.gestor),t.join(", ")}function Xh(e){
1118
+ let t=e.deteccion,n=Nl.find(([,s])=>s===e.capa)?.[0],r=n?t.deps[n]:void 0,o=t.capas.includes(e.capa);return `${`${On[e.capa]}${o&&r&&e.capa!=="sdk"?` ${r}`:""}`}${o||e.capa==="sdk"?"":" (not installed \
1119
+ yet)"} with ${e.proveedor==="openai"?"OpenAI":"Anthropic"} models \u2192 ${zi[e.capa]}`}function Fl(e,t,n,r={}){let o=e.deteccion,i=[t,"",`Detected in ${o.dir}`,` app: ${Zh(o)}`,` LLM calls: \
1120
+ ${Xh(e)}`];if(e.alternativas.length>0&&i.push(` also found: ${e.alternativas.map(u=>`${On[u]} (${n} --stack ${u})`).join(", ")}`),o.yaInstalado){let u=o.deps["@bivelio/savings-layer"];i.push(` inst\
1106
1121
  alled: @bivelio/savings-layer ${u??`(declared as "${o.yaInstalado}")`}`);}for(let u of e.avisos)i.push("",`note: ${u}`);let s=1;i.push("",`${s++} \xB7 Install`),i.push(e.comandoDeInstalacion?` ${e.comandoDeInstalacion}`:
1107
1122
  " nothing to install: every package the snippets import is already a dependency."),i.push("",`${s++} \xB7 Keys (checked by name in this shell; values are never read or shown)`);let a=Math.max(...e.claves.
1108
1123
  map(u=>u.nombre.length));for(let u of e.claves)i.push(` ${u.nombre.padEnd(a)} ${u.puesta?"set ":"not set"} ${u.para}`);i.push(" Copy the BiVelio keys from https://savings.bivelio.com/dashboard/\
1109
1124
  install. Running needs an active license:"," without one, every call fails with LicenseError and the model is not called.",` ${e.dondeVanLasClaves}`);let c=e.ficheros.find(u=>u.proposito==="wiring");
1110
- i.push("",`${s++} \xB7 Wire it`),c&&i.push(Bi(`${c.ruta} (new file${c.existe?"; it already exists, compare it":""})`,c.contenido));for(let u of e.usos)i.push(Bi(u.titulo,u.contenido));let l=e.ficheros.
1111
- find(u=>u.proposito==="check");i.push("",`${s++} \xB7 Check it, for free`),l&&i.push(Bi(`${l.ruta} (new file${l.existe?"; it already exists, compare it":""})`,l.contenido));for(let u of e.comoComprobar)
1112
- i.push(` ${u}`);let p=e.ficheros.filter(u=>!u.existe);return r.escribira||(i.push(""),p.length>0?i.push(`Nothing was written. To create ${p.length===1?"the new file":`the ${p.length} new files`} abov\
1113
- e (${p.map(u=>u.ruta).join(", ")}): ${n} --write. It asks first and never overwrites; nothing else is touched.`):i.push("Nothing was written: the files above already exist in your project.")),i.join(`\
1125
+ i.push("",`${s++} \xB7 Wire it`),c&&i.push(Gi(`${c.ruta} (new file${c.existe?"; it already exists, compare it":""})`,c.contenido));for(let u of e.usos)i.push(Gi(u.titulo,u.contenido));let l=e.ficheros.
1126
+ find(u=>u.proposito==="check");i.push("",`${s++} \xB7 Check it, for free`),l&&i.push(Gi(`${l.ruta} (new file${l.existe?"; it already exists, compare it":""})`,l.contenido));for(let u of e.comoComprobar)
1127
+ i.push(` ${u}`);let d=e.ficheros.filter(u=>!u.existe);return r.escribira||(i.push(""),d.length>0?i.push(`Nothing was written. To create ${d.length===1?"the new file":`the ${d.length} new files`} abov\
1128
+ e (${d.map(u=>u.ruta).join(", ")}): ${n} --write. It asks first and never overwrites; nothing else is touched.`):i.push("Nothing was written: the files above already exist in your project.")),i.join(`\
1114
1129
 
1115
- `)}function Pl(e,t){let n=e.deteccion;return JSON.stringify({version:t,dir:n.dir,detected:{host:n.anfitrion,hostVersion:n.versionDelAnfitrion??null,appDir:n.appDir??null,typescript:n.ts,esm:n.esm,packageManager:n.
1116
- gestor,stacks:n.capas,installed:n.yaInstalado?n.deps["@bivelio/savings-layer"]??n.yaInstalado:null},stack:e.capa,provider:e.proveedor,adapter:$i[e.capa],install:e.comandoDeInstalacion??null,keys:e.claves.
1130
+ `)}function zl(e,t){let n=e.deteccion;return JSON.stringify({version:t,dir:n.dir,detected:{host:n.anfitrion,hostVersion:n.versionDelAnfitrion??null,appDir:n.appDir??null,typescript:n.ts,esm:n.esm,packageManager:n.
1131
+ gestor,stacks:n.capas,installed:n.yaInstalado?n.deps["@bivelio/savings-layer"]??n.yaInstalado:null},stack:e.capa,provider:e.proveedor,adapter:zi[e.capa],install:e.comandoDeInstalacion??null,keys:e.claves.
1117
1132
  map(r=>({name:r.nombre,set:r.puesta,purpose:r.para})),files:e.ficheros.map(r=>({path:r.ruta,purpose:r.proposito,exists:r.existe,content:r.contenido})),snippets:e.usos.map(r=>({title:r.titulo,content:r.
1118
- contenido})),check:e.comoComprobar,notes:e.avisos},null,2)}async function Dl(e,t){let n=[],r=[],o=e.ficheros.filter(a=>!a.existe);for(let a of e.ficheros.filter(c=>c.existe))n.push(`left as is: ${a.ruta}\
1133
+ contenido})),check:e.comoComprobar,notes:e.avisos},null,2)}async function Vl(e,t){let n=[],r=[],o=e.ficheros.filter(a=>!a.existe);for(let a of e.ficheros.filter(c=>c.existe))n.push(`left as is: ${a.ruta}\
1119
1134
  already exists (compare it with the code above).`);if(o.length===0)return n.push("Nothing to write."),{salida:0,lineas:n,creados:r};n.push(`About to create ${o.length===1?"1 new file":`${o.length} ne\
1120
1135
  w files`} in ${e.deteccion.dir}:`);for(let a of o)n.push(` ${a.ruta}`);n.push("No existing file is changed, nothing is installed and nothing is run.");let i=t.si;if(!i){if(!t.esTerminal)return n.push(
1121
1136
  "Not writing: this is not an interactive terminal and --yes was not given. Re-run with --write --yes, or copy the code above by hand."),{salida:1,lineas:n,creados:r};let a=await t.preguntar("Create th\
1122
1137
  em? [y/N] ");if(i=/^(y|yes)$/i.test(a.trim()),!i)return n.push("Nothing written."),{salida:0,lineas:n,creados:r}}let s=0;for(let a of o){let c=join(e.deteccion.dir,...a.ruta.split("/"));try{t.crearDir(dirname(
1123
1138
  c)),t.crearExclusivo(c,a.contenido),r.push(a.ruta),n.push(`created ${a.ruta}`);}catch(l){l.code==="EEXIST"?n.push(`left as is: ${a.ruta} appeared while we asked; it was not overwritten.`):(s=1,n.push(`\
1124
- could not create ${a.ruta}: ${l instanceof Error?l.message:String(l)}`));}}return {salida:s,lineas:n,creados:r}}var Ol="savings-mode";function Ll(e,t){for(let n of e){let r=join(n,"skills",Ol,"SKILL.md");if(t.existe(r))return r}return null}var $l="<!-- bvsala:savings-mode:inicio -->",
1125
- Mr="<!-- bvsala:savings-mode:fin -->";function qh(e){let t=e.replace(/^---\n[\s\S]*?\n---\n*/,"").trim();return `${$l}
1139
+ could not create ${a.ruta}: ${l instanceof Error?l.message:String(l)}`));}}return {salida:s,lineas:n,creados:r}}var ql="savings-mode";function Hl(e,t){for(let n of e){let r=join(n,"skills",ql,"SKILL.md");if(t.existe(r))return r}return null}var Gl="<!-- bvsala:savings-mode:inicio -->",
1140
+ Fr="<!-- bvsala:savings-mode:fin -->";function Qh(e){let t=e.replace(/^---\n[\s\S]*?\n---\n*/,"").trim();return `${Gl}
1126
1141
  ${t}
1127
1142
 
1128
1143
  _Always on (AGENTS.md has no activation step). Delete this block to turn it off; \`bvsala skill --codex --force\` restores it._
1129
- ${Mr}`}function Ml(e){let t=Ll(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=qh(e.fs.leer(t)),
1144
+ ${Fr}`}function Wl(e){let t=Hl(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=Qh(e.fs.leer(t)),
1130
1145
  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+`
1131
- `),{ok:true,destino:o,mensaje:zi(o,"installed")};let i=e.fs.leer(o),s=i.indexOf($l),a=i.indexOf(Mr);return s===-1||a===-1||a<s?(e.fs.escribir(o,i.trimEnd()+`
1146
+ `),{ok:true,destino:o,mensaje:Ji(o,"installed")};let i=e.fs.leer(o),s=i.indexOf(Gl),a=i.indexOf(Fr);return s===-1||a===-1||a<s?(e.fs.escribir(o,i.trimEnd()+`
1132
1147
 
1133
1148
  `+n+`
1134
- `),{ok:true,destino:o,mensaje:zi(o,"appended to the existing AGENTS.md")}):i.slice(s,a+Mr.length)===n?{ok:true,destino:o,mensaje:`[bvsala skill] already installed and up to date: ${o}`}:e.forzar?(e.fs.escribir(
1135
- o,i.slice(0,s)+n+i.slice(a+Mr.length)),{ok:true,destino:o,mensaje:zi(o,"block updated")}):{ok:false,destino:o,mensaje:`[bvsala skill] the savings-mode block in ${o} has DIFFERENT content \u2014 not overwriting \
1136
- it; use --force to update it`}}function zi(e,t){return `[bvsala skill] ${t}: ${e}
1149
+ `),{ok:true,destino:o,mensaje:Ji(o,"appended to the existing AGENTS.md")}):i.slice(s,a+Fr.length)===n?{ok:true,destino:o,mensaje:`[bvsala skill] already installed and up to date: ${o}`}:e.forzar?(e.fs.escribir(
1150
+ o,i.slice(0,s)+n+i.slice(a+Fr.length)),{ok:true,destino:o,mensaje:Ji(o,"block updated")}):{ok:false,destino:o,mensaje:`[bvsala skill] the savings-mode block in ${o} has DIFFERENT content \u2014 not overwriting \
1151
+ it; use --force to update it`}}function Ji(e,t){return `[bvsala skill] ${t}: ${e}
1137
1152
  [bvsala skill] AGENTS.md is ALWAYS active in Codex (there is no activation step); delete the block to turn it off.
1138
- [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 Nl(e){let t=Ll(e.origenes,e.fs);if(!t)return {ok:false,destino:"",
1139
- 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,Ol),o=join(r,"SKILL.\
1153
+ [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 Kl(e){let t=Hl(e.origenes,e.fs);if(!t)return {ok:false,destino:"",
1154
+ 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,ql),o=join(r,"SKILL.\
1140
1155
  md"),i=e.fs.leer(t);if(e.fs.existe(o)&&!e.forzar){let s=e.fs.leer(o)===i;return {ok:s,destino:o,mensaje:s?`[bvsala skill] already installed and up to date: ${o}`:`[bvsala skill] ${o} already exists wit\
1141
1156
  h DIFFERENT content \u2014 not overwriting it; use --force to overwrite`}}return e.fs.crearDir(r),e.fs.escribir(o,i),{ok:true,destino:o,mensaje:`[bvsala skill] installed: ${o}
1142
1157
  [bvsala skill] start (or restart) Claude Code and ask for "savings mode" \u2014 or let it activate on its own when you mention limits.
1143
- [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 Nr=class{id;exact=false;constructor(t="heuristic"){this.id=t;}count(t){if(t.length===0)return 0;let n=t.match(/[A-Za-z]+|\d+|\s+|[^\sA-Za-z\d]/g)??[],r=0;for(let o of n){let i=o[0];if(/\s/.test(i)){let s=(o.
1158
+ [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 zr=class{id;exact=false;constructor(t="heuristic"){this.id=t;}count(t){if(t.length===0)return 0;let n=t.match(/[A-Za-z]+|\d+|\s+|[^\sA-Za-z\d]/g)??[],r=0;for(let o of n){let i=o[0];if(/\s/.test(i)){let s=(o.
1144
1159
  match(/\n/g)??[]).length;r+=s+Math.floor(Math.max(0,o.length-1)/2);}else /[A-Za-z]/.test(i)?r+=Math.max(1,Math.ceil(o.length/4)):/\d/.test(i)?r+=Math.max(1,Math.ceil(o.length/2)):r+=1;}return Math.max(r,
1145
- Math.ceil(t.length/4))}},jr=new Nr;var Br=class{estimators=new Map;modelToTokenizer=new Map;fallbackId;constructor(t=jr){this.fallbackId=t.id,this.estimators.set(t.id,t);}register(t){return this.estimators.set(t.id,t),this}mapModel(t,n){
1160
+ Math.ceil(t.length/4))}},Vr=new zr;var qr=class{estimators=new Map;modelToTokenizer=new Map;fallbackId;constructor(t=Vr){this.fallbackId=t.id,this.estimators.set(t.id,t);}register(t){return this.estimators.set(t.id,t),this}mapModel(t,n){
1146
1161
  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.
1147
- get(r);if(o)return o}}return this.estimators.get(this.fallbackId)}count(t,n){return this.resolve(n).count(t)}};new Br;var Vi={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",
1148
- "text-embedding-3-large"]};var Kh=new Map;function A(e,t){for(let n of e.split(/\s+/).filter(Boolean))Kh.set(n,t);}var Jh=["zero","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen",
1149
- "fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"];Jh.forEach((e,t)=>A(e,{k:"unidad",v:t}));["twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"].forEach((e,t)=>A(e,{k:"\
1150
- decena",v:20+10*t}));A("hundred hundreds",{k:"cien"});A("thousand thousands",{k:"escala",v:1e3});A("million millions",{k:"escala",v:1e6});A("billion billions",{k:"escala",v:1e9});var Yh=["","first","s\
1151
- econd","third","fourth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelfth","thirteenth","fourteenth","fifteenth","sixteenth","seventeenth","eighteenth","nineteenth"];Yh.forEach((e,t)=>{
1152
- e&&(A(e,{k:"ordinal",v:t}),t>=3&&A(`${e}s`,{k:"ordinal",v:t}));});["twentieth","thirtieth","fortieth","fiftieth","sixtieth","seventieth","eightieth","ninetieth"].forEach((e,t)=>{A(e,{k:"ordinal",v:20+10*
1153
- t}),A(`${e}s`,{k:"ordinal",v:20+10*t});});A("hundredth hundredths",{k:"ordinal",v:100});A("thousandth thousandths",{k:"ordinal",v:1e3});A("millionth millionths",{k:"ordinal",v:1e6});A("half halves",{k:"\
1154
- token",t:"f:1/2"});A("quarter quarters",{k:"token",t:"f:1/4"});A("once single",{k:"token",t:"m:1"});A("twice double doubled doubles doubling",{k:"token",t:"m:2"});A("thrice triple tripled triples trip\
1155
- ling",{k:"token",t:"m:3"});A("quadruple quadrupled quadruples quadrupling",{k:"token",t:"m:4"});A("dozen dozens",{k:"token",t:"c:12"});A("pair pairs",{k:"token",t:"c:2"});A("times time",{k:"veces"});A(
1156
- "and",{k:"conector"});var Zh=["cero","uno","dos","tres","cuatro","cinco","seis","siete","ocho","nueve","diez","","doce","trece","catorce","quince","dieciseis","diecisiete","dieciocho","diecinueve"];Zh.
1157
- forEach((e,t)=>e&&A(e,{k:"unidad",v:t}));A("veinte",{k:"decena",v:20});["veintiuno","veintidos","veintitres","veinticuatro","veinticinco","veintiseis","veintisiete","veintiocho","veintinueve"].forEach(
1158
- (e,t)=>A(e,{k:"unidad",v:21+t}));["treinta","cuarenta","cincuenta","sesenta","setenta","ochenta","noventa"].forEach((e,t)=>A(e,{k:"decena",v:30+10*t}));A("cien ciento",{k:"centena",v:100});[["doscient\
1162
+ get(r);if(o)return o}}return this.estimators.get(this.fallbackId)}count(t,n){return this.resolve(n).count(t)}};new qr;var Yi={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",
1163
+ "text-embedding-3-large"]};var rg=new Map;function I(e,t){for(let n of e.split(/\s+/).filter(Boolean))rg.set(n,t);}var og=["zero","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen",
1164
+ "fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"];og.forEach((e,t)=>I(e,{k:"unidad",v:t}));["twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"].forEach((e,t)=>I(e,{k:"\
1165
+ decena",v:20+10*t}));I("hundred hundreds",{k:"cien"});I("thousand thousands",{k:"escala",v:1e3});I("million millions",{k:"escala",v:1e6});I("billion billions",{k:"escala",v:1e9});var ig=["","first","s\
1166
+ econd","third","fourth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelfth","thirteenth","fourteenth","fifteenth","sixteenth","seventeenth","eighteenth","nineteenth"];ig.forEach((e,t)=>{
1167
+ e&&(I(e,{k:"ordinal",v:t}),t>=3&&I(`${e}s`,{k:"ordinal",v:t}));});["twentieth","thirtieth","fortieth","fiftieth","sixtieth","seventieth","eightieth","ninetieth"].forEach((e,t)=>{I(e,{k:"ordinal",v:20+10*
1168
+ t}),I(`${e}s`,{k:"ordinal",v:20+10*t});});I("hundredth hundredths",{k:"ordinal",v:100});I("thousandth thousandths",{k:"ordinal",v:1e3});I("millionth millionths",{k:"ordinal",v:1e6});I("half halves",{k:"\
1169
+ token",t:"f:1/2"});I("quarter quarters",{k:"token",t:"f:1/4"});I("once single",{k:"token",t:"m:1"});I("twice double doubled doubles doubling",{k:"token",t:"m:2"});I("thrice triple tripled triples trip\
1170
+ ling",{k:"token",t:"m:3"});I("quadruple quadrupled quadruples quadrupling",{k:"token",t:"m:4"});I("dozen dozens",{k:"token",t:"c:12"});I("pair pairs",{k:"token",t:"c:2"});I("times time",{k:"veces"});I(
1171
+ "and",{k:"conector"});var sg=["cero","uno","dos","tres","cuatro","cinco","seis","siete","ocho","nueve","diez","","doce","trece","catorce","quince","dieciseis","diecisiete","dieciocho","diecinueve"];sg.
1172
+ forEach((e,t)=>e&&I(e,{k:"unidad",v:t}));I("veinte",{k:"decena",v:20});["veintiuno","veintidos","veintitres","veinticuatro","veinticinco","veintiseis","veintisiete","veintiocho","veintinueve"].forEach(
1173
+ (e,t)=>I(e,{k:"unidad",v:21+t}));["treinta","cuarenta","cincuenta","sesenta","setenta","ochenta","noventa"].forEach((e,t)=>I(e,{k:"decena",v:30+10*t}));I("cien ciento",{k:"centena",v:100});[["doscient\
1159
1174
  os doscientas",200],["trescientos trescientas",300],["cuatrocientos cuatrocientas",400],["quinientos quinientas",500],["seiscientos seiscientas",600],["setecientos setecientas",700],["ochocientos ocho\
1160
- cientas",800],["novecientos novecientas",900]].forEach(([e,t])=>A(e,{k:"centena",v:t}));A("mil miles",{k:"escala",v:1e3});A("millon millones",{k:"escala",v:1e6});A("billon billones",{k:"escala",v:1e12});
1175
+ cientas",800],["novecientos novecientas",900]].forEach(([e,t])=>I(e,{k:"centena",v:t}));I("mil miles",{k:"escala",v:1e3});I("millon millones",{k:"escala",v:1e6});I("billon billones",{k:"escala",v:1e12});
1161
1176
  [["primero primera primer primeros primeras",1],["segundo segunda segundos segundas",2],["tercero tercera tercer terceros terceras tercio tercios",3],["cuarto cuarta cuartos cuartas",4],["quinto quint\
1162
1177
  a quintos quintas",5],["sexto sexta sextos sextas",6],["septimo septima septimos septimas",7],["octavo octava octavos octavas",8],["noveno novena novenos novenas",9],["decimo decima decimos decimas",10]].
1163
- forEach(([e,t])=>A(e,{k:"ordinal",v:t}));A("mitad mitades medio media medios medias",{k:"token",t:"f:1/2"});A("doble dobles",{k:"token",t:"m:2"});A("cuadruple",{k:"token",t:"m:4"});A("docena docenas",
1164
- {k:"token",t:"c:12"});A("par pares",{k:"token",t:"c:2"});A("veces vez",{k:"veces"});A("y",{k:"conector"});[["zero",0],["dues",2],["quatre",4],["cinc",5],["sis",6],["set",7],["vuit",8],["nou",9],["deu",
1165
- 10],["onze",11],["dotze",12],["tretze",13],["catorze",14],["quinze",15],["setze",16],["disset",17],["divuit",18],["dinou",19]].forEach(([e,t])=>A(e,{k:"unidad",v:t}));["vint","trenta","quaranta","cinq\
1166
- uanta","seixanta","setanta","vuitanta","noranta"].forEach((e,t)=>A(e,{k:"decena",v:20+10*t}));A("cent",{k:"centena",v:100});A("cents centes",{k:"cien"});A("milio milions",{k:"escala",v:1e6});[["segon \
1178
+ forEach(([e,t])=>I(e,{k:"ordinal",v:t}));I("mitad mitades medio media medios medias",{k:"token",t:"f:1/2"});I("doble dobles",{k:"token",t:"m:2"});I("cuadruple",{k:"token",t:"m:4"});I("docena docenas",
1179
+ {k:"token",t:"c:12"});I("par pares",{k:"token",t:"c:2"});I("veces vez",{k:"veces"});I("y",{k:"conector"});[["zero",0],["dues",2],["quatre",4],["cinc",5],["sis",6],["set",7],["vuit",8],["nou",9],["deu",
1180
+ 10],["onze",11],["dotze",12],["tretze",13],["catorze",14],["quinze",15],["setze",16],["disset",17],["divuit",18],["dinou",19]].forEach(([e,t])=>I(e,{k:"unidad",v:t}));["vint","trenta","quaranta","cinq\
1181
+ uanta","seixanta","setanta","vuitanta","noranta"].forEach((e,t)=>I(e,{k:"decena",v:20+10*t}));I("cent",{k:"centena",v:100});I("cents centes",{k:"cien"});I("milio milions",{k:"escala",v:1e6});[["segon \
1167
1182
  segona segons segones",2],["terc tercos",3],["quart quarta quarts quartes",4],["cinque cinquena",5],["sise sisena",6],["sete setena",7],["vuite vuitena",8],["nove novena",9],["dese desena",10]].forEach(
1168
- ([e,t])=>A(e,{k:"ordinal",v:t}));A("meitat meitats mig mitja",{k:"token",t:"f:1/2"});A("dotzena dotzenes",{k:"token",t:"c:12"});A("parell parells",{k:"token",t:"c:2"});A("vegades vegada",{k:"veces"});
1169
- A("i",{k:"conector"});var Eg={"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}};
1170
- uo(Eg);new Set(Object.values(Vi).flatMap(e=>e.flatMap(t=>[t,`openai/${t}`])));function Qg(e,t=300){return new Promise(n=>{let r=connect({port:e,host:"127.0.0.1"}),o=i=>{r.destroy(),n(i);};r.setTimeout(t,()=>o(false)),r.once("connect",()=>o(true)),r.once("error",()=>o(false));})}var Dn=ol(process.
1171
- argv.slice(2));function eb(){console.log(`bvsala ${ye} \u2014 BiVelio Savings Layer
1183
+ ([e,t])=>I(e,{k:"ordinal",v:t}));I("meitat meitats mig mitja",{k:"token",t:"f:1/2"});I("dotzena dotzenes",{k:"token",t:"c:12"});I("parell parells",{k:"token",t:"c:2"});I("vegades vegada",{k:"veces"});
1184
+ I("i",{k:"conector"});var Og={"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}};
1185
+ vo(Og);new Set(Object.values(Yi).flatMap(e=>e.flatMap(t=>[t,`openai/${t}`])));function cb(e,t=300){return new Promise(n=>{let r=connect({port:e,host:"127.0.0.1"}),o=i=>{r.destroy(),n(i);};r.setTimeout(t,()=>o(false)),r.once("connect",()=>o(true)),r.once("error",()=>o(false));})}var Mn=hl(process.
1186
+ argv.slice(2));function lb(){console.log(`bvsala ${Se} \u2014 BiVelio Savings Layer
1172
1187
 
1173
1188
  Commands:
1174
1189
  gateway [--port N] [--upstream U]
@@ -1292,49 +1307,49 @@ forwards and warns. On a Claude or ChatGPT subscription there is no per-token in
1292
1307
  traffic is metered at list-price equivalent and never carries commission.
1293
1308
  Your prompts, completions and provider keys never reach BiVelio: what it receives is per-request
1294
1309
  usage (token counts, cost, the model id and opaque ids); LICENSE \xA75 lists every field.
1295
- More: savings.bivelio.com`);}Dn.tipo==="ayuda"&&(eb(),process.exit(Dn.salida));Dn.tipo==="version"&&(console.log(ye),process.exit(0));var{comando:W}=Dn,gt=Cn(W),xe=Dn.resto,au=al(gt?[]:xe,process.env,{
1296
- checkEnv:gt||W==="gateway"});if(au.length>0){for(let e of au)console.error(e);process.exit(1);}var Zi=process.env.BVSALA_GATEWAY_EFFORT,fu=process.env.BVSALA_GATEWAY_SIBLING_MODEL;if(W==="init"){let e=El(
1297
- xe,process.cwd());e.ok||(console.error(`[bvsala init] ${e.mensaje}`),process.exit(1));let t=e.valor,n={leer:c=>{try{return readFileSync(c,"utf8")}catch{return}},existe:existsSync},r=Tl(t.cwd,n);r.ok||(console.error(`[b\
1298
- vsala init] ${r.mensaje}`),process.exit(1));let o=Rl(r.valor,t,{node:process.versions.node,env:c=>!!process.env[c]?.trim()});o.ok||(console.error(`[bvsala init] ${o.mensaje}`),process.exit(1));let i=Al(
1299
- o.valor,n);t.json&&(console.log(Pl(i,ye)),process.exit(0)),console.log(Il(i,`bvsala init \xB7 BiVelio Savings Layer ${ye}`,"npx @bivelio/savings-layer@latest init",{escribira:t.escribir})),t.escribir||
1300
- process.exit(0),console.log("");let{createInterface:s}=await import('readline/promises'),a=await Dl(i,{si:t.si,esTerminal:!!process.stdin.isTTY,preguntar:async c=>{let l=s({input:process.stdin,output:process.
1310
+ More: savings.bivelio.com`);}Mn.tipo==="ayuda"&&(lb(),process.exit(Mn.salida));Mn.tipo==="version"&&(console.log(Se),process.exit(0));var{comando:K}=Mn,St=In(K),Ce=Mn.resto,vu=vl(St?[]:Ce,process.env,{
1311
+ checkEnv:St||K==="gateway"});if(vu.length>0){for(let e of vu)console.error(e);process.exit(1);}var os=process.env.BVSALA_GATEWAY_EFFORT,Eu=process.env.BVSALA_GATEWAY_SIBLING_MODEL;if(K==="init"){let e=$l(
1312
+ Ce,process.cwd());e.ok||(console.error(`[bvsala init] ${e.mensaje}`),process.exit(1));let t=e.valor,n={leer:c=>{try{return readFileSync(c,"utf8")}catch{return}},existe:existsSync},r=jl(t.cwd,n);r.ok||(console.error(`[b\
1313
+ vsala init] ${r.mensaje}`),process.exit(1));let o=Bl(r.valor,t,{node:process.versions.node,env:c=>!!process.env[c]?.trim()});o.ok||(console.error(`[bvsala init] ${o.mensaje}`),process.exit(1));let i=Ul(
1314
+ o.valor,n);t.json&&(console.log(zl(i,Se)),process.exit(0)),console.log(Fl(i,`bvsala init \xB7 BiVelio Savings Layer ${Se}`,"npx @bivelio/savings-layer@latest init",{escribira:t.escribir})),t.escribir||
1315
+ process.exit(0),console.log("");let{createInterface:s}=await import('readline/promises'),a=await Vl(i,{si:t.si,esTerminal:!!process.stdin.isTTY,preguntar:async c=>{let l=s({input:process.stdin,output:process.
1301
1316
  stdout});try{return await l.question(c)}finally{l.close();}},crearDir:c=>mkdirSync(c,{recursive:true}),crearExclusivo:(c,l)=>writeFileSync(c,l,{flag:"wx"})});for(let c of a.lineas)(a.salida===0?console.log:console.error)(
1302
- c);process.exit(a.salida);}if(W==="skill"){let e=dirname(fileURLToPath(import.meta.url)),t={origenes:[join(e,"..",".."),join(e,"..")],home:homedir(),cwd:process.cwd(),proyecto:xe.includes("--project"),forzar:xe.includes("--for\
1303
- ce"),fs:{existe:existsSync,leer:r=>readFileSync(r,"utf8"),escribir:(r,o)=>writeFileSync(r,o),crearDir:r=>mkdirSync(r,{recursive:true})}},n=xe.includes("--codex")?Ml(t):Nl(t);console.log(n.mensaje),process.exit(n.ok?0:1);}var Xi=xe.indexOf(
1304
- "--port"),It=gt?0:Xi>=0?Number(xe[Xi+1]):8402;(!Number.isInteger(It)||(W==="doctor"?It<1:It<0)||It>65535)&&(console.error(`[bvsala ${W}] invalid port: ${xe[Xi+1]}`),process.exit(1));if(W==="doctor"){xe.
1305
- 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 ul(It);console.log(e.texto),process.exit(
1306
- 0);}function tb(e,t){Cn(e)||process.exit(1);let n=Lr(e,0,[],{}).bin;if(process.platform==="win32"){let o=Oi(n);o.tipo==="exe"?n=o.ruta:o.tipo==="solo-shim"&&(console.error(`[bvsala ${e}] \`${n}\` is ins\
1317
+ c);process.exit(a.salida);}if(K==="skill"){let e=dirname(fileURLToPath(import.meta.url)),t={origenes:[join(e,"..",".."),join(e,"..")],home:homedir(),cwd:process.cwd(),proyecto:Ce.includes("--project"),forzar:Ce.includes("--for\
1318
+ ce"),fs:{existe:existsSync,leer:r=>readFileSync(r,"utf8"),escribir:(r,o)=>writeFileSync(r,o),crearDir:r=>mkdirSync(r,{recursive:true})}},n=Ce.includes("--codex")?Wl(t):Kl(t);console.log(n.mensaje),process.exit(n.ok?0:1);}var is=Ce.indexOf(
1319
+ "--port"),jt=St?0:is>=0?Number(Ce[is+1]):8402;(!Number.isInteger(jt)||(K==="doctor"?jt<1:jt<0)||jt>65535)&&(console.error(`[bvsala ${K}] invalid port: ${Ce[is+1]}`),process.exit(1));if(K==="doctor"){Ce.
1320
+ 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 wl(jt);console.log(e.texto),process.exit(
1321
+ 0);}function ub(e,t){In(e)||process.exit(1);let n=Br(e,0,[],{}).bin;if(process.platform==="win32"){let o=Ui(n);o.tipo==="exe"?n=o.ruta:o.tipo==="solo-shim"&&(console.error(`[bvsala ${e}] \`${n}\` is ins\
1307
1322
  talled 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 on the PATH) or use the manual reci\
1308
1323
  pe 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(o)}. Is it installed and on the PA\
1309
- TH?`),process.exit(127);}),r.on("exit",(o,i)=>process.exit(o??(i?1:0))),new Promise(()=>{})}gt&&il(xe)&&await tb(W,xe);if(gt){let e=tl(W);e&&(console.error(`[bvsala ${W}] ${e}`),process.exit(1));}var nb=W===
1310
- "gateway"?Rc(xe):void 0,fe=Ac({flag:nb,env:process.env.BVSALA_GATEWAY_UPSTREAM});fe.ok||(console.error(fe.error),process.exit(1));var mu=process.env.BIVELIO_SERVICE_KEY?.trim()||void 0,Pt=await yc({serviceAccountKey:mu,
1311
- licenseKey:process.env.BIVELIO_LICENSE_KEY,licenseServerUrl:xi});Pt.ok||(console.error(`[bvsala ${W}] ${Pt.message}`),process.exit(1));var Je=gt?Lr(W,0,xe,{modoCodex:W==="codex"?Zc({leerAuth:()=>readFileSync(
1312
- join(homedir(),".codex","auth.json"),"utf8")}):void 0,...fe.upstream?{upstreamElegido:fe.upstream}:{}}):null,rb=gt&&process.env.BVSALA_GATEWAY_LOG!=="1",Yi=Je?.upstream?null:cl(()=>readFileSync(process.env.BVSALA_ANILLO2_FICHERO??
1313
- join(homedir(),".bvsala","anillo2.json"),"utf8")),Pn=ll({enrolamiento:Yi,espiaVivo:Yi!==null&&await Qg(Yi.espia),upstreamEnv:fe.upstream,...fe.origen!=="none"?{upstreamOrigen:fe.origen}:{},elisionEnv:process.
1314
- env.BVSALA_GATEWAY_ELISION,hoyUtcIso:new Date().toISOString().slice(0,10)}),Qi=fe.upstream??Pn.upstream,Vr=process.env.BVSALA_GATEWAY_ELISION??Pn.elision,Ie;try{Ie=await Wc({puerto:It,...rb?{log:()=>{},
1315
- avisosDeNoMedido:!1}:{},license:{token:Pt.license.token,publicKey:St,licenseServerUrl:xi,checkOnStart:Pt.source==="offline"},warn:e=>console.error(e),serviceAccountKey:mu,...process.env.BVSALA_SEAT_ID?
1316
- {seatId:process.env.BVSALA_SEAT_ID}:{},...Qi?{upstream:Qi}:Je?.upstream?{upstream:Je.upstream}:{},...process.env.BVSALA_GATEWAY_COALESCE==="1"?{coalescer:!0}:{},...process.env.BVSALA_GATEWAY_USAGE_INJECT===
1317
- "1"?{usageInject:!0}:{},...process.env.BVSALA_GATEWAY_SHADOW==="1"?{sombra:!0}:{},elision:Vr!=="0",...process.env.BVSALA_GATEWAY_DIALES_ELISION==="1"?{dialesElision:!0}:{},...fu==="1"?{modeloHermano:!0}:
1318
- {},...Zi?{esfuerzo:Zi}:{},...process.env.BVSALA_METERING_URL?{meteringUrl:process.env.BVSALA_METERING_URL}:{}});}catch(e){console.error(`[bvsala ${W}] ${sl(e,W,It)}`),process.exit(1);}var hu=Qi??Je?.upstream??
1319
- "https://api.anthropic.com";console.log(`[bvsala gateway] v${ye} listening on http://127.0.0.1:${Ie.puerto} \u2192 ${hu}`);(Pt.lineIsWarning?console.error:console.log)(`[bvsala gateway] ${Pt.line}`);for(let e of Pt.
1324
+ TH?`),process.exit(127);}),r.on("exit",(o,i)=>process.exit(o??(i?1:0))),new Promise(()=>{})}St&&gl(Ce)&&await ub(K,Ce);if(St){let e=pl(K);e&&(console.error(`[bvsala ${K}] ${e}`),process.exit(1));}var db=K===
1325
+ "gateway"?Bc(Ce):void 0,ge=Uc({flag:db,env:process.env.BVSALA_GATEWAY_UPSTREAM});ge.ok||(console.error(ge.error),process.exit(1));var _u=process.env.BIVELIO_SERVICE_KEY?.trim()||void 0,Bt=await Ic({serviceAccountKey:_u,
1326
+ licenseKey:process.env.BIVELIO_LICENSE_KEY,licenseServerUrl:Ai});Bt.ok||(console.error(`[bvsala ${K}] ${Bt.message}`),process.exit(1));var Ye=St?Br(K,0,Ce,{modoCodex:K==="codex"?cl({leerAuth:()=>readFileSync(
1327
+ join(homedir(),".codex","auth.json"),"utf8")}):void 0,...ge.upstream?{upstreamElegido:ge.upstream}:{}}):null,pb=St&&process.env.BVSALA_GATEWAY_LOG!=="1",rs=Ye?.upstream?null:yl(()=>readFileSync(process.env.BVSALA_ANILLO2_FICHERO??
1328
+ join(homedir(),".bvsala","anillo2.json"),"utf8")),$n=kl({enrolamiento:rs,espiaVivo:rs!==null&&await cb(rs.espia),upstreamEnv:ge.upstream,...ge.origen!=="none"?{upstreamOrigen:ge.origen}:{},elisionEnv:process.
1329
+ env.BVSALA_GATEWAY_ELISION,hoyUtcIso:new Date().toISOString().slice(0,10)}),ss=ge.upstream??$n.upstream,Kr=process.env.BVSALA_GATEWAY_ELISION??$n.elision,De;try{De=await ol({puerto:jt,...pb?{log:()=>{},
1330
+ avisosDeNoMedido:!1}:{},license:{token:Bt.license.token,publicKey:Pt,licenseServerUrl:Ai,checkOnStart:Bt.source==="offline"},warn:e=>console.error(e),serviceAccountKey:_u,...process.env.BVSALA_SEAT_ID?
1331
+ {seatId:process.env.BVSALA_SEAT_ID}:{},...ss?{upstream:ss}:Ye?.upstream?{upstream:Ye.upstream}:{},...process.env.BVSALA_GATEWAY_COALESCE==="1"?{coalescer:!0}:{},...process.env.BVSALA_GATEWAY_USAGE_INJECT===
1332
+ "1"?{usageInject:!0}:{},...process.env.BVSALA_GATEWAY_SHADOW==="1"?{sombra:!0}:{},elision:Kr!=="0",...process.env.BVSALA_GATEWAY_DIALES_ELISION==="1"?{dialesElision:!0}:{},...Eu==="1"?{modeloHermano:!0}:
1333
+ {},...os?{esfuerzo:os}:{},...process.env.BVSALA_METERING_URL?{meteringUrl:process.env.BVSALA_METERING_URL}:{}});}catch(e){console.error(`[bvsala ${K}] ${bl(e,K,jt)}`),process.exit(1);}var Cu=ss??Ye?.upstream??
1334
+ "https://api.anthropic.com";console.log(`[bvsala gateway] v${Se} listening on http://127.0.0.1:${De.puerto} \u2192 ${Cu}`);(Bt.lineIsWarning?console.error:console.log)(`[bvsala gateway] ${Bt.line}`);for(let e of Bt.
1320
1335
  warnings)console.error(`[bvsala gateway] ${e}`);console.log("[bvsala gateway] metering: ON (service key present)");process.env.BVSALA_METERING_URL&&console.error(`[bvsala gateway] WARNING: BVSALA_METE\
1321
1336
  RING_URL=${process.env.BVSALA_METERING_URL} redirects usage reporting away from savings.bivelio.com (development only): your dashboard will not see this usage. The license and the entitlements channel\
1322
- still use savings.bivelio.com.`);fe.aviso&&console.error(fe.aviso);process.env.BVSALA_GATEWAY_USAGE_INJECT==="1"&&console.log("[bvsala gateway] usage injection: ON (BVSALA_GATEWAY_USAGE_INJECT=1) \u2014 s\
1323
- treamed chat completions without stream_options get include_usage; their last chunk has an empty choices list.");{let e=as(Vr,true,process.env.BVSALA_GATEWAY_DIALES_ELISION==="1");(e.aviso?console.error:
1324
- console.log)(`[bvsala gateway] ${e.linea}`);let t=ws(fu,true,Vr!=="0");(t.aviso?console.error:console.log)(`[bvsala gateway] ${t.linea}`);let n=gs(Zi,true,Vr!=="0");(n.aviso?console.error:console.log)(`[b\
1325
- vsala gateway] ${n.linea}`),Pn.linea&&(Pn.aviso?console.error:console.log)(`[bvsala gateway] ${Pn.linea}`);}fe.upstream&&Je?.upstream&&fe.upstream!==Je.upstream&&console.error(`[bvsala ${W}] WARNING: B\
1326
- VSALA_GATEWAY_UPSTREAM=${fe.upstream} overrides this terminal's upstream (${Je.upstream}). If that is not what you want, unset the variable.`);W==="codex"&&!Ya()&&console.error(`[bvsala codex] WARNING\
1327
- : this Node (${process.version}) cannot decompress zstd and Codex sends its body in zstd: traffic passes through but is NOT metered. Use Node >= 22.15.`);var cu=false;function gu(){if(cu)return;cu=true;let e=Vc(
1328
- Ie.degradaciones());e&&console.error(e),console.error(Ic(Ie.medicion(),W));}if(Je&&gt){let e=Lr(W,Ie.puerto,xe,{...Je.upstream?{modoCodex:Je.upstream.includes("chatgpt.com")?"chatgpt":"api-key"}:{},...fe.
1329
- upstream?{upstreamElegido:fe.upstream}:{}});e.nota&&console.log(`[bvsala ${W}] ${e.nota}`);let t=e.bin;if(process.platform==="win32"){let r=Oi(e.bin);r.tipo==="exe"?t=r.ruta:r.tipo==="solo-shim"&&(console.
1330
- error(`[bvsala ${W}] \`${e.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 ${e.
1331
- bin}.exe on the PATH) or use the manual recipe in docs/terminales/.`),await Ie.cerrar(),process.exit(127));}let n=spawn(t,e.args,{stdio:"inherit",env:{...process.env,...e.env}});n.on("error",r=>{console.error(
1332
- `[bvsala ${W}] could not launch \`${e.bin}\`: ${String(r)}. Is it installed and on the PATH?`),Ie.cerrar().then(()=>process.exit(127));}),n.on("exit",(r,o)=>{gu(),Ie.cerrar().then(()=>process.exit(r??(o?
1333
- 1:0)));});}else {let e=new URL(hu).hostname;e==="api.openai.com"?console.log(`[bvsala gateway] point your SDK at it: base_url=http://127.0.0.1:${Ie.puerto}/v1 (OpenAI SDKs) \xB7 streamed chat completions ar\
1334
- e metered when the request sets stream_options.include_usage \xB7 bvsala doctor for recipes`):e==="api.anthropic.com"||fe.upstream===void 0?console.log(`[bvsala gateway] point your terminal at it (or \
1335
- use \`bvsala ${Di.join("|")}\`): ANTHROPIC_BASE_URL=http://127.0.0.1:${Ie.puerto} claude \xB7 bvsala doctor for the others`):console.log(`[bvsala gateway] point your client at http://127.0.0.1:${Ie.
1336
- puerto} plus the path prefix it already uses (for example /v1) \xB7 bvsala doctor for recipes`);}var bu=async()=>{gu(),await Ie.cerrar(),process.exit(0);};process.on("SIGINT",()=>{bu();});process.on("SIG\
1337
- TERM",()=>{bu();});
1337
+ still use savings.bivelio.com.`);ge.aviso&&console.error(ge.aviso);process.env.BVSALA_GATEWAY_USAGE_INJECT==="1"&&console.log("[bvsala gateway] usage injection: ON (BVSALA_GATEWAY_USAGE_INJECT=1) \u2014 s\
1338
+ treamed chat completions without stream_options get include_usage; their last chunk has an empty choices list.");{let e=ms(Kr,true,process.env.BVSALA_GATEWAY_DIALES_ELISION==="1");(e.aviso?console.error:
1339
+ console.log)(`[bvsala gateway] ${e.linea}`);let t=Rs(Eu,true,Kr!=="0");(t.aviso?console.error:console.log)(`[bvsala gateway] ${t.linea}`);let n=Ss(os,true,Kr!=="0");(n.aviso?console.error:console.log)(`[b\
1340
+ vsala gateway] ${n.linea}`),$n.linea&&($n.aviso?console.error:console.log)(`[bvsala gateway] ${$n.linea}`);}ge.upstream&&Ye?.upstream&&ge.upstream!==Ye.upstream&&console.error(`[bvsala ${K}] WARNING: B\
1341
+ VSALA_GATEWAY_UPSTREAM=${ge.upstream} overrides this terminal's upstream (${Ye.upstream}). If that is not what you want, unset the variable.`);K==="codex"&&!ac()&&console.error(`[bvsala codex] WARNING\
1342
+ : this Node (${process.version}) cannot decompress zstd and Codex sends its body in zstd: traffic passes through but is NOT metered. Use Node >= 22.15.`);var yu=false;function Tu(){if(yu)return;yu=true;let e=el(
1343
+ De.degradaciones());e&&console.error(e),console.error(Fc(De.medicion(),K));}if(Ye&&St){let e=Br(K,De.puerto,Ce,{...Ye.upstream?{modoCodex:Ye.upstream.includes("chatgpt.com")?"chatgpt":"api-key"}:{},...ge.
1344
+ upstream?{upstreamElegido:ge.upstream}:{}});e.nota&&console.log(`[bvsala ${K}] ${e.nota}`);let t=e.bin;if(process.platform==="win32"){let r=Ui(e.bin);r.tipo==="exe"?t=r.ruta:r.tipo==="solo-shim"&&(console.
1345
+ error(`[bvsala ${K}] \`${e.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 ${e.
1346
+ bin}.exe on the PATH) or use the manual recipe in docs/terminales/.`),await De.cerrar(),process.exit(127));}let n=spawn(t,e.args,{stdio:"inherit",env:{...process.env,...e.env}});n.on("error",r=>{console.error(
1347
+ `[bvsala ${K}] could not launch \`${e.bin}\`: ${String(r)}. Is it installed and on the PATH?`),De.cerrar().then(()=>process.exit(127));}),n.on("exit",(r,o)=>{Tu(),De.cerrar().then(()=>process.exit(r??(o?
1348
+ 1:0)));});}else {let e=new URL(Cu).hostname;e==="api.openai.com"?console.log(`[bvsala gateway] point your SDK at it: base_url=http://127.0.0.1:${De.puerto}/v1 (OpenAI SDKs) \xB7 streamed chat completions ar\
1349
+ e metered when the request sets stream_options.include_usage \xB7 bvsala doctor for recipes`):e==="api.anthropic.com"||ge.upstream===void 0?console.log(`[bvsala gateway] point your terminal at it (or \
1350
+ use \`bvsala ${Bi.join("|")}\`): ANTHROPIC_BASE_URL=http://127.0.0.1:${De.puerto} claude \xB7 bvsala doctor for the others`):console.log(`[bvsala gateway] point your client at http://127.0.0.1:${De.
1351
+ puerto} plus the path prefix it already uses (for example /v1) \xB7 bvsala doctor for recipes`);}var Ru=async()=>{Tu(),await De.cerrar(),process.exit(0);};process.on("SIGINT",()=>{Ru();});process.on("SIG\
1352
+ TERM",()=>{Ru();});
1338
1353
  /*! Bundled license information:
1339
1354
 
1340
1355
  @noble/curves/utils.js: