@bivelio/savings-layer 0.4.33 → 0.4.35

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 rt from'zlib';import {connect}from'net';var Nn="context-management-2025-06-27";function Vr(){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 pu=new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});function fu(e){try{return pu.decode(e)}catch{return null}}function mu(e){return /^(?:0|[1-9]\d{0,9})$/.test(e)&&Number(e)<4294967295}function hu(e){
3
- return e===32||e===10||e===13||e===9}function gu(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&&hu(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(mu(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 jn(e,t){
7
- if(t!==void 0&&t!==""&&t!=="identity")return null;let n=fu(e);if(n===null)return null;let r;try{r=JSON.parse(n);}catch{return null}return gu(n)?r:null}function rs(e,t){try{let n=jn(e,t);if(n===null||typeof n!="object"||Array.isArray(n)||typeof n.model!="string"||!Array.isArray(n.messages))return null;let r=vu(n.context_management),o=yu(n.context_management);
8
- return n.context_management=ku(n.context_management),{cuerpo:Buffer.from(JSON.stringify(n),"utf8"),nuestros:r,triggerDelCliente:o}}catch{return null}}function vu(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===qr);return ts(n)!==ts([Vr().edits[0]])}function yu(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===qr);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 ts(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 qr="clear_tool_uses_20250919",ns="clear_thinking_20251015";function ku(e){
13
- let t=Vr().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!==qr),o=r.filter(
14
- s=>s.type===ns),i=r.filter(s=>s.type!==ns);return {...n,edits:[...o,...i,t]}}function os(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 rt from'zlib';import {connect}from'net';var Fn="context-management-2025-06-27";function Gr(){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 hu=new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});function gu(e){try{return hu.decode(e)}catch{return null}}function bu(e){return /^(?:0|[1-9]\d{0,9})$/.test(e)&&Number(e)<4294967295}function vu(e){
3
+ return e===32||e===10||e===13||e===9}function yu(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&&vu(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(bu(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 zn(e,t){
7
+ if(t!==void 0&&t!==""&&t!=="identity")return null;let n=gu(e);if(n===null)return null;let r;try{r=JSON.parse(n);}catch{return null}return yu(n)?r:null}function cs(e,t){try{let n=zn(e,t);if(n===null||typeof n!="object"||Array.isArray(n)||typeof n.model!="string"||!Array.isArray(n.messages))return null;let r=wu(n.context_management),o=xu(n.context_management);
8
+ return n.context_management=Su(n.context_management),{cuerpo:Buffer.from(JSON.stringify(n),"utf8"),nuestros:r,triggerDelCliente:o}}catch{return null}}function wu(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===Wr);return ss(n)!==ss([Gr().edits[0]])}function xu(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===Wr);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 ss(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 Wr="clear_tool_uses_20250919",as="clear_thinking_20251015";function Su(e){
13
+ let t=Gr().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!==Wr),o=r.filter(
14
+ s=>s.type===as),i=r.filter(s=>s.type!==as);return {...n,edits:[...o,...i,t]}}function ls(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 is(e){return e===void 0||e.trim()===""?Nn:e.split(",").map(n=>n.trim()).filter(
18
- n=>n.length>0).includes(Nn)?e:`${e},${Nn}`}function ss(e){let t=e.toLowerCase(),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function wu(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=ss(e);return t.startsWith("gpt-")||t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4")?wu(t)?1.25:1:t.startsWith("gemini")?1:1.25}function Nt(e){let t=e.toLowerCase();return t.startsWith("claude")||t.startsWith("anthropic/")||ss(t).startsWith("claude")?2:ve(e)}var Su=1.25,Eu=2,_u=.3,Cu=/^(custom|bash_|text_editor_|computer_|browser_|memory_)/;function Kr(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"&&!Cu.test(n)}):false}var Au=4096,Tu=(e,t)=>e==="cache_control"?void 0:t;function Hr(e){return e===void 0?"":JSON.stringify(e,Tu)??
21
- ""}function Ru(e){return Array.isArray(e)?e.filter(t=>!(t!==null&&typeof t=="object"&&t.defer_loading===true)):e}function Wr(e){return createHash("sha1").update(e).digest("base64url").slice(0,16)}function st(e,t){
22
- let n=jn(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 Jr(e){let t=Hr(e.system),n=Hr(Ru(e.tools)),
23
- r=Array.isArray(e.messages)?e.messages.slice(0,Au):[],o=[],i=[];for(let s of r){let a=Hr(s);o.push(Wr(a)),i.push(Buffer.byteLength(a,"utf8"));}return {system:Wr(t),tools:Wr(n),mensajes:o,bytes:i,bytesFijos:Buffer.
24
- byteLength(t,"utf8")+Buffer.byteLength(n,"utf8")}}function Yr(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 Zr(e){let{fraccionNueva:t,umbral:n=_u}=e;
26
- return t>=n}function Iu(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),Gr=e=>sn(e)&&sn(e.cache_control)?
27
- e.cache_control:null,Pu=8;function Bn(e,t,n,r){if(!(!Array.isArray(e)||r>Pu))for(let o of e){let i=Gr(o);if(i&&n(i,t),!sn(o))continue;Array.isArray(o.content)&&Bn(o.content,t,n,r+1);let s=o.source;sn(
28
- s)&&s.type==="content"&&Array.isArray(s.content)&&Bn(s.content,t,n,r+1);}}function Xr(e,t){let n=Gr(e);if(n&&t(n,"raiz"),Bn(e.system,"system",t,0),Array.isArray(e.tools))for(let r of e.tools){let o=Gr(
29
- r);o&&t(o,"tools");}if(Array.isArray(e.messages)){let r=e.messages.length-1;e.messages.forEach((o,i)=>{sn(o)&&Bn(o.content,i===r?"ultimoMensaje":"mensaje",t,0);});}}function Qr(e,t){let n=Buffer.isBuffer(
30
- e)?st(e,t):e;if(n===null)return null;try{let r={rebajadas:0,yaEran5m:0};return Xr(n,o=>Iu(o,r)),r.rebajadas===0?null:{cuerpo:Buffer.from(JSON.stringify(n),"utf8"),rebajadas:r.rebajadas,yaEran5m:r.yaEran5m,
31
- herramientaDeServidor:Kr(n)}}catch{return null}}function Du(e){let{cacheEscrita5m:t,inputPer1k:n,yaEran5m:r,herramientaDeServidor:o}=e;return r>0||o||t<=0||n<=0?0:t/1e3*n*(Eu-Su)}function as(e,t,n){return e.
32
- rebajadas<=0?0:Du({cacheEscrita5m:t,inputPer1k:n,yaEran5m:e.yaEran5m,herramientaDeServidor:e.herramientaDeServidor})}var Un=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 us(e){return e===void 0||e.trim()===""?Fn:e.split(",").map(n=>n.trim()).filter(
18
+ n=>n.length>0).includes(Fn)?e:`${e},${Fn}`}function ds(e){let t=e.toLowerCase(),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Eu(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=ds(e);return t.startsWith("gpt-")||t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4")?Eu(t)?1.25:1:t.startsWith("gemini")?1:1.25}function Ut(e){let t=e.toLowerCase();return t.startsWith("claude")||t.startsWith("anthropic/")||ds(t).startsWith("claude")?2:ve(e)}var Cu=1.25,Ru=2,Au=.3,Tu=/^(custom|bash_|text_editor_|computer_|browser_|memory_)/;function Xr(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"&&!Tu.test(n)}):false}var Iu=4096,Pu=(e,t)=>e==="cache_control"?void 0:t;function Kr(e){return e===void 0?"":JSON.stringify(e,Pu)??
21
+ ""}function Du(e){return Array.isArray(e)?e.filter(t=>!(t!==null&&typeof t=="object"&&t.defer_loading===true)):e}function Jr(e){return createHash("sha1").update(e).digest("base64url").slice(0,16)}function st(e,t){
22
+ let n=zn(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 Zr(e){let t=Kr(e.system),n=Kr(Du(e.tools)),
23
+ r=Array.isArray(e.messages)?e.messages.slice(0,Iu):[],o=[],i=[];for(let s of r){let a=Kr(s);o.push(Jr(a)),i.push(Buffer.byteLength(a,"utf8"));}return {system:Jr(t),tools:Jr(n),mensajes:o,bytes:i,bytesFijos:Buffer.
24
+ byteLength(t,"utf8")+Buffer.byteLength(n,"utf8")}}function Qr(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 eo(e){let{fraccionNueva:t,umbral:n=Au}=e;
26
+ return t>=n}function Ou(e,t){e.ttl==="1h"?(e.ttl="5m",t.rebajadas++):(e.ttl==="5m"||e.ttl===void 0)&&t.yaEran5m++;}var ln=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Yr=e=>ln(e)&&ln(e.cache_control)?
27
+ e.cache_control:null,Lu=8;function Vn(e,t,n,r){if(!(!Array.isArray(e)||r>Lu))for(let o of e){let i=Yr(o);if(i&&n(i,t),!ln(o))continue;Array.isArray(o.content)&&Vn(o.content,t,n,r+1);let s=o.source;ln(
28
+ s)&&s.type==="content"&&Array.isArray(s.content)&&Vn(s.content,t,n,r+1);}}function to(e,t){let n=Yr(e);if(n&&t(n,"raiz"),Vn(e.system,"system",t,0),Array.isArray(e.tools))for(let r of e.tools){let o=Yr(
29
+ r);o&&t(o,"tools");}if(Array.isArray(e.messages)){let r=e.messages.length-1;e.messages.forEach((o,i)=>{ln(o)&&Vn(o.content,i===r?"ultimoMensaje":"mensaje",t,0);});}}function no(e,t){let n=Buffer.isBuffer(
30
+ e)?st(e,t):e;if(n===null)return null;try{let r={rebajadas:0,yaEran5m:0};return to(n,o=>Ou(o,r)),r.rebajadas===0?null:{cuerpo:Buffer.from(JSON.stringify(n),"utf8"),rebajadas:r.rebajadas,yaEran5m:r.yaEran5m,
31
+ herramientaDeServidor:Xr(n)}}catch{return null}}function $u(e){let{cacheEscrita5m:t,inputPer1k:n,yaEran5m:r,herramientaDeServidor:o}=e;return r>0||o||t<=0||n<=0?0:t/1e3*n*(Ru-Cu)}function ps(e,t,n){return e.
32
+ rebajadas<=0?0:$u({cacheEscrita5m:t,inputPer1k:n,yaEran5m:e.yaEran5m,herramientaDeServidor:e.herramientaDeServidor})}var qn=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 eo="mid-conversation-output-config-2026-07-01",Vn=["low","medium","high","xhigh","max"],Ou=new Set(["claude-fable-5-1","claude-mythos-5-1","claude-opus-5-5","claude-opus-5"]),cs={"claude-fable-5-1":"\
35
- high","claude-mythos-5-1":"high","claude-opus-5-5":"medium","claude-opus-5":"high"};function Lu(e){return us(e)?cs[e]:void 0}function ls(e,t){let n=Lu(e);return n!==void 0&&Vn.indexOf(t)<Vn.indexOf(n)}
36
- var Fn=Vn.filter(e=>Object.keys(cs).some(t=>ls(t,e)));function us(e){return Ou.has(e)}function to(e){return e!==void 0&&Vn.includes(e)}function $u(e){return {role:"system",content:[],output_config:{effort:e}}}
37
- function Mu(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 ds(e,t,n){
38
- let r=st(e,n);if(r===null||typeof r.model!="string"||!us(r.model)||!ls(r.model,t)||Mu(r))return null;let o=r.messages;return Array.isArray(o)?(r.messages=[...o,$u(t)],{cuerpo:Buffer.from(JSON.stringify(
39
- r),"utf8"),nivel:t}):null}function ps(e){return e===void 0||e.trim()===""?eo:e.split(",").map(n=>n.trim()).includes(eo)?e:`${e},${eo}`}function fs(e,t,n){return e===void 0||e===""?{linea:`per-turn eff\
40
- ort: OFF (BVSALA_GATEWAY_EFFORT=${Fn.join("|")} turns it on)`,aviso:false}:to(e)?Fn.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 ro="mid-conversation-output-config-2026-07-01",Wn=["low","medium","high","xhigh","max"],Mu=new Set(["claude-fable-5-1","claude-mythos-5-1","claude-opus-5-5","claude-opus-5"]),fs={"claude-fable-5-1":"\
35
+ high","claude-mythos-5-1":"high","claude-opus-5-5":"medium","claude-opus-5":"high"};function Nu(e){return hs(e)?fs[e]:void 0}function ms(e,t){let n=Nu(e);return n!==void 0&&Wn.indexOf(t)<Wn.indexOf(n)}
36
+ var Gn=Wn.filter(e=>Object.keys(fs).some(t=>ms(t,e)));function hs(e){return Mu.has(e)}function oo(e){return e!==void 0&&Wn.includes(e)}function ju(e){return {role:"system",content:[],output_config:{effort:e}}}
37
+ function Bu(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 gs(e,t,n){
38
+ let r=st(e,n);if(r===null||typeof r.model!="string"||!hs(r.model)||!ms(r.model,t)||Bu(r))return null;let o=r.messages;return Array.isArray(o)?(r.messages=[...o,ju(t)],{cuerpo:Buffer.from(JSON.stringify(
39
+ r),"utf8"),nivel:t}):null}function bs(e){return e===void 0||e.trim()===""?ro:e.split(",").map(n=>n.trim()).includes(ro)?e:`${e},${ro}`}function vs(e,t,n){return e===void 0||e===""?{linea:`per-turn eff\
40
+ ort: OFF (BVSALA_GATEWAY_EFFORT=${Gn.join("|")} turns it on)`,aviso:false}:oo(e)?Gn.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 ${Fn.join(" or ")}`,aviso:true}:{linea:`per-turn effort: NOT ARMED \u2014 "${e}" is not a level. Use one of: ${Fn.
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 ${Gn.join(" or ")}`,aviso:true}:{linea:`per-turn effort: NOT ARMED \u2014 "${e}" is not a level. Use one of: ${Gn.
45
+ join(", ")}`,aviso:true}}var dn={"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,29 +64,29 @@ 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
- Nu={"gemini-3.8-flash":{vigenteHasta:"2027-01-01"},"gemini-3.7-flash":{vigenteHasta:"2027-01-01"},"gemini-3.6-flash":{vigenteHasta:"2027-01-01"}},ju={"gemini-3.8-flash":[{vigenteDesde:"2027-01-01",precio:{
67
+ Uu={"gemini-3.8-flash":{vigenteHasta:"2027-01-01"},"gemini-3.7-flash":{vigenteHasta:"2027-01-01"},"gemini-3.6-flash":{vigenteHasta:"2027-01-01"}},Fu={"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}}]},Bu=Object.fromEntries(Object.keys(cn).map(e=>[e,[{...Nu[e],precio:cn[e]},...ju[e]??[]]]));var Uu=864e13;function ms(e){let t=e instanceof Date?e.getTime():e,n=typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<=Uu?t:Date.now();return new Date(n).toISOString().slice(0,10)}function hs(e,t){
70
- for(let n of Bu[e]??[])if(!(n.vigenteDesde!==void 0&&t<n.vigenteDesde)&&!(n.vigenteHasta!==void 0&&t>=n.vigenteHasta))return n.precio}function gs(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 ro(e){return Object.keys(e).sort((t,n)=>n.length-t.length)}var zu=["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"],no={...cn,...Object.
73
- fromEntries(zu.map(e=>[e,null]))},Fu=ro(no);function Oe(e,t){let n=gt(e);return n===void 0?void 0:hs(n,ms(t))}var Vu=Object.fromEntries(Object.keys(no).map(e=>[e,no[e]===null?null:e]));function gt(e){
74
- return gs(Vu,Fu,e)??void 0}var qu=/^\d{4}-?\d{2}-?\d{2}$/;function jt(e,t){let n=gt(e);if(n===void 0)return;let r=e.lastIndexOf("/"),o=r>=0?e.slice(r+1):e;if(!(n!==e&&n!==o&&!qu.test(o.slice(n.length+
75
- 1))))return hs(n,ms(t))}var bs={"claude-fable-5":"claude-fable-5-1"};function Hu(e,t){let n=Oe(e),r=Oe(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 Wu(e){let t=gt(e);if(t===void 0||t!==e)return null;let n=bs[t];return n===void 0||n===t||!Hu(t,n)?null:{solicitado:e,
77
- servido:n}}var Gu=/(^|,)\s*context-1m/i;function Ku(e){let t=e.tool_choice;if(t===null||typeof t!="object")return false;let n=t.type;return n==="any"||n==="tool"}function oo(e,t,n={}){if(n.betas!==void 0&&
78
- Gu.test(n.betas))return null;let r=st(e,t);if(r===null||Ku(r))return null;let o=Wu(r.model);return o===null?null:(r.model=o.servido,{cuerpo:Buffer.from(JSON.stringify(r),"utf8"),cambio:o})}function vs(e,t,n){
79
- let r=Object.entries(bs).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}}]},zu=Object.fromEntries(Object.keys(dn).map(e=>[e,[{...Uu[e],precio:dn[e]},...Fu[e]??[]]]));var Vu=864e13;function ys(e){let t=e instanceof Date?e.getTime():e,n=typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<=Vu?t:Date.now();return new Date(n).toISOString().slice(0,10)}function ks(e,t){
70
+ for(let n of zu[e]??[])if(!(n.vigenteDesde!==void 0&&t<n.vigenteDesde)&&!(n.vigenteHasta!==void 0&&t>=n.vigenteHasta))return n.precio}function ws(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 so(e){return Object.keys(e).sort((t,n)=>n.length-t.length)}var qu=["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"],io={...dn,...Object.
73
+ fromEntries(qu.map(e=>[e,null]))},Hu=so(io);function Oe(e,t){let n=bt(e);return n===void 0?void 0:ks(n,ys(t))}var Gu=Object.fromEntries(Object.keys(io).map(e=>[e,io[e]===null?null:e]));function bt(e){
74
+ return ws(Gu,Hu,e)??void 0}var Wu=/^\d{4}-?\d{2}-?\d{2}$/;function Ft(e,t){let n=bt(e);if(n===void 0)return;let r=e.lastIndexOf("/"),o=r>=0?e.slice(r+1):e;if(!(n!==e&&n!==o&&!Wu.test(o.slice(n.length+
75
+ 1))))return ks(n,ys(t))}var xs={"claude-fable-5":"claude-fable-5-1"};function Ku(e,t){let n=Oe(e),r=Oe(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 Ju(e){let t=bt(e);if(t===void 0||t!==e)return null;let n=xs[t];return n===void 0||n===t||!Ku(t,n)?null:{solicitado:e,
77
+ servido:n}}var Yu=/(^|,)\s*context-1m/i;function Xu(e){let t=e.tool_choice;if(t===null||typeof t!="object")return false;let n=t.type;return n==="any"||n==="tool"}function ao(e,t,n={}){if(n.betas!==void 0&&
78
+ Yu.test(n.betas))return null;let r=st(e,t);if(r===null||Xu(r))return null;let o=Ju(r.model);return o===null?null:(r.model=o.servido,{cuerpo:Buffer.from(JSON.stringify(r),"utf8"),cambio:o})}function Ss(e,t,n){
79
+ let r=Object.entries(xs).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 ys=new Set;function Q(e,t){ys.has(e)||(ys.add(e),console.warn(t));}var ye="0.4.33",io="x-bvsala-version";var Bt=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 Es=new Set;function Q(e,t){Es.has(e)||(Es.add(e),console.warn(t));}var ye="0.4.35",co="x-bvsala-version";var vt=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=Ju(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=Zu(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}`,[io]:`${this.options.surface??"sdk"}/${ye}`},body:JSON.stringify(r)});o.ok?this.fallosSeguidos=0:o.status>=500?(this.fallosSeguidos++,
89
+ e":"application/json",authorization:`Bearer ${this.options.serviceAccountKey}`,[co]:`${this.options.surface??"sdk"}/${ye}`},body:JSON.stringify(r)});o.ok?this.fallosSeguidos=0:o.status>=500?(this.fallosSeguidos++,
90
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\
@@ -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}:{},...Yu(n),baselineCost:n.cost.baselineEstimate,actualCost:n.cost.actual,netSavings:n.cost.netSavings,...n.cost.basis?{basis:n.cost.basis}:{},...n.cost.basis==="referen\
100
+ cost.eliminatedInputFloorCost}:{},...Qu(n),baselineCost:n.cost.baselineEstimate,actualCost:n.cost.actual,netSavings:n.cost.netSavings,...n.cost.basis?{basis:n.cost.basis}:{},...n.cost.basis==="referen\
101
101
  ce"&&n.cache.reference&&/^[A-Za-z0-9._:/-]{1,128}$/.test(n.cache.reference.requestId)&&Number.isInteger(n.cache.reference.at)?{referenceRequestId:n.cache.reference.requestId,referenceAt:n.cache.reference.
102
- at}:{},...n.attribution?.sessionId?{sessionId:n.attribution.sessionId}:{},...n.attribution?.agentId?{agentId:n.attribution.agentId}:{}}}};function Ju(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 Zu(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,netSavings:s,netSavingsRatio:s,netSavingsUsd:o-i,basis:"shadow"}}}function Yu(e){
104
+ o):0,{measure:a,nativeSavings:c,...l}=e;return {...l,requestId:r,cache:{...e.cache,result:"miss"},cost:{baselineEstimate:o,actual:i,netSavings:s,netSavingsRatio:s,netSavingsUsd:o-i,basis:"shadow"}}}function Qu(e){
105
105
  let t=e.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.
106
- readDiscountUsd>0?{nativeCacheReadSavings:t.readDiscountUsd}:{},...t.writePremiumUsd>0?{nativeCacheWritePremium:t.writePremiumUsd}:{}}}function qn(){return globalThis.process}function Zu(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 Xu(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 Qu(){if(qn()?.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 ed(e,t=Qu){
109
- if(e.KUBERNETES_SERVICE_HOST||Xu(e))return;let n=e.HOSTNAME??e.COMPUTERNAME??await t();if(!(!n||Zu(n)))return n}async function td(){let e=qn();if(!e||!e.env)return;let t=e.env,n=await ed(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 nd=["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 Hn(){let e=qn()?.env;if(!e)
112
- return false;for(let t of nd){let n=e[t];if(n&&n!=="false"&&n!=="0")return true}return false}async function rd(e,t){let n=globalThis.crypto,r=new TextEncoder;if(n?.subtle)try{let s=await n.subtle.importKey("raw",
106
+ readDiscountUsd>0?{nativeCacheReadSavings:t.readDiscountUsd}:{},...t.writePremiumUsd>0?{nativeCacheWritePremium:t.writePremiumUsd}:{}}}function Kn(){return globalThis.process}function ed(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 td(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 nd(){if(Kn()?.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 rd(e,t=nd){
109
+ if(e.KUBERNETES_SERVICE_HOST||td(e))return;let n=e.HOSTNAME??e.COMPUTERNAME??await t();if(!(!n||ed(n)))return n}async function od(){let e=Kn();if(!e||!e.env)return;let t=e.env,n=await rd(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 id=["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 pn(){let e=Kn()?.env;if(!e)
112
+ return false;for(let t of id){let n=e[t];if(n&&n!=="false"&&n!=="0")return true}return false}async function sd(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 Wn(e){let n=qn()?.env?.BVSALA_SEAT_ID;if(n&&od.test(n))return n;let r=await td();
115
- if(!r)return;let o=await rd(e,r);if(o)return `m-${o.slice(0,32)}`}var od=/^[A-Za-z0-9._:/-]{1,128}$/;function so(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Gn(e,t=""){if(typeof e!="number"){let n=t&&
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 fn(e){let n=Kn()?.env?.BVSALA_SEAT_ID;if(n&&ad.test(n))return n;let r=await od();
115
+ if(!r)return;let o=await sd(e,r);if(o)return `m-${o.slice(0,32)}`}var ad=/^[A-Za-z0-9._:/-]{1,128}$/;function lo(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
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 Le(e,t,n=""){
117
- let r=so(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 ao(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 ws(e,t){Le(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 Kn(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var xs=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",id=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Jn(e){if(Le(e),xs)return e.toHex();
120
- let t="";for(let n=0;n<e.length;n++)t+=id[e[n]];return t}var Xe={_0:48,_9:57,A:65,F:70,a:97,f:102};function ks(e){if(e>=Xe._0&&e<=Xe._9)return e-Xe._0;if(e>=Xe.A&&e<=Xe.F)return e-(Xe.A-10);if(e>=Xe.a&&
121
- e<=Xe.f)return e-(Xe.a-10)}function un(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);if(xs)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=ks(e.charCodeAt(
123
- i)),a=ks(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 co(...e){let t=0;for(let r=0;r<e.length;r++){let o=e[r];Le(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 Ss(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 Es(e=32){
124
- Gn(e,"bytesLength");let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(e>65536)throw new RangeError(
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 Yn=class{blockLen;outputLen;canXOF=false;padOffset;isLE;buffer;view;finished=false;length=0;pos=0;destroyed=false;constructor(t,n,r,o){this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=
126
- new Uint8Array(t),this.view=Kn(this.buffer);}update(t){ao(this),Le(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=Kn(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){ao(this),
128
- ws(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=Kn(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\
117
+ let r=lo(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 uo(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 Cs(e,t){Le(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 mn(...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 Rs=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",cd=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Xn(e){if(Le(e),Rs)return e.toHex();
120
+ let t="";for(let n=0;n<e.length;n++)t+=cd[e[n]];return t}var Ze={_0:48,_9:57,A:65,F:70,a:97,f:102};function _s(e){if(e>=Ze._0&&e<=Ze._9)return e-Ze._0;if(e>=Ze.A&&e<=Ze.F)return e-(Ze.A-10);if(e>=Ze.a&&
121
+ e<=Ze.f)return e-(Ze.a-10)}function hn(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);if(Rs)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=_s(e.charCodeAt(
123
+ i)),a=_s(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 po(...e){let t=0;for(let r=0;r<e.length;r++){let o=e[r];Le(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 As(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 Is=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});var Zn=class{blockLen;outputLen;canXOF=false;padOffset;isLE;buffer;view;finished=false;length=0;pos=0;destroyed=false;constructor(t,n,r,o){this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=
126
+ new Uint8Array(t),this.view=Yn(this.buffer);}update(t){uo(this),Le(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){uo(this),
128
+ Cs(t,this),this.finished=true;let{buffer:n,view:r,blockLen:o,isLE:i}=this,{pos:s}=this;n[s++]=128,mn(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
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 Zn=BigInt(4294967295),Cs=BigInt(32);function sd(e,t=false){return t?{h:Number(e&Zn),l:Number(e>>Cs&Zn)}:{h:Number(e>>Cs&Zn)|0,l:Number(e&Zn)|0}}function As(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}=sd(e[i],t);[r[i],o[i]]=[s,a];}return [r,o]}var lo=(e,t,n)=>e>>>n,uo=(e,t,n)=>e<<32-n|t>>>n,bt=(e,t,n)=>e>>>n|t<<32-n,vt=(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 Be(e,t,n,r){let o=(t>>>0)+(r>>>0);return {h:e+n+(o/2**32|0)|0,l:o|0}}var Ts=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Rs=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Is=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Ps=(e,t,n,r,o)=>t+
133
- n+r+o+(e/2**32|0)|0,Ds=(e,t,n,r,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(o>>>0),Os=(e,t,n,r,o,i)=>t+n+r+o+i+(e/2**32|0)|0;var Ls=As(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242",
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),Ps=BigInt(32);function ld(e,t=false){return t?{h:Number(e&Qn),l:Number(e>>Ps&Qn)}:{h:Number(e>>Ps&Qn)|0,l:Number(e&Qn)|0}}function Ds(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}=ld(e[i],t);[r[i],o[i]]=[s,a];}return [r,o]}var fo=(e,t,n)=>e>>>n,mo=(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,gn=(e,t,n)=>e<<64-n|t>>>n-32,bn=(e,t,n)=>e>>>n-32|t<<64-n;function Be(e,t,n,r){let o=(t>>>0)+(r>>>0);return {h:e+n+(o/2**32|0)|0,l:o|0}}var Os=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Ls=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,$s=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Ms=(e,t,n,r,o)=>t+
133
+ n+r+o+(e/2**32|0)|0,Ns=(e,t,n,r,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(o>>>0),js=(e,t,n,r,o,i)=>t+n+r+o+i+(e/2**32|0)|0;var Bs=Ds(["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,153 +138,153 @@ 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))),cd=Ls[0],ld=Ls[1],at=new Uint32Array(80),ct=new Uint32Array(80),po=class extends Yn{constructor(t){
141
+ 00d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),dd=Bs[0],pd=Bs[1],at=new Uint32Array(80),ct=new Uint32Array(80),ho=class extends Zn{constructor(t){
142
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:v,Hl:g}=this;return [t,n,r,o,i,s,a,c,l,p,u,f,m,b,v,g]}set(t,n,r,o,i,s,a,c,l,p,u,f,m,b,v,g){this.Ah=
143
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=v|0,this.Hl=g|0;}process(t,n){for(let S=0;S<
144
- 16;S++,n+=4)at[S]=t.getUint32(n),ct[S]=t.getUint32(n+=4);for(let S=16;S<80;S++){let y=at[S-15]|0,I=ct[S-15]|0,D=bt(y,I,1)^bt(y,I,8)^lo(y,I,7),O=vt(y,I,1)^vt(y,I,8)^uo(y,I,7),$=at[S-2]|0,B=ct[S-2]|0,Z=bt(
145
- $,B,19)^dn($,B,61)^lo($,B,6),ne=vt($,B,19)^pn($,B,61)^uo($,B,6),C=Is(O,ne,ct[S-7],ct[S-16]),R=Ps(C,D,Z,at[S-7],at[S-16]);at[S]=R|0,ct[S]=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,
146
- Fl:b,Gh:v,Gl:g,Hh:k,Hl:x}=this;for(let S=0;S<80;S++){let y=bt(u,f,14)^bt(u,f,18)^dn(u,f,41),I=vt(u,f,14)^vt(u,f,18)^pn(u,f,41),D=u&m^~u&v,O=f&b^~f&g,$=Ds(x,I,O,ld[S],ct[S]),B=Os($,k,y,D,cd[S],at[S]),Z=$|
147
- 0,ne=bt(r,o,28)^dn(r,o,34)^dn(r,o,39),C=vt(r,o,28)^pn(r,o,34)^pn(r,o,39),R=r&i^r&a^i&a,M=o&s^o&c^s&c;k=v|0,x=g|0,v=m|0,g=b|0,m=u|0,b=f|0,{h:u,l:f}=Be(l|0,p|0,B|0,Z|0),l=a|0,p=c|0,a=i|0,c=s|0,i=r|0,s=o|
148
- 0;let j=Ts(Z,C,M);r=Rs(j,B,ne,R),o=j|0;}(({h:r,l:o}=Be(this.Ah|0,this.Al|0,r|0,o|0))),{h:i,l:s}=Be(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Be(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:p}=Be(this.Dh|0,this.Dl|0,
144
+ 16;S++,n+=4)at[S]=t.getUint32(n),ct[S]=t.getUint32(n+=4);for(let S=16;S<80;S++){let y=at[S-15]|0,I=ct[S-15]|0,D=yt(y,I,1)^yt(y,I,8)^fo(y,I,7),O=kt(y,I,1)^kt(y,I,8)^mo(y,I,7),$=at[S-2]|0,B=ct[S-2]|0,X=yt(
145
+ $,B,19)^gn($,B,61)^fo($,B,6),ne=kt($,B,19)^bn($,B,61)^mo($,B,6),C=$s(O,ne,ct[S-7],ct[S-16]),T=Ms(C,D,X,at[S-7],at[S-16]);at[S]=T|0,ct[S]=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,
146
+ Fl:b,Gh:v,Gl:g,Hh:k,Hl:x}=this;for(let S=0;S<80;S++){let y=yt(u,f,14)^yt(u,f,18)^gn(u,f,41),I=kt(u,f,14)^kt(u,f,18)^bn(u,f,41),D=u&m^~u&v,O=f&b^~f&g,$=Ns(x,I,O,pd[S],ct[S]),B=js($,k,y,D,dd[S],at[S]),X=$|
147
+ 0,ne=yt(r,o,28)^gn(r,o,34)^gn(r,o,39),C=kt(r,o,28)^bn(r,o,34)^bn(r,o,39),T=r&i^r&a^i&a,M=o&s^o&c^s&c;k=v|0,x=g|0,v=m|0,g=b|0,m=u|0,b=f|0,{h:u,l:f}=Be(l|0,p|0,B|0,X|0),l=a|0,p=c|0,a=i|0,c=s|0,i=r|0,s=o|
148
+ 0;let j=Os(X,C,M);r=Ls(j,B,ne,T),o=j|0;}(({h:r,l:o}=Be(this.Ah|0,this.Al|0,r|0,o|0))),{h:i,l:s}=Be(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Be(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:p}=Be(this.Dh|0,this.Dl|0,
149
149
  l|0,p|0),{h:u,l:f}=Be(this.Eh|0,this.El|0,u|0,f|0),{h:m,l:b}=Be(this.Fh|0,this.Fl|0,m|0,b|0),{h:v,l:g}=Be(this.Gh|0,this.Gl|0,v|0,g|0),{h:k,l:x}=Be(this.Hh|0,this.Hl|0,k|0,x|0),this.set(r,o,i,s,a,c,l,
150
- p,u,f,m,b,v,g,k,x);}roundClean(){ln(at,ct);}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);}},fo=class extends po{Ah=ue[0]|0;Al=ue[1]|0;Bh=ue[2]|0;Bl=ue[3]|0;Ch=ue[4]|
151
- 0;Cl=ue[5]|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 Xn=Ss(()=>new fo,_s(3));var ie=(e,t,n)=>Le(e,t,n),ho=Gn,go=Jn,Ue=(...e)=>co(...e),$s=e=>un(e),tr=so,Ms=e=>Es(e),er=BigInt(0),mo=BigInt(1);function Ut(e,t=""){if(typeof e!="boolean"){let n=t&&`"${t}" `;throw new TypeError(n+"\
152
- expected boolean, got type="+typeof e)}return e}function ud(e){if(typeof e=="bigint"){if(!Qn(e))throw new RangeError("positive bigint expected, got "+e)}else ho(e);return e}function Qe(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 Ns(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);return e===""?er:BigInt("0x"+e)}function bo(e){return Ns(Jn(e))}function et(e){return Ns(Jn(fn(Le(e)).reverse()))}
154
- function vo(e,t){if(Gn(t),t===0)throw new RangeError("zero length");e=ud(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 js(e,t){
155
- return vo(e,t).reverse()}function Bs(e,t){if(e=ie(e),t=ie(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(ie(e))}var Qn=e=>typeof e=="bigint"&&er<=e;function dd(e,t,n){return Qn(e)&&Qn(t)&&Qn(n)&&t<=e&&e<n}function yo(e,t,n,r){if(!dd(t,n,r))throw new RangeError(
156
- "expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function ko(e){if(e<er)throw new Error("expected non-negative bigint, got "+e);let t;for(t=0;e>er;e>>=mo,t+=1);return t}var Us=e=>(mo<<BigInt(e))-mo;function yt(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(
150
+ p,u,f,m,b,v,g,k,x);}roundClean(){mn(at,ct);}destroy(){this.destroyed=true,mn(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}},go=class extends ho{Ah=ue[0]|0;Al=ue[1]|0;Bh=ue[2]|0;Bl=ue[3]|0;Ch=ue[4]|
151
+ 0;Cl=ue[5]|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=As(()=>new go,Is(3));var ie=(e,t,n)=>Le(e,t,n),vo=Jn,yo=Xn,Ue=(...e)=>po(...e),Us=e=>hn(e),rr=lo,Fs=e=>Ts(e),nr=BigInt(0),bo=BigInt(1);function zt(e,t=""){if(typeof e!="boolean"){let n=t&&`"${t}" `;throw new TypeError(n+"\
152
+ expected boolean, got type="+typeof e)}return e}function fd(e){if(typeof e=="bigint"){if(!tr(e))throw new RangeError("positive bigint expected, got "+e)}else vo(e);return e}function Qe(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 zs(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);return e===""?nr:BigInt("0x"+e)}function ko(e){return zs(Xn(e))}function et(e){return zs(Xn(vn(Le(e)).reverse()))}
154
+ function wo(e,t){if(Jn(t),t===0)throw new RangeError("zero length");e=fd(e);let n=e.toString(16);if(n.length>t*2)throw new RangeError("number too large");return hn(n.padStart(t*2,"0"))}function Vs(e,t){
155
+ return wo(e,t).reverse()}function qs(e,t){if(e=ie(e),t=ie(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 vn(e){return Uint8Array.from(ie(e))}var tr=e=>typeof e=="bigint"&&nr<=e;function md(e,t,n){return tr(e)&&tr(t)&&tr(n)&&t<=e&&e<n}function xo(e,t,n,r){if(!md(t,n,r))throw new RangeError(
156
+ "expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function So(e){if(e<nr)throw new Error("expected non-negative bigint, got "+e);let t;for(t=0;e>nr;e>>=bo,t+=1);return t}var Hs=e=>(bo<<BigInt(e))-bo;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(
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 wo=()=>{throw new Error("not implemented")};var de=BigInt(0),ae=BigInt(1),kt=BigInt(2),qs=BigInt(3),Hs=BigInt(4),Ws=BigInt(5),pd=BigInt(7),Gs=BigInt(8),fd=BigInt(9),Ks=BigInt(16);function te(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 $e(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 zs(e,t){if(e===de)throw new Error("invert: expected non-zer\
158
+ entries(i).forEach(([a,c])=>r(a,c,s));o(t,false),o(n,true);}var Eo=()=>{throw new Error("not implemented")};var de=BigInt(0),ae=BigInt(1),xt=BigInt(2),Js=BigInt(3),Ys=BigInt(4),Xs=BigInt(5),hd=BigInt(7),Zs=BigInt(8),gd=BigInt(9),Qs=BigInt(16);function te(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 $e(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 Gs(e,t){if(e===de)throw new Error("invert: expected non-zer\
160
160
  o number");if(t<=de)throw new Error("invert: expected positive modulus, got "+t);let n=te(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 te(o,t)}function xo(e,t,n){let r=e;if(!r.eql(r.sqr(t),n))throw new Error("Cannot find square root")}function Js(e,t){let n=e,r=(n.ORDER+ae)/Hs,o=n.pow(
162
- t,r);return xo(n,o,t),o}function md(e,t){let n=e,r=(n.ORDER-Ws)/Gs,o=n.mul(t,kt),i=n.pow(o,r),s=n.mul(t,i),a=n.mul(n.mul(s,kt),i),c=n.mul(s,n.sub(a,n.ONE));return xo(n,c,t),c}function hd(e){let t=ir(e),
163
- n=Ys(e),r=n(t,t.neg(t.ONE)),o=n(t,r),i=n(t,t.neg(r)),s=(e+pd)/Ks;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),v=l.eql(l.sqr(f),c);p=l.cmov(p,u,b),u=l.
164
- cmov(m,f,v);let g=l.eql(l.sqr(u),c),k=l.cmov(p,u,g);return xo(l,k,c),k})}function Ys(e){if(e<qs)throw new Error("sqrt is not defined for small field");let t=e-ae,n=0;for(;t%kt===de;)t/=kt,n++;let r=kt,
165
- o=ir(e);for(;Fs(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Js;let i=o.pow(r,t),s=(t+ae)/kt;return function(c,l){let p=c;if(p.is0(l))return l;
166
- if(Fs(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 v=1,g=p.sqr(m);for(;!p.eql(g,p.ONE);)if(v++,
167
- g=p.sqr(g),v===u)throw new Error("Cannot find square root");let k=ae<<BigInt(u-v-1),x=p.pow(f,k);u=v,f=p.sqr(x),m=p.mul(m,f),b=p.mul(b,x);}return b}}function gd(e){return e%Hs===qs?Js:e%Gs===Ws?md:e%Ks===
168
- fd?hd(e):Ys(e)}var tt=(e,t)=>(te(e,t)&ae)===ae,bd=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Zs(e){let t={ORDER:"bigin\
169
- t",BYTES:"number",BITS:"number"},n=bd.reduce((r,o)=>(r[o]="function",r),t);if(yt(e,n),Qe(e.BYTES,"BYTES"),Qe(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 vd(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 or(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 Fs(e,t){let n=e,r=(n.ORDER-ae)/kt,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 yd(e,t){if(t!==void 0&&ho(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=ko(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 Vs=new WeakMap,
174
- rr=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.
161
+ throw new Error("invert: does not exist");return te(o,t)}function _o(e,t,n){let r=e;if(!r.eql(r.sqr(t),n))throw new Error("Cannot find square root")}function ea(e,t){let n=e,r=(n.ORDER+ae)/Ys,o=n.pow(
162
+ t,r);return _o(n,o,t),o}function bd(e,t){let n=e,r=(n.ORDER-Xs)/Zs,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 _o(n,c,t),c}function vd(e){let t=ar(e),
163
+ n=ta(e),r=n(t,t.neg(t.ONE)),o=n(t,r),i=n(t,t.neg(r)),s=(e+hd)/Qs;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),v=l.eql(l.sqr(f),c);p=l.cmov(p,u,b),u=l.
164
+ cmov(m,f,v);let g=l.eql(l.sqr(u),c),k=l.cmov(p,u,g);return _o(l,k,c),k})}function ta(e){if(e<Js)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(;Ws(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return ea;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(Ws(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 v=1,g=p.sqr(m);for(;!p.eql(g,p.ONE);)if(v++,
167
+ g=p.sqr(g),v===u)throw new Error("Cannot find square root");let k=ae<<BigInt(u-v-1),x=p.pow(f,k);u=v,f=p.sqr(x),m=p.mul(m,f),b=p.mul(b,x);}return b}}function yd(e){return e%Ys===Js?ea:e%Zs===Xs?bd:e%Qs===
168
+ gd?vd(e):ta(e)}var tt=(e,t)=>(te(e,t)&ae)===ae,kd=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function na(e){let t={ORDER:"bigin\
169
+ t",BYTES:"number",BITS:"number"},n=kd.reduce((r,o)=>(r[o]="function",r),t);if(wt(e,n),Qe(e.BYTES,"BYTES"),Qe(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 wd(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 Ws(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 xd(e,t){if(t!==void 0&&vo(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=So(e);if(t!==void 0&&t<n)throw new Error(`invalid n length: expected bit length (${n}) >= n.length (${t})`);let r=t!==void 0?t:n,o=Math.ceil(r/8);return {nBitLength:r,nByteLength:o}}var Ks=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.
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}=yd(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}=xd(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 te(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new TypeError("invalid field element: expected bigint, go\
178
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 te(-t,this.ORDER)}eql(t,n){return t===n}sqr(t){
179
- return te(t*t,this.ORDER)}add(t,n){return te(t+n,this.ORDER)}sub(t,n){return te(t-n,this.ORDER)}mul(t,n){return te(t*n,this.ORDER)}pow(t,n){return vd(this,t,n)}div(t,n){return te(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=Vs.get(this);return n||Vs.set(this,n=gd(this.ORDER)),n(this,t)}toBytes(t){
181
- return this.isLE?js(t,this.BYTES):vo(t,this.BYTES)}fromBytes(t,n=false){ie(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\
179
+ return te(t*t,this.ORDER)}add(t,n){return te(t+n,this.ORDER)}sub(t,n){return te(t-n,this.ORDER)}mul(t,n){return te(t*n,this.ORDER)}pow(t,n){return wd(this,t,n)}div(t,n){return te(t*Gs(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 Gs(t,this.ORDER)}sqrt(t){let n=Ks.get(this);return n||Ks.set(this,n=yd(this.ORDER)),n(this,t)}toBytes(t){
181
+ return this.isLE?Vs(t,this.BYTES):wo(t,this.BYTES)}fromBytes(t,n=false){ie(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?et(t):bo(t);if(a&&(c=te(c,s)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return or(this,t)}cmov(t,n,r){return Ut(r,"condit\
184
- ion"),r?n:t}};Object.freeze(rr.prototype);function ir(e,t={}){return new rr(e,t)}var sr=BigInt(0),Co=BigInt(1);function Xs(e,t){let n=t.negate();return e?n:t}function cr(e,t){let n=or(e.Fp,t.map(r=>r.Z));return t.map((r,o)=>e.fromAffine(r.toAffine(n[o])))}function na(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)
185
- throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function So(e,t){na(e,t);let n=Math.ceil(t/e)+1,r=2**(e-1),o=2**e,i=Us(e),s=BigInt(e);return {windows:n,windowSize:r,mask:i,maxNumber:o,
186
- shiftBy:s}}function Qs(e,t,n){let{windowSize:r,mask:o,maxNumber:i,shiftBy:s}=n,a=Number(e&o),c=e>>s;a>r&&(a-=i,c+=Co);let l=t*r,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 Eo=new WeakMap,ra=new WeakMap;function _o(e){return ra.get(e)||1}function ea(e){if(e!==sr)throw new Error("invalid wNAF")}var ar=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>sr;)n&Co&&(r=r.add(o)),o=o.double(),n>>=Co;return r}precomputeWindow(t,n){let{windows:r,windowSize:o}=So(n,this.bits),i=[],
183
+ let c=i?et(t):ko(t);if(a&&(c=te(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 zt(r,"condit\
184
+ ion"),r?n:t}};Object.freeze(ir.prototype);function ar(e,t={}){return new ir(e,t)}var cr=BigInt(0),To=BigInt(1);function ra(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 aa(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)
185
+ throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Co(e,t){aa(e,t);let n=Math.ceil(t/e)+1,r=2**(e-1),o=2**e,i=Hs(e),s=BigInt(e);return {windows:n,windowSize:r,mask:i,maxNumber:o,
186
+ shiftBy:s}}function oa(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+=To);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 Ro=new WeakMap,ca=new WeakMap;function Ao(e){return ca.get(e)||1}function ia(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&To&&(r=r.add(o)),o=o.double(),n>>=To;return r}precomputeWindow(t,n){let{windows:r,windowSize:o}=Co(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=So(t,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:l,isZero:p,isNeg:u,isNegF:f,offsetF:m}=Qs(r,a,s);r=c,p?i=i.add(Xs(f,n[m])):o=o.add(Xs(u,n[l]));}return ea(r),{p:o,f:i}}wNAFUnsafe(t,n,r,o=this.
191
- ZERO){let i=So(t,this.bits);for(let s=0;s<i.windows&&r!==sr;s++){let{nextN:a,offset:c,isZero:l,isNeg:p}=Qs(r,s,i);if(r=a,!l){let u=n[c];o=o.add(p?u.negate():u);}}return ea(r),o}getPrecomputes(t,n,r){let o=Eo.
192
- get(n);return o||(o=this.precomputeWindow(n,t),t!==1&&(typeof r=="function"&&(o=r(o)),Eo.set(n,o))),o}cached(t,n,r){let o=_o(t);return this.wNAF(o,this.getPrecomputes(o,t,r),n)}unsafe(t,n,r,o){let i=_o(
193
- t);return i===1?this._unsafeLadder(t,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,t,r),n,o)}createCache(t,n){na(n,this.bits),ra.set(t,n),Eo.delete(t);}hasCache(t){return _o(t)!==1}};function ta(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Zs(t),t}else return ir(e,{isLE:n})}function oa(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>sr))throw new Error(`CURVE.${c} must be positive bigint`)}
195
- let o=ta(t.p,n.Fp,r),i=ta(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 ia(e,t){return function(r){let o=e(r);return {secretKey:o,publicKey:t(o)}}}var lt=BigInt(0),ce=BigInt(1),Ao=BigInt(2),kd=BigInt(8);function wd(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 sa(e,t={}){
197
- let n=t,r=oa("edwards",e,n,n.FpFnLE),{Fp:o,Fn:i}=r,s=r.CURVE,{h:a}=s;yt(n,{},{uvRatio:"function"});let c=Ao<<BigInt(i.BYTES*8)-ce,l=v=>o.create(v),p=n.uvRatio===void 0?(v,g)=>{try{return {isValid:!0,value:o.
198
- sqrt(o.div(v,g))}}catch{return {isValid:false,value:lt}}}:n.uvRatio;if(!wd(o,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function u(v,g,k=false){let x=k?ce:lt;return yo("coordinate "+v,
190
+ s=Co(t,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:l,isZero:p,isNeg:u,isNegF:f,offsetF:m}=oa(r,a,s);r=c,p?i=i.add(ra(f,n[m])):o=o.add(ra(u,n[l]));}return ia(r),{p:o,f:i}}wNAFUnsafe(t,n,r,o=this.
191
+ ZERO){let i=Co(t,this.bits);for(let s=0;s<i.windows&&r!==cr;s++){let{nextN:a,offset:c,isZero:l,isNeg:p}=oa(r,s,i);if(r=a,!l){let u=n[c];o=o.add(p?u.negate():u);}}return ia(r),o}getPrecomputes(t,n,r){let o=Ro.
192
+ get(n);return o||(o=this.precomputeWindow(n,t),t!==1&&(typeof r=="function"&&(o=r(o)),Ro.set(n,o))),o}cached(t,n,r){let o=Ao(t);return this.wNAF(o,this.getPrecomputes(o,t,r),n)}unsafe(t,n,r,o){let i=Ao(
193
+ t);return i===1?this._unsafeLadder(t,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,t,r),n,o)}createCache(t,n){aa(n,this.bits),ca.set(t,n),Ro.delete(t);}hasCache(t){return Ao(t)!==1}};function sa(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return na(t),t}else return ar(e,{isLE:n})}function la(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=sa(t.p,n.Fp,r),i=sa(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 ua(e,t){return function(r){let o=e(r);return {secretKey:o,publicKey:t(o)}}}var lt=BigInt(0),ce=BigInt(1),Io=BigInt(2),Sd=BigInt(8);function Ed(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 da(e,t={}){
197
+ let n=t,r=la("edwards",e,n,n.FpFnLE),{Fp:o,Fn:i}=r,s=r.CURVE,{h:a}=s;wt(n,{},{uvRatio:"function"});let c=Io<<BigInt(i.BYTES*8)-ce,l=v=>o.create(v),p=n.uvRatio===void 0?(v,g)=>{try{return {isValid:!0,value:o.
198
+ sqrt(o.div(v,g))}}catch{return {isValid:false,value:lt}}}:n.uvRatio;if(!Ed(o,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function u(v,g,k=false){let x=k?ce:lt;return xo("coordinate "+v,
199
199
  g,x,c),g}function f(v){if(!(v 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(lt,ce,ce,lt);static Fp=o;static Fn=i;X;Y;Z;T;constructor(g,k,x,S){
200
200
  this.X=u("x",g),this.Y=u("y",k),this.Z=u("z",x,true),this.T=u("t",S),Object.freeze(this);}static CURVE(){return s}static fromAffine(g){if(g instanceof m)throw new Error("extended point not allowed");let{
201
- x:k,y:x}=g||{};return u("x",k),u("y",x),new m(k,x,ce,l(k*x))}static fromBytes(g,k=false){let x=o.BYTES,{a:S,d:y}=s;g=fn(ie(g,x,"point")),Ut(k,"zip215");let I=fn(g),D=g[x-1];I[x-1]=D&-129;let O=et(I),$=k?
202
- c:o.ORDER;yo("point.y",O,lt,$);let B=l(O*O),Z=l(B-ce),ne=l(y*B-S),{isValid:C,value:R}=p(Z,ne);if(!C)throw new Error("bad point: invalid y coordinate");let M=(R&ce)===ce,j=(D&128)!==0;if(!k&&R===lt&&j)
203
- throw new Error("bad point: x=0 and x_0=1");return j!==M&&(R=l(-R)),m.fromAffine({x:R,y:O})}static fromHex(g,k=false){return m.fromBytes($s(g),k)}get x(){return this.toAffine().x}get y(){return this.toAffine().
204
- y}precompute(g=8,k=true){return b.createCache(this,g),k||this.multiply(Ao),this}assertValidity(){let g=this,{a:k,d:x}=s;if(g.is0())throw new Error("bad point: ZERO");let{X:S,Y:y,Z:I,T:D}=g,O=l(S*S),$=l(
205
- y*y),B=l(I*I),Z=l(B*B),ne=l(O*k),C=l(B*l(ne+$)),R=l(Z+l(x*l(O*$)));if(C!==R)throw new Error("bad point: equation left != right (1)");let M=l(S*y),j=l(I*D);if(M!==j)throw new Error("bad point: equation\
206
- left != right (2)")}equals(g){f(g);let{X:k,Y:x,Z:S}=this,{X:y,Y:I,Z:D}=g,O=l(k*D),$=l(y*S),B=l(x*D),Z=l(I*S);return O===$&&B===Z}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:k,Y:x,Z:S}=this,y=l(k*k),I=l(x*x),D=l(Ao*l(S*S)),O=l(g*y),$=k+x,B=l(l($*$)-y-I),Z=O+I,ne=Z-D,C=O-I,R=l(B*ne),M=l(Z*C),j=l(B*C),se=l(ne*Z);return new m(R,M,se,
208
- j)}add(g){f(g);let{a:k,d:x}=s,{X:S,Y:y,Z:I,T:D}=this,{X:O,Y:$,Z:B,T:Z}=g,ne=l(S*O),C=l(y*$),R=l(D*x*Z),M=l(I*B),j=l((S+y)*(O+$)-ne-C),se=M-R,re=M+R,xe=l(C-k*ne),Se=l(j*se),We=l(re*xe),it=l(j*xe),h=l(se*
209
- re);return new m(Se,We,h,it)}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:k,f:x}=b.cached(this,
210
- g,S=>cr(m,S));return cr(m,[k,x])[0]}multiplyUnsafe(g){if(!i.isValid(g))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return g===lt?m.ZERO:this.is0()||g===ce?this:b.unsafe(this,g,k=>cr(
211
- m,k))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return b.unsafe(this,s.n).is0()}toAffine(g){let k=this,x=g,{X:S,Y:y,Z:I}=k,D=k.is0();x==null&&(x=D?kd:o.inv(I));let O=l(S*x),$=l(
201
+ x:k,y:x}=g||{};return u("x",k),u("y",x),new m(k,x,ce,l(k*x))}static fromBytes(g,k=false){let x=o.BYTES,{a:S,d:y}=s;g=vn(ie(g,x,"point")),zt(k,"zip215");let I=vn(g),D=g[x-1];I[x-1]=D&-129;let O=et(I),$=k?
202
+ c:o.ORDER;xo("point.y",O,lt,$);let B=l(O*O),X=l(B-ce),ne=l(y*B-S),{isValid:C,value:T}=p(X,ne);if(!C)throw new Error("bad point: invalid y coordinate");let M=(T&ce)===ce,j=(D&128)!==0;if(!k&&T===lt&&j)
203
+ throw new Error("bad point: x=0 and x_0=1");return j!==M&&(T=l(-T)),m.fromAffine({x:T,y:O})}static fromHex(g,k=false){return m.fromBytes(Us(g),k)}get x(){return this.toAffine().x}get y(){return this.toAffine().
204
+ y}precompute(g=8,k=true){return b.createCache(this,g),k||this.multiply(Io),this}assertValidity(){let g=this,{a:k,d:x}=s;if(g.is0())throw new Error("bad point: ZERO");let{X:S,Y:y,Z:I,T:D}=g,O=l(S*S),$=l(
205
+ y*y),B=l(I*I),X=l(B*B),ne=l(O*k),C=l(B*l(ne+$)),T=l(X+l(x*l(O*$)));if(C!==T)throw new Error("bad point: equation left != right (1)");let M=l(S*y),j=l(I*D);if(M!==j)throw new Error("bad point: equation\
206
+ left != right (2)")}equals(g){f(g);let{X:k,Y:x,Z:S}=this,{X:y,Y:I,Z:D}=g,O=l(k*D),$=l(y*S),B=l(x*D),X=l(I*S);return O===$&&B===X}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:k,Y:x,Z:S}=this,y=l(k*k),I=l(x*x),D=l(Io*l(S*S)),O=l(g*y),$=k+x,B=l(l($*$)-y-I),X=O+I,ne=X-D,C=O-I,T=l(B*ne),M=l(X*C),j=l(B*C),se=l(ne*X);return new m(T,M,se,
208
+ j)}add(g){f(g);let{a:k,d:x}=s,{X:S,Y:y,Z:I,T:D}=this,{X:O,Y:$,Z:B,T:X}=g,ne=l(S*O),C=l(y*$),T=l(D*x*X),M=l(I*B),j=l((S+y)*(O+$)-ne-C),se=M-T,re=M+T,xe=l(C-k*ne),Se=l(j*se),Ge=l(re*xe),it=l(j*xe),h=l(se*
209
+ re);return new m(Se,Ge,h,it)}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:k,f:x}=b.cached(this,
210
+ g,S=>ur(m,S));return ur(m,[k,x])[0]}multiplyUnsafe(g){if(!i.isValid(g))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return g===lt?m.ZERO:this.is0()||g===ce?this:b.unsafe(this,g,k=>ur(
211
+ m,k))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return b.unsafe(this,s.n).is0()}toAffine(g){let k=this,x=g,{X:S,Y:y,Z:I}=k,D=k.is0();x==null&&(x=D?Sd:o.inv(I));let O=l(S*x),$=l(
212
212
  y*x),B=o.mul(I,x);if(D)return {x:lt,y:ce};if(B!==ce)throw new Error("invZ was invalid");return {x:O,y:$}}clearCofactor(){return a===ce?this:this.multiplyUnsafe(a)}toBytes(){let{x:g,y:k}=this.toAffine(),
213
- x=o.toBytes(k);return x[x.length-1]|=g&ce?128:0,x}toHex(){return go(this.toBytes())}toString(){return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let b=new ar(m,i.BITS);return i.BITS>=8&&m.BASE.precompute(
214
- 8),Object.freeze(m.prototype),Object.freeze(m),m}var lr=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(t){this.ep=t;}static fromBytes(t){wo();}static fromHex(t){wo();}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 go(this.toBytes())}toString(){
213
+ x=o.toBytes(k);return x[x.length-1]|=g&ce?128:0,x}toHex(){return yo(this.toBytes())}toString(){return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let b=new lr(m,i.BITS);return i.BITS>=8&&m.BASE.precompute(
214
+ 8),Object.freeze(m.prototype),Object.freeze(m),m}var dr=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(t){this.ep=t;}static fromBytes(t){Eo();}static fromHex(t){Eo();}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 yo(this.toBytes())}toString(){
216
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
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 aa(e,t,n={}){if(typeof t!="function")throw new Error('"hash" function param is required');let r=t,o=n;yt(o,{},{adjustScalarBytes:"function",randomBytes:"\
218
+ return this.ep.precompute(t,n),this}};function pa(e,t,n={}){if(typeof t!="function")throw new Error('"hash" function param is required');let r=t,o=n;wt(o,{},{adjustScalarBytes:"function",randomBytes:"\
219
219
  function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:i}=o,{BASE:s,Fp:a,Fn:c}=e,l=r.outputLen,p=2*a.BYTES;if(l!==void 0&&(Qe(l,"hash.outputLen"),l!==p))throw new Error(
220
- `hash.outputLen must be ${p}, got ${l}`);let u=o.randomBytes===void 0?Ms:o.randomBytes,f=o.adjustScalarBytes===void 0?C=>C:o.adjustScalarBytes,m=o.domain===void 0?(C,R,M)=>{if(Ut(M,"phflag"),R.length||
221
- M)throw new Error("Contexts/pre-hash are not supported");return C}:o.domain;function b(C){return c.create(et(C))}function v(C){let R=O.secretKey;ie(C,O.secretKey,"secretKey");let M=ie(r(C),2*R,"hashed\
222
- SecretKey"),j=f(M.slice(0,R)),se=M.slice(R,2*R),re=b(j);return {head:j,prefix:se,scalar:re}}function g(C){let{head:R,prefix:M,scalar:j}=v(C),se=s.multiply(j),re=se.toBytes();return {head:R,prefix:M,scalar:j,
223
- point:se,pointBytes:re}}function k(C){return g(C).pointBytes}function x(C=Uint8Array.of(),...R){let M=Ue(...R);return b(r(m(M,ie(C,void 0,"context"),!!i)))}function S(C,R,M={}){C=ie(C,void 0,"message"),
224
- i&&(C=i(C));let{prefix:j,scalar:se,pointBytes:re}=g(R),xe=x(M.context,j,C),Se=s.multiply(xe).toBytes(),We=x(M.context,Se,re,C),it=c.create(xe+We*se);if(!c.isValid(it))throw new Error("sign failed: inv\
225
- alid s");let h=Ue(Se,c.toBytes(it));return ie(h,O.signature,"result")}let y={zip215:o.zip215};function I(C,R,M,j=y){let{context:se}=j,re=j.zip215===void 0?!!y.zip215:j.zip215,xe=O.signature;C=ie(C,xe,
226
- "signature"),R=ie(R,void 0,"message"),M=ie(M,O.publicKey,"publicKey"),re!==void 0&&Ut(re,"zip215"),i&&(R=i(R));let Se=xe/2,We=C.subarray(0,Se),it=et(C.subarray(Se,xe)),h,A,N;try{h=e.fromBytes(M,re),A=
227
- e.fromBytes(We,re),N=s.multiplyUnsafe(it);}catch{return false}if(!re&&h.isSmallOrder())return false;let U=x(se,We,M,R);return A.add(h.multiplyUnsafe(U)).subtract(N).clearCofactor().is0()}let D=a.BYTES,O={secretKey:D,
228
- publicKey:D,signature:2*D,seed:D};function $(C){return C=C===void 0?u(O.seed):C,ie(C,O.seed,"seed")}function B(C){return tr(C)&&C.length===O.secretKey}function Z(C,R){try{return !!e.fromBytes(C,R===void 0?
229
- y.zip215:R)}catch{return false}}let ne={getExtendedPublicKey:g,randomSecretKey:$,isValidSecretKey:B,isValidPublicKey:Z,toMontgomery(C){let{y:R}=e.fromBytes(C),M=O.publicKey,j=M===32;if(!j&&M!==57)throw new Error(
230
- "only defined for 25519 and 448");let se=j?a.div(ce+R,ce-R):a.div(R-ce,R+ce);return a.toBytes(se)},toMontgomerySecret(C){let R=O.secretKey;ie(C,R);let M=r(C.subarray(0,R));return f(M).subarray(0,R)}};
231
- return Object.freeze(O),Object.freeze(ne),Object.freeze({keygen:ia($,k),getPublicKey:k,sign:S,verify:I,utils:ne,Point:e,lengths:O})}var Ed=BigInt(0),nt=BigInt(1),la=BigInt(2);var _d=BigInt(5),Cd=BigInt(8),zt=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Do={p:zt,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Cd,
220
+ `hash.outputLen must be ${p}, got ${l}`);let u=o.randomBytes===void 0?Fs:o.randomBytes,f=o.adjustScalarBytes===void 0?C=>C:o.adjustScalarBytes,m=o.domain===void 0?(C,T,M)=>{if(zt(M,"phflag"),T.length||
221
+ M)throw new Error("Contexts/pre-hash are not supported");return C}:o.domain;function b(C){return c.create(et(C))}function v(C){let T=O.secretKey;ie(C,O.secretKey,"secretKey");let M=ie(r(C),2*T,"hashed\
222
+ SecretKey"),j=f(M.slice(0,T)),se=M.slice(T,2*T),re=b(j);return {head:j,prefix:se,scalar:re}}function g(C){let{head:T,prefix:M,scalar:j}=v(C),se=s.multiply(j),re=se.toBytes();return {head:T,prefix:M,scalar:j,
223
+ point:se,pointBytes:re}}function k(C){return g(C).pointBytes}function x(C=Uint8Array.of(),...T){let M=Ue(...T);return b(r(m(M,ie(C,void 0,"context"),!!i)))}function S(C,T,M={}){C=ie(C,void 0,"message"),
224
+ i&&(C=i(C));let{prefix:j,scalar:se,pointBytes:re}=g(T),xe=x(M.context,j,C),Se=s.multiply(xe).toBytes(),Ge=x(M.context,Se,re,C),it=c.create(xe+Ge*se);if(!c.isValid(it))throw new Error("sign failed: inv\
225
+ alid s");let h=Ue(Se,c.toBytes(it));return ie(h,O.signature,"result")}let y={zip215:o.zip215};function I(C,T,M,j=y){let{context:se}=j,re=j.zip215===void 0?!!y.zip215:j.zip215,xe=O.signature;C=ie(C,xe,
226
+ "signature"),T=ie(T,void 0,"message"),M=ie(M,O.publicKey,"publicKey"),re!==void 0&&zt(re,"zip215"),i&&(T=i(T));let Se=xe/2,Ge=C.subarray(0,Se),it=et(C.subarray(Se,xe)),h,R,N;try{h=e.fromBytes(M,re),R=
227
+ e.fromBytes(Ge,re),N=s.multiplyUnsafe(it);}catch{return false}if(!re&&h.isSmallOrder())return false;let U=x(se,Ge,M,T);return R.add(h.multiplyUnsafe(U)).subtract(N).clearCofactor().is0()}let D=a.BYTES,O={secretKey:D,
228
+ publicKey:D,signature:2*D,seed:D};function $(C){return C=C===void 0?u(O.seed):C,ie(C,O.seed,"seed")}function B(C){return rr(C)&&C.length===O.secretKey}function X(C,T){try{return !!e.fromBytes(C,T===void 0?
229
+ y.zip215:T)}catch{return false}}let ne={getExtendedPublicKey:g,randomSecretKey:$,isValidSecretKey:B,isValidPublicKey:X,toMontgomery(C){let{y:T}=e.fromBytes(C),M=O.publicKey,j=M===32;if(!j&&M!==57)throw new Error(
230
+ "only defined for 25519 and 448");let se=j?a.div(ce+T,ce-T):a.div(T-ce,T+ce);return a.toBytes(se)},toMontgomerySecret(C){let T=O.secretKey;ie(C,T);let M=r(C.subarray(0,T));return f(M).subarray(0,T)}};
231
+ return Object.freeze(O),Object.freeze(ne),Object.freeze({keygen:ua($,k),getPublicKey:k,sign:S,verify:I,utils:ne,Point:e,lengths:O})}var Rd=BigInt(0),nt=BigInt(1),ma=BigInt(2);var Ad=BigInt(5),Td=BigInt(8),Vt=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),$o={p:Vt,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Td,
232
232
  a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6d\
233
- c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Ad(e){let t=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),i=zt,a=e*e%
234
- i*e%i,c=$e(a,la,i)*a%i,l=$e(c,nt,i)*e%i,p=$e(l,_d,i)*l%i,u=$e(p,t,i)*p%i,f=$e(u,n,i)*u%i,m=$e(f,r,i)*f%i,b=$e(m,o,i)*m%i,v=$e(b,o,i)*m%i,g=$e(v,t,i)*p%i;return {pow_p_5_8:$e(g,la,i)*e%i,b2:a}}function Td(e){
235
- return e[0]&=248,e[31]&=127,e[31]|=64,e}var Ro=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Oo(e,t){let n=zt,r=te(t*t*t,n),o=te(r*r*t,n),i=Ad(e*o).pow_p_5_8,
236
- s=te(e*r*i,n),a=te(t*s*s,n),c=s,l=te(s*Ro,n),p=a===e,u=a===te(-e,n),f=a===te(-e*Ro,n);return p&&(s=c),(u||f)&&(s=l),tt(s,n)&&(s=te(-s,n)),{isValid:p||u,value:s}}var dt=sa(Do,{uvRatio:Oo}),ut=dt.Fp,pa=dt.
237
- Fn;function Rd(e){return aa(dt,Xn,Object.assign({adjustScalarBytes:Td,zip215:true},e))}var fa=Rd({});var Io=Ro;BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");var Pd=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt(
238
- "1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var ua=e=>Oo(nt,e),Ld=BigInt("0x7\
239
- fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Po=e=>ut.create(et(e)&Ld);var pt=class e extends lr{static BASE=new e(
240
- dt.BASE);static ZERO=new e(dt.ZERO);static Fp=ut;static Fn=pa;constructor(t){super(t);}static fromAffine(t){return new e(dt.fromAffine(t))}assertSame(t){if(!(t instanceof e))throw new Error("RistrettoP\
241
- oint expected")}init(t){return new e(t)}static fromBytes(t){Le(t,32);let{a:n,d:r}=Do,o=zt,i=y=>ut.create(y),s=Po(t);if(!Bs(ut.toBytes(s),t)||tt(s,o))throw new Error("invalid ristretto255 encoding 1");
242
- let a=i(s*s),c=i(nt+n*a),l=i(nt-n*a),p=i(c*c),u=i(l*l),f=i(n*r*p-u),{isValid:m,value:b}=ua(i(f*u)),v=i(b*l),g=i(b*v*f),k=i((s+s)*v);tt(k,o)&&(k=i(-k));let x=i(c*g),S=i(k*x);if(!m||tt(S,o)||x===Ed)throw new Error(
243
- "invalid ristretto255 encoding 2");return new e(new dt(k,x,nt,S))}static fromHex(t){return e.fromBytes(un(t))}toBytes(){let{X:t,Y:n,Z:r,T:o}=this.ep,i=zt,s=g=>ut.create(g),a=s(s(r+n)*s(r-n)),c=s(t*n),
244
- l=s(c*c),{value:p}=ua(s(a*l)),u=s(p*a),f=s(p*c),m=s(u*f*o),b;if(tt(o*m,i)){let g=s(n*Io),k=s(t*Io);t=g,n=k,b=s(u*Pd);}else b=f;tt(t*m,i)&&(n=s(-n));let v=s((r-n)*b);return tt(v,i)&&(v=s(-v)),ut.toBytes(
233
+ c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Id(e){let t=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),i=Vt,a=e*e%
234
+ i*e%i,c=$e(a,ma,i)*a%i,l=$e(c,nt,i)*e%i,p=$e(l,Ad,i)*l%i,u=$e(p,t,i)*p%i,f=$e(u,n,i)*u%i,m=$e(f,r,i)*f%i,b=$e(m,o,i)*m%i,v=$e(b,o,i)*m%i,g=$e(v,t,i)*p%i;return {pow_p_5_8:$e(g,ma,i)*e%i,b2:a}}function Pd(e){
235
+ return e[0]&=248,e[31]&=127,e[31]|=64,e}var Do=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Mo(e,t){let n=Vt,r=te(t*t*t,n),o=te(r*r*t,n),i=Id(e*o).pow_p_5_8,
236
+ s=te(e*r*i,n),a=te(t*s*s,n),c=s,l=te(s*Do,n),p=a===e,u=a===te(-e,n),f=a===te(-e*Do,n);return p&&(s=c),(u||f)&&(s=l),tt(s,n)&&(s=te(-s,n)),{isValid:p||u,value:s}}var dt=da($o,{uvRatio:Mo}),ut=dt.Fp,ba=dt.
237
+ Fn;function Dd(e){return pa(dt,er,Object.assign({adjustScalarBytes:Pd,zip215:true},e))}var va=Dd({});var Oo=Do;BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");var Ld=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt(
238
+ "1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var ha=e=>Mo(nt,e),Nd=BigInt("0x7\
239
+ fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Lo=e=>ut.create(et(e)&Nd);var pt=class e extends dr{static BASE=new e(
240
+ dt.BASE);static ZERO=new e(dt.ZERO);static Fp=ut;static Fn=ba;constructor(t){super(t);}static fromAffine(t){return new e(dt.fromAffine(t))}assertSame(t){if(!(t instanceof e))throw new Error("RistrettoP\
241
+ oint expected")}init(t){return new e(t)}static fromBytes(t){Le(t,32);let{a:n,d:r}=$o,o=Vt,i=y=>ut.create(y),s=Lo(t);if(!qs(ut.toBytes(s),t)||tt(s,o))throw new Error("invalid ristretto255 encoding 1");
242
+ let a=i(s*s),c=i(nt+n*a),l=i(nt-n*a),p=i(c*c),u=i(l*l),f=i(n*r*p-u),{isValid:m,value:b}=ha(i(f*u)),v=i(b*l),g=i(b*v*f),k=i((s+s)*v);tt(k,o)&&(k=i(-k));let x=i(c*g),S=i(k*x);if(!m||tt(S,o)||x===Rd)throw new Error(
243
+ "invalid ristretto255 encoding 2");return new e(new dt(k,x,nt,S))}static fromHex(t){return e.fromBytes(hn(t))}toBytes(){let{X:t,Y:n,Z:r,T:o}=this.ep,i=Vt,s=g=>ut.create(g),a=s(s(r+n)*s(r-n)),c=s(t*n),
244
+ l=s(c*c),{value:p}=ha(s(a*l)),u=s(p*a),f=s(p*c),m=s(u*f*o),b;if(tt(o*m,i)){let g=s(n*Oo),k=s(t*Oo);t=g,n=k,b=s(u*Ld);}else b=f;tt(t*m,i)&&(n=s(-n));let v=s((r-n)*b);return tt(v,i)&&(v=s(-v)),ut.toBytes(
245
245
  v)}equals(t){this.assertSame(t);let{X:n,Y:r}=this.ep,{X:o,Y:i}=t.ep,s=l=>ut.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(pt.BASE);Object.freeze(
246
- pt.ZERO);Object.freeze(pt.prototype);Object.freeze(pt);function ur(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 wt=`-----BEGIN PUBLIC KEY-----
246
+ pt.ZERO);Object.freeze(pt.prototype);Object.freeze(pt);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)?
247
+ e.measure_grace_days:0;return {...e,expires_at:e.measure_expires_at,grace_days:Math.max(0,t)}}var ft=`-----BEGIN PUBLIC KEY-----
248
248
  MCowBQYDK2VwAyEAWBiklf0kmDIVmM7nMiCxwiEAkwQIiqWGuRiRDJonsFY=
249
- -----END PUBLIC KEY-----`;function ma(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 Lo(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.
250
- length%4?"=".repeat(4-t.length%4):"";return ma(t+n)}function Md(e){let t=e.replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=ma(t);return n.subarray(n.length-32)}var Nd=new TextEncoder,ha=new TextDecoder;
251
- function $o(e){return typeof e=="object"&&e!==null&&"keys"in e}function Ft(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 jd=/^[A-Za-z0-9_-]+$/;
252
- function ga(e){let t=e.split(".");return t.length===3&&t.every(n=>jd.test(n))}function hn(e){return e===""?"empty":ga(e)?"token":"malformed"}function gn(e,t){if(!ga(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(ha.decode(Lo(r)));}catch{return {ok:false,reason:"header is not valid JSON"}}let a;if($o(t)){let p=typeof s.kid=="string"?s.kid:t.defaultKid,
254
- 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=Md(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=fa.verify(Lo(i),Nd.encode(`${r}.${o}`),c);}catch{return {ok:false,reason:"signature verification error"}}return l?{ok:true,header:s,payloadBytes:Lo(o)}:
256
- {ok:false,reason:"bad signature"}}function Mo(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(ha.decode(n.payloadBytes));return {
257
- signatureValid:!0,payload:ur(r)}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function dr(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 ba="BVSALA-REVOC",Bd=300,Ud=new TextDecoder;function va(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");
259
- if(o.header?.typ!==ba)return r(`unexpected token type "${String(o.header?.typ??"")}" (want ${ba})`);let i;try{i=JSON.parse(Ud.decode(o.payloadBytes));}catch{return r("payload is not valid JSON")}if(typeof i.
249
+ -----END PUBLIC KEY-----`;function ya(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 No(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.
250
+ length%4?"=".repeat(4-t.length%4):"";return ya(t+n)}function Bd(e){let t=e.replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=ya(t);return n.subarray(n.length-32)}var Ud=new TextEncoder,ka=new TextDecoder;
251
+ function fr(e){return typeof e=="object"&&e!==null&&"keys"in e}function St(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 Fd=/^[A-Za-z0-9_-]+$/;
252
+ function wa(e){let t=e.split(".");return t.length===3&&t.every(n=>Fd.test(n))}function qt(e){return e===""?"empty":wa(e)?"token":"malformed"}function Ht(e,t){if(!wa(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(ka.decode(No(r)));}catch{return {ok:false,reason:"header is not valid JSON"}}let a;if(fr(t)){let p=typeof s.kid=="string"?s.kid:t.defaultKid,
254
+ 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=Bd(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=va.verify(No(i),Ud.encode(`${r}.${o}`),c);}catch{return {ok:false,reason:"signature verification error"}}return l?{ok:true,header:s,payloadBytes:No(o)}:
256
+ {ok:false,reason:"bad signature"}}function mr(e,t){let n=Ht(e,t);if(!n.ok||!n.payloadBytes)return {signatureValid:false,...n.reason?{reason:n.reason}:{}};try{let r=JSON.parse(ka.decode(n.payloadBytes));return {
257
+ signatureValid:!0,payload:pr(r)}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function kn(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 xa="BVSALA-REVOC",zd=300,Vd=new TextDecoder;function jo(e,t,n={}){let r=l=>({ok:false,seq:-1,asOf:0,revoked:new Set,reason:l}),o=Ht(e,t);if(!o.ok||!o.payloadBytes)return r(o.reason??"bad signature");
259
+ if(o.header?.typ!==xa)return r(`unexpected token type "${String(o.header?.typ??"")}" (want ${xa})`);let i;try{i=JSON.parse(Vd.decode(o.payloadBytes));}catch{return r("payload is not valid JSON")}if(typeof i.
260
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.
261
- nowSeconds??Math.floor(Date.now()/1e3),c=n.maxSkewSeconds??Bd;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 Vt=class{_seq=-1;_asOf=0;_lastContactAt=0;set=new Set;get seq(){
261
+ nowSeconds??Math.floor(Date.now()/1e3),c=n.maxSkewSeconds??zd;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 Et=class{_seq=-1;_asOf=0;_lastContactAt=0;set=new Set;get seq(){
262
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.
263
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&&
264
- (this._asOf=t.asOf),r||o}};function pr(e,t,n){let r=()=>Math.floor((n.now?n.now():Date.now())/1e3),o=n.startedAt??r(),i=Ft(e),s=hn(i),a=s==="token"?Mo(i,t):{signatureValid:false,reason:s},c=a.signatureValid?a.payload:void 0,l=new Set(
265
- c?.plan==="measure"?[]:c?.features??[]),p=()=>{if(s==="empty")return "none";if(!c)return "invalid";let f=dr(c,r(),n.revocation.snapshot());if(n.maxStalenessSeconds!=null&&(f==="active"||f==="grace")){let m=c.
264
+ (this._asOf=t.asOf),r||o}};function wn(e,t,n){let r=()=>Math.floor((n.now?n.now():Date.now())/1e3),o=n.startedAt??r(),i=St(e),s=qt(i),a=s==="token"?mr(i,t):{signatureValid:false,reason:s},c=a.signatureValid?a.payload:void 0,l=new Set(
265
+ c?.plan==="measure"?[]:c?.features??[]),p=()=>{if(s==="empty")return "none";if(!c)return "invalid";let f=kn(c,r(),n.revocation.snapshot());if(n.maxStalenessSeconds!=null&&(f==="active"||f==="grace")){let m=c.
266
266
  expires_at+c.grace_days*86400,b=Math.min(o,m),v=Math.max(n.revocation.lastContactAt,b);if(r()-v>n.maxStalenessSeconds)return "stale"}return f},u=()=>{let f=p();return f==="active"||f==="grace"};return {
267
- 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 qt={pollIntervalSeconds:900,floorSeconds:300,maxIntervalSeconds:3600,jitterRatio:.1,maxSkewSeconds:300,requestTimeoutMs:3e4},ya=3,zd=12;function Fd(e){let t=e.random??Math.random,n;if(e.consecutiveFailures>
267
+ 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 Gt={pollIntervalSeconds:900,floorSeconds:300,maxIntervalSeconds:3600,jitterRatio:.1,maxSkewSeconds:300,requestTimeoutMs:3e4},Sa=3,qd=12;function Ea(e){let t=e.random??Math.random,n;if(e.consecutiveFailures>
268
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:
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 Vd=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 Hd=10,Wt=class{constructor(t){this.opts=t;}opts;timer=null;controller=null;consecutiveFailures=0;stopped=false;started=false;lastEtag=null;consecutive304=0;now(){
270
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();
271
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"});
272
- return}let n=new AbortController;this.controller=n;let r=this.opts.requestTimeoutMs??qt.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??Gt.requestTimeoutMs,o=setTimeout(()=>n.abort(),r);o.unref?.();let i={accept:"application/json"};this.lastEtag&&(i["\
273
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?.(
274
- {type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=Vd&&(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=va(c.list,this.opts.publicKeyPem,{minSeq:this.
276
- opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??qt.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>=Hd&&(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=jo(c.list,this.opts.publicKeyPem,{minSeq:this.
276
+ opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??Gt.maxSkewSeconds});if(!l.ok){let u=l.reason??"rejected";this.opts.onEvent?.({type:"rejected",reason:u}),this.avisar(`r\
277
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}.`);
278
278
  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:"\
279
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.
280
- silenceWarnings??this.opts.silenciarAvisos)}avisar(t,n){this.callado()||Q(`poller:${this.opts.url}:${t}`,n);}avisarFalloDeRed(t){if(this.callado())return;let n=this.consecutiveFailures;if(n<ya||(n-ya)%
281
- zd!==0)return;let r=t instanceof Error?t.message:String(t);console.warn(`[bv-sala] could not reach the revocation server ${n} times in a row (${r}). The license KEEPS working and known revocations sti\
280
+ silenceWarnings??this.opts.silenciarAvisos)}avisar(t,n){this.callado()||Q(`poller:${this.opts.url}:${t}`,n);}avisarFalloDeRed(t){if(this.callado())return;let n=this.consecutiveFailures;if(n<Sa||(n-Sa)%
281
+ qd!==0)return;let r=t instanceof Error?t.message:String(t);console.warn(`[bv-sala] could not reach the revocation server ${n} times in a row (${r}). The license KEEPS working and known revocations sti\
282
282
  ll apply, but NEW ones are not arriving. Check egress to ${this.opts.url}.`);}start(){this.started||this.stopped||(this.started=true,this.pollOnce().finally(()=>this.schedule()));}schedule(){if(this.stopped)
283
- return;let t=Fd({refreshAfter:this.opts.getRefreshAfter?.(),nowSeconds:this.now(),consecutiveFailures:this.consecutiveFailures,floorSeconds:this.opts.floorSeconds??qt.floorSeconds,pollIntervalSeconds:this.
284
- opts.pollIntervalSeconds??qt.pollIntervalSeconds,maxIntervalSeconds:this.opts.maxIntervalSeconds??qt.maxIntervalSeconds,jitterRatio:this.opts.jitterRatio??qt.jitterRatio,...this.opts.random?{random:this.
283
+ return;let t=Ea({refreshAfter:this.opts.getRefreshAfter?.(),nowSeconds:this.now(),consecutiveFailures:this.consecutiveFailures,floorSeconds:this.opts.floorSeconds??Gt.floorSeconds,pollIntervalSeconds:this.
284
+ opts.pollIntervalSeconds??Gt.pollIntervalSeconds,maxIntervalSeconds:this.opts.maxIntervalSeconds??Gt.maxIntervalSeconds,jitterRatio:this.opts.jitterRatio??Gt.jitterRatio,...this.opts.random?{random:this.
285
285
  opts.random}:{}});this.timer=setTimeout(()=>{this.pollOnce().finally(()=>this.schedule());},t*1e3),this.timer.unref?.();}stop(){this.stopped=true,this.timer&&(clearTimeout(this.timer),this.timer=null),this.
286
- controller?.abort();}};var qd="https://developers.openai.com/api/docs/pricing",Hd="https://ai.google.dev/gemini-api/docs/pricing",No="2026-09-27",L=e=>({...e,fuente:qd,consultado:No}),ze=e=>({...e,fuente:Hd,consultado:No}),
287
- Wd="https://platform.claude.com/docs/en/about-claude/pricing",le=e=>({...e,fuente:Wd,consultado:No});({openai:{flex:{"gpt-5":L({inputPer1k:625e-6,cachedInputPer1k:625e-7,outputPer1k:.005}),"gpt-5-mi\
286
+ controller?.abort();}};var Gd="https://developers.openai.com/api/docs/pricing",Wd="https://ai.google.dev/gemini-api/docs/pricing",Bo="2026-09-27",L=e=>({...e,fuente:Gd,consultado:Bo}),Fe=e=>({...e,fuente:Wd,consultado:Bo}),
287
+ Kd="https://platform.claude.com/docs/en/about-claude/pricing",le=e=>({...e,fuente:Kd,consultado:Bo});({openai:{flex:{"gpt-5":L({inputPer1k:625e-6,cachedInputPer1k:625e-7,outputPer1k:.005}),"gpt-5-mi\
288
288
  ni":L({inputPer1k:125e-6,cachedInputPer1k:125e-7,outputPer1k:.001}),"gpt-5-nano":L({inputPer1k:25e-6,cachedInputPer1k:25e-7,outputPer1k:2e-4}),"gpt-5.2":L({inputPer1k:875e-6,cachedInputPer1k:875e-7,outputPer1k:.007}),
289
289
  "gpt-5.4":L({inputPer1k:.00125,cachedInputPer1k:13e-5,outputPer1k:.0075,largo:{estandar:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225},tier:{inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.01125}}}),
290
290
  "gpt-5.4-mini":L({inputPer1k:375e-6,cachedInputPer1k:375e-7,outputPer1k:.00225}),"gpt-5.4-nano":L({inputPer1k:1e-4,cachedInputPer1k:1e-5,outputPer1k:625e-6}),"gpt-5.5":L({inputPer1k:.0025,cachedInputPer1k:25e-5,
@@ -321,151 +321,156 @@ cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4":le({inputPer1k:.0075
321
321
  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,
322
322
  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,
323
323
  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,
324
- cachedInputPer1k:4e-5,cacheWritePer1k:5e-4,outputPer1k:.002})}},google:{flex:{"gemini-3.7-flash":ze({inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3\
325
- .5-flash":ze({inputPer1k:75e-5,outputPer1k:.0045,cachedInputPer1k:8e-5}),"gemini-3.5-flash-lite":ze({inputPer1k:15e-5,outputPer1k:.00125,cachedInputPer1k:2e-5}),"gemini-3.1-pro-preview":ze({inputPer1k:.001,
326
- 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":ze({inputPer1k:625e-6,
324
+ cachedInputPer1k:4e-5,cacheWritePer1k:5e-4,outputPer1k:.002})}},google:{flex:{"gemini-3.7-flash":Fe({inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3\
325
+ .5-flash":Fe({inputPer1k:75e-5,outputPer1k:.0045,cachedInputPer1k:8e-5}),"gemini-3.5-flash-lite":Fe({inputPer1k:15e-5,outputPer1k:.00125,cachedInputPer1k:2e-5}),"gemini-3.1-pro-preview":Fe({inputPer1k:.001,
326
+ 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":Fe({inputPer1k:625e-6,
327
327
  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\
328
- sh":ze({inputPer1k:15e-5,outputPer1k:.00125,cachedInputPer1k:3e-5}),"gemini-3.8-flash":ze({inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.6-flash":ze(
329
- {inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.1-flash-lite":ze({inputPer1k:125e-6,outputPer1k:75e-5,cachedInputPer1k:125e-7}),"gemini-3-flash-pre\
330
- view":ze({inputPer1k:25e-5,outputPer1k:.0015,cachedInputPer1k:5e-5})}}});function jo(e){let t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}function fr(e){let t=e.toLowerCase(),n=t.indexOf("/"),r=n>0?t.
331
- slice(0,n):"",o=jo(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\
332
- i")?"google":o.startsWith("claude-")?"anthropic":null}var ka={flex:.5,default:1,auto:1,priority:1,fast:1,scale:1,standard:1,batch:.5};Math.min(...Object.values(ka).filter(e=>e<1));function mr(e){if(e==null||e==="")return null;let t=ka[e];return t==null?{servido:e,factor:null,conDescuento:false}:{servido:e,factor:t,conDescuento:t<1}}var Yd={"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.\
328
+ sh":Fe({inputPer1k:15e-5,outputPer1k:.00125,cachedInputPer1k:3e-5}),"gemini-3.8-flash":Fe({inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.6-flash":Fe(
329
+ {inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.1-flash-lite":Fe({inputPer1k:125e-6,outputPer1k:75e-5,cachedInputPer1k:125e-7}),"gemini-3-flash-pre\
330
+ view":Fe({inputPer1k:25e-5,outputPer1k:.0015,cachedInputPer1k:5e-5})}}});function Uo(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.
331
+ slice(0,n):"",o=Uo(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\
332
+ i")?"google":o.startsWith("claude-")?"anthropic":null}var _a={flex:.5,default:1,auto:1,priority:1,fast:1,scale:1,standard:1,batch:.5};Math.min(...Object.values(_a).filter(e=>e<1));function gr(e){if(e==null||e==="")return null;let t=_a[e];return t==null?{servido:e,factor:null,conDescuento:false}:{servido:e,factor:t,conDescuento:t<1}}var Zd={"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.\
333
333
  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\
334
334
  .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,
335
335
  "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\
336
336
  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\
337
337
  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},
338
- Zd=new Set(["claude-opus-4-7","claude-opus-4-8"]),Xd=[/^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($|[-_.])/,
339
- /^qwq/,/^qwen3/,/^glm-(4\.[5-9]|[5-9])/,/magistral/];function Bo(e){let t=e.lastIndexOf("/"),n=(t>=0?e.slice(t+1):e).toLowerCase();if(Xd.some(i=>i.test(n)))return "reasoning-model";let r=gt(e);if(r===void 0)
340
- return "unclassified-model";let o=Yd[r];if(o===true)return "reasoning-model";if(o!==false)return "unclassified-model";if(Zd.has(r))return "temperature-ignored"}var Ht=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0;function Uo(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){
341
- if(n===null||typeof n!="object")continue;let r=n;if(r.type!=="compaction")continue;t.iteraciones++,t.input+=Ht(r.input_tokens),t.output+=Ht(r.output_tokens),t.cacheRead+=Ht(r.cache_read_input_tokens);
342
- let o=r.cache_creation,i=Ht(o?.ephemeral_5m_input_tokens),s=Ht(o?.ephemeral_1h_input_tokens),a=typeof r.cache_creation_input_tokens=="number"?Ht(r.cache_creation_input_tokens):i+s;t.cacheWrite+=a,t.cacheWrite1h+=
343
- Math.min(s,a);}return t.iteraciones>0?t:null}var Qd={anthropic:"explicit",openai:"automatic",google:"implicit",unknown:"unknown"};function zo(e){return Math.round(e*1e10)/1e10}function Fo(e,t,n){let r=Math.max(0,n.leidos),o=Math.max(0,n.escritos),
344
- i=Math.min(o,Math.max(0,n.escritos1h));if(r===0&&o===0)return;let a=fr(e)??"unknown",c=ve(e),l=Nt(e),p=t.cachedInputPer1k,u=p!==void 0&&Number.isFinite(p),f=p??t.inputPer1k,m=u?r/1e3*
345
- 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:Qd[a],...n.marcadoPorLaCapa!==void 0?{layerMarked:n.marcadoPorLaCapa}:
346
- {},cacheReadTokens:r,cacheWriteTokens:o,cacheWrite1hTokens:i,inputPer1k:t.inputPer1k,cachedInputPer1k:f,writeMultiplier:c,write1hMultiplier:l,readDiscountUsd:zo(m),writePremiumUsd:zo(b),netUsd:zo(m-b),
347
- basis:u?"measured":"unmeasured"}}var ep=new Set([null,"cyber","general_harms"]);function hr(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\
348
- efusal"||!("category"in n))return false;let r=n.category;return !(r!==null&&typeof r!="string"||!ep.has(r)||e.bloques!==0||e.outputTokens!==0||Array.isArray(e.iterations)&&e.iterations.length>1)}var Ho="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\
349
- able","do not feel comfortable","'d rather not","would rather not","don't think i can","do not think i can"].join("|")+")",Vo="(?:much|many times|happy|glad|grateful|excited|thankful|proud|sorry|impor\
350
- tant|good|great|amazing|nice|relieved|pleased|delighted|impressed|helpful|useful|valuable|lucky|blessed|thrilled|fun|cool|beautiful|wonderful)",tp=`(?:help(?! but| feeling| thinking| noticing| wonderi\
338
+ Qd=new Set(["claude-opus-4-7","claude-opus-4-8"]),ep=[/^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($|[-_.])/,
339
+ /^qwq/,/^qwen3/,/^glm-(4\.[5-9]|[5-9])/,/magistral/];function Fo(e){let t=e.lastIndexOf("/"),n=(t>=0?e.slice(t+1):e).toLowerCase();if(ep.some(i=>i.test(n)))return "reasoning-model";let r=bt(e);if(r===void 0)
340
+ return "unclassified-model";let o=Zd[r];if(o===true)return "reasoning-model";if(o!==false)return "unclassified-model";if(Qd.has(r))return "temperature-ignored"}var Kt=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0;function zo(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){
341
+ if(n===null||typeof n!="object")continue;let r=n;if(r.type!=="compaction")continue;t.iteraciones++,t.input+=Kt(r.input_tokens),t.output+=Kt(r.output_tokens),t.cacheRead+=Kt(r.cache_read_input_tokens);
342
+ let o=r.cache_creation,i=Kt(o?.ephemeral_5m_input_tokens),s=Kt(o?.ephemeral_1h_input_tokens),a=typeof r.cache_creation_input_tokens=="number"?Kt(r.cache_creation_input_tokens):i+s;t.cacheWrite+=a,t.cacheWrite1h+=
343
+ Math.min(s,a);}return t.iteraciones>0?t:null}var tp={anthropic:"explicit",openai:"automatic",google:"implicit",unknown:"unknown"};function Vo(e){return Math.round(e*1e10)/1e10}function qo(e,t,n){let r=Math.max(0,n.leidos),o=Math.max(0,n.escritos),
344
+ i=Math.min(o,Math.max(0,n.escritos1h));if(r===0&&o===0)return;let a=hr(e)??"unknown",c=ve(e),l=Ut(e),p=t.cachedInputPer1k,u=p!==void 0&&Number.isFinite(p),f=p??t.inputPer1k,m=u?r/1e3*
345
+ 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:tp[a],...n.marcadoPorLaCapa!==void 0?{layerMarked:n.marcadoPorLaCapa}:
346
+ {},cacheReadTokens:r,cacheWriteTokens:o,cacheWrite1hTokens:i,inputPer1k:t.inputPer1k,cachedInputPer1k:f,writeMultiplier:c,write1hMultiplier:l,readDiscountUsd:Vo(m),writePremiumUsd:Vo(b),netUsd:Vo(m-b),
347
+ basis:u?"measured":"unmeasured"}}var np=new Set([null,"cyber","general_harms"]);function br(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\
348
+ efusal"||!("category"in n))return false;let r=n.category;return !(r!==null&&typeof r!="string"||!np.has(r)||e.bloques!==0||e.outputTokens!==0||Array.isArray(e.iterations)&&e.iterations.length>1)}var Wo="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\
349
+ able","do not feel comfortable","'d rather not","would rather not","don't think i can","do not think i can"].join("|")+")",Ho="(?:much|many times|happy|glad|grateful|excited|thankful|proud|sorry|impor\
350
+ tant|good|great|amazing|nice|relieved|pleased|delighted|impressed|helpful|useful|valuable|lucky|blessed|thrilled|fun|cool|beautiful|wonderful)",rp=`(?:help(?! but| feeling| thinking| noticing| wonderi\
351
351
  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\
352
- itate|contribute|go along|go into|walk you through|explain how|describe how(?! ${Vo})|tell you how(?! ${Vo})|teach|instruct|encourage|condone|endorse|promote|role-?play|pretend|do that|do this|do so|w\
352
+ itate|contribute|go along|go into|walk you through|explain how|describe how(?! ${Ho})|tell you how(?! ${Ho})|teach|instruct|encourage|condone|endorse|promote|role-?play|pretend|do that|do this|do so|w\
353
353
  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\
354
354
  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\
355
- s|evaluate|comment on|speak to|give out|dox|tell (?:you )?(?:whether|if))`,np="i(?:'ll| will| must| need to|'d| would)?(?: have to)? ?(?:respectfully |politely )?decline",rp="(?:(?:that|this|it)(?:'s|\
355
+ s|evaluate|comment on|speak to|give out|dox|tell (?:you )?(?:whether|if))`,op="i(?:'ll| will| must| need to|'d| would)?(?: have to)? ?(?:respectfully |politely )?decline",ip="(?:(?:that|this|it)(?:'s|\
356
356
  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\
357
- sure (?:that )?it(?:'s| is| would be) appropriate)",op="(?:(?:i'm |i am |i'm really |i am really |i'm so |really |so )?sorry|i apologi[sz]e|my apologies|apologies|unfortunately|regrettably|i'm afraid\
358
- |i am afraid|as an ai|as a language model|as an assistant|i understand|i appreciate|thank you for|thanks for|while i understand|while i appreciate)",d="\\p{L}*",xa="no (?:puedo|voy a|me es posible|est\
359
- oy en condiciones de|me siento c\xF3mod[oa])",ip=`(?:ayudar${d}|asistir${d}|proporcionar${d}|facilitar${d}|dar${d}|ofrecer${d}|crear${d}|escribir${d}|generar${d}|compartir${d}|cumplir|responder${d}|co\
360
- laborar|participar|atender${d}|hacer eso|hacerlo|con eso|con esto|con esa|con esta|con tu|determinar${d}|identificar${d}|saber${d}|acceder|revelar${d}|divulgar${d}|verificar${d}|confirmar${d}|localiza\
361
- r${d}|rastrear${d}|adivinar${d}|predecir${d}|diagnosticar${d}|recomendar${d}(?![^.!?]{0,60}suficiente)|recetar${d}|aconsejar${d})`,sp="(?:lo siento|lo lamento|siento|lamento|disculpa|disculpe|perd\xF3n|p\
362
- erdona|lamentablemente|desafortunadamente|me temo que|como (?:una )?(?:ia|inteligencia artificial|modelo de lenguaje|asistente)|entiendo)",Sa="no (?:puc|et puc|us puc|em sento c\xF2mod[ea]|estic en condi\
363
- cions de)",ap=`(?:ajudar${d}|assistir${d}|proporcionar${d}|facilitar${d}|donar${d}|oferir${d}|crear${d}|escriure${d}|generar${d}|compartir${d}|complir|respondre${d}|col\xB7laborar|participar|fer aix\xF2|fer\
364
- -ho|amb aix\xF2|amb aquesta|amb la teva|determinar${d}|identificar${d}|saber${d}|accedir|revelar${d}|divulgar${d}|verificar${d}|confirmar${d}|localitzar${d}|rastrejar${d}|endevinar${d}|predir${d}|diag\
365
- nosticar${d}|recomanar${d}(?![^.!?]{0,60}prou)|receptar${d}|aconsellar${d})`,cp="(?:ho sento|ho lamento|em sap greu|disculpa|disculpeu|perdona|malauradament|lamentablement|dissortadament|com a (?:ia|i\
366
- ntel\xB7lig\xE8ncia artificial|model de llenguatge|assistent)|entenc)",Ea="(?:je ne (?:peux|pourrai|pourrais|vais|souhaite)(?: malheureusement)? pas|je ne suis pas en mesure d[e']|je refuse d[e'])",lp="\
367
- (?:aider|assister|fournir|r\xE9pondre|cr\xE9er|\xE9crire|g\xE9n\xE9rer|partager|donner|proposer|participer|expliquer comment|acc\xE9der \xE0|satisfaire|faire cela|faire \xE7a|le faire|d\xE9terminer|identifier|savoir|divulguer|r\
368
- \xE9v\xE9ler|v\xE9rifier|confirmer|localiser|retrouver|deviner|pr\xE9dire|diagnostiquer|prescrire|conseiller|recommander(?![^.!?]{0,60}assez))",up="(?:d\xE9sol\xE9e?|je suis d\xE9sol\xE9e?|je regrette|malheureuse\
369
- ment|h\xE9las|je comprends|en tant qu'(?:ia|intelligence artificielle|mod\xE8le de langage|assistant))",_a="(?:ich (?:kann|werde|darf|m\xF6chte)|(?:kann|werde|darf|m\xF6chte) ich)(?: \\p{L}+){0,4}? (?:nicht|\
370
- keine\\p{L}*)(?: \\p{L}+){0,3}?",dp="(?:helfen|unterst\xFCtzen|bereitstellen|geben|erstellen|schreiben|generieren|beantworten|liefern|nachkommen|teilen|anbieten|erkl\xE4ren|behilflich sein|bestimmen|festste\
371
- llen|identifizieren|wissen|zugreifen|preisgeben|offenlegen|verraten|\xFCberpr\xFCfen|best\xE4tigen|ausfindig machen|orten|verfolgen|erraten|vorhersagen|diagnostizieren|verschreiben|raten|sagen, ob)",pp="\
372
- (?:es tut mir leid|tut mir leid|entschuldigung|entschuldige|leider|bedauerlicherweise|ich verstehe|als (?:eine )?(?:ki|k\xFCnstliche intelligenz|sprachmodell|assistent))",Ca="non (?:posso|sono in grad\
373
- o di|riesco a|mi sento a mio agio (?:a|nel))",fp=`(?:aiutar${d}|assister${d}|fornir${d}|crear${d}|scriver${d}|generar${d}|condivider${d}|risponder${d}|dar${d}|offrir${d}|soddisfare|partecipare|farlo|f\
374
- are questo|con questo|con questa|determinar${d}|identificar${d}|saper${d}|accedere|rivelar${d}|divulgar${d}|verificar${d}|confermar${d}|localizzar${d}|rintracciar${d}|indovinar${d}|prevedere|diagnosti\
375
- car${d}|prescriver${d}|consigliar${d}(?![^.!?]{0,60}abbastanza))`,mp="(?:mi dispiace|spiacente|purtroppo|sfortunatamente|capisco|come (?:un'?\\s?)?(?:ia|intelligenza artificiale|modello linguistico|ass\
376
- istente))",Aa="n\xE3o (?:posso|consigo|vou|sou capaz de|estou em condi\xE7\xF5es de|me sinto confort\xE1vel (?:em|a))",hp=`(?:ajudar${d}|auxiliar${d}|assistir${d}|fornecer${d}|criar${d}|escrever${d}|g\
377
- erar${d}|compartilhar${d}|partilhar${d}|dar${d}|oferecer${d}|responder${d}|atender${d}|cumprir|participar|fazer isso|com isso|com esse|com essa|determinar${d}|identificar${d}|saber${d}|acessar|aceder|\
378
- revelar${d}|divulgar${d}|verificar${d}|confirmar${d}|localizar${d}|rastrear${d}|adivinhar${d}|prever${d}|diagnosticar${d}|receitar${d}|aconselhar${d}|recomendar${d}(?![^.!?]{0,60}o suficiente))`,gp="(\
379
- ?:desculpe|desculpa|sinto muito|lamento|infelizmente|entendo|compreendo|como (?:uma? )?(?:ia|intelig\xEAncia artificial|modelo de linguagem|assistente))",Et="(?:[\\s,]+[\\p{L}'\u2019-]+){0,4}?[\\s,]+",
380
- Wo=[`${Ho}${Et}${tp}`,np,rp,`${xa}${Et}${ip}`,"lamento no poder",`${Sa}${Et}${ap}`,`${Ea}${Et}${lp}`,`${_a} ${dp}`,`${Ca}${Et}${fp}`,`${Aa}${Et}${hp}`].join("|"),bp=[op,sp,cp,up,pp,mp,gp].join("|"),vp=new RegExp(
381
- `^(?:${Wo})(?![\\p{L}])`,"u"),yp=new RegExp(`^(?:${bp})(?![\\p{L}])`,"u"),Ta=new RegExp(`(?:^|[^\\p{L}'])(?:${Wo})(?![\\p{L}])`,"u"),kp="(?:really|even|honestly|quite|possibly|truly|personally|actuall\
382
- y|simply|just|ever|always)",Go="i(?:'m| am)? ?(?:can't|cannot|can not|won't|will not|not going to|not able to|unable to)",wp=["wait","believe","imagine (?:how|what|why|anything|anyone|anybody|life|liv\
383
- ing|being|a (?:better|world|life|time|single))","thank","stress","(?:over|under)?emphasi[sz]e","overstate","understate","exaggerate","(?:recommend|praise|rave about|speak highly of|say enough good)[^.\
384
- !?]{0,60}enough","say enough","get enough","help (?:but|feeling|thinking|noticing|wondering|laughing|smiling|myself|it)",`(?:tell you|say|express|describe|explain|put into words) (?:how|what a) ${Vo}`,
385
- "express (?:my|our) (?:gratitude|thanks|appreciation)","begin to (?:describe|imagine|tell|express|thank|understand|fathom|comprehend|count)","agree (?:more|with you more)","complain","disagree","deny \
386
- (?:that|it|this|the)","fault (?:you|it|that|this|the)","argue with (?:that|this|you|those|these|the (?:logic|results|data|numbers|math|facts))","find (?:any|anything|a single|no|nothing)","identify (?\
387
- :any|anything|a single)","spot (?:any|anything|a single)","see (?:any|anything|a single|why not|a (?:reason|problem|downside|issue|bug))","think of (?:any|anything|a (?:reason|better|single|downside))",
388
- "lie","sugar-?coat(?: it| this| that)?","bore you","belabou?r","rehash","judge you","keep you","get over","resist","top (?:that|this)","go wrong","say (?:that )?i","pretend (?:otherwise|(?:that )?(?:i\
389
- 'm|i am|it's|it is|this is|everything|there's|there is|we|you))","remember (?:a time|the last time|when i)","stop (?:thinking|smiling|laughing|listening|reading|talking about)"],xp="(?:be (?:100% |com\
390
- pletely |entirely |absolutely |totally |fully |one hundred percent )?(?:sure|certain)|say (?:for (?:sure|certain)|with (?:certainty|confidence)|definitively|exactly|precisely|for a fact)|know (?:for (\
391
- ?:sure|certain)|exactly|precisely)|guarantee|promise|speak for|vouch for|recall|remember|run|test|execute|see (?:your|the) (?:screen|code|file|image|output|logs?))[^.!?]{0,160}?(?:,|\\s)(?:but|however)\
392
- (?![\\p{L}])",gr=`(?:${kp} ){0,2}(?:(?:${wp.join("|")})(?![\\p{L}])|${xp})`,Ra="no (?:(?:te|le|les|os|lo|la|me|se) )?(?:puedo|voy a)",Sp=["esperar",`creer${d}`,`imaginar${d}`,"dejar de",`evitar${d}`,`\
393
- 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 para no|raz\xF3n para no)`,`recomend\
394
- ar${d}[^.!?]{0,60}(?:suficiente|bastante)`,`(?:enfatizar|recalcar|subrayar|insistir|exagerar|ponderar)${d}`,`(?:decir|expresar)${d} (?:lo|cu\xE1nto|cuanto|c\xF3mo de|como de)`,`resistir${d}`,"m\xE1s que",
395
- "sino","pedir m\xE1s"],Ep=`(?:estar (?:100 ?% |completamente |totalmente |del todo )?segur[oa]|asegurar${d}|garantizar${d}|prometer${d}|(?:decir|saber|afirmar)${d} con (?:certeza|seguridad|exactitud)|\
396
- ejecutar${d}|probar${d}|recordar${d}|ver (?:tu|la|el) (?:pantalla|c\xF3digo|archivo))[^.!?]{0,160}?(?:,|\\s)(?:pero|aunque|sin embargo)(?![\\p{L}])`,Ko=`(?:(?:${Sp.join("|")})(?![\\p{L}])|${Ep})`,Ia="\
397
- no (?:(?:et|us|el|la|ho|em|li|els|les) )?(?:puc|penso|podr\xE9)",_p=[`esperar${d}`,`creure${d}`,`imaginar${d}`,"deixar de",`evitar${d}`,`agrair${d}`,`negar${d}`,`mentir${d}`,`queixar${d}`,"estar m\xE9s",
398
- `(?:trobar|veure|detectar|identificar)${d} (?:cap|res|ni un|ni una)`,`recomanar${d}[^.!?]{0,60}prou`,`(?:emfatitzar|remarcar|subratllar|insistir|exagerar)${d}`,`dir${d} (?:com de|quant|prou)`,`resisti\
399
- r${d}`,"m\xE9s que","sin\xF3","fer altra cosa que"],Cp=`(?:estar (?:100 ?% |completament |del tot )?segura?|assegurar${d}|garantir${d}|prometre${d}|(?:dir|saber|afirmar)${d} amb (?:certesa|seguretat)|\
400
- executar${d}|provar${d}|recordar${d})[^.!?]{0,160}?(?:,|\\s)(?:per\xF2|pero|tot i que)(?![\\p{L}])`,Jo=`(?:(?:${_p.join("|")})(?![\\p{L}])|${Cp})`,Pa="je ne (?:peux|pourrai|pourrais|vais)(?: malheureu\
401
- sement)? pas",Ap="(?:vous |te |t'|me |m'|le |la |les |l'|lui |leur |y |en |se |s')",Tp=["attendre","croire","imaginer","emp\xEAcher","remercier","(?:trop |assez )?(?:insister|souligner|exag\xE9rer)","\
402
- mentir","nier","plaindre","\xEAtre plus","(?:trouver|voir|d\xE9tecter|identifier|rep\xE9rer) (?:aucun|aucune|rien|de (?:probl\xE8me|raison|souci))","dire (?:\xE0 quel point|combien|assez)","recommande\
403
- r[^.!?]{0,60}assez","r\xE9sister","faire autrement que"],Rp="(?:\xEAtre (?:(?:tout \xE0 fait|absolument|enti\xE8rement|100 ?%) )?(?:s\xFBre?|certaine?)|garantir|promettre|affirmer|dire avec certitude|ex\xE9cuter|tes\
404
- ter|souvenir|rappeler|voir (?:votre|ton|ta|le|la) (?:\xE9cran|code|fichier))[^.!?]{0,160}?(?:,|\\s)(?:mais|cependant|toutefois)(?![\\p{L}])",Yo=`${Ap}*(?:(?:${Tp.join("|")})(?![\\p{L}])|${Rp})`,Da="no\
405
- n (?:(?:ti|vi|la|lo|le|gli|ne|mi|ci) )?(?:posso|riesco a|sono in grado di|ho intenzione di)",Ip=[`aspettar${d}`,`creder${d}`,`immaginar${d}`,"fare a meno",`ringraziar${d}`,"che","non",`negar${d}`,`men\
406
- tir${d}`,`lamentar${d}`,"(?:essere|esser) pi\xF9",`(?:trovare|vedere|notare|individuare|rilevare) (?:nessun${d}|niente|alcun${d}|un solo)`,`consigliar${d}[^.!?]{0,60}abbastanza`,`(?:sottolinear|enfati\
407
- zzar|insister|esagerar)${d}`,`dir${d} (?:quanto|abbastanza)`,`resister${d}`],Pp=`(?:(?:esserne|essere) (?:del tutto |completamente |al 100 ?% )?(?:sicur[oa]|cert[oa])|garantir${d}|prometter${d}|(?:dir\
408
- |affermar)${d} con certezza|eseguir${d}|testar${d}|ricordar${d})[^.!?]{0,160}?(?:,|\\s)(?:ma|per\xF2|tuttavia)(?![\\p{L}])`,Zo=`(?:(?:${Ip.join("|")})(?![\\p{L}])|${Pp})`,Oa="n\xE3o (?:(?:te|lhe|lhes|vos\
409
- |o|a|me) )?(?:posso|consigo|vou|sou capaz de)",Dp=["esperar","acreditar",`imaginar${d}`,"deixar de",`evitar${d}`,`agradecer${d}`,`negar${d}`,`mentir${d}`,`(?:me )?(?:queixar|reclamar)${d}`,"concordar \
410
- mais","estar mais","sen\xE3o","(?:fazer )?mais (?:do )?que",`(?:encontrar|ver|identificar|detetar|detectar|notar) (?:nenhum${d}|nada|um \xFAnico|uma \xFAnica)`,`recomendar${d}[^.!?]{0,60}(?:o )?sufici\
411
- ente`,`(?:enfatizar|sublinhar|ressaltar|insistir|exagerar)${d}`,`dizer${d} (?:o quanto|quanto|como|o suficiente)`,`resistir${d}`],Op=`(?:ter (?:a )?certeza|estar (?:100 ?% |completamente |totalmente )\
412
- ?(?: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\xE9m|contudo)(?![\\p{L}])`,
413
- Xo=`(?:(?:${Dp.join("|")})(?![\\p{L}])|${Op})`,La="(?:ich (?:kann|werde|darf)|kann ich|werde ich)",Lp=["(?:kaum|nicht) erwarten","glauben","vorstellen","genug (?:danken|betonen|empfehlen|loben|sagen|h\
414
- ervorheben)","oft genug","\\p{L}*l\xFCgen","leugnen","bestreiten","beschweren","beklagen","(?:mehr|besser) zustimmen","widerstehen","keine?n? (?:fehler|probleme?|grund|haken|m\xE4ngel|bugs?|nachteile?|ei\
415
- nw\xE4nde?)","sagen, wie (?:sehr|froh|dankbar|gl\xFCcklich)"],$p="(?:(?:mit )?sicherheit|genau|garantieren|versprechen|100 ?%|ausf\xFChren|testen|erinnern)[^.!?]{0,160}?(?:,|\\s)(?:aber|jedoch|allerdings)\
416
- (?![\\p{L}])",$a=`[^.!?]*?(?<![\\p{L}])(?:(?:${Lp.join("|")})(?![\\p{L}])|${$p})`,Ma="(?:no[,.!]? |non[,.!]? |n\xE3o[,.!]? |nein[,.!]? )?",Mp=new RegExp("^"+Ma+"(?:"+[`${Go}\\s(?!${gr})\\p{L}`,`${Ra}\\\
417
- s(?!${Ko})\\p{L}`,`${Ia}\\s(?!${Jo})\\p{L}`,`${Pa}\\s?(?!${Yo})\\p{L}`,`${Da}\\s(?!${Zo})\\p{L}`,`${Oa}\\s(?!${Xo})\\p{L}`,`${La}(?!${$a})(?:\\s[\\p{L}\\p{N}'-]+){0,6}?\\s(?:nicht|keine?\\p{L}*)(?![\\p{L}])\
418
- (?!\\s(?:nur|mehr als|anders|umhin))`].join("|")+")","u"),Np=new RegExp("^"+Ma+"(?:"+[`${Go}\\s(?=${gr})`,`${Ra}\\s(?=${Ko})`,`${Ia}\\s(?=${Jo})`,`${Pa}\\s?(?=${Yo})`,`${Da}\\s(?=${Zo})`,`${Oa}\\s(?=${Xo}\
419
- )`,`${La}(?=${$a})`].join("|")+")","u"),jp="(?:(?:i'm |i am )?(?:really |so |very |truly |terribly )?sorry|i apologi[sz]e|my apologies|apologies|unfortunately|regrettably|i'm afraid|i am afraid)",Bp="\
420
- (?:lo siento(?: mucho)?|lo lamento|disculpa|disculpe|perd\xF3n|perdona|lamentablemente|desafortunadamente|me temo que)",Up="(?:ho sento(?: molt)?|em sap greu|disculpa|disculpeu|perdona|malauradament|l\
421
- amentablement|dissortadament)",zp="(?:(?:je suis )?(?:vraiment )?d\xE9sol\xE9e?|je regrette|pardon|malheureusement|h\xE9las)",Fp="(?:es tut mir (?:sehr |wirklich )?leid|tut mir leid|entschuldigung|lei\
422
- der|bedauerlicherweise)",Vp="(?:mi dispiace(?: molto)?|spiacente|scusa|scusami|mi scuso|purtroppo|sfortunatamente)",qp="(?:desculpe|desculpa|sinto muito|lamento|pe\xE7o desculpa|infelizmente)",Hp=gr,Wp=Ko,
423
- Gp=Jo,Kp=Yo,Jp=Zo,Yp=Xo,xt=e=>`[,.!:;]?\\s(?:(?:${e})\\s)?`,Zp="\\s\\p{L}",Xp=[`${jp}${xt("but|however,?")}(?:as an ai(?: language model| assistant)?,?\\s)?${Ho}\\s(?!${Hp})\\p{L}`,`${Bp}${xt("pero")}${xa}\
424
- (?:\\s(?:te|le|les|os))?\\s(?!${Wp})\\p{L}`,`${Up}${xt("per\xF2|pero")}${Sa}\\s(?!${Gp})\\p{L}`,`${zp}${xt("mais")}${Ea}(?:\\s(?:vous|te))?\\s?(?!${Kp})\\p{L}`,`${Fp}${xt("aber")}${_a}${Zp}`,`${Vp}${xt(
425
- "ma")}${Ca}\\s(?!${Jp})\\p{L}`,`${qp}${xt("mas")}${Aa}\\s(?!${Yp})\\p{L}`].join("|"),Qp="(?:(?:i'm |i am )?(?:really |so |very |truly |terribly )?sorry|i apologi[sz]e|my apologies|apologies)",ef="(?:(\
426
- ?:is|are|was|would be|could be|may be|might be|it's|that's|this is|it is|that is)(?: considered| generally| strictly| both)? (?:illegal|unlawful|unethical|against|a violation|a serious violation|a bre\
427
- ach|an invasion|prohibited|not (?:something|appropriate|possible|allowed|permitted|legal|ethical|safe|advisable|ok|okay))|violates?|goes against|go against|infringes?|i (?:don't|do not) have (?:access\
428
- |the ability|the means|the capability|any way|a way|information about|any information about|personal (?:information|data)))",tf="(?:(?:es|son|ser\xEDa|ser\xEDan|est\xE1|estar\xEDa|resulta)(?: considerado)? (?:ile\
429
- gal|poco \xE9tic[oa]|inapropiad[oa]|contrari[oa] a|una violaci\xF3n|una infracci\xF3n|una invasi\xF3n|prohibid[oa])|no (?:es|ser\xEDa|est\xE1) (?:apropiado|posible|\xE9tico|legal|permitido|algo)|viola|violar\xEDa|infringe|va\
430
- en contra|no tengo (?:acceso|la capacidad|forma de|manera de|informaci\xF3n (?:sobre|personal)|datos personales))",nf="(?:(?:\xE9s|s\xF3n|seria|serien) (?:il\xB7legal|ilegal|poc \xE8tic|inadequat|inapropiat|cont\
431
- rari a|una violaci\xF3|una infracci\xF3|prohibit)|no (?:\xE9s|seria) (?:apropiat|adequat|possible|\xE8tic|legal|perm\xE8s)|viola|infringeix|va en contra)",rf="(?:(?:c'est|est|sont|serait|seraient) (?:\
432
- ill\xE9gale?|contraire \xE0|une violation|une atteinte|interdite?|inappropri\xE9)|(?:ce )?n'est pas (?:appropri\xE9|possible|\xE9thique|l\xE9gal|autoris\xE9)|viole|enfreint|va \xE0 l'encontre)",of="(?\
433
- :(?:ist|sind|w\xE4re|w\xE4ren)(?: \\p{L}+)? (?:illegal|rechtswidrig|unethisch|verboten|unangemessen|unzul\xE4ssig|ein versto\xDF|nicht (?:angemessen|m\xF6glich|erlaubt|zul\xE4ssig|legal|ethisch))|verst\xF6\xDFt|verletzt)",
434
- sf="(?:(?:\xE8|sono|sarebbe|sarebbero) (?:illegale|illecito|non etico|contrario a|una violazione|vietato|inappropriato)|non (?:\xE8|sarebbe) (?:appropriato|possibile|etico|legale|consentito)|viola|va contro\
435
- )",af="(?:(?:\xE9|s\xE3o|seria|seriam) (?:ilegal|anti\xE9tic[oa]|contr\xE1ri[oa] a|uma viola\xE7\xE3o|proibid[oa]|inapropriad[oa])|n\xE3o (?:\xE9|seria) (?:apropriado|poss\xEDvel|\xE9tico|legal|permitido)|viola|vai contra)",
436
- St="(?:[\\p{L}\\p{N}'\u2019-]+[\\s,]+){0,14}?",cf=[`${Qp},?\\sbut\\s${St}${ef}`,`(?:lo siento(?: mucho)?|lo lamento|disculpa|disculpe|perd\xF3n|perdona),?\\spero\\s${St}${tf}`,`(?:ho sento(?: molt)?|e\
437
- m sap greu|disculpa|perdona),?\\s(?:per\xF2|pero)\\s${St}${nf}`,`(?:(?:je suis )?(?:vraiment )?d\xE9sol\xE9e?|pardon),?\\smais\\s${St}${rf}`,`(?:es tut mir (?:sehr |wirklich )?leid|tut mir leid|entsch\
438
- uldigung),?\\saber\\s${St}${of}`,`(?:mi dispiace(?: molto)?|spiacente|scusa|scusami|mi scuso),?\\sma\\s${St}${sf}`,`(?:desculpe|desculpa|sinto muito|lamento|pe\xE7o desculpa),?\\smas\\s${St}${af}`].join(
439
- "|"),lf=new RegExp(`^(?:${Xp}|(?:${cf})(?![\\p{L}]))`,"u"),uf="(?:(?:i'm |i am )?(?:really |so |very |truly |deeply |terribly )?sorry (?:to hear|to read|that you|you(?:'re| are)|you feel|for what you|\
440
- about what you)|it sounds like you(?:'re| are)|that sounds (?:really |so |very |incredibly )?(?:hard|difficult|painful|overwhelming|tough|awful)|i(?:'m| am) (?:really |so |very )?(?:concerned|worried)\
441
- (?: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)",df="(?:mental health (?:professional|provider|expert|specialist|servi\
442
- ce|services|support|crisis|line)|therapist|counsel(?:l)?or|psychologist|psychiatrist|crisis (?:line|hotline|helpline|center|centre|text line|counsel(?:l)?or|team|service|services)|(?:suicide|crisis) (\
443
- ?:prevention|hotline|helpline|lifeline)|hotline|helpline|lifeline|samaritans|emergency services|emergency number|call (?:911|988|999|112|000|emergency)|988|someone you trust|people you trust|(?:a )?tr\
444
- usted (?:person|friend|adult|family member|individual|someone|loved one)|someone who can (?:help|support|provide support)|reach out to (?:someone|a friend|friends|family|a loved one|loved ones)|profes\
445
- sional (?:help|support)|seek (?:immediate|urgent|professional) (?:help|support))",pf="(?:(?:lo )?(?:siento|lamento) (?:mucho |much\xEDsimo )?(?:que (?:te sientas|est\xE9s|estes|te encuentres|pases|est\xE9s pas\
446
- ando)|escuchar|o\xEDr|leer|saber)|parece que (?:est\xE1s|estas) (?:pasando|atravesando)|me preocupa)",ff="(?:profesional(?:es)? de (?:la )?salud mental|psic\xF3log[oa]|psiquiatra|terapeuta|l\xEDnea (?:de )?\
447
- (?:crisis|ayuda|prevenci\xF3n|atenci\xF3n)|tel\xE9fono de la esperanza|024|servicios de emergencia|(?:llama|llamar|llames) al (?:112|911|024)|alguien de (?:tu )?confianza|(?:una )?persona de (?:tu )?confianza|\
448
- ayuda profesional)",mf="(?:em sap (?:molt )?greu (?:que (?:et sentis|estiguis|passis)|sentir|llegir|saber)|ho sento (?:molt|molt\xEDssim)|sembla que (?:est\xE0s|passes) (?:passant|travessant)?)",hf="(\
449
- ?:professional(?:s)? de (?:la )?salut mental|psic\xF2leg|psic\xF2loga|psiquiatre|terapeuta|l\xEDnia (?:d'ajuda|d'atenci\xF3|de crisi|de prevenci\xF3)|tel\xE8fon de l'esperan\xE7a|024|serveis d'emerg\xE8ncia|(?:truca|trucar|t\
450
- ruquis) al (?:112|024)|alg\xFA de (?:la teva )?confian\xE7a|(?:una )?persona de confian\xE7a|ajuda professional)",gf="(?:(?:je suis )?(?:vraiment |sinc\xE8rement |tellement |profond\xE9ment )?d\xE9sol\xE9e? (?:d'\
451
- 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))",bf="(?:professionnel(?:le)?s? de (?:la )?sant\xE9 ment\
452
- ale|psychologue|psychiatre|th\xE9rapeute|ligne d'\xE9coute|ligne de crise|ligne d'assistance|num\xE9ro d'urgence|services d'urgence|(?:appelle|appelez|composez|compose) le (?:3114|15|112|911)|3114|personne de \
453
- confiance|quelqu'un en qui (?:tu as|vous avez) confiance|aide professionnelle|sos amiti\xE9)",vf="(?:es tut mir (?:sehr |wirklich |so )?leid,? (?:dass|zu h\xF6ren|das zu h\xF6ren|zu lesen|das zu lesen)|das \
454
- klingt (?:sehr |wirklich )?(?:schwer|belastend|schmerzhaft)|ich mache mir sorgen)",yf="(?:psychotherapeut\\p{L}*|psycholog\\p{L}*|psychiater\\p{L}*|therapeut\\p{L}*|fachkraft f\xFCr psychische|telefonseelsor\
455
- ge|krisendienst|krisentelefon|notruf\\p{L}*|notdienst|rettungsdienst|vertrauensperson|jemandem,? dem (?:du|sie) vertrau\\p{L}*|professionelle hilfe|professionelle unterst\xFCtzung)",kf="(?:mi dispiace\
456
- (?:molto |davvero |tanto )?(?:sentire|leggere|sapere|che tu|che ti|che stia)|sembra che (?:tu stia|stai) (?:passando|attraversando))",wf="(?:professionista della salute mentale|psicolog[oa]|psichiatr\
457
- a|terapeuta|linea (?:di crisi|di ascolto|di supporto|d'ascolto)|telefono amico|telefono azzurro|numero di emergenza|servizi di emergenza|(?:chiama|chiamare) (?:il )?(?:112|118)|persona di fiducia|qual\
458
- cuno di cui ti fidi|aiuto professionale)",xf="(?:sinto muito (?:que voc\xEA|por voc\xEA estar|em saber|ouvir|que esteja|que estejas)|lamento (?:muito )?(?:que voc\xEA|saber|ouvir)|parece que voc\xEA (?:est\xE1|estej\
459
- a) (?:passando|a passar))",Sf="(?:profissional de sa\xFAde mental|profissionais de sa\xFAde mental|psic\xF3log[oa]|psiquiatra|terapeuta|cvv|linha de (?:apoio|crise|ajuda)|servi\xE7os de emerg\xEAncia|(?:ligue|liga|l\
460
- igar) (?:para )?(?:o )?(?:188|192|112|190)|188|pessoa de confian\xE7a|algu\xE9m (?:de confian\xE7a|em quem (?:voc\xEA )?confie)|ajuda profissional|sns 24)",Ef=new RegExp(`^(?:${[uf,pf,mf,gf,vf,kf,xf].
461
- join("|")})(?![\\p{L}])`,"u"),_f=new RegExp(`(?<![\\p{L}\\p{N}])(?:${[df,ff,hf,bf,yf,wf,Sf].join("|")})(?![\\p{L}\\p{N}])`,"u"),Cf=2e4,Af="(?:explain|detail|describe|elaborate)",Tf=new RegExp(`(?:^|[^\
462
- \\p{L}'])(?:${Wo}|${Ho}${Et}${Af})(?![\\p{L}])`,"gu"),Rf=new RegExp(`^[^\\p{L}]*${Go}\\s${gr}`,"u");function wa(e,t){for(let n of e.matchAll(t))if(!Rf.test(e.slice(n.index)))return true;return false}var If=new RegExp(
463
- Ta.source,"gu");function Pf(e){return e.slice(0,4*300).replace(/[‘’ʼ`´]/g,"'").toLowerCase().replace(/\s+/g," ").trim().replace(/^[\s*#>_"'«“¿¡(\[-]+/u,"").trim()}function Df(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 qo(e){let t=/[.!?。:;](?:\s|$)/.exec(e);return t?e.slice(t.index+1).trim():""}function Qo(e){
465
- if(typeof e!="string"||e==="")return null;let t=Pf(e);if(t==="")return null;let n=Df(t),r=Np.test(n);if(!r&&(vp.test(n)||Mp.test(n)))return "opens-with-refusal";let o=r?qo(n):n;return yp.test(n)&&Ta.test(
466
- o)||lf.test(n)?"apology-then-refusal":t.length<=300&&wa(r?qo(t):t,If)?"short-refusal":Ef.test(n)&&_f.test(n)?"redirection":wa(Of(e,r),Tf)?"partial-refusal":null}function Of(e,t){let n=e.slice(0,Cf).replace(
467
- /[‘’ʼ`´]/g,"'").toLowerCase().replace(/\s+/g," ").trim().replace(/^[\s*#>_"'«“¿¡(\[-]+/u,"").trim();return t?qo(n):n}var Lf=/^content_filter(?:\s*:\s*(.*?))?\s*$/;function ei(e){return typeof e=="string"&&Lf.test(e)}function ti(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function ni(e){if(!e)return 0;let{prompt_tokens:t,completion_tokens:n,total_tokens:r}=e;return !ti(t)||!ti(n)||!ti(r)?0:Math.max(0,r-
468
- t-n)}var q="\\p{L}*",$f=[`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\
357
+ 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\
358
+ d)|(?:this|that|your) request (?:is|would be) (?:considered )?(?:inappropriate|illegal|unlawful|unethical|harmful|dangerous|against|not appropriate|a violation))",sp="(?:(?:i'm |i am |i'm really |i am\
359
+ 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 \
360
+ 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])",ap=`(?:ayudar${d}|asistir${d}|proporcionar${d}\
361
+ |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\
362
+ 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\
363
+ uficiente)|recetar${d}|aconsejar${d})`,cp="(?:lo siento|lo lamento|siento|lamento|disculpa|disculpe|perd\xF3n|perdona|lamentablemente|desafortunadamente|me temo que|como (?:una )?(?:ia|inteligencia artif\
364
+ icial|modelo de lenguaje|asistente)|entiendo)",Ia="no (?:puc|et puc|us puc|em sento c\xF2mod[ea]|estic en condicions de)",lp=`(?:ajudar${d}|assistir${d}|proporcionar${d}|facilitar${d}|donar${d}|oferir${d}\
365
+ |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\
366
+ 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})`,up="(?:ho \
367
+ sento|ho lamento|em sap greu|disculpa|disculpeu|perdona|malauradament|lamentablement|dissortadament|com a (?:ia|intel\xB7lig\xE8ncia artificial|model de llenguatge|assistent)|entenc)",Pa="(?:je ne (?:\
368
+ peux|pourrai|pourrais|vais|souhaite)(?: malheureusement)? pas|je ne suis pas en mesure d[e']|je refuse d[e'])",dp="(?:aider|assister|fournir|r\xE9pondre|cr\xE9er|\xE9crire|g\xE9n\xE9rer|partager|donner|proposer|part\
369
+ 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\
370
+ |conseiller|recommander(?![^.!?]{0,60}assez))",pp="(?: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))",
371
+ Da="(?:ich (?:kann|werde|darf|m\xF6chte)|(?:kann|werde|darf|m\xF6chte) ich)(?: \\p{L}+){0,4}? (?:nicht|keine\\p{L}*)(?: \\p{L}+){0,3}?",fp="(?:helfen|unterst\xFCtzen|bereitstellen|geben|erstellen|schreib\
372
+ en|generieren|beantworten|liefern|nachkommen|teilen|anbieten|erkl\xE4ren|behilflich sein|bestimmen|feststellen|identifizieren|wissen|zugreifen|preisgeben|offenlegen|verraten|\xFCberpr\xFCfen|best\xE4tigen|ausfind\
373
+ ig machen|orten|verfolgen|erraten|vorhersagen|diagnostizieren|verschreiben|raten|sagen, ob)",mp="(?:es tut mir leid|tut mir leid|entschuldigung|entschuldige|leider|bedauerlicherweise|ich verstehe|als \
374
+ (?:eine )?(?:ki|k\xFCnstliche intelligenz|sprachmodell|assistent))",Oa="non (?:posso|sono in grado di|riesco a|mi sento a mio agio (?:a|nel))",hp=`(?:aiutar${d}|assister${d}|fornir${d}|crear${d}|scriv\
375
+ 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}\
376
+ |verificar${d}|confermar${d}|localizzar${d}|rintracciar${d}|indovinar${d}|prevedere|diagnosticar${d}|prescriver${d}|consigliar${d}(?![^.!?]{0,60}abbastanza))`,gp="(?:mi dispiace|spiacente|purtroppo|sf\
377
+ ortunatamente|capisco|come (?:un'?\\s?)?(?:ia|intelligenza artificiale|modello linguistico|assistente))",La="n\xE3o (?:posso|consigo|vou|sou capaz de|estou em condi\xE7\xF5es de|me sinto confort\xE1vel (?:em|a))",
378
+ bp=`(?: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\
379
+ 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}\
380
+ |receitar${d}|aconselhar${d}|recomendar${d}(?![^.!?]{0,60}o suficiente))`,vp="(?:desculpe|desculpa|sinto muito|lamento|infelizmente|entendo|compreendo|como (?:uma? )?(?:ia|intelig\xEAncia artificial|mode\
381
+ lo de linguagem|assistente))",Rt="(?:[\\s,]+[\\p{L}'\u2019-]+){0,4}?[\\s,]+",Ko=[`${Wo}${Rt}${rp}`,op,ip,`${Ta}${Rt}${ap}`,"lamento no poder","(?:esta|esa|la|tu) (?:solicitud|petici\xF3n) no (?:se )?pued\
382
+ e (?:ser )?(?:atender|atendida|cumplir|cumplida|completar|completada|procesar|procesada)",`${Ia}${Rt}${lp}`,`${Pa}${Rt}${dp}`,`${Da} ${fp}`,`${Oa}${Rt}${hp}`,`${La}${Rt}${bp}`].join("|"),yp=[sp,cp,up,
383
+ pp,mp,gp,vp].join("|"),kp=new RegExp(`^(?:${Ko})(?![\\p{L}])`,"u"),wp=new RegExp(`^(?:${yp})(?![\\p{L}])`,"u"),$a=new RegExp(`(?:^|[^\\p{L}'])(?:${Ko})(?![\\p{L}])`,"u"),xp="(?:really|even|honestly|qu\
384
+ ite|possibly|truly|personally|actually|simply|just|ever|always)",Jo="i(?:'m| am)? ?(?:can't|cannot|can not|won't|will not|not going to|not able to|unable to)",Sp=["wait","believe","imagine (?:how|what\
385
+ |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\
386
+ 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|\
387
+ put into words) (?:how|what a) ${Ho}`,"express (?:my|our) (?:gratitude|thanks|appreciation)","begin to (?:describe|imagine|tell|express|thank|understand|fathom|comprehend|count)","agree (?:more|with y\
388
+ 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\
389
+ 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\
390
+ 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 )\
391
+ ?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\
392
+ |talking about)"],Ep="(?:be (?:100% |completely |entirely |absolutely |totally |fully |one hundred percent )?(?:sure|certain)|say (?:for (?:sure|certain)|with (?:certainty|confidence)|definitively|exa\
393
+ 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\
394
+ ?))[^.!?]{0,160}?(?:,|\\s)(?:but|however)(?![\\p{L}])",vr=`(?:${xp} ){0,2}(?:(?:${Sp.join("|")})(?![\\p{L}])|${Ep})`,Ma="no (?:(?:te|le|les|os|lo|la|me|se) )?(?:puedo|voy a)",_p=["esperar",`creer${d}`,
395
+ `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\
396
+ 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\
397
+ o de)`,`resistir${d}`,"m\xE1s que","sino","pedir m\xE1s"],Cp=`(?:estar (?:100 ?% |completamente |totalmente |del todo )?segur[oa]|asegurar${d}|garantizar${d}|prometer${d}|(?:decir|saber|afirmar)${d} c\
398
+ 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}])`,Yo=`(?:(?:${_p.join(
399
+ "|")})(?![\\p{L}])|${Cp})`,Na="no (?:(?:et|us|el|la|ho|em|li|els|les) )?(?:puc|penso|podr\xE9)",Rp=[`esperar${d}`,`creure${d}`,`imaginar${d}`,"deixar de",`evitar${d}`,`agrair${d}`,`negar${d}`,`mentir${d}`,
400
+ `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} (?\
401
+ :com de|quant|prou)`,`resistir${d}`,"m\xE9s que","sin\xF3","fer altra cosa que"],Ap=`(?:estar (?:100 ?% |completament |del tot )?segura?|assegurar${d}|garantir${d}|prometre${d}|(?:dir|saber|afirmar)${d}\
402
+ amb (?:certesa|seguretat)|executar${d}|provar${d}|recordar${d})[^.!?]{0,160}?(?:,|\\s)(?:per\xF2|pero|tot i que)(?![\\p{L}])`,Xo=`(?:(?:${Rp.join("|")})(?![\\p{L}])|${Ap})`,ja="je ne (?:peux|pourrai|\
403
+ pourrais|vais)(?: malheureusement)? pas",Tp="(?:vous |te |t'|me |m'|le |la |les |l'|lui |leur |y |en |se |s')",Ip=["attendre","croire","imaginer","emp\xEAcher","remercier","(?:trop |assez )?(?:insiste\
404
+ 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\
405
+ bien|assez)","recommander[^.!?]{0,60}assez","r\xE9sister","faire autrement que"],Pp="(?:\xEAtre (?:(?:tout \xE0 fait|absolument|enti\xE8rement|100 ?%) )?(?:s\xFBre?|certaine?)|garantir|promettre|affirmer|dire ave\
406
+ c certitude|ex\xE9cuter|tester|souvenir|rappeler|voir (?:votre|ton|ta|le|la) (?:\xE9cran|code|fichier))[^.!?]{0,160}?(?:,|\\s)(?:mais|cependant|toutefois)(?![\\p{L}])",Zo=`${Tp}*(?:(?:${Ip.join("|")})\
407
+ (?![\\p{L}])|${Pp})`,Ba="non (?:(?:ti|vi|la|lo|le|gli|ne|mi|ci) )?(?:posso|riesco a|sono in grado di|ho intenzione di)",Dp=[`aspettar${d}`,`creder${d}`,`immaginar${d}`,"fare a meno",`ringraziar${d}`,"\
408
+ 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\
409
+ nza`,`(?:sottolinear|enfatizzar|insister|esagerar)${d}`,`dir${d} (?:quanto|abbastanza)`,`resister${d}`],Op=`(?:(?:esserne|essere) (?:del tutto |completamente |al 100 ?% )?(?:sicur[oa]|cert[oa])|garant\
410
+ ir${d}|prometter${d}|(?:dir|affermar)${d} con certezza|eseguir${d}|testar${d}|ricordar${d})[^.!?]{0,160}?(?:,|\\s)(?:ma|per\xF2|tuttavia)(?![\\p{L}])`,Qo=`(?:(?:${Dp.join("|")})(?![\\p{L}])|${Op})`,Ua="\
411
+ n\xE3o (?:(?:te|lhe|lhes|vos|o|a|me) )?(?:posso|consigo|vou|sou capaz de)",Lp=["esperar","acreditar",`imaginar${d}`,"deixar de",`evitar${d}`,`agradecer${d}`,`negar${d}`,`mentir${d}`,`(?:me )?(?:queixa\
412
+ 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}\
413
+ [^.!?]{0,60}(?:o )?suficiente`,`(?:enfatizar|sublinhar|ressaltar|insistir|exagerar)${d}`,`dizer${d} (?:o quanto|quanto|como|o suficiente)`,`resistir${d}`],$p=`(?:ter (?:a )?certeza|estar (?:100 ?% |co\
414
+ 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\
415
+ \xE9m|contudo)(?![\\p{L}])`,ei=`(?:(?:${Lp.join("|")})(?![\\p{L}])|${$p})`,Fa="(?:ich (?:kann|werde|darf)|kann ich|werde ich)",Mp=["(?:kaum|nicht) erwarten","glauben","vorstellen","genug (?:danken|bet\
416
+ 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\
417
+ n|m\xE4ngel|bugs?|nachteile?|einw\xE4nde?)","sagen, wie (?:sehr|froh|dankbar|gl\xFCcklich)"],Np="(?:(?:mit )?sicherheit|genau|garantieren|versprechen|100 ?%|ausf\xFChren|testen|erinnern)[^.!?]{0,160}?(?:\
418
+ ,|\\s)(?:aber|jedoch|allerdings)(?![\\p{L}])",za=`[^.!?]*?(?<![\\p{L}])(?:(?:${Mp.join("|")})(?![\\p{L}])|${Np})`,Va="(?:no[,.!]? |non[,.!]? |n\xE3o[,.!]? |nein[,.!]? )?",jp=new RegExp("^"+Va+"(?:"+[`${Jo}\
419
+ \\s(?!${vr})\\p{L}`,`${Ma}\\s(?!${Yo})\\p{L}`,`${Na}\\s(?!${Xo})\\p{L}`,`${ja}\\s?(?!${Zo})\\p{L}`,`${Ba}\\s(?!${Qo})\\p{L}`,`${Ua}\\s(?!${ei})\\p{L}`,`${Fa}(?!${za})(?:\\s[\\p{L}\\p{N}'-]+){0,6}?\\s(?:ni\
420
+ cht|keine?\\p{L}*)(?![\\p{L}])(?!\\s(?:nur|mehr als|anders|umhin))`].join("|")+")","u"),Bp=new RegExp("^"+Va+"(?:"+[`${Jo}\\s(?=${vr})`,`${Ma}\\s(?=${Yo})`,`${Na}\\s(?=${Xo})`,`${ja}\\s?(?=${Zo})`,`${Ba}\
421
+ \\s(?=${Qo})`,`${Ua}\\s(?=${ei})`,`${Fa}(?=${za})`].join("|")+")","u"),Up="(?:(?:i'm |i am )?(?:really |so |very |truly |terribly )?sorry|i apologi[sz]e|my apologies|apologies|unfortunately|regrettabl\
422
+ y|i'm afraid|i am afraid)",Fp="(?:lo siento(?: mucho)?|lo lamento|disculpa|disculpe|perd\xF3n|perdona|lamentablemente|desafortunadamente|me temo que)",zp="(?:ho sento(?: molt)?|em sap greu|disculpa|di\
423
+ sculpeu|perdona|malauradament|lamentablement|dissortadament)",Vp="(?:(?:je suis )?(?:vraiment )?d\xE9sol\xE9e?|je regrette|pardon|malheureusement|h\xE9las)",qp="(?:es tut mir (?:sehr |wirklich )?leid|\
424
+ tut mir leid|entschuldigung|leider|bedauerlicherweise)",Hp="(?:mi dispiace(?: molto)?|spiacente|scusa|scusami|mi scuso|purtroppo|sfortunatamente)",Gp="(?:desculpe|desculpa|sinto muito|lamento|pe\xE7o des\
425
+ culpa|infelizmente)",Wp=vr,Kp=Yo,Jp=Xo,Yp=Zo,Xp=Qo,Zp=ei,_t=e=>`[,.!:;]?\\s(?:(?:${e})\\s)?`,Qp="\\s\\p{L}",ef=[`${Up}${_t("but|however,?")}(?:as an ai(?: language model| assistant)?,?\\s)?${Wo}\\s(?!${Wp}\
426
+ )\\p{L}`,`${Fp}${_t("pero")}${Ta}(?:\\s(?:te|le|les|os))?\\s(?!${Kp})\\p{L}`,`${zp}${_t("per\xF2|pero")}${Ia}\\s(?!${Jp})\\p{L}`,`${Vp}${_t("mais")}${Pa}(?:\\s(?:vous|te))?\\s?(?!${Yp})\\p{L}`,`${qp}${_t(
427
+ "aber")}${Da}${Qp}`,`${Hp}${_t("ma")}${Oa}\\s(?!${Xp})\\p{L}`,`${Gp}${_t("mas")}${La}\\s(?!${Zp})\\p{L}`].join("|"),tf="(?:(?:i'm |i am )?(?:really |so |very |truly |terribly )?sorry|i apologi[sz]e|my\
428
+ apologies|apologies)",nf="(?:(?: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\
429
+ 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 \
430
+ (?:don't|do not) have (?:access|the ability|the means|the capability|any way|a way|information about|any information about|personal (?:information|data)))",rf="(?:(?:es|son|ser\xEDa|ser\xEDan|est\xE1|estar\xEDa|r\
431
+ 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\
432
+ lgo)|viola|violar\xEDa|infringe|va en contra|no tengo (?:acceso|la capacidad|forma de|manera de|informaci\xF3n (?:sobre|personal)|datos personales))",of="(?:(?:\xE9s|s\xF3n|seria|serien) (?:il\xB7legal|ilegal|\
433
+ 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)",sf="(?:(\
434
+ ?: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\
435
+ ntre)",af="(?:(?: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\
436
+ erletzt)",cf="(?:(?:\xE8|sono|sarebbe|sarebbero) (?:illegale|illecito|non etico|contrario a|una violazione|vietato|inappropriato)|non (?:\xE8|sarebbe) (?:appropriato|possibile|etico|legale|consentito)|viola\
437
+ |va contro)",lf="(?:(?:\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\
438
+ a)",Ct="(?:[\\p{L}\\p{N}'\u2019-]+[\\s,]+){0,14}?",uf=[`${tf},?\\sbut\\s${Ct}${nf}`,`(?:lo siento(?: mucho)?|lo lamento|disculpa|disculpe|perd\xF3n|perdona),?\\spero\\s${Ct}${rf}`,`(?:ho sento(?: molt\
439
+ )?|em sap greu|disculpa|perdona),?\\s(?:per\xF2|pero)\\s${Ct}${of}`,`(?:(?:je suis )?(?:vraiment )?d\xE9sol\xE9e?|pardon),?\\smais\\s${Ct}${sf}`,`(?:es tut mir (?:sehr |wirklich )?leid|tut mir leid|en\
440
+ tschuldigung),?\\saber\\s${Ct}${af}`,`(?:mi dispiace(?: molto)?|spiacente|scusa|scusami|mi scuso),?\\sma\\s${Ct}${cf}`,`(?:desculpe|desculpa|sinto muito|lamento|pe\xE7o desculpa),?\\smas\\s${Ct}${lf}`].
441
+ join("|"),df=new RegExp(`^(?:${ef}|(?:${uf})(?![\\p{L}]))`,"u"),pf="(?:(?:i'm |i am )?(?:really |so |very |truly |deeply |terribly )?sorry (?:to hear|to read|that you|you(?:'re| are)|you feel|for what\
442
+ 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\
443
+ 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)",ff="(?:mental health (?:professional|provider|expert|specialist|\
444
+ 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\
445
+ 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\
446
+ )?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\
447
+ rofessional (?:help|support)|seek (?:immediate|urgent|professional) (?:help|support))",mf="(?:(?:lo )?(?:siento|lamento) (?:mucho |much\xEDsimo )?(?:que (?:te sientas|est\xE9s|estes|te encuentres|pases|est\xE9\
448
+ s pasando)|escuchar|o\xEDr|leer|saber)|parece que (?:est\xE1s|estas) (?:pasando|atravesando)|me preocupa)",hf="(?:profesional(?:es)? de (?:la )?salud mental|psic\xF3log[oa]|psiquiatra|terapeuta|l\xEDnea (?:\
449
+ 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\
450
+ anza|ayuda profesional)",gf="(?:em sap (?:molt )?greu (?:que (?:et sentis|estiguis|passis)|sentir|llegir|saber)|ho sento (?:molt|molt\xEDssim)|sembla que (?:est\xE0s|passes) (?:passant|travessant)?)",
451
+ bf="(?: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\
452
+ car|truquis) al (?:112|024)|alg\xFA de (?:la teva )?confian\xE7a|(?:una )?persona de confian\xE7a|ajuda professional)",vf="(?:(?:je suis )?(?:vraiment |sinc\xE8rement |tellement |profond\xE9ment )?d\xE9sol\xE9e? \
453
+ (?: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))",yf="(?:professionnel(?:le)?s? de (?:la )?sant\xE9\
454
+ 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\
455
+ e de confiance|quelqu'un en qui (?:tu as|vous avez) confiance|aide professionnelle|sos amiti\xE9)",kf="(?:es tut mir (?:sehr |wirklich |so )?leid,? (?:dass|zu h\xF6ren|das zu h\xF6ren|zu lesen|das zu lesen)\
456
+ |das klingt (?:sehr |wirklich )?(?:schwer|belastend|schmerzhaft)|ich mache mir sorgen)",wf="(?:psychotherapeut\\p{L}*|psycholog\\p{L}*|psychiater\\p{L}*|therapeut\\p{L}*|fachkraft f\xFCr psychische|telefonse\
457
+ elsorge|krisendienst|krisentelefon|notruf\\p{L}*|notdienst|rettungsdienst|vertrauensperson|jemandem,? dem (?:du|sie) vertrau\\p{L}*|professionelle hilfe|professionelle unterst\xFCtzung)",xf="(?:mi dis\
458
+ piace (?:molto |davvero |tanto )?(?:sentire|leggere|sapere|che tu|che ti|che stia)|sembra che (?:tu stia|stai) (?:passando|attraversando))",Sf="(?:professionista della salute mentale|psicolog[oa]|psic\
459
+ 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\
460
+ |qualcuno di cui ti fidi|aiuto professionale)",Ef="(?: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|\
461
+ esteja) (?:passando|a passar))",_f="(?: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\
462
+ 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)",Cf=new RegExp(`^(?:${[pf,mf,gf,vf,kf,xf,
463
+ Ef].join("|")})(?![\\p{L}])`,"u"),Rf=new RegExp(`(?<![\\p{L}\\p{N}])(?:${[ff,hf,bf,yf,wf,Sf,_f].join("|")})(?![\\p{L}\\p{N}])`,"u"),Af=2e4,Tf="(?:explain|detail|describe|elaborate)",If=new RegExp(`(?:\
464
+ ^|[^\\p{L}'])(?:${Ko}|${Wo}${Rt}${Tf})(?![\\p{L}])`,"gu"),Pf=new RegExp(`^[^\\p{L}]*${Jo}\\s${vr}`,"u");function Ca(e,t){for(let n of e.matchAll(t))if(!Pf.test(e.slice(n.index)))return true;return false}var Df=new RegExp(
465
+ $a.source,"gu");function Of(e){return e.slice(0,4*300).replace(/[‘’ʼ`´]/g,"'").toLowerCase().replace(/\s+/g," ").trim().replace(/^[\s*#>_"'«“¿¡(\[-]+/u,"").trim()}function Lf(e){let t=[...e.
466
+ matchAll(/[.!?。](?:\s|$)/g)],n=t.length>=2?t[1].index+1:e.length;return e.slice(0,Math.min(n,240))}function Go(e){let t=/[.!?。:;](?:\s|$)/.exec(e);return t?e.slice(t.index+1).trim():""}function ti(e){
467
+ if(typeof e!="string"||e==="")return null;let t=Ra(e);if(t)return t;for(let n of Nf(e))if(Ra(n))return "refusal-in-structured-output";return null}var $f=200,Mf=4e4;function Nf(e){let t=e.trim();if(!(t.
468
+ startsWith("{")||t.startsWith("["))||t.length>Mf)return [];let n;try{n=JSON.parse(t);}catch{return []}let r=[],o=[n];for(;o.length>0&&r.length<$f;){let i=o.pop();if(typeof i=="string")i.trim()!==""&&r.push(
469
+ 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 Ra(e){
470
+ let t=Of(e);if(t==="")return null;let n=Lf(t),r=Bp.test(n);if(!r&&(kp.test(n)||jp.test(n)))return "opens-with-refusal";let o=r?Go(n):n;return wp.test(n)&&$a.test(o)||df.test(n)?"apology-then-refusal":t.
471
+ length<=300&&Ca(r?Go(t):t,Df)?"short-refusal":Cf.test(n)&&Rf.test(Aa(e,false))?"redirection":Ca(Aa(e,r),If)?"partial-refusal":null}function Aa(e,t){let n=e.slice(0,Af).replace(/[‘’ʼ`´]/g,"'").toLowerCase().
472
+ replace(/\s+/g," ").trim().replace(/^[\s*#>_"'«“¿¡(\[-]+/u,"").trim();return t?Go(n):n}var jf=/^content_filter(?:\s*:\s*(.*?))?\s*$/;function ni(e){return typeof e=="string"&&jf.test(e)}function ri(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function oi(e){if(!e)return 0;let{prompt_tokens:t,completion_tokens:n,total_tokens:r}=e;return !ri(t)||!ri(n)||!ri(r)?0:Math.max(0,r-
473
+ t-n)}var q="\\p{L}*",Bf=[`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\
469
474
  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\
470
475
  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",
471
476
  "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\
@@ -479,450 +484,450 @@ rcar|enforcar-me|me afogar|me machucar)","tirar a (?:minha )?(?:pr\xF3pria )?vid
479
484
  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 \
480
485
  \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",
481
486
  "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"],
482
- Mf=["panic attacks?","(?:mental|nervous) breakdown","psychotic (?:episode|break)","hearing voices","mental health crisis","feel(?:ing)? (?:so |really |very |completely )?(?:hopeless|worthless|suicidal\
487
+ Uf=["panic attacks?","(?:mental|nervous) breakdown","psychotic (?:episode|break)","hearing voices","mental health crisis","feel(?:ing)? (?:so |really |very |completely )?(?:hopeless|worthless|suicidal\
483
488
  |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\
484
489
  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\
485
490
  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\
486
491
  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\
487
- tak(?:i)? paniki",`panik atak${q}`,"serangan panik","c\u01A1n ho\u1EA3ng lo\u1EA1n"],Nf=["heart attack","having a stroke","(?:can't|cannot|can not) breathe","(?:not|stopped) breathing","chest pains?",
492
+ tak(?:i)? paniki",`panik atak${q}`,"serangan panik","c\u01A1n ho\u1EA3ng lo\u1EA1n"],Ff=["heart attack","having a stroke","(?:can't|cannot|can not) breathe","(?:not|stopped) breathing","chest pains?",
488
493
  `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\
489
494
  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\
490
495
  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\
491
496
  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",
492
497
  "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"],
493
- jf=/(?<![\p{L}\p{N}])(?:suicide (?:squad|doors?|burn|king|linux|slide|bid)|shoot myself in the foot)(?![\p{L}\p{N}])/gu,ri=e=>new RegExp(`(?<![\\p{L}\\p{N}])(?:${e.join("|")})(?![\\p{L}\\p{N}])`,"u"),
494
- Bf=ri($f),Uf=ri(Mf),zf=ri(Nf);function Ff(e){return e.normalize("NFC").replace(/[‘’ʼ`´]/g,"'").toLowerCase().replace(/\s+/g," ").replace(jf," ")}function Vf(e){if(typeof e!="string"||e==="")return null;
495
- let t=Ff(e);return Bf.test(t)?"self-harm":Uf.test(t)?"mental-health-crisis":zf.test(t)?"medical-emergency":null}function oi(e){for(let t of e){let n=Vf(t);if(n!==null)return n}return null}var br=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(
498
+ zf=/(?<![\p{L}\p{N}])(?:suicide (?:squad|doors?|burn|king|linux|slide|bid)|shoot myself in the foot)(?![\p{L}\p{N}])/gu,ii=e=>new RegExp(`(?<![\\p{L}\\p{N}])(?:${e.join("|")})(?![\\p{L}\\p{N}])`,"u"),
499
+ Vf=ii(Bf),qf=ii(Uf),Hf=ii(Ff);function Gf(e){return e.normalize("NFC").replace(/[‘’ʼ`´]/g,"'").toLowerCase().replace(/\s+/g," ").replace(zf," ")}function Wf(e){if(typeof e!="string"||e==="")return null;
500
+ let t=Gf(e);return Vf.test(t)?"self-harm":qf.test(t)?"mental-health-crisis":Hf.test(t)?"medical-emergency":null}function si(e){for(let t of e){let n=Wf(t);if(n!==null)return n}return null}var yr=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(
496
501
  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,
497
502
  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(
498
503
  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.
499
504
  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),
500
505
  i=t.slice(r+1),i.charCodeAt(0)===32&&(i=i.slice(1))),o){case "data":this.datos+=i+`
501
506
  `;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":
502
- this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};var Fe=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.
507
+ this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};var ze=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.
503
508
  resto.indexOf(`
504
509
 
505
510
  `))>=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()){
506
511
  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.
507
512
  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.
508
- detallesDeParada=s.delta.stop_details);let a=Ba(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?.
513
+ detallesDeParada=s.delta.stop_details);let a=Ha(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?.
509
514
  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(){
510
- return this.elisionObservada}negativa(){return this.paradaFinal==="refusal"}textoInicial(){return this.texto.valor()}negativaNoCobrada(){let t=this.usageFinal();return t!==null&&hr({stopReason:this.paradaFinal,
511
- stopDetails:this.detallesDeParada,bloques:this.eventos.content_block_start??0,outputTokens:t.output_tokens,iterations:t.iterations})}};function qf(e,t){if(!t||t.atribuible!==true||!(t.tokensLimpiadosToolUses>
512
- 0))return 0;let n=e.cachedInputPer1k;return typeof n!="number"||!Number.isFinite(n)||n<=0?0:t.tokensLimpiadosToolUses/1e3*n}function Ba(e){if(e===null||typeof e!="object")return null;let t=e.applied_edits;
515
+ return this.elisionObservada}negativa(){return this.paradaFinal==="refusal"}textoInicial(){return this.texto.valor()}negativaNoCobrada(){let t=this.usageFinal();return t!==null&&br({stopReason:this.paradaFinal,
516
+ stopDetails:this.detallesDeParada,bloques:this.eventos.content_block_start??0,outputTokens:t.output_tokens,iterations:t.iterations})}};function Kf(e,t){if(!t||t.atribuible!==true||!(t.tokensLimpiadosToolUses>
517
+ 0))return 0;let n=e.cachedInputPer1k;return typeof n!="number"||!Number.isFinite(n)||n<=0?0:t.tokensLimpiadosToolUses/1e3*n}function Ha(e){if(e===null||typeof e!="object")return null;let t=e.applied_edits;
513
518
  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));}
514
- return {borrados:t.length,tokensLimpiados:n,tokensLimpiadosToolUses:r}}function Ua(e){try{let t=JSON.parse(typeof e=="string"?e:e.toString("utf8"));return Ba(t.context_management)}catch{return null}}var Wt=class{resto="";uso=null;final=null;negada=false;texto=new yn;eventos={};observar(t){
519
+ return {borrados:t.length,tokensLimpiados:n,tokensLimpiadosToolUses:r}}function Ga(e){try{let t=JSON.parse(typeof e=="string"?e:e.toString("utf8"));return Ha(t.context_management)}catch{return null}}var Jt=class{resto="";uso=null;final=null;negada=false;texto=new Sn;eventos={};observar(t){
515
520
  this.resto+=typeof t=="string"?t:t.toString("utf8");let n;for(;(n=this.resto.indexOf(`
516
521
 
517
522
  `))>=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.
518
- parse(i),a=o??s.type;Hf(a,s)&&(this.negada=!0),a==="response.output_text.delta"&&this.texto.sumar(s.delta);let c=a!==void 0&&Object.hasOwn(Na,a)?Na[a]:void 0;if(c===void 0)continue;this.final=c;let l=s.
519
- response?.usage;if(!l)continue;c==="completed"?this.uso=vr(l):typeof l.input_tokens=="number"&&typeof l.output_tokens=="number"&&(this.uso=vr(l));}catch{}}}usage(){return this.uso}usageFinal(){return this.
520
- uso}estadoFinal(){return this.final}negativa(){return this.negada}textoInicial(){return this.texto.valor()}};function Hf(e,t){if(e==="response.refusal.delta"||e==="response.refusal.done")return true;if(t===
521
- null||typeof t!="object")return false;let n=t;return za(n.part)||si([n.item])?true:n.response!==null&&typeof n.response=="object"&&si(n.response.output)}function za(e){return e!==null&&typeof e=="object"&&e.
522
- type==="refusal"}function si(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(za)})}var Na={"response.completed":"complet\
523
- ed","response.incomplete":"incomplete","response.failed":"failed"};function vr(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.
524
- 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 Fa(e){
525
- return !e||typeof e.prompt_tokens!="number"||typeof e.completion_tokens!="number"?null:vr({input_tokens:e.prompt_tokens,output_tokens:e.completion_tokens+ni(e),input_tokens_details:{...e.prompt_tokens_details?.
523
+ parse(i),a=o??s.type;Jf(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.
524
+ response?.usage;if(!l)continue;c==="completed"?this.uso=kr(l):typeof l.input_tokens=="number"&&typeof l.output_tokens=="number"&&(this.uso=kr(l));}catch{}}}usage(){return this.uso}usageFinal(){return this.
525
+ uso}estadoFinal(){return this.final}negativa(){return this.negada}textoInicial(){return this.texto.valor()}};function Jf(e,t){if(e==="response.refusal.delta"||e==="response.refusal.done")return true;if(t===
526
+ null||typeof t!="object")return false;let n=t;return Wa(n.part)||ci([n.item])?true:n.response!==null&&typeof n.response=="object"&&ci(n.response.output)}function Wa(e){return e!==null&&typeof e=="object"&&e.
527
+ type==="refusal"}function ci(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(Wa)})}var qa={"response.completed":"complet\
528
+ ed","response.incomplete":"incomplete","response.failed":"failed"};function kr(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.
529
+ 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 Ka(e){
530
+ return !e||typeof e.prompt_tokens!="number"||typeof e.completion_tokens!="number"?null:kr({input_tokens:e.prompt_tokens,output_tokens:e.completion_tokens+oi(e),input_tokens_details:{...e.prompt_tokens_details?.
526
531
  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}:
527
- {}}})}var vn=class{parser=new br;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.
532
+ {}}})}var xn=class{parser=new yr;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.
528
533
  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.
529
534
  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\
530
- ject")return;if(this.eventos.chunk=(this.eventos.chunk??0)+1,Ga(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.
531
- usage===null||typeof n.usage!="object")return;let r=Fa(n.usage);r!==null&&(this.ultimoUso=r,Array.isArray(n.choices)&&n.choices.length===0&&(this.vioUsoFinal=true));}};function Va(e,t,n){let r=e.cachedInputPer1k??
532
- 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 ai(e,t,n){
533
- let r=n??Date.now(),o=Oe(e,r);if(!o)return null;let i=Uo(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.
535
+ ject")return;if(this.eventos.chunk=(this.eventos.chunk??0)+1,Qa(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.
536
+ usage===null||typeof n.usage!="object")return;let r=Ka(n.usage);r!==null&&(this.ultimoUso=r,Array.isArray(n.choices)&&n.choices.length===0&&(this.vioUsoFinal=true));}};function Ja(e,t,n){let r=e.cachedInputPer1k??
537
+ 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 ui(e,t,n){
538
+ let r=n??Date.now(),o=Oe(e,r);if(!o)return null;let i=zo(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.
534
539
  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??
535
- 0),u),m={entrada:s,salida:a,cacheLeida:c,cacheEscrita:u,cacheEscrita1h:f};return {costeUsd:Va(o,m,e),precio:o,tokens:m,instante:r}}function qa(e,t){let r=Gt(e,t)?.model;return typeof r=="string"?r:""}function Gt(e,t){
536
- try{let n=e,r={maxOutputLength:Wf};switch((t??"").trim().toLowerCase()){case "gzip":case "x-gzip":n=rt.gunzipSync(e,r);break;case "deflate":n=rt.inflateSync(e,r);break;case "br":n=rt.brotliDecompressSync(
537
- e,r);break;case "zstd":{let o=rt.zstdDecompressSync;if(typeof o!="function")return null;n=o(e,r);break}default:break}return JSON.parse(n.toString("utf8"))}catch{return null}}var Wf=5*1024*1024;function Ha(){
538
- return typeof rt.zstdDecompressSync=="function"}function Gf(e){try{return JSON.parse(typeof e=="string"?e:e.toString("utf8")).usage??null}catch{return null}}function yr(e,t){if(e==="/v1/messages")return Gf(
539
- 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 Fa(n.usage);let r=n.usage;return r&&
540
- typeof r.input_tokens=="number"&&typeof r.output_tokens=="number"?vr(r):null}catch{return null}}function Wa(e,t){if(!e.endsWith("/responses"))return false;try{let n=JSON.parse(typeof t=="string"?t:t.toString(
541
- "utf8"));return n!==null&&typeof n=="object"&&n.status==="failed"}catch{return false}}function Ga(e){let t=n=>{let r=n!==null&&typeof n=="object"?n.refusal:void 0;return typeof r=="string"&&r!==""};return Array.
542
- isArray(e)&&e.some(n=>{if(n===null||typeof n!="object")return false;let r=n;return ei(r.finish_reason)||t(r.message)||t(r.delta)})}function Ka(e,t){if(e!=="/v1/messages"&&!e.endsWith("/chat/completions")&&
540
+ 0),u),m={entrada:s,salida:a,cacheLeida:c,cacheEscrita:u,cacheEscrita1h:f};return {costeUsd:Ja(o,m,e),precio:o,tokens:m,instante:r}}function Ya(e,t){let r=Yt(e,t)?.model;return typeof r=="string"?r:""}function Yt(e,t){
541
+ try{let n=e,r={maxOutputLength:Yf};switch((t??"").trim().toLowerCase()){case "gzip":case "x-gzip":n=rt.gunzipSync(e,r);break;case "deflate":n=rt.inflateSync(e,r);break;case "br":n=rt.brotliDecompressSync(
542
+ e,r);break;case "zstd":{let o=rt.zstdDecompressSync;if(typeof o!="function")return null;n=o(e,r);break}default:break}return JSON.parse(n.toString("utf8"))}catch{return null}}var Yf=5*1024*1024;function Xa(){
543
+ return typeof rt.zstdDecompressSync=="function"}function Xf(e){try{return JSON.parse(typeof e=="string"?e:e.toString("utf8")).usage??null}catch{return null}}function wr(e,t){if(e==="/v1/messages")return Xf(
544
+ t);if(!At(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 Ka(n.usage);let r=n.usage;return r&&
545
+ typeof r.input_tokens=="number"&&typeof r.output_tokens=="number"?kr(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(
546
+ "utf8"));return n!==null&&typeof n=="object"&&n.status==="failed"}catch{return false}}function Qa(e){let t=n=>{let r=n!==null&&typeof n=="object"?n.refusal:void 0;return typeof r=="string"&&r!==""};return Array.
547
+ isArray(e)&&e.some(n=>{if(n===null||typeof n!="object")return false;let r=n;return ni(r.finish_reason)||t(r.message)||t(r.delta)})}function ec(e,t){if(e!=="/v1/messages"&&!e.endsWith("/chat/completions")&&
543
548
  !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\
544
- ompletions")?Ga(n.choices):si(n.output)}catch{return false}}var ii=1200,yn=class{t="";sumar(t){typeof t=="string"&&this.t.length<ii&&(this.t=(this.t+t).slice(0,ii));}lleno(){return this.t.length>=ii}valor(){
545
- return this.t}};function Ja(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
+ ompletions")?Qa(n.choices):ci(n.output)}catch{return false}}var ai=1200,Sn=class{t="";sumar(t){typeof t=="string"&&this.t.length<ai&&(this.t=(this.t+t).slice(0,ai));}lleno(){return this.t.length>=ai}valor(){
550
+ return this.t}};function tc(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==
546
551
  "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)?
547
552
  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,
548
- "output_text","text"):"").join(""):""}catch{return ""}}function Ya(e){return Qo(e)!==null}function ci(e,t){if(e!=="/v1/messages")return false;try{let n=JSON.parse(typeof t=="string"?t:t.toString("utf8"));return n===
549
- null||typeof n!="object"?!1:hr({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{
550
- return false}}function Za(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/\
553
+ "output_text","text"):"").join(""):""}catch{return ""}}function nc(e){return ti(e)!==null}function di(e,t){if(e!=="/v1/messages")return false;try{let n=JSON.parse(typeof t=="string"?t:t.toString("utf8"));return n===
554
+ null||typeof n!="object"?!1:br({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{
555
+ return false}}function rc(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/\
551
556
  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===
552
557
  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(`
553
- `)){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\
554
- ions")||e.endsWith("/responses")}var Kf=Buffer.from('"stream_options":{"include_usage":true},',"utf8");function Xa(e,t){let n=(t??"").trim().toLowerCase();if(n!==""&&n!=="identity")return {cuerpo:null,
558
+ `)){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 At(e){return e==="/v1/messages"||e.endsWith("/chat/complet\
559
+ ions")||e.endsWith("/responses")}var Zf=Buffer.from('"stream_options":{"include_usage":true},',"utf8");function oc(e,t){let n=(t??"").trim().toLowerCase();if(n!==""&&n!=="identity")return {cuerpo:null,
555
560
  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:"\
556
561
  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,
557
562
  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,
558
- motivo:"ilegible"}:{cuerpo:Buffer.concat([e.subarray(0,i+1),Kf,e.subarray(i+1)]),motivo:"inyectado"}}function Qa(e,t){let n=Gt(e,t);if(n===null||typeof n!="object")return null;let r=n;return r.stream!==
559
- true?null:r.stream_options?.include_usage===true}function li(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();
560
- return r==="chatgpt.com"||r.endsWith(".chatgpt.com")}catch{return false}}function ec(e,t,n,r,o,i,s,a,c,l){return rc(e,t,n,false,r,o,i,s,a,c,l===true)}function Jf(e){if(e===null||typeof e!="object"||Array.isArray(
563
+ motivo:"ilegible"}:{cuerpo:Buffer.concat([e.subarray(0,i+1),Zf,e.subarray(i+1)]),motivo:"inyectado"}}function ic(e,t){let n=Yt(e,t);if(n===null||typeof n!="object")return null;let r=n;return r.stream!==
564
+ true?null:r.stream_options?.include_usage===true}function pi(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();
565
+ return r==="chatgpt.com"||r.endsWith(".chatgpt.com")}catch{return false}}function sc(e,t,n,r,o,i,s,a,c,l){return lc(e,t,n,false,r,o,i,s,a,c,l===true)}function Qf(e){if(e===null||typeof e!="object"||Array.isArray(
561
566
  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"):
562
- [],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 Yf(e){
563
- return oi(Jf(e))}var Zf=new Set(["auto","default","priority","standard_only"]);function Xf(e){if(e==null)return 1;if(typeof e!="string")return null;if(Zf.has(e))return 1;let t=mr(e);return t!==null&&t.
564
- conDescuento&&t.factor!==null?t.factor:null}function Qf(e){if(e===void 0)return 1;if(e==="scale")return null;let t=mr(e);return t!==null&&t.factor!==null?t.factor:null}function tc(e,t,n,r,o){if(!n||!n.
567
+ [],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 em(e){
568
+ return si(Qf(e))}var tm=new Set(["auto","default","priority","standard_only"]);function nm(e){if(e==null)return 1;if(typeof e!="string")return null;if(tm.has(e))return 1;let t=gr(e);return t!==null&&t.
569
+ conDescuento&&t.factor!==null?t.factor:null}function rm(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 ac(e,t,n,r,o){if(!n||!n.
565
570
  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)
566
571
  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:"\
567
- primary-text-refusal"};if(Yf(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=Xf(
568
- i.service_tier),a=Qf(o.tierServido);if(s===null||a===null)return {ok:false,reason:"service-tier"};let c=Math.min(s,a),l=jt(e,t.instante),p=l?.cachedInputPer1k;if(!l||typeof p!="number"||!Number.isFinite(p)||
572
+ primary-text-refusal"};if(em(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=nm(
573
+ i.service_tier),a=rm(o.tierServido);if(s===null||a===null)return {ok:false,reason:"service-tier"};let c=Math.min(s,a),l=Ft(e,t.instante),p=l?.cachedInputPer1k;if(!l||typeof p!="number"||!Number.isFinite(p)||
569
574
  !(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=v=>Number.
570
- isInteger(v)&&v>=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&&Bo(e)===void 0;return {ok:true,credit:{requestId:n.
571
- 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 ui(e){
572
- return e.tierFactor*(e.creditedInputTokens/1e3*e.cachedInputPer1k+e.creditedOutputTokens/1e3*e.outputPer1k)}function nc(e,t,n,r,o,i){let s=o?ui(o):0;return i===true||!o||!(s>0)||!Number.isFinite(s)?rc(e,
575
+ isInteger(v)&&v>=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&&Fo(e)===void 0;return {ok:true,credit:{requestId:n.
576
+ 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 fi(e){
577
+ return e.tierFactor*(e.creditedInputTokens/1e3*e.cachedInputPer1k+e.creditedOutputTokens/1e3*e.outputPer1k)}function cc(e,t,n,r,o,i){let s=o?fi(o):0;return i===true||!o||!(s>0)||!Number.isFinite(s)?lc(e,
573
578
  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,
574
579
  eliminatedInput:0,compressedInput:0,baselineOutput:o.creditedOutputTokens,actualOutput:0,providerCachedInput:0},cache:{result:"singleflight",reference:o},cost:{baselineEstimate:s,actual:0,netSavings:1,
575
- basis:"reference"}}}function di(e,t,n,r,o){return {requestId:e,model:t,...o&&(o.sessionId||o.agentId)?{attribution:o}:{},calls:{avoidedLlm:0,actualLlm:0},tokens:{baselineInput:0,actualInput:0,eliminatedInput:0,
576
- compressedInput:0,baselineOutput:0,actualOutput:0,providerCachedInput:0},cache:{result:"miss"},cost:{baselineEstimate:n,actual:r,netSavings:n>0?Math.max(-100,Math.min(1,(n-r)/n)):0,basis:"shadow"}}}function em(e,t){
577
- let n=Oe(e.solicitado,t.instante);return n===void 0?0:Math.max(0,Va(n,t.tokens,e.solicitado)-t.costeUsd)}function rc(e,t,n,r,o,i,s,a,c=false,l=false,p=false){p&&(n={...n,costeUsd:0});let u=n.tokens.entrada+n.tokens.
580
+ basis:"reference"}}}function mi(e,t,n,r,o){return {requestId:e,model:t,...o&&(o.sessionId||o.agentId)?{attribution:o}:{},calls:{avoidedLlm:0,actualLlm:0},tokens:{baselineInput:0,actualInput:0,eliminatedInput:0,
581
+ compressedInput:0,baselineOutput:0,actualOutput:0,providerCachedInput:0},cache:{result:"miss"},cost:{baselineEstimate:n,actual:r,netSavings:n>0?Math.max(-100,Math.min(1,(n-r)/n)):0,basis:"shadow"}}}function om(e,t){
582
+ let n=Oe(e.solicitado,t.instante);return n===void 0?0:Math.max(0,Ja(n,t.tokens,e.solicitado)-t.costeUsd)}function lc(e,t,n,r,o,i,s,a,c=false,l=false,p=false){p&&(n={...n,costeUsd:0});let u=n.tokens.entrada+n.tokens.
578
583
  cacheLeida+n.tokens.cacheEscrita,m=!r&&!c&&!l&&!p,b=n.tokens.cacheEscrita-n.tokens.cacheEscrita1h,v=m&&s&&s.rebajadas>0&&s.yaEran5m===0&&!s.herramientaDeServidor&&b>0?b/1e3*n.precio.inputPer1k*(2-1.25):
579
- 0,g=m&&a?em(a,n):0,k=n.costeUsd+v+g,x=v+g,S=r||l||p?0:qf(n.precio,i),y=m?Fo(t,n.precio,{leidos:n.tokens.cacheLeida,escritos:n.tokens.cacheEscrita,escritos1h:n.tokens.cacheEscrita1h}):
584
+ 0,g=m&&a?om(a,n):0,k=n.costeUsd+v+g,x=v+g,S=r||l||p?0:Kf(n.precio,i),y=m?qo(t,n.precio,{leidos:n.tokens.cacheLeida,escritos:n.tokens.cacheEscrita,escritos1h:n.tokens.cacheEscrita1h}):
580
585
  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,actualInput:r?0:u,eliminatedInput:r?
581
586
  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?"singleflight":"miss"},...y?{nativeSavings:y}:
582
587
  {},cost:r?{baselineEstimate:n.costeUsd,actual:0,netSavings:p?0:1,basis:"estimated"}:{baselineEstimate:k,actual:n.costeUsd,netSavings:k>0?Math.max(-100,Math.min(1,x/k)):0,basis:"measured",...S>0?{eliminatedInputFloorCost:S}:
583
- {}}}}var tm=1024,kn=120,nm=8,rm=256*1024,om=/error|exception|traceback|warn|fatal|fail|panic|assert|denied|refused|timeout|\bat\s+\S+:\d+/i,sc=/^\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)/;
584
- function im(e){return Buffer.byteLength(typeof e=="string"?e:JSON.stringify(e??""))}function sm(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t&&typeof t=="object"&&typeof t.text=="string"?
588
+ {}}}}var im=1024,En=120,sm=8,am=256*1024,cm=/error|exception|traceback|warn|fatal|fail|panic|assert|denied|refused|timeout|\bat\s+\S+:\d+/i,pc=/^\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)/;
589
+ function lm(e){return Buffer.byteLength(typeof e=="string"?e:JSON.stringify(e??""))}function um(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t&&typeof t=="object"&&typeof t.text=="string"?
585
590
  t.text:"").join(`
586
- `):""}var am=/^\s*\d+[\t→]/;function ac(e){return e.replace(am,"")}function cm(e){if(!e)return "otro";let t=e.split(`
587
- `),n=Math.max(1,t.length),r=0,o=0,i=0;for(let s of t){let a=ac(s);(/^[+-](?![+-])/.test(a)||a.startsWith("@@")||a.startsWith("diff --git"))&&(r+=1),sc.test(a)&&(o+=1),(/^\s*(\d{4}-\d{2}-\d{2}|\[\d|\d{2}:\d{2}:\d{2})/.
588
- 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 lm(e,t){if(t==="diff"||t==="otro")return Buffer.byteLength(e);let n=e.
591
+ `):""}var dm=/^\s*\d+[\t→]/;function fc(e){return e.replace(dm,"")}function pm(e){if(!e)return "otro";let t=e.split(`
592
+ `),n=Math.max(1,t.length),r=0,o=0,i=0;for(let s of t){let a=fc(s);(/^[+-](?![+-])/.test(a)||a.startsWith("@@")||a.startsWith("diff --git"))&&(r+=1),pc.test(a)&&(o+=1),(/^\s*(\d{4}-\d{2}-\d{2}|\[\d|\d{2}:\d{2}:\d{2})/.
593
+ 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 fm(e,t){if(t==="diff"||t==="otro")return Buffer.byteLength(e);let n=e.
589
594
  split(`
590
- `),r=new Set;for(let i=0;i<n.length;i++){let s=ac(n[i]);(t==="log"?om.test(s):sc.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(
591
- n[i])+1;return Math.min(o,Buffer.byteLength(e))}var um=(e,t)=>e==="cache_control"?void 0:t;function dm(e){if(typeof e=="string")return `text:${e}`;if(!e||typeof e!="object"||Array.isArray(e))return `jso\
592
- 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,um)}`}
593
- function pm(e){return createHash("sha256").update(dm(e)).digest("hex").slice(0,16)}function fm(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.cache_control;return !t||typeof t!="object"?null:
594
- t.ttl==="1h"?"1h":"5m"}function cc(e){let t=[],n=(r,o)=>{let i=im(o),s={clave:pm(o),tipo:r,marca:fm(o),bytes:i,bytesV1:i,clase:"otro",esError:false};if(r.endsWith(":tool_result")&&o&&typeof o=="object"){
595
- let a=o;s.esError=a.is_error===true;let c=sm(a.content);s.clase=cm(c);let l=i-Buffer.byteLength(c);s.bytesV1=Math.min(i,Math.max(0,l)+lm(c,s.clase));}t.push(s);};if(Array.isArray(e.tools))for(let r of e.tools)
595
+ `),r=new Set;for(let i=0;i<n.length;i++){let s=fc(n[i]);(t==="log"?cm.test(s):pc.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(
596
+ n[i])+1;return Math.min(o,Buffer.byteLength(e))}var mm=(e,t)=>e==="cache_control"?void 0:t;function hm(e){if(typeof e=="string")return `text:${e}`;if(!e||typeof e!="object"||Array.isArray(e))return `jso\
597
+ 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,mm)}`}
598
+ function gm(e){return createHash("sha256").update(hm(e)).digest("hex").slice(0,16)}function bm(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.cache_control;return !t||typeof t!="object"?null:
599
+ t.ttl==="1h"?"1h":"5m"}function mc(e){let t=[],n=(r,o)=>{let i=lm(o),s={clave:gm(o),tipo:r,marca:bm(o),bytes:i,bytesV1:i,clase:"otro",esError:false};if(r.endsWith(":tool_result")&&o&&typeof o=="object"){
600
+ let a=o;s.esError=a.is_error===true;let c=um(a.content);s.clase=pm(c);let l=i-Buffer.byteLength(c);s.bytesV1=Math.min(i,Math.max(0,l)+fm(c,s.clase));}t.push(s);};if(Array.isArray(e.tools))for(let r of e.tools)
596
601
  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!=
597
602
  "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}\
598
- :${s?.type??"?"}`,s);}return t}function mm(){return {nacimiento:new Map,turno:0,elididosV2m:new Set}}function hm(e,t){let n=e.turno++;for(let r of t)e.nacimiento.has(r.clave)||e.nacimiento.set(r.clave,n);
599
- return n}function lc(e,t,n,r,o=rm){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>=tm&&f!==i;return t.map((u,f)=>{if(!s(u,
600
- f))return {clave:u.clave,bytes:u.bytes};let m=r-(n.nacimiento.get(u.clave)??r);return m>=2&&m*u.bytes/1024>=nm?{clave:`${u.clave}:e`,bytes:kn}:{clave:u.clave,bytes:u.bytes}});}function gm(e,t){let n=Oe(e,t);return n?{inputPer1k:n.inputPer1k,lecturaPer1k:n.cachedInputPer1k??n.inputPer1k,escrituraPer1k:n.inputPer1k*
601
- ve(e),escritura1hPer1k:n.inputPer1k*Nt(e)}:null}function oc(){return {lecturaUsd:0,escrituraUsd:0,entradaUsd:0,totalUsd:0,tokensLeidos:0,tokensEscritos:0,tokensEntrada:0,tokensInvalidados:0,invalidacionUsd:0}}
602
- var fi={"1h":36e5,"5m":3e5},bm=20,vm=6e3,ym=2e4,Kt=class{constructor(t=ym){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?
603
- r:null}escribir(t,n,r){this.entradas.delete(t),this.entradas.set(t,{expira:n+fi[r],ttl:r}),this.entradas.size>this.tope&&this.podar(n);}refrescar(t,n){let r=this.entradas.get(t);r&&(this.entradas.delete(
604
- t),this.entradas.set(t,{expira:n+fi[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().
605
- value;if(n===void 0)break;this.entradas.delete(n);}}};function km(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(
606
- "|").update(t[o]).digest("hex").slice(0,32),n[o]=r;return n}function wm(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\
607
- t");s&&i===r||(n+=1),r=s?i:"",t[o]=n;}return t}function ic(e,t){return e.endsWith(":image")?Math.min(t,vm):t}var wn=class{constructor(t,n){this.transformar=t;this.cache=n??new Kt;}transformar;estado=mm();cache;previo=[];previoUltimoBp=-1;previoTtl="\
608
- 5m";hayPrevio=false;atPrevio=0;acumulado=oc();paso(t){let n=oc(),r=hm(this.estado,t.bloques),o=gm(t.model,t.at),i=this.transformar(t.bloques,this.estado,r);if(!o||t.entradaReal<=0||i.length===0)return this.
603
+ :${s?.type??"?"}`,s);}return t}function vm(){return {nacimiento:new Map,turno:0,elididosV2m:new Set}}function ym(e,t){let n=e.turno++;for(let r of t)e.nacimiento.has(r.clave)||e.nacimiento.set(r.clave,n);
604
+ return n}function hc(e,t,n,r,o=am){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>=im&&f!==i;return t.map((u,f)=>{if(!s(u,
605
+ f))return {clave:u.clave,bytes:u.bytes};let m=r-(n.nacimiento.get(u.clave)??r);return m>=2&&m*u.bytes/1024>=sm?{clave:`${u.clave}:e`,bytes:En}:{clave:u.clave,bytes:u.bytes}});}function km(e,t){let n=Oe(e,t);return n?{inputPer1k:n.inputPer1k,lecturaPer1k:n.cachedInputPer1k??n.inputPer1k,escrituraPer1k:n.inputPer1k*
606
+ ve(e),escritura1hPer1k:n.inputPer1k*Ut(e)}:null}function uc(){return {lecturaUsd:0,escrituraUsd:0,entradaUsd:0,totalUsd:0,tokensLeidos:0,tokensEscritos:0,tokensEntrada:0,tokensInvalidados:0,invalidacionUsd:0}}
607
+ var gi={"1h":36e5,"5m":3e5},wm=20,xm=6e3,Sm=2e4,Xt=class{constructor(t=Sm){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?
608
+ r:null}escribir(t,n,r){this.entradas.delete(t),this.entradas.set(t,{expira:n+gi[r],ttl:r}),this.entradas.size>this.tope&&this.podar(n);}refrescar(t,n){let r=this.entradas.get(t);r&&(this.entradas.delete(
609
+ t),this.entradas.set(t,{expira:n+gi[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().
610
+ value;if(n===void 0)break;this.entradas.delete(n);}}};function Em(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(
611
+ "|").update(t[o]).digest("hex").slice(0,32),n[o]=r;return n}function _m(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\
612
+ t");s&&i===r||(n+=1),r=s?i:"",t[o]=n;}return t}function dc(e,t){return e.endsWith(":image")?Math.min(t,xm):t}var _n=class{constructor(t,n){this.transformar=t;this.cache=n??new Xt;}transformar;estado=vm();cache;previo=[];previoUltimoBp=-1;previoTtl="\
613
+ 5m";hayPrevio=false;atPrevio=0;acumulado=uc();paso(t){let n=uc(),r=ym(this.estado,t.bloques),o=km(t.model,t.at),i=this.transformar(t.bloques,this.estado,r);if(!o||t.entradaReal<=0||i.length===0)return this.
609
614
  previo=i,this.previoUltimoBp=-1,this.previoTtl="5m",this.hayPrevio=true,this.atPrevio=t.at,n;let s=i.map((y,I)=>t.bloques[I]?.tipo??""),a=i.map((y,I)=>t.bloques[I]?.marca??null),c=t.bloques.reduce((y,I)=>y+
610
- ic(I.tipo,I.bytes),0),l=c>0?t.entradaReal/c:0,p=i.map((y,I)=>ic(s[I],y.bytes)*l),u=km(t.model,i.map(y=>y.clave)),f=wm(s),m=a.map((y,I)=>y?I:-1).filter(y=>y>=0);if(m.length===0){for(let y=0;y<i.length;y++)
615
+ dc(I.tipo,I.bytes),0),l=c>0?t.entradaReal/c:0,p=i.map((y,I)=>dc(s[I],y.bytes)*l),u=Em(t.model,i.map(y=>y.clave)),f=_m(s),m=a.map((y,I)=>y?I:-1).filter(y=>y>=0);if(m.length===0){for(let y=0;y<i.length;y++)
611
616
  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+=
612
- n.tokensEntrada,this.acumulado.entradaUsd+=n.entradaUsd,this.acumulado.totalUsd+=n.totalUsd,n}let b=-1;for(let y of m){let I=f[y]-(bm-1);for(let D=y;D>=0&&f[D]>=I;D--)if(this.cache.viva(u[D],t.at)){D>
613
- b&&(b=D);break}}for(let y=0;y<=b;y++)this.cache.refrescar(u[y],t.at);let v=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>fi[this.previoTtl]?
617
+ n.tokensEntrada,this.acumulado.entradaUsd+=n.entradaUsd,this.acumulado.totalUsd+=n.totalUsd,n}let b=-1;for(let y of m){let I=f[y]-(wm-1);for(let D=y;D>=0&&f[D]>=I;D--)if(this.cache.viva(u[D],t.at)){D>
618
+ b&&(b=D);break}}for(let y=0;y<=b;y++)this.cache.refrescar(u[y],t.at);let v=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>gi[this.previoTtl]?
614
619
  []:this.previo.slice(b+1,this.previoUltimoBp+1),S=0;for(let y=0;y<i.length;y++){let I=i[y],D=p[y];if(y<=b){n.tokensLeidos+=D,n.lecturaUsd+=D/1e3*o.lecturaPer1k;continue}if(y>v){n.tokensEntrada+=D,n.entradaUsd+=
615
620
  D/1e3*o.inputPer1k;continue}for(;m[g]<y;)g+=1;let O=a[m[g]]==="1h"?o.escritura1hPer1k:o.escrituraPer1k;n.tokensEscritos+=D,n.escrituraUsd+=D/1e3*O;let $=S;for(;$<x.length&&x[$].clave!==I.clave;)$+=1;$<
616
621
  x.length&&(x[$].bytes===I.bytes&&(n.tokensInvalidados+=D,n.invalidacionUsd+=D/1e3*(O-o.lecturaPer1k)),S=$+1);}return this.previo=i,this.previoUltimoBp=v,this.previoTtl=a[v]??"5m",this.hayPrevio=true,this.
617
622
  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.
618
623
  totalUsd+=n.totalUsd,this.acumulado.tokensLeidos+=n.tokensLeidos,this.acumulado.tokensEscritos+=n.tokensEscritos,this.acumulado.tokensEntrada+=n.tokensEntrada,this.acumulado.tokensInvalidados+=n.tokensInvalidados,
619
- this.acumulado.invalidacionUsd+=n.invalidacionUsd,n}};function uc(e){return e.map(t=>({clave:t.clave,bytes:t.bytes}))}var Sm=64,kr=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??
620
- 0),r=(t.uso.input_tokens??0)+(t.uso.cache_read_input_tokens??0)+n;if(r<=0)return null;let o={bloques:cc(t.cuerpo),at:t.at,model:t.model,entradaReal:r,escritura1h:(t.uso.cache_creation?.ephemeral_1h_input_tokens??
624
+ this.acumulado.invalidacionUsd+=n.invalidacionUsd,n}};function gc(e){return e.map(t=>({clave:t.clave,bytes:t.bytes}))}var Rm=64,xr=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??
625
+ 0),r=(t.uso.input_tokens??0)+(t.uso.cache_read_input_tokens??0)+n;if(r<=0)return null;let o={bloques:mc(t.cuerpo),at:t.at,model:t.model,entradaReal:r,escritura1h:(t.uso.cache_creation?.ephemeral_1h_input_tokens??
621
626
  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){
622
627
  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(
623
- "hex").slice(0,16)}\xB7${t.model}`}cachesDe(t){let n=this.cachesPorModelo.get(t);return n||(n={base:new Kt,v0:new Kt},this.cachesPorModelo.set(t,n)),n}cadenaPara(t,n){let r=this.cadenas.get(t);if(!r){
624
- let o=this.cachesDe(n);if(r={base:new wn(i=>uc(i),o.base),v0:new wn((i,s,a)=>lc("v0",i,s,a),o.v0),ultimoUso:0},this.cadenas.set(t,r),this.cadenas.size>Sm){let i=null,s=1/0;for(let[a,c]of this.cadenas)
625
- c.ultimoUso<s&&(s=c.ultimoUso,i=a);i!==null&&this.cadenas.delete(i);}}return r.ultimoUso=Date.now(),r}};var Em="[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\
626
- oard/install and relaunch",wr=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,
628
+ "hex").slice(0,16)}\xB7${t.model}`}cachesDe(t){let n=this.cachesPorModelo.get(t);return n||(n={base:new Xt,v0:new Xt},this.cachesPorModelo.set(t,n)),n}cadenaPara(t,n){let r=this.cadenas.get(t);if(!r){
629
+ let o=this.cachesDe(n);if(r={base:new _n(i=>gc(i),o.base),v0:new _n((i,s,a)=>hc("v0",i,s,a),o.v0),ultimoUso:0},this.cadenas.set(t,r),this.cadenas.size>Rm){let i=null,s=1/0;for(let[a,c]of this.cadenas)
630
+ c.ultimoUso<s&&(s=c.ultimoUso,i=a);i!==null&&this.cadenas.delete(i);}}return r.ultimoUso=Date.now(),r}};var Am="[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\
631
+ oard/install and relaunch",Sr=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,
627
632
  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(),
628
633
  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===
629
634
  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(
630
- "entitlements HTTP 401",Em);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(
635
+ "entitlements HTTP 401",Am);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(
631
636
  "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==
632
637
  "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,
633
638
  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\
634
- ing`));}};var hi="https://savings.bivelio.com",ge="https://savings.bivelio.com/dashboard/account",ft="https://savings.bivelio.com/dashboard/install",_m=1e4,Cm=3e3,pc=6e4,Am=36e5,Tm=7*86400,Rm=3e4,Im=86400,Pm="B\
635
- VL";function gi(e){return wt}function Dm(e){return $o(e)?Object.keys(e.keys??{}).length===0:e.trim()===""}var mi=e=>typeof e=="string"&&e.trim()!=="",xr=e=>typeof e=="number"&&Number.
636
- isFinite(e);function Om(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let t=e;return mi(t.jti)&&mi(t.org_id)&&mi(t.plan)&&xr(t.seats)&&xr(t.issued_at)&&xr(t.expires_at)&&xr(t.grace_days)&&
637
- t.grace_days>=0&&Array.isArray(t.features)&&t.features.every(n=>typeof n=="string")}function Er(e,t){try{let n=Ft(typeof e=="string"?e:""),r=hn(n);if(r==="empty")return {ok:!1,shape:"empty",reason:"emp\
638
- 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;
639
- if(i!==Pm)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:"\
640
- payload is not valid JSON"}}return Om(s)?{ok:!0,license:{token:n,payload:ur(s)}}:{ok:!1,shape:"token",reason:"license payload has the wrong field types"}}catch(n){return {ok:false,shape:"token",reason:`ve\
641
- rification error: ${Sn(String(n))}`}}}function Jt(e,t,n){return dr(e,Math.floor(t/1e3),n)}var Yt=e=>e==="active"||e==="grace";function Sn(e,t=200){let n=e.replace(/[^\x20-\x7E]/g,"?");return n.length>
642
- t?`${n.slice(0,t)}...`:n}function Lm(e){return `${Number((e/1e3).toFixed(3))} s`}function $m(e){let t=e,n=typeof t?.message=="string"&&t.message!==""?t.message:String(e),r=t?.cause,o=r&&typeof r.code==
643
- "string"?r.code:r&&typeof r.message=="string"?r.message:void 0;return o?`${n} (${o})`:n}async function fc(e){let t=`${e.licenseServerUrl.replace(/\/+$/,"")}/api/license/current`,n=c=>e.serviceAccountKey?
639
+ ing`));}};var vi="https://savings.bivelio.com",ge="https://savings.bivelio.com/dashboard/account",mt="https://savings.bivelio.com/dashboard/install",Tm=1e4,Im=3e3,vc=6e4,Pm=36e5,Dm=7*86400,Om=3e4,Lm=86400,$m="B\
640
+ VL";function yi(e){return ft}function Mm(e){return fr(e)?Object.keys(e.keys??{}).length===0:e.trim()===""}var bi=e=>typeof e=="string"&&e.trim()!=="",Er=e=>typeof e=="number"&&Number.
641
+ isFinite(e);function Nm(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let t=e;return bi(t.jti)&&bi(t.org_id)&&bi(t.plan)&&Er(t.seats)&&Er(t.issued_at)&&Er(t.expires_at)&&Er(t.grace_days)&&
642
+ t.grace_days>=0&&Array.isArray(t.features)&&t.features.every(n=>typeof n=="string")}function Cr(e,t){try{let n=St(typeof e=="string"?e:""),r=qt(n);if(r==="empty")return {ok:!1,shape:"empty",reason:"emp\
643
+ ty"};if(r==="malformed")return {ok:!1,shape:"malformed",reason:"malformed"};let o=Ht(n,t);if(!o.ok||!o.payloadBytes)return {ok:!1,shape:"token",reason:Rn(o.reason??"bad signature")};let i=o.header?.typ;
644
+ if(i!==$m)return {ok:!1,shape:"token",reason:`not a license token (typ ${Rn(String(i??"none"))})`};let s;try{s=JSON.parse(new TextDecoder().decode(o.payloadBytes));}catch{return {ok:!1,shape:"token",reason:"\
645
+ payload is not valid JSON"}}return Nm(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\
646
+ rification error: ${Rn(String(n))}`}}}function Zt(e,t,n){return kn(e,Math.floor(t/1e3),n)}var Qt=e=>e==="active"||e==="grace";function Rn(e,t=200){let n=e.replace(/[^\x20-\x7E]/g,"?");return n.length>
647
+ t?`${n.slice(0,t)}...`:n}function jm(e){return `${Number((e/1e3).toFixed(3))} s`}function Bm(e){let t=e,n=typeof t?.message=="string"&&t.message!==""?t.message:String(e),r=t?.cause,o=r&&typeof r.code==
648
+ "string"?r.code:r&&typeof r.message=="string"?r.message:void 0;return o?`${n} (${o})`:n}async function yc(e){let t=`${e.licenseServerUrl.replace(/\/+$/,"")}/api/license/current`,n=c=>e.serviceAccountKey?
644
649
  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.
645
- addEventListener("abort",s,{once:true}));let a=c=>o?{kind:"unreachable",cause:`timed out after ${Lm(e.timeoutMs)}`}:{kind:"unreachable",cause:Sn(n(`network error: ${$m(c)}`))};try{let c=e.fetchImpl??globalThis.
650
+ addEventListener("abort",s,{once:true}));let a=c=>o?{kind:"unreachable",cause:`timed out after ${jm(e.timeoutMs)}`}:{kind:"unreachable",cause:Rn(n(`network error: ${Bm(c)}`))};try{let c=e.fetchImpl??globalThis.
646
651
  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\
647
652
  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:"\
648
- 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=Er(u,e.publicKey);return f.
649
- 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 Me(e){try{return new Date(
650
- e*1e3).toISOString().slice(0,10)}catch{return "an unknown date"}}var En=(e,t)=>e+t*Im,Mm="WARNING: BIVELIO_LICENSE_KEY belongs to a different organization than BIVELIO_SERVICE_KEY and is ignored; the l\
651
- icense of the service key's organization is used. Unset BIVELIO_LICENSE_KEY or replace it with this organization's license key.",Nm=e=>`WARNING: the license served by savings.bivelio.com does not veri\
652
- fy against this build's BiVelio key (${e}); starting with BIVELIO_LICENSE_KEY. Update @bivelio/savings-layer (npm i -g @bivelio/savings-layer).`;function jm(e,t={}){switch(e){case "no-public-key":return "\
653
+ 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=Cr(u,e.publicKey);return f.
654
+ ok?{kind:"token",license:f.license}:{kind:"not-verifying",reason:Rn(f.reason)}}catch(c){return a(c)}finally{clearTimeout(i),e.signal?.removeEventListener("abort",s);}}function Me(e){try{return new Date(
655
+ e*1e3).toISOString().slice(0,10)}catch{return "an unknown date"}}var An=(e,t)=>e+t*Lm,Um="WARNING: BIVELIO_LICENSE_KEY belongs to a different organization than BIVELIO_SERVICE_KEY and is ignored; the l\
656
+ icense of the service key's organization is used. Unset BIVELIO_LICENSE_KEY or replace it with this organization's license key.",Fm=e=>`WARNING: the license served by savings.bivelio.com does not veri\
657
+ fy against this build's BiVelio key (${e}); starting with BIVELIO_LICENSE_KEY. Update @bivelio/savings-layer (npm i -g @bivelio/savings-layer).`;function zm(e,t={}){switch(e){case "no-public-key":return "\
653
658
  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 `\
654
- 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 ${ft}, step 2). Export the\
659
+ 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 ${mt}, step 2). Export the\
655
660
  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?
656
- " It looks like a license key: that one goes in BIVELIO_LICENSE_KEY.":"")+` Create a service key at ${ft} (step 2), export it and relaunch.`;case "service-key-not-recognised":return `BIVELIO_SERVICE_KEY\
657
- is not recognised by savings.bivelio.com (HTTP 401): it was deleted or rotated, or it was copied incompletely. Create a new one at ${ft} (step 2), export it and relaunch.`;case "no-license":return `you\
658
- 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 ${ft}, or subscribe a\
661
+ " It looks like a license key: that one goes in BIVELIO_LICENSE_KEY.":"")+` Create a service key at ${mt} (step 2), export it and relaunch.`;case "service-key-not-recognised":return `BIVELIO_SERVICE_KEY\
662
+ is not recognised by savings.bivelio.com (HTTP 401): it was deleted or rotated, or it was copied incompletely. Create a new one at ${mt} (step 2), export it and relaunch.`;case "no-license":return `you\
663
+ 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 ${mt}, or subscribe a\
659
664
  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 ${Me(n)} and its grace period e\
660
- nded on ${Me(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??
665
+ nded on ${Me(An(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??
661
666
  "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\
662
667
  @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\
663
- 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 ${ft}. Or unset BIVELIO_LICENSE_KEY: the gateway collects the l\
664
- icense online by itself.`:`BIVELIO_LICENSE_KEY does not verify against this build's BiVelio key (${n}). Copy the WHOLE key again from ${ft}, or unset BIVELIO_LICENSE_KEY to collect it online; if it pe\
668
+ 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 ${mt}. Or unset BIVELIO_LICENSE_KEY: the gateway collects the l\
669
+ icense online by itself.`:`BIVELIO_LICENSE_KEY does not verify against this build's BiVelio key (${n}). Copy the WHOLE key again from ${mt}, or unset BIVELIO_LICENSE_KEY to collect it online; if it pe\
665
670
  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\
666
- 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 ${ft}) as a fallback: it is verified on t\
667
- his machine and used only when savings.bivelio.com cannot be reached, and it must be replaced by hand every billing period.`}}function dc(e,t,n,r){let o=e.plan.toUpperCase(),i=e.grace_days,s=Me(e.expires_at),
671
+ 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 ${mt}) as a fallback: it is verified on t\
672
+ his machine and used only when savings.bivelio.com cannot be reached, and it must be replaced by hand every billing period.`}}function bc(e,t,n,r){let o=e.plan.toUpperCase(),i=e.grace_days,s=Me(e.expires_at),
668
673
  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, \
669
- verified on this machine";if(n==="grace"){let c=Me(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\
670
- til ${s} (+${i} ${i===1?"day":"days"} grace), ${a}`}var Ve=(e,t)=>({ok:false,code:e,message:jm(e,t)});async function mc(e){let t=e.now??Date.now,n=gi();if(Dm(n))return Ve("no-public-key");let r=e.
671
- serviceAccountKey?.trim();if(!r)return Ve("service-key-missing");if(!r.startsWith("bvk_"))return Ve("service-key-malformed",{keyLooksLikeLicense:hn(Ft(r))==="token"});let o=null;if(e.licenseKey!==void 0){
672
- let c=Er(e.licenseKey,n);if(c.ok)o=c.license;else if(c.shape!=="empty")return Ve("license-invalid",{tokenSource:"BIVELIO_LICENSE_KEY",shape:c.shape,reason:c.reason})}let i=o!==null&&Yt(Jt(o.payload,t())),
673
- s=await fc({licenseServerUrl:e.licenseServerUrl,serviceAccountKey:r,publicKey:n,timeoutMs:e.timeoutMs??(i?Cm:_m),...e.fetchImpl?{fetchImpl:e.fetchImpl}:{}}),a=(c,l)=>{let p=Jt(o.payload,t());return Yt(
674
- p)?{ok:true,license:o,source:"offline",status:p,line:dc(o.payload,"offline",p,c),lineIsWarning:true,warnings:l}:Ve("license-expired",{expiresAt:o.payload.expires_at,graceDays:o.payload.grace_days,...c?{cause:c}:
675
- {}})};switch(s.kind){case "key-unknown":return Ve("service-key-not-recognised");case "no-license":return Ve("no-license");case "token":{let c=s.license,l=Jt(c.payload,t()),p=o&&o.payload.org_id!==c.payload.
676
- org_id?[Mm]:[];return Yt(l)?{ok:true,license:c,source:"online",status:l,line:dc(c.payload,"online",l),lineIsWarning:l==="grace",warnings:p}:Ve("license-expired",{expiresAt:c.payload.expires_at,graceDays:c.
677
- payload.grace_days})}case "not-verifying":return i?a(void 0,[Nm(s.reason)]):Ve("license-invalid",{tokenSource:"savings.bivelio.com",reason:s.reason});case "unreachable":return o?a(s.cause,[]):Ve("unreac\
678
- hable",{cause:s.cause})}}var Bm=new Set(["expired","revoked","no-license","blocked","invalid"]);function bi(e,t,n){let r=typeof t=="string"?t.trim():"";if(r!==""){let i="reported by savings.bivelio.co\
674
+ verified on this machine";if(n==="grace"){let c=Me(An(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\
675
+ til ${s} (+${i} ${i===1?"day":"days"} grace), ${a}`}var Ve=(e,t)=>({ok:false,code:e,message:zm(e,t)});async function kc(e){let t=e.now??Date.now,n=yi();if(Mm(n))return Ve("no-public-key");let r=e.
676
+ serviceAccountKey?.trim();if(!r)return Ve("service-key-missing");if(!r.startsWith("bvk_"))return Ve("service-key-malformed",{keyLooksLikeLicense:qt(St(r))==="token"});let o=null;if(e.licenseKey!==void 0){
677
+ let c=Cr(e.licenseKey,n);if(c.ok)o=c.license;else if(c.shape!=="empty")return Ve("license-invalid",{tokenSource:"BIVELIO_LICENSE_KEY",shape:c.shape,reason:c.reason})}let i=o!==null&&Qt(Zt(o.payload,t())),
678
+ s=await yc({licenseServerUrl:e.licenseServerUrl,serviceAccountKey:r,publicKey:n,timeoutMs:e.timeoutMs??(i?Im:Tm),...e.fetchImpl?{fetchImpl:e.fetchImpl}:{}}),a=(c,l)=>{let p=Zt(o.payload,t());return Qt(
679
+ p)?{ok:true,license:o,source:"offline",status:p,line:bc(o.payload,"offline",p,c),lineIsWarning:true,warnings:l}:Ve("license-expired",{expiresAt:o.payload.expires_at,graceDays:o.payload.grace_days,...c?{cause:c}:
680
+ {}})};switch(s.kind){case "key-unknown":return Ve("service-key-not-recognised");case "no-license":return Ve("no-license");case "token":{let c=s.license,l=Zt(c.payload,t()),p=o&&o.payload.org_id!==c.payload.
681
+ org_id?[Um]:[];return Qt(l)?{ok:true,license:c,source:"online",status:l,line:bc(c.payload,"online",l),lineIsWarning:l==="grace",warnings:p}:Ve("license-expired",{expiresAt:c.payload.expires_at,graceDays:c.
682
+ payload.grace_days})}case "not-verifying":return i?a(void 0,[Fm(s.reason)]):Ve("license-invalid",{tokenSource:"savings.bivelio.com",reason:s.reason});case "unreachable":return o?a(s.cause,[]):Ve("unreac\
683
+ hable",{cause:s.cause})}}var Vm=new Set(["expired","revoked","no-license","blocked","invalid"]);function ki(e,t,n){let r=typeof t=="string"?t.trim():"";if(r!==""){let i="reported by savings.bivelio.co\
679
684
  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\
680
- 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 ${Me(En(n.expires_at,n.grace_days))}`:"grace\
681
- 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\
682
- ted";function Um(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 `\
683
- 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 `\
684
- 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\
685
- 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\
686
- s are refused; ${xn}. Relaunch the terminal; if it persists, write to support@bivelio.com.`}}function hc(e){return JSON.stringify({type:"error",error:{type:"license_error",status:e,message:Um(e)}})}var zm={
685
+ 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 ${Me(An(n.expires_at,n.grace_days))}`:"grace\
686
+ 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\
687
+ ted";function qm(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}; ${Cn}.`;case "revoked":return `\
688
+ bvsala gateway: the BiVelio license for this organization is no longer active (revoked or cancelled). New requests are refused; ${Cn}. Check ${ge} or write to support@bivelio.com.`;case "no-license":return `\
689
+ bvsala gateway: this organization has no active BiVelio license. New requests are refused until you subscribe at ${ge}; ${Cn}.`;case "blocked":return `bvsala gateway: savings.bivelio.com reports the BiV\
690
+ elio license for this organization as not active. New requests are refused; ${Cn}. Check ${ge}.`;case "invalid":return `bvsala gateway: the license loaded by this gateway no longer verifies. New request\
691
+ s are refused; ${Cn}. Relaunch the terminal; if it persists, write to support@bivelio.com.`}}function wc(e){return JSON.stringify({type:"error",error:{type:"license_error",status:e,message:qm(e)}})}var Hm={
687
692
  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@\
688
- bivelio.com"};function gc(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.
689
- state]}`;let r=Me(n.expires_at),o=Me(En(n.expires_at,n.grace_days));return e!==null&&Bm.has(e)?t.state==="grace"?`[bvsala gateway] license in grace again (it expired on ${r} and keeps working until ${o}\
693
+ bivelio.com"};function xc(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. ${Hm[t.
694
+ state]}`;let r=Me(n.expires_at),o=Me(An(n.expires_at,n.grace_days));return e!==null&&Vm.has(e)?t.state==="grace"?`[bvsala gateway] license in grace again (it expired on ${r} and keeps working until ${o}\
690
695
  ): 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 \
691
- on ${r} and keeps working until ${o}. Renew at ${ge}`:null}function vi(e,t,n,r){return {license:e,gate:pr(e.token,t,{revocation:n,...r?{now:r}:{}})}}var Sr=class{constructor(t){this.o=t;}o;timer=null;enVuelo=false;parado=false;ctrl=null;avisados=new Set;ahora(){
692
- return this.o.now?this.o.now():Date.now()}start(t={}){this.parado||this.timer!==null||(this.timer=setInterval(()=>{this.check();},this.o.intervalMs??Am),this.timer.unref?.(),t.checkNow&&this.check({force:true}));}stop(){
696
+ on ${r} and keeps working until ${o}. Renew at ${ge}`:null}function wi(e,t,n,r){return {license:e,gate:wn(e.token,t,{revocation:n,...r?{now:r}:{}})}}var _r=class{constructor(t){this.o=t;}o;timer=null;enVuelo=false;parado=false;ctrl=null;avisados=new Set;ahora(){
697
+ return this.o.now?this.o.now():Date.now()}start(t={}){this.parado||this.timer!==null||(this.timer=setInterval(()=>{this.check();},this.o.intervalMs??Pm),this.timer.unref?.(),t.checkNow&&this.check({force:true}));}stop(){
693
698
  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.
694
- enVuelo||this.parado)return false;let n=this.o.current(),r=Yt(Jt(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.
695
- force&&!i&&r&&o>(this.o.leadSeconds??Tm))return false;this.enVuelo=true;let s=new AbortController;this.ctrl=s;try{let a=await fc({licenseServerUrl:this.o.licenseServerUrl,serviceAccountKey:this.o.serviceAccountKey,
696
- publicKey:this.o.publicKey,timeoutMs:this.o.timeoutMs??Rm,signal:s.signal,...this.o.fetchImpl?{fetchImpl:this.o.fetchImpl}:{}});if(this.parado)return !1;let c=Me(En(n.payload.expires_at,n.payload.grace_days));
697
- 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)||!Yt(Jt(l,this.ahora(),p)))return !1;let u=Yt(Jt(n.payload,this.
699
+ enVuelo||this.parado)return false;let n=this.o.current(),r=Qt(Zt(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.
700
+ force&&!i&&r&&o>(this.o.leadSeconds??Dm))return false;this.enVuelo=true;let s=new AbortController;this.ctrl=s;try{let a=await yc({licenseServerUrl:this.o.licenseServerUrl,serviceAccountKey:this.o.serviceAccountKey,
701
+ publicKey:this.o.publicKey,timeoutMs:this.o.timeoutMs??Om,signal:s.signal,...this.o.fetchImpl?{fetchImpl:this.o.fetchImpl}:{}});if(this.parado)return !1;let c=Me(An(n.payload.expires_at,n.payload.grace_days));
702
+ 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)||!Qt(Zt(l,this.ahora(),p)))return !1;let u=Qt(Zt(n.payload,this.
698
703
  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",
699
- `[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 ${ft} and relaunch.`),!1;case "no-licen\
704
+ `[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 ${mt} and relaunch.`),!1;case "no-licen\
700
705
  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}\
701
706
  ; 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\
702
- 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 bc(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)?.
703
- length??0;return {definiciones:t,referencias:r,diferidas:o}}var Fm=40;function vc(e){return e.referencias>0||(e.diferidas??0)>0||e.definiciones<Fm?null:`[bvsala gateway] your client sends ${e.definiciones}\
707
+ 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 Sc(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)?.
708
+ length??0;return {definiciones:t,referencias:r,diferidas:o}}var Gm=40;function Ec(e){return e.referencias>0||(e.diferidas??0)>0||e.definiciones<Gm?null:`[bvsala gateway] your client sends ${e.definiciones}\
704
709
  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\
705
- 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 yi=5*1024*1024,qm=["authorization","x-api-key","anthropic-version","anthropic-beta","api-key","openai-organization","openai-project"];function yc(e,t,n,r=""){return createHash(
710
+ 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 xi=5*1024*1024,Km=["authorization","x-api-key","anthropic-version","anthropic-beta","api-key","openai-organization","openai-project"];function _c(e,t,n,r=""){return createHash(
706
711
  "sha256").update(e).update(`
707
712
  `).update(t).update(`
708
713
  `).update(r).update(`
709
- `).update(n).digest("hex")}function kc(e){return qm.map(t=>`${t}=${e(t)??""}`).join(`
710
- `)}var _r=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=[],
711
- i=0,s=false;return {capturar:a=>{if(!s){if(i+=a.length,i>yi){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?
714
+ `).update(n).digest("hex")}function Cc(e){return Km.map(t=>`${t}=${e(t)??""}`).join(`
715
+ `)}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=[],
716
+ i=0,s=false;return {capturar:a=>{if(!s){if(i+=a.length,i>xi){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?
712
717
  {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;
713
- return r&&(this.gemelas+=1),r}tieneEnVuelo(t){return this.enVuelo.has(t)}};var wc={openai:"https://api.openai.com",anthropic:"https://api.anthropic.com"};function xc(e){let t;try{t=new URL(e).origin;}catch{return false}return Object.values(wc).includes(t)}function Sc(e){for(let t=0;t<
714
- 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 Hm(e){
715
- 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 Ec(e){if(e.flag===
718
+ return r&&(this.gemelas+=1),r}tieneEnVuelo(t){return this.enVuelo.has(t)}};var Rc={openai:"https://api.openai.com",anthropic:"https://api.anthropic.com"};function Ac(e){let t;try{t=new URL(e).origin;}catch{return false}return Object.values(Rc).includes(t)}function Tc(e){for(let t=0;t<
719
+ 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 Jm(e){
720
+ 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 Ic(e){if(e.flag===
716
721
  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&&
717
- e.env.trim()!=="")t=e.env,n="env";else return {ok:true,upstream:void 0,origen:"none"};let r=wc[t.trim().toLowerCase()];if(r!==void 0)return {ok:true,upstream:r,origen:n};let o={ok:false,error:`[bvsala gateway]\
718
- invalid upstream ${Hm(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
+ e.env.trim()!=="")t=e.env,n="env";else return {ok:true,upstream:void 0,origen:"none"};let r=Rc[t.trim().toLowerCase()];if(r!==void 0)return {ok:true,upstream:r,origen:n};let o={ok:false,error:`[bvsala gateway]\
723
+ invalid upstream ${Jm(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!==
719
724
  ""||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\
720
- ns), so put that prefix in the client's base URL instead.`}:{ok:true,upstream:i.origin,origen:n}}var Wm="other reasons",Cr=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:Wm;this.noMedidas.
721
- set(n,(this.noMedidas.get(n)??0)+1);}estado(){return {medidas:this.medidas,replicas:this.replicas,noMedidas:Object.fromEntries(this.noMedidas)}}};function _c(e,t){let n=`[bvsala ${t}] metering in this r\
725
+ ns), so put that prefix in the client's base URL instead.`}:{ok:true,upstream:i.origin,origen:n}}var Ym="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:Ym;this.noMedidas.
726
+ set(n,(this.noMedidas.get(n)??0)+1);}estado(){return {medidas:this.medidas,replicas:this.replicas,noMedidas:Object.fromEntries(this.noMedidas)}}};function Pc(e,t){let n=`[bvsala ${t}] metering in this r\
722
727
  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\
723
728
  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\
724
729
  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(
725
- "; ");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",wi="x-bvsala-request-id",Gm="/_bvsala/",Km="bvsala.gateway.report/1",Cc="bvsala.gateway.status/1";var Ar=/^[A-Za-z0-9._:-]{1,200}$/;function Ac(e){let t=(Array.isArray(e)?e[0]:e)?.trim().toLowerCase();return t==="1"||t==="true"}var Tr=class{entradas=new Map;porRespuestaId=new Map;oyentes=new Set;capacidad;now;constructor(t={}){
730
+ "; ");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 Tn="x-bvsala-report",Ei="x-bvsala-request-id",Xm="/_bvsala/",Zm="bvsala.gateway.report/1",Dc="bvsala.gateway.status/1";var Tr=/^[A-Za-z0-9._:-]{1,200}$/;function Oc(e){let t=(Array.isArray(e)?e[0]:e)?.trim().toLowerCase();return t==="1"||t==="true"}var Ir=class{entradas=new Map;porRespuestaId=new Map;oyentes=new Set;capacidad;now;constructor(t={}){
726
731
  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>=
727
- this.capacidad;){let r=this.entradas.keys().next().value;if(r===void 0)break;this.quitar(r);}this.entradas.set(t,{informe:{schema:Km,requestId:t,responseId:null,path:n,status:"pending",reason:null,report:null},
728
- abiertaMs:this.now()}),this.avisar();}anotarRespuesta(t,n){let r=this.entradas.get(t);!r||r.informe.responseId!==null||!n||!Ar.test(n)||(r.informe.responseId=n,this.porRespuestaId.set(n,t),this.avisar());}medido(t,n){
732
+ this.capacidad;){let r=this.entradas.keys().next().value;if(r===void 0)break;this.quitar(r);}this.entradas.set(t,{informe:{schema:Zm,requestId:t,responseId:null,path:n,status:"pending",reason:null,report:null},
733
+ abiertaMs:this.now()}),this.avisar();}anotarRespuesta(t,n){let r=this.entradas.get(t);!r||r.informe.responseId!==null||!n||!Tr.test(n)||(r.informe.responseId=n,this.porRespuestaId.set(n,t),this.avisar());}medido(t,n){
729
734
  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.
730
735
  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=()=>{
731
736
  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){
732
737
  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);
733
738
  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;
734
- this.quitar(n);}}avisar(){for(let t of [...this.oyentes])t();}};function Tc(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==
735
- "string"&&Ar.test(n))return n;return null}function xi(e){try{return Tc(JSON.parse(e.toString("utf8")))}catch{return null}}var Rr=class{resto="";leidos=0;id=null;observar(t){if(this.id!==null||this.leidos>
739
+ this.quitar(n);}}avisar(){for(let t of [...this.oyentes])t();}};function Lc(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==
740
+ "string"&&Tr.test(n))return n;return null}function _i(e){try{return Lc(JSON.parse(e.toString("utf8")))}catch{return null}}var Pr=class{resto="";leidos=0;id=null;observar(t){if(this.id!==null||this.leidos>
736
741
  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(`
737
- `))>=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=Tc(JSON.parse(i));
738
- if(s!==null){this.id=s,this.resto="";return}}catch{}}this.leidos>262144&&(this.resto="");}valor(){return this.id}};function Rc(e){try{return new URL(e).origin}catch{return "unknown"}}function Ic(e){let t;
739
- try{t=new URL(e??"/","http://127.0.0.1");}catch{return null}return t.pathname.startsWith(Gm)?t:null}var Jm=new Set(["127.0.0.1","localhost","[::1]"]);function Ym(e){if(e===void 0||e==="")return true;let t;
740
- try{t=new URL(`http://${e}`).hostname.toLowerCase();}catch{return false}return Jm.has(t)}function ki(e,t,n){e.writeHead(t,{"content-type":"application/json","cache-control":"no-store"}),e.end(JSON.stringify(
741
- n));}function Ct(e,t,n,r){ki(e,t,{type:"error",error:{type:n,message:r}});}async function Pc(e,t,n,r){if(e.resume(),!Ym(e.headers.host)){Ct(t,403,"forbidden","bvsala gateway: local routes answer only to\
742
- 127.0.0.1 or localhost");return}if(e.method!=="GET"){t.setHeader("allow","GET"),Ct(t,405,"method_not_allowed","bvsala gateway: local routes only answer GET");return}if(n.pathname==="/_bvsala/v1/statu\
743
- s"){ki(t,200,r.estado());return}let o=Number(n.searchParams.get("wait_ms")??"0");if(!Number.isFinite(o)||o<0){Ct(t,400,"invalid_request","bvsala gateway: wait_ms must be a non-negative number of milli\
742
+ `))>=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=Lc(JSON.parse(i));
743
+ if(s!==null){this.id=s,this.resto="";return}}catch{}}this.leidos>262144&&(this.resto="");}valor(){return this.id}};function $c(e){try{return new URL(e).origin}catch{return "unknown"}}function Mc(e){let t;
744
+ try{t=new URL(e??"/","http://127.0.0.1");}catch{return null}return t.pathname.startsWith(Xm)?t:null}var Qm=new Set(["127.0.0.1","localhost","[::1]"]);function eh(e){if(e===void 0||e==="")return true;let t;
745
+ try{t=new URL(`http://${e}`).hostname.toLowerCase();}catch{return false}return Qm.has(t)}function Si(e,t,n){e.writeHead(t,{"content-type":"application/json","cache-control":"no-store"}),e.end(JSON.stringify(
746
+ n));}function Tt(e,t,n,r){Si(e,t,{type:"error",error:{type:n,message:r}});}async function Nc(e,t,n,r){if(e.resume(),!eh(e.headers.host)){Tt(t,403,"forbidden","bvsala gateway: local routes answer only to\
747
+ 127.0.0.1 or localhost");return}if(e.method!=="GET"){t.setHeader("allow","GET"),Tt(t,405,"method_not_allowed","bvsala gateway: local routes only answer GET");return}if(n.pathname==="/_bvsala/v1/statu\
748
+ s"){Si(t,200,r.estado());return}let o=Number(n.searchParams.get("wait_ms")??"0");if(!Number.isFinite(o)||o<0){Tt(t,400,"invalid_request","bvsala gateway: wait_ms must be a non-negative number of milli\
744
749
  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(
745
- l[1]);}catch{u="";}if(!Ar.test(u)){Ct(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"){
746
- let u=n.searchParams.get("response_id")??"";if(!Ar.test(u)){Ct(t,400,"invalid_request","bvsala gateway: pass ?response_id=<the id of the provider's response>");return}a=()=>r.buzon.porRespuesta(u),c=`\
747
- response id ${u}`;}if(a===null){Ct(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){Ct(t,404,"not_found",
748
- `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}ki(
749
- t,200,p);}}var Dc=4096;function Oc(e){let t={marcas:0,de1h:0,deOtroTtl:0,enLaCola:false,herramientaDeServidor:false};return Xr(e,(n,r)=>{t.marcas++,n.ttl==="1h"?t.de1h++:t.deOtroTtl++,(r==="raiz"||r==="ultimoMensaje")&&
750
- (t.enLaCola=true);}),t.herramientaDeServidor=Kr(e),t}function Lc(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==
751
- "string"&&n.startsWith("claude-cli/")}var $c=e=>e.cache_creation_input_tokens??(e.cache_creation?.ephemeral_5m_input_tokens??0)+(e.cache_creation?.ephemeral_1h_input_tokens??0);function Mc(e){if((e.cache_read_input_tokens??
752
- 0)===0&&$c(e)===0&&(e.input_tokens??0)>=Dc)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 Nc(e){let{vista:t,uso:n,
753
- ttlReescritoPorLaCapa:r}=e;if(t.marcas===0)return null;if((n.cache_read_input_tokens??0)===0&&$c(n)===0&&t.enLaCola&&(n.input_tokens??0)>=Dc)return "cacheIgnorada";let i=n.cache_creation;return !r&&t.de1h>
754
- 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 Si(e,t){let n=`[gateway] degraded traffic${t.
750
+ l[1]);}catch{u="";}if(!Tr.test(u)){Tt(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"){
751
+ let u=n.searchParams.get("response_id")??"";if(!Tr.test(u)){Tt(t,400,"invalid_request","bvsala gateway: pass ?response_id=<the id of the provider's response>");return}a=()=>r.buzon.porRespuesta(u),c=`\
752
+ response id ${u}`;}if(a===null){Tt(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){Tt(t,404,"not_found",
753
+ `bvsala gateway: no report for ${c}. Reports exist only for requests sent with the header "${Tn}: 1", while this gateway process keeps them (the last ${r.buzon.limite}, one hour at most).`);return}Si(
754
+ t,200,p);}}var jc=4096;function Bc(e){let t={marcas:0,de1h:0,deOtroTtl:0,enLaCola:false,herramientaDeServidor:false};return to(e,(n,r)=>{t.marcas++,n.ttl==="1h"?t.de1h++:t.deOtroTtl++,(r==="raiz"||r==="ultimoMensaje")&&
755
+ (t.enLaCola=true);}),t.herramientaDeServidor=Xr(e),t}function Uc(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==
756
+ "string"&&n.startsWith("claude-cli/")}var Fc=e=>e.cache_creation_input_tokens??(e.cache_creation?.ephemeral_5m_input_tokens??0)+(e.cache_creation?.ephemeral_1h_input_tokens??0);function zc(e){if((e.cache_read_input_tokens??
757
+ 0)===0&&Fc(e)===0&&(e.input_tokens??0)>=jc)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 Vc(e){let{vista:t,uso:n,
758
+ ttlReescritoPorLaCapa:r}=e;if(t.marcas===0)return null;if((n.cache_read_input_tokens??0)===0&&Fc(n)===0&&t.enLaCola&&(n.input_tokens??0)>=jc)return "cacheIgnorada";let i=n.cache_creation;return !r&&t.de1h>
759
+ 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 Ci(e,t){let n=`[gateway] degraded traffic${t.
755
760
  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 \
756
761
  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\
757
762
  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 \
758
763
  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\
759
764
  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 \
760
765
  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\
761
- y hand.`+r}var Ir=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??""}`;
766
+ y hand.`+r}var Dr=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??""}`;
762
767
  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.
763
- cuentas}}};function jc(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) \
768
+ cuentas}}};function qc(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) \
764
769
  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\
765
- 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 Qm="[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\
766
- 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.",zc='\
770
+ 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 rh="[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\
771
+ 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.",Wc='\
767
772
  [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\
768
- ll (Node: stream_options: { include_usage: true }); its last chunk then has an empty choices list.',eh=zc+" Or start the gateway with BVSALA_GATEWAY_USAGE_INJECT=1 to add it for clients you cannot cha\
769
- nge.",th=zc+" 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.",nh=e=>`[bvsala gateway] POST ${e} answered with\
770
- out the provider's final usage, so it was forwarded but NOT metered. Nothing is estimated in its place.`,rh=e=>`[bvsala gateway] POST ${e} is forwarded but NOT metered: the gateway reads usage from /v\
771
- 1/messages, \u2026/chat/completions and \u2026/responses only.`,Bc=/\/(count_tokens|input_tokens)$/,oh=["content-encoding","content-length","transfer-encoding"],ih=new Set(["connection","keep-alive","\
772
- proxy-connection","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","expect"]);function Zt(e){let t=e?.cause;if(t==null)return String(e);let n=t instanceof AggregateError&&
773
- t.errors.length>0?t.errors.map(r=>String(r)).join("; "):String(t);return `${String(e)} \xB7 cause: ${n}`}var Ei=class extends Error{code;puerto;constructor(t,n,r){super(t==="EADDRINUSE"?`port ${n} is a\
773
+ ll (Node: stream_options: { include_usage: true }); its last chunk then has an empty choices list.',oh=Wc+" Or start the gateway with BVSALA_GATEWAY_USAGE_INJECT=1 to add it for clients you cannot cha\
774
+ nge.",ih=Wc+" 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.",sh=e=>`[bvsala gateway] POST ${e} answered with\
775
+ out the provider's final usage, so it was forwarded but NOT metered. Nothing is estimated in its place.`,ah=e=>`[bvsala gateway] POST ${e} is forwarded but NOT metered: the gateway reads usage from /v\
776
+ 1/messages, \u2026/chat/completions and \u2026/responses only.`,Hc=/\/(count_tokens|input_tokens)$/,ch=["content-encoding","content-length","transfer-encoding"],lh=new Set(["connection","keep-alive","\
777
+ proxy-connection","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","expect"]);function en(e){let t=e?.cause;if(t==null)return String(e);let n=t instanceof AggregateError&&
778
+ t.errors.length>0?t.errors.map(r=>String(r)).join("; "):String(t);return `${String(e)} \xB7 cause: ${n}`}var Ri=class extends Error{code;puerto;constructor(t,n,r){super(t==="EADDRINUSE"?`port ${n} is a\
774
779
  lready in use: the gateway could not start`:t==="EACCES"?`port ${n} cannot be opened: permission denied`:`could not listen on 127.0.0.1:${n} (${t})`,{cause:r}),this.name="ErrorDeEscucha",this.code=t,this.
775
- puerto=n;}};function Uc(e,t){if(e===t)return true;let n=Object.keys(e);return n.length!==Object.keys(t).length?false:n.every(r=>Object.hasOwn(t,r)&&e[r]===t[r])}function sh(e){return e.writableFinished?Promise.
776
- resolve(true):e.destroyed?Promise.resolve(false):new Promise(t=>{let n=()=>o(true),r=()=>o(e.writableFinished),o=i=>{e.off("finish",n),e.off("close",r),t(i);};e.once("finish",n),e.once("close",r);})}async function Fc(e){
777
- if(!e?.license)throw new Error("arrancarGateway: a verified BiVelio license is required (LICENSE section 2)");let t=gi(e.license.publicKey),n=Er(e.license.token,t);if(!n.ok)throw new Error(`arrancarGa\
778
- teway: the license token does not verify (${n.reason})`);let r=(e.upstream??"https://api.anthropic.com").replace(/\/+$/,""),o=xc(r),i=e.fetchImpl??fetch,s=e.log??(h=>console.log(h)),a=e.warn??(h=>console.
779
- error(h)),c=e.license.now??Date.now,l=e.license.licenseServerUrl?.replace(/\/+$/,""),p=new Vt,u=vi(n.license,t,p,c),f;if(e.serviceAccountKey){f=new Bt({url:e.meteringUrl??"https://savings.bivelio.com/\
780
- api/metering/usage",serviceAccountKey:e.serviceAccountKey,surface:"gateway",...e.fetchImpl?{fetchImpl:e.fetchImpl}:{},onAuthError:A=>Q("gateway-ingest-auth",`[bvsala gateway] the usage ingest is rejec\
781
- ting the credential (${A}). Traffic keeps flowing (warn, never break), but this usage is not reaching your dashboard. Check BIVELIO_SERVICE_KEY and your subscription status at savings.bivelio.com.`)});
782
- let h=Hn();e.seatId?f.setSeat(e.seatId,h):Wn(e.serviceAccountKey).then(A=>f?.setSeat(A,h)).catch(()=>{}),f.start();}else Q("gateway-sin-clave","[bvsala gateway] no BIVELIO_SERVICE_KEY: this in-process \
783
- gateway forwards traffic but does not meter it (the bvsala CLI refuses to start without the key).");let m=e.coalescer?new _r:null,b=e.sombra&&f?new kr:null,v=new Tr,g=new Un,k=new Ir,x=new Cr,S=e.serviceAccountKey?
784
- new wr({url:l?`${l}/api/org/entitlements`:new URL("/api/org/entitlements",e.meteringUrl??"https://savings.bivelio.com/api/metering/usage").toString(),serviceAccountKey:e.serviceAccountKey,...e.fetchImpl?
785
- {fetchImpl:e.fetchImpl}:{},...e.entitlementsTtlMs!==void 0?{ttlMs:e.entitlementsTtlMs}:{},log:s}):null,y=S!==null&&e.elision!==false,I=()=>bi(u.gate,S?.blockReason()??null,u.license.payload),D=null;{let h=bi(
786
- u.gate,null,u.license.payload);h.serve&&(D=h.state);}let O=h=>{let A=gc(D,h,u.license.payload);D=h.state,A&&a(A);},$,B,Z=Number.NEGATIVE_INFINITY,ne=new Set,C=(h,A)=>{ne.has(h)||(ne.add(h),s(A));},R=false,M=h=>h===
787
- "/v1/messages"?new Fe:h.endsWith("/responses")?new Wt:h.endsWith("/chat/completions")?new vn:null,j=(h,A,N,U,W,H,G)=>{v.noMedido(h,H),s(`[gateway] ${A} ${N} \u2192 ${U}${W?" (stream)":""} \xB7 not metere\
788
- d: ${H}`),(_t(N)||N.startsWith("/v1/"))&&x.noMedida(H),e.avisosDeNoMedido!==false&&(G==="chat"&&Q("gateway-chat-sin-include-usage",eh),G==="chat-con-inyeccion"&&Q("gateway-chat-sin-include-usage-con-inye\
789
- ccion",th),G==="uso"&&Q(`gateway-sin-usage:${N}`,nh(N)),G==="dialecto"&&Q(`gateway-sin-dialecto:${N}`,rh(N)));},se=(h,A,N,U)=>{let W=h instanceof Wt?h.estadoFinal():null;if(W!==null&&W!=="completed")return {
790
- motivo:`the response ended as response.${W} without usage`,aviso:"uso"};if(!(h instanceof vn&&U!=="inyectado"&&Qa(A,N)!==true))return {motivo:"the stream ended without the provider's final usage event",aviso:"\
791
- uso"};let G="the request did not ask for usage (stream_options.include_usage)";return U==="rechazada-por-el-upstream"?{motivo:`${G}, and the upstream rejects that option`,aviso:null}:U==="comprimido"?
792
- {motivo:`${G}; usage injection skips compressed request bodies`,aviso:"chat-con-inyeccion"}:U!==null?{motivo:G,aviso:"chat-con-inyeccion"}:{motivo:G,aviso:"chat"}},re=(h,A,N,U,W,H,G,ee,be,Pt,Ne,Ee,Ge,E,z,Dt)=>{
793
- if(!f||!N){v.noMedido(h,f?"the provider reported no usage":"metering is off: the gateway has no BIVELIO_SERVICE_KEY");return}let Ot=f,tn=N,K=qa(A,H),Ie=`[gateway] POST ${W}${U?" \xB7 COALESCED (call avoi\
780
+ puerto=n;}};function Gc(e,t){if(e===t)return true;let n=Object.keys(e);return n.length!==Object.keys(t).length?false:n.every(r=>Object.hasOwn(t,r)&&e[r]===t[r])}function uh(e){return e.writableFinished?Promise.
781
+ resolve(true):e.destroyed?Promise.resolve(false):new Promise(t=>{let n=()=>o(true),r=()=>o(e.writableFinished),o=i=>{e.off("finish",n),e.off("close",r),t(i);};e.once("finish",n),e.once("close",r);})}async function Kc(e){
782
+ if(!e?.license)throw new Error("arrancarGateway: a verified BiVelio license is required (LICENSE section 2)");let t=yi(e.license.publicKey),n=Cr(e.license.token,t);if(!n.ok)throw new Error(`arrancarGa\
783
+ teway: the license token does not verify (${n.reason})`);let r=(e.upstream??"https://api.anthropic.com").replace(/\/+$/,""),o=Ac(r),i=e.fetchImpl??fetch,s=e.log??(h=>console.log(h)),a=e.warn??(h=>console.
784
+ error(h)),c=e.license.now??Date.now,l=e.license.licenseServerUrl?.replace(/\/+$/,""),p=new Et,u=wi(n.license,t,p,c),f;if(e.serviceAccountKey){f=new vt({url:e.meteringUrl??"https://savings.bivelio.com/\
785
+ api/metering/usage",serviceAccountKey:e.serviceAccountKey,surface:"gateway",...e.fetchImpl?{fetchImpl:e.fetchImpl}:{},onAuthError:R=>Q("gateway-ingest-auth",`[bvsala gateway] the usage ingest is rejec\
786
+ ting the credential (${R}). Traffic keeps flowing (warn, never break), but this usage is not reaching your dashboard. Check BIVELIO_SERVICE_KEY and your subscription status at savings.bivelio.com.`)});
787
+ let h=pn();e.seatId?f.setSeat(e.seatId,h):fn(e.serviceAccountKey).then(R=>f?.setSeat(R,h)).catch(()=>{}),f.start();}else Q("gateway-sin-clave","[bvsala gateway] no BIVELIO_SERVICE_KEY: this in-process \
788
+ gateway forwards traffic but does not meter it (the bvsala CLI refuses to start without the key).");let m=e.coalescer?new Rr:null,b=e.sombra&&f?new xr:null,v=new Ir,g=new qn,k=new Dr,x=new Ar,S=e.serviceAccountKey?
789
+ new Sr({url:l?`${l}/api/org/entitlements`:new URL("/api/org/entitlements",e.meteringUrl??"https://savings.bivelio.com/api/metering/usage").toString(),serviceAccountKey:e.serviceAccountKey,...e.fetchImpl?
790
+ {fetchImpl:e.fetchImpl}:{},...e.entitlementsTtlMs!==void 0?{ttlMs:e.entitlementsTtlMs}:{},log:s}):null,y=S!==null&&e.elision!==false,I=()=>ki(u.gate,S?.blockReason()??null,u.license.payload),D=null;{let h=ki(
791
+ u.gate,null,u.license.payload);h.serve&&(D=h.state);}let O=h=>{let R=xc(D,h,u.license.payload);D=h.state,R&&a(R);},$,B,X=Number.NEGATIVE_INFINITY,ne=new Set,C=(h,R)=>{ne.has(h)||(ne.add(h),s(R));},T=false,M=h=>h===
792
+ "/v1/messages"?new ze:h.endsWith("/responses")?new Jt:h.endsWith("/chat/completions")?new xn:null,j=(h,R,N,U,G,H,W)=>{v.noMedido(h,H),s(`[gateway] ${R} ${N} \u2192 ${U}${G?" (stream)":""} \xB7 not metere\
793
+ d: ${H}`),(At(N)||N.startsWith("/v1/"))&&x.noMedida(H),e.avisosDeNoMedido!==false&&(W==="chat"&&Q("gateway-chat-sin-include-usage",oh),W==="chat-con-inyeccion"&&Q("gateway-chat-sin-include-usage-con-inye\
794
+ ccion",ih),W==="uso"&&Q(`gateway-sin-usage:${N}`,sh(N)),W==="dialecto"&&Q(`gateway-sin-dialecto:${N}`,ah(N)));},se=(h,R,N,U)=>{let G=h instanceof Jt?h.estadoFinal():null;if(G!==null&&G!=="completed")return {
795
+ motivo:`the response ended as response.${G} without usage`,aviso:"uso"};if(!(h instanceof xn&&U!=="inyectado"&&ic(R,N)!==true))return {motivo:"the stream ended without the provider's final usage event",aviso:"\
796
+ uso"};let W="the request did not ask for usage (stream_options.include_usage)";return U==="rechazada-por-el-upstream"?{motivo:`${W}, and the upstream rejects that option`,aviso:null}:U==="comprimido"?
797
+ {motivo:`${W}; usage injection skips compressed request bodies`,aviso:"chat-con-inyeccion"}:U!==null?{motivo:W,aviso:"chat-con-inyeccion"}:{motivo:W,aviso:"chat"}},re=(h,R,N,U,G,H,W,ee,be,Lt,Ne,Ee,We,E,F,$t)=>{
798
+ if(!f||!N){v.noMedido(h,f?"the provider reported no usage":"metering is off: the gateway has no BIVELIO_SERVICE_KEY");return}let Mt=f,on=N,K=Ya(R,H),Ie=`[gateway] POST ${G}${U?" \xB7 COALESCED (call avoi\
794
799
  ded)":""}`;if(!K){let he=`could not read the model from the request body${H?` (content-encoding: ${H})`:""}`;s(`${Ie} \xB7 not metered: ${he}`),x.noMedida(he),v.noMedido(h,"could not read the model fr\
795
- om the request body"),Q(`gateway-sin-modelo:${W}`,`[bvsala gateway] could not read the model from the ${W} request body (content-encoding: ${H??"none"}); its usage is forwarded but not metered.`);return}
796
- let me=!U&&Ne?Ne.servido:K,J=ai(me,N,Pt);if(J){let he=U?tc(K,J,Ge,Gt(A,H),{suscripcion:Ee===true,entregada:E?.entregada===true,tierServido:E?.tierServido}):null,mt=U?nc(h,K,J,G,he?.ok?he.credit:null,z===true):
797
- ec(h,me,J,G,ee,be,Ne,Ee===true,!o,z===true);f.record(mt),U?x.replica():x.medida(),v.medido(h,mt);let oe=mt.cost.eliminatedInputFloorCost;s(`[gateway] POST ${W} ${U?"\xB7 COALESCED (call avoided)":""} \xB7 ${me!==
798
- K?`${K}\u2192${me} (sibling model)`:K} \xB7 $${(z?0:J.costeUsd).toFixed(6)} (in ${J.tokens.entrada}, cache\u2191${J.tokens.cacheEscrita}${J.tokens.cacheEscrita1h?` (1h ${J.tokens.cacheEscrita1h})`:""}\
800
+ om the request body"),Q(`gateway-sin-modelo:${G}`,`[bvsala gateway] could not read the model from the ${G} request body (content-encoding: ${H??"none"}); its usage is forwarded but not metered.`);return}
801
+ let me=!U&&Ne?Ne.servido:K,J=ui(me,N,Lt);if(J){let he=U?ac(K,J,We,Yt(R,H),{suscripcion:Ee===true,entregada:E?.entregada===true,tierServido:E?.tierServido}):null,ht=U?cc(h,K,J,W,he?.ok?he.credit:null,F===true):
802
+ sc(h,me,J,W,ee,be,Ne,Ee===true,!o,F===true);f.record(ht),U?x.replica():x.medida(),v.medido(h,ht);let oe=ht.cost.eliminatedInputFloorCost;s(`[gateway] POST ${G} ${U?"\xB7 COALESCED (call avoided)":""} \xB7 ${me!==
803
+ K?`${K}\u2192${me} (sibling model)`:K} \xB7 $${(F?0:J.costeUsd).toFixed(6)} (in ${J.tokens.entrada}, cache\u2191${J.tokens.cacheEscrita}${J.tokens.cacheEscrita1h?` (1h ${J.tokens.cacheEscrita1h})`:""}\
799
804
  cache\u2193${J.tokens.cacheLeida}, out ${J.tokens.salida})`+(ee?` \xB7 elision: ${ee.borrados} clear(s), ${ee.tokensLimpiados} tok cleared by the provider`+(oe!==void 0?` \xB7 floor $${oe.toFixed(6)}\
800
805
  (cache read price)`:ee.tokensLimpiadosToolUses>0?ee.atribuible?" \xB7 no cache read price in the catalog: no floor":" \xB7 your own context_management settings: counted, not credited":ee.tokensLimpiados>
801
- 0?" \xB7 thinking only (your config): counted, not credited":""):"")+(z?" \xB7 refusal the provider does not bill: measured at $0, no saving credited":"")+(Ee&&!U&&(be||Ne)?" \xB7 subscription traffic: l\
806
+ 0?" \xB7 thinking only (your config): counted, not credited":""):"")+(F?" \xB7 refusal the provider does not bill: measured at $0, no saving credited":"")+(Ee&&!U&&(be||Ne)?" \xB7 subscription traffic: l\
802
807
  ever applied, saving not credited (no per-token invoice)":"")+(!o&&!Ee&&!U&&(be||Ne||ee?.atribuible)?" \xB7 unofficial upstream: lever applied, saving not credited (list prices only hold at the provider'\
803
- s own API)":"")+(he?he.ok?` \xB7 by reference: floor $${ui(he.credit).toFixed(6)} (cache read price${he.credit.creditedOutputTokens>0?`, ${he.credit.creditedOutputTokens} output tok at temperature 0`:
804
- ", no output credited"})`:` \xB7 estimated, not by reference: ${he.reason}`:""));let Dn=ee?.atribuible===true&&ee.tokensLimpiadosToolUses>0,Pe=u.license.payload.plan==="measure";if(Pe&&!U&&W==="/v1/mess\
805
- ages"&&!Ee&&o&&z!==true)try{let _e=oo(A,H),pe=_e?ai(_e.cambio.servido,tn,Pt):null,V=_e&&pe&&pe.costeUsd<J.costeUsd?pe:null,P=V??J,je=Dt?as(Dt,P.tokens.cacheEscrita1h,P.precio.inputPer1k):0,Ke=P.costeUsd-
806
- je;Ke<J.costeUsd&&(Ot.record(di(`${h}:shadow`,K,J.costeUsd,Ke,G)),s(`[gateway] measure (shadow) \xB7 ${K} \xB7 `+[V&&_e?`sibling model ${_e.cambio.servido}`:null,je>0?`cache TTL 1h\u21925m on ${P.tokens.
807
- cacheEscrita1h} written tok`:null].filter(Boolean).join(" + ")+` \xB7 this call would have cost $${Ke.toFixed(6)} instead of $${J.costeUsd.toFixed(6)} (not applied)`));}catch{}b&&!Pe&&!U&&W==="/v1/mess\
808
- ages"&&setImmediate(()=>{try{let _e=Gt(A,H);if(!_e||typeof _e!="object")return;let pe=b.observar({cuerpo:_e,uso:tn,model:K,at:Pt??Date.now(),...G?.sessionId!==void 0?{sessionId:G.sessionId}:{},...G?.agentId!==
809
- void 0?{agentId:G.agentId}:{}});if(!pe)return;if(Dn){s(`[gateway] shadow estimate \xB7 ${K} \xB7 the provider already cleared context via our settings: chain advances, nothing emitted`);return}Ot.record(
810
- di(`${h}:shadow`,K,pe.baselineUsd,pe.politicaUsd,G)),s(`[gateway] shadow estimate \xB7 ${K} \xB7 baseline $${pe.baselineUsd.toFixed(6)} \u2192 with elision $${pe.politicaUsd.toFixed(6)}`);}catch{}});}else
808
+ s own API)":"")+(he?he.ok?` \xB7 by reference: floor $${fi(he.credit).toFixed(6)} (cache read price${he.credit.creditedOutputTokens>0?`, ${he.credit.creditedOutputTokens} output tok at temperature 0`:
809
+ ", no output credited"})`:` \xB7 estimated, not by reference: ${he.reason}`:""));let Mn=ee?.atribuible===true&&ee.tokensLimpiadosToolUses>0,Pe=u.license.payload.plan==="measure";if(Pe&&!U&&G==="/v1/mess\
810
+ ages"&&!Ee&&o&&F!==true)try{let _e=ao(R,H),pe=_e?ui(_e.cambio.servido,on,Lt):null,V=_e&&pe&&pe.costeUsd<J.costeUsd?pe:null,P=V??J,je=$t?ps($t,P.tokens.cacheEscrita1h,P.precio.inputPer1k):0,Ke=P.costeUsd-
811
+ je;Ke<J.costeUsd&&(Mt.record(mi(`${h}:shadow`,K,J.costeUsd,Ke,W)),s(`[gateway] measure (shadow) \xB7 ${K} \xB7 `+[V&&_e?`sibling model ${_e.cambio.servido}`:null,je>0?`cache TTL 1h\u21925m on ${P.tokens.
812
+ cacheEscrita1h} written tok`:null].filter(Boolean).join(" + ")+` \xB7 this call would have cost $${Ke.toFixed(6)} instead of $${J.costeUsd.toFixed(6)} (not applied)`));}catch{}b&&!Pe&&!U&&G==="/v1/mess\
813
+ ages"&&setImmediate(()=>{try{let _e=Yt(R,H);if(!_e||typeof _e!="object")return;let pe=b.observar({cuerpo:_e,uso:on,model:K,at:Lt??Date.now(),...W?.sessionId!==void 0?{sessionId:W.sessionId}:{},...W?.agentId!==
814
+ void 0?{agentId:W.agentId}:{}});if(!pe)return;if(Mn){s(`[gateway] shadow estimate \xB7 ${K} \xB7 the provider already cleared context via our settings: chain advances, nothing emitted`);return}Mt.record(
815
+ mi(`${h}:shadow`,K,pe.baselineUsd,pe.politicaUsd,W)),s(`[gateway] shadow estimate \xB7 ${K} \xB7 baseline $${pe.baselineUsd.toFixed(6)} \u2192 with elision $${pe.politicaUsd.toFixed(6)}`);}catch{}});}else
811
816
  v.noMedido(h,`model "${me}" has no list price in the catalog`),s(`${Ie} \xB7 not metered: model "${me}" has no list price in the catalog`),x.noMedida(`model "${me}" has no list price in the catalog`),
812
- Q(`gateway-sin-precio:${me}`,`[bvsala gateway] model "${me}" is not in the price catalog; its usage is forwarded but not metered.`);},xe=(h,A,N,U,W,H)=>{if(!(h!=="/v1/messages"||U===null||!Mc(U)||(N===
813
- void 0||N===""||N==="identity")&&!A.includes('"cache_control"')))try{let ee=Gt(A,N);if(ee===null||typeof ee!="object"||Array.isArray(ee))return;let be=Nc({vista:Oc(ee),uso:U,ttlReescritoPorLaCapa:W});
814
- be!==null&&k.anotar(be,H)&&s(Si(be,{sesion:H,entrada:U.input_tokens??0,escrita5m:U.cache_creation?.ephemeral_5m_input_tokens??0}));}catch{}},Se=createServer(async(h,A)=>{let N=randomUUID(),U=Date.now(),W=I();if(O(W),!W.
815
- serve){let V=c();B&&V-Z>=pc&&(Z=V,B.check({force:true})),h.resume(),A.writeHead(402,{"content-type":"application/json","cache-control":"no-store","x-bvsala-license-status":W.state}),A.end(h.method==="HE\
816
- AD"?void 0:hc(W.state));let P="/";try{P=new URL(h.url??"/","http://x").pathname;}catch{}s(`[gateway] ${h.method} ${P} \u2192 402 (license ${W.state})`);return}let H=u.license.payload.plan==="measure";H&&
817
- Q("gateway-licencia-medir",Qm);let G=Ic(h.url);if(G!==null){await Pc(h,A,G,{buzon:v,estado:()=>({schema:Cc,gateway:"bvsala",version:ye,upstream:Rc(r),license:{state:W.state,plan:u.license.payload.plan??
818
- null,expiresAt:Me(u.license.payload.expires_at)},metering:f!==void 0,reports:{requestHeader:_n,responseHeader:wi,capacity:v.limite}})});return}let ee=Ac(h.headers[_n]),be=ee?new Rr:null;if(ee){let V="\
819
- /";try{V=new URL(h.url??"/","http://x").pathname;}catch{}v.abrir(N,V);}let Pt=V=>ee?{...V,[wi]:N}:V,Ne=null,Ee=new AbortController;A.on("close",()=>{A.writableEnded||Ee.abort();});let Ge=null,E=new URL(h.
820
- url??"/",r),z=null,Dt=Buffer.alloc(0),Ot=false,tn=false,K=null,Ie=null,me=false,J=false,he=(V,P)=>{if(V===null||K===null||!K.nuestros)return V;let je=P?.cache_creation,Ke=P?.cache_creation_input_tokens??(je?.ephemeral_5m_input_tokens??
821
- 0)+(je?.ephemeral_1h_input_tokens??0),nn=(P?.input_tokens??0)+(P?.cache_read_input_tokens??0)+Ke+V.tokensLimpiados,rn=K.triggerDelCliente!==null&&nn>=K.triggerDelCliente;return {...V,atribuible:!rn}},mt=h.
822
- headers["content-encoding"],oe=Array.isArray(mt)?mt[0]:mt,Dn=V=>{let P=Array.isArray(V)?V[0]:V;return P!==void 0&&/^[A-Za-z0-9._:/-]{1,128}$/.test(P)?P:void 0},Pe=Dn(h.headers["x-claude-code-session-i\
823
- d"]),_e=Dn(h.headers["x-claude-code-agent-id"]),pe=Pe!==void 0||_e!==void 0?{...Pe!==void 0?{sessionId:Pe}:{},..._e!==void 0?{agentId:_e}:{}}:void 0;try{let V=[];for await(let w of h)V.push(w);let P=Buffer.
824
- concat(V);Dt=P,E=new URL(h.url??"/",r);let je=m!==null&&!H&&h.method==="POST"&&P.length>0,Ke=kc(w=>{let _=h.headers[w];return Array.isArray(_)?_.join(", "):_}),nn=je?yc("POST",E.pathname+E.search,P,Ke):
825
- "";if(je)if(m.tieneEnVuelo(nn)){let w=await m.esperar(nn);if(w){let _=Ee.signal.aborted||A.destroyed;_||A.writeHead(w.status,Pt(w.headers)),Ne=w.status;let X=M(E.pathname)??new Fe;for(let Mt of w.chunks)
826
- _||A.write(Mt),X.observar(Mt),be?.observar(Mt);be&&v.anotarRespuesta(N,be.valor()??xi(Buffer.concat(w.chunks))),_||A.end();let Ze=_?!1:await sh(A),De=X.usageFinal()??yr(E.pathname,Buffer.concat(w.chunks));
827
- if(De===null){if(f&&!Bc.test(E.pathname)){let Mt=String(w.headers["content-type"]??"").includes("text/event-stream");j(N,h.method??"POST",E.pathname,w.status,Mt,_t(E.pathname)?Mt?se(X,P,oe,null).motivo:
828
- "the response carried no usage":"no usage dialect for this route",null);}return}let Te=h.headers["anthropic-beta"],ht=li(E.pathname,Array.isArray(Te)?Te.join(", "):Te,r);re(N,P,De,!0,E.pathname,oe,pe,null,
829
- null,U,null,ht,w.primaria??null,{entregada:Ze,tierServido:Za(E.pathname,Buffer.concat(w.chunks))},E.pathname==="/v1/messages"&&(X instanceof Fe&&X.negativaNoCobrada()||ci(E.pathname,Buffer.concat(w.chunks))));
830
- return}}else Ge=m.registrar(nn);let rn=h.headers.connection,du=new Set((Array.isArray(rn)?rn.join(","):rn??"").split(",").map(w=>w.trim().toLowerCase()).filter(w=>w!=="")),Je={};for(let[w,_]of Object.
831
- entries(h.headers))w==="host"||w==="content-length"||_===void 0||ih.has(w)||du.has(w)||w!==_n&&(Je[w]=Array.isArray(_)?_.join(", "):_);let on={...Je};me=li(E.pathname,on["anthropic-beta"],r);let Ce=P;
832
- if(y&&!H&&e.dialesElision===!0&&h.method==="POST"&&E.pathname==="/v1/messages"&&S.tiene("context_elision"))try{let w=rs(P,oe);w!==null&&(Ce=w.cuerpo,K={nuestros:w.nuestros,triggerDelCliente:w.triggerDelCliente},
833
- Je["anthropic-beta"]=is(Je["anthropic-beta"]));}catch{}if(h.method==="POST"&&E.pathname==="/v1/messages"&&(oe??"")==="")try{let w=bc(P.toString("utf8")),_=vc(w);_&&(Q("gateway-busqueda-herramientas",_),
834
- Lc(h.headers)&&k.anotar("busquedaApagada",Pe)&&s(Si("busquedaApagada",{sesion:Pe,definiciones:w.definiciones})));}catch{}let Xi=y&&!H&&e.modeloHermano===!0&&h.method==="POST"&&(E.pathname==="/v1/messag\
835
- es"||E.pathname==="/v1/messages/count_tokens");if(Xi&&!S.tiene("sibling_model_routing")&&Q("gateway-hermano-sin-feature","[bvsala gateway] sibling model routing: the flag is set but your org's license\
836
- does not include sibling_model_routing; the request is forwarded unchanged (fail-closed)."),Xi&&S.tiene("sibling_model_routing"))try{let _=oo(Ce,Ce===P?oe:"identity",{betas:Je["anthropic-beta"]});_!==
837
- null&&(Ce=_.cuerpo,Ie=_.cambio);}catch{}let On=!1;if(y&&!H&&to(e.esfuerzo)&&h.method==="POST"&&E.pathname==="/v1/messages"&&S.tiene("per_turn_effort"))try{let w=Ce===P?oe:"identity",_=ds(Ce,e.esfuerzo,
838
- w);_!==null&&(Ce=_.cuerpo,Je["anthropic-beta"]=ps(Je["anthropic-beta"]),On=!0);}catch{}let Lt=null;if(y&&!H&&h.method==="POST"&&E.pathname==="/v1/messages"&&S.tiene("cache_ttl_tuning"))try{let _=st(Ce,
839
- Ce===P?oe:"identity");if(_!==null){let X=Jr(_),Ze=`${pe?.sessionId??"sin-sesion"}:${X.system}`,De=Date.now(),Te=g.ultima(Ze,De);if(g.anotar(Ze,X,De),Zr({fraccionNueva:Yr(Te,X)})){let ht=Qr(_);ht!==null&&
840
- (Ce=ht.cuerpo,Lt={rebajadas:ht.rebajadas,yaEran5m:ht.yaEran5m,herramientaDeServidor:ht.herramientaDeServidor},J=!0);}}}catch{}let Br=null;if(H&&e.elision!==!1&&h.method==="POST"&&E.pathname==="/v1/mess\
841
- ages")try{let w=st(P,oe);if(w!==null){let _=Jr(w),X=`${pe?.sessionId??"sin-sesion"}:${_.system}`,Ze=Date.now(),De=g.ultima(X,Ze);if(g.anotar(X,_,Ze),Zr({fraccionNueva:Yr(De,_)})){let Te=Qr(w);Te!==null&&
842
- (Br={rebajadas:Te.rebajadas,yaEran5m:Te.yaEran5m,herramientaDeServidor:Te.herramientaDeServidor});}}}catch{}let $t=!1,Ln=null;if(h.method==="POST"&&E.pathname.endsWith("/chat/completions")&&f&&e.usageInject===
843
- !0&&!H)if(R)Ln="rechazada-por-el-upstream";else try{let w=Xa(P,oe);Ln=w.motivo,w.cuerpo&&(Ce=w.cuerpo,$t=!0);}catch{}let F,Ur=Ce,zr=Je;try{F=await i(E,{method:h.method,headers:Je,body:["GET","HEAD"].includes(
844
- h.method??"")?void 0:Ce,redirect:"manual",signal:Ee.signal});}catch(w){Ge?.abortar(),A.headersSent||(A.writeHead(502,{"content-type":"application/json"}),A.end(JSON.stringify({error:"bvsala gateway: up\
845
- stream unreachable",detail:Zt(w)}))),s(`[gateway] ${h.method} ${E.pathname} \u2192 upstream unreachable: ${Zt(w)}`);return}if(((Ur!==P||!Uc(zr,on))&&F.status===400||$t&&(F.status===400||F.status===422))&&
846
- !Ee.signal.aborted){let w="";try{w=(await F.text()).slice(0,300).replace(/\s+/g," ");}catch{}let _=$t;s(_?`[gateway] the upstream rejected (${F.status}) the request with stream_options.include_usage ad\
847
- ded; forwarding it unchanged \xB7 ${w}`:`[gateway] the upstream rejected (400) the rewritten request${Ie?` to ${Ie.servido}`:""}${On?" (per-turn effort)":""}${Lt?" (cache TTL)":""}${K?" (context editi\
848
- ng dials)":""}; forwarding it unchanged \xB7 ${w}`),Ie=null,On=!1,Lt=null,J=!1,K=null,$t=!1,_&&(Ln="rechazada-por-el-upstream"),Ur=P,zr=on;try{F=await i(E,{method:h.method,headers:on,body:P,redirect:"\
849
- manual",signal:Ee.signal});}catch(X){Ge?.abortar(),A.headersSent||(A.writeHead(502,{"content-type":"application/json"}),A.end(JSON.stringify({error:"bvsala gateway: upstream unreachable",detail:Zt(X)}))),
850
- s(`[gateway] ${h.method} ${E.pathname} \u2192 upstream unreachable on retry: ${Zt(X)}`);return}_&&F.ok&&(R=!0,Q("gateway-sin-stream-options","[bvsala gateway] the upstream rejects stream_options, so u\
851
- sage injection is off for the rest of this process: streamed /v1/chat/completions answers from it are forwarded but NOT metered (stream=false answers still are)."));}let Fr=Object.fromEntries(F.headers.
852
- entries());for(let w of oh)delete Fr[w];A.writeHead(F.status,Pt(Fr)),Ne=F.status;let $n=F.headers.get("content-type")??"",Mn=$n.includes("text/event-stream")||$n===""&&F.ok&&M(E.pathname)!==null&&!E.pathname.
853
- endsWith("/chat/completions");z=Mn?M(E.pathname):null,tn=F.ok;let Ye=!Mn&&F.ok&&f!==void 0&&h.method==="POST"&&_t(E.pathname)&&(F.headers.get("content-type")??"").includes("application/json")?[]:null,
854
- Qi=0,es=!1;if(F.body)for await(let w of F.body){let _=Buffer.from(w);A.write(_),z?.observar(_),be?.observar(_),Ye&&(Qi+=_.length,Qi>yi?(Ye=null,es=!0):Ye.push(_)),Ge?.capturar(_);}if(A.end(),be&&v.anotarRespuesta(
855
- N,be.valor()??(Ye?xi(Buffer.concat(Ye)):null)),Ge){let w=Ie===null&&!On&&K===null&&!$t&&Lt===null&&Ur===P&&Uc(zr,on),_=Ye?Buffer.concat(Ye):null,X=F.ok&&(z?z.usageFinal()!==null:_!==null&&yr(E.pathname,
856
- _)!==null),Ze=z instanceof Wt&&z.estadoFinal()==="failed"||_!==null&&Wa(E.pathname,_),De=z!==null&&z.negativa()||_!==null&&Ka(E.pathname,_),Te=!De&&Ya(z!==null?z.textoInicial():_!==null?Ja(E.pathname,
857
- _):"");Ge.terminar(F.status,Fr,{requestId:N,at:Date.now(),intacta:w,proveedorOficial:o,conContador:X,suscripcion:me,fallida:Ze,...De?{negativa:De}:{},...Te?{negativaEnTexto:!0}:{}});}if(z&&F.ok){Ot=!0;
858
- let w=z.usageFinal();if(w===null&&f){let _=se(z,P,oe,$t?"inyectado":Ln);j(N,h.method??"POST",E.pathname,F.status,!0,_.motivo,_.aviso);}else {let _=he(z instanceof Fe?z.elision():null,w),X=E.pathname==="\
859
- /v1/messages"&&z instanceof Fe&&z.negativaNoCobrada();re(N,P,w,!1,E.pathname,oe,pe,_,Lt,U,Ie,me,void 0,void 0,X,Br),xe(E.pathname,P,oe,w,J,Pe);}f||s(`[gateway] ${h.method} ${E.pathname} \u2192 ${F.status}\
860
- (stream) \xB7 not metered: no BIVELIO_SERVICE_KEY`);}else if(Ye){let w=Buffer.concat(Ye),_=yr(E.pathname,w);if(_===null)j(N,h.method??"POST",E.pathname,F.status,!1,"the response carried no usage","uso");else {
861
- let X=E.pathname==="/v1/messages"?Ua(w):null;re(N,P,_,!1,E.pathname,oe,pe,he(X,_),Lt,U,Ie,me,void 0,void 0,ci(E.pathname,w),Br),xe(E.pathname,P,oe,_,J,Pe);}}else es?j(N,h.method??"POST",E.pathname,F.status,
862
- !1,"the response was too large to read its usage",null):f&&h.method==="POST"&&F.ok&&_t(E.pathname)?j(N,h.method,E.pathname,F.status,!1,`the response is neither JSON nor an event stream (content-type: ${$n===
863
- ""?"none":$n.slice(0,80)})`,null):f&&h.method==="POST"&&F.ok&&!_t(E.pathname)&&!Bc.test(E.pathname)?j(N,h.method,E.pathname,F.status,Mn,"no usage dialect for this route",E.pathname.startsWith("/v1/")?
864
- "dialecto":null):s(`[gateway] ${h.method} ${E.pathname} \u2192 ${F.status}${Mn?" (stream)":""}`);}catch(V){if(Ge?.abortar(),Ee.signal.aborted){let P=!Ot&&z?z.usageFinal():null;if(P){s(`[gateway] ${h.method}\
865
- ${E.pathname} \u2192 client closed after the final usage; metered anyway`);let je=he(z instanceof Fe?z.elision():null,P),Ke=E.pathname==="/v1/messages"&&z instanceof Fe&&z.negativaNoCobrada();re(N,Dt,
866
- P,false,E.pathname,oe,pe,je,void 0,U,Ie,me,void 0,void 0,Ke),xe(E.pathname,Dt,oe,P,J,Pe);}else s(`[gateway] ${h.method} ${E.pathname} \u2192 client aborted; upstream cancelled`),z&&tn&&!Ot&&x.noMedida("th\
867
- e client closed the stream before the provider's final usage");}else if(s(`[gateway] ${h.method} ${E.pathname} \u2192 error while serving: ${Zt(V)}`),!A.headersSent){A.writeHead(502,{"content-type":"ap\
868
- plication/json"}),A.end(JSON.stringify({error:"bvsala gateway: stream interrupted",detail:Zt(V)}));return}A.writableEnded||A.end();}finally{ee&&v.noMedido(N,Ee.signal.aborted?"the client closed the con\
869
- nection before the provider's final usage":Ne===null?"the request did not get an answer from the provider":`no usage was read from the provider's answer (HTTP ${Ne})`);}});Se.on("upgrade",(h,A)=>{s(`[g\
870
- ateway] ${h.method} ${new URL(h.url??"/","http://x").pathname} \u2192 426 (WebSocket not supported; the client falls back to HTTP)`),A.once("error",()=>{}),A.once("finish",()=>A.destroy()),A.end(`HTTP\
817
+ Q(`gateway-sin-precio:${me}`,`[bvsala gateway] model "${me}" is not in the price catalog; its usage is forwarded but not metered.`);},xe=(h,R,N,U,G,H)=>{if(!(h!=="/v1/messages"||U===null||!zc(U)||(N===
818
+ void 0||N===""||N==="identity")&&!R.includes('"cache_control"')))try{let ee=Yt(R,N);if(ee===null||typeof ee!="object"||Array.isArray(ee))return;let be=Vc({vista:Bc(ee),uso:U,ttlReescritoPorLaCapa:G});
819
+ be!==null&&k.anotar(be,H)&&s(Ci(be,{sesion:H,entrada:U.input_tokens??0,escrita5m:U.cache_creation?.ephemeral_5m_input_tokens??0}));}catch{}},Se=createServer(async(h,R)=>{let N=randomUUID(),U=Date.now(),G=I();if(O(G),!G.
820
+ serve){let V=c();B&&V-X>=vc&&(X=V,B.check({force:true})),h.resume(),R.writeHead(402,{"content-type":"application/json","cache-control":"no-store","x-bvsala-license-status":G.state}),R.end(h.method==="HE\
821
+ AD"?void 0:wc(G.state));let P="/";try{P=new URL(h.url??"/","http://x").pathname;}catch{}s(`[gateway] ${h.method} ${P} \u2192 402 (license ${G.state})`);return}let H=u.license.payload.plan==="measure";H&&
822
+ Q("gateway-licencia-medir",rh);let W=Mc(h.url);if(W!==null){await Nc(h,R,W,{buzon:v,estado:()=>({schema:Dc,gateway:"bvsala",version:ye,upstream:$c(r),license:{state:G.state,plan:u.license.payload.plan??
823
+ null,expiresAt:Me(u.license.payload.expires_at)},metering:f!==void 0,reports:{requestHeader:Tn,responseHeader:Ei,capacity:v.limite}})});return}let ee=Oc(h.headers[Tn]),be=ee?new Pr:null;if(ee){let V="\
824
+ /";try{V=new URL(h.url??"/","http://x").pathname;}catch{}v.abrir(N,V);}let Lt=V=>ee?{...V,[Ei]:N}:V,Ne=null,Ee=new AbortController;R.on("close",()=>{R.writableEnded||Ee.abort();});let We=null,E=new URL(h.
825
+ url??"/",r),F=null,$t=Buffer.alloc(0),Mt=false,on=false,K=null,Ie=null,me=false,J=false,he=(V,P)=>{if(V===null||K===null||!K.nuestros)return V;let je=P?.cache_creation,Ke=P?.cache_creation_input_tokens??(je?.ephemeral_5m_input_tokens??
826
+ 0)+(je?.ephemeral_1h_input_tokens??0),sn=(P?.input_tokens??0)+(P?.cache_read_input_tokens??0)+Ke+V.tokensLimpiados,an=K.triggerDelCliente!==null&&sn>=K.triggerDelCliente;return {...V,atribuible:!an}},ht=h.
827
+ headers["content-encoding"],oe=Array.isArray(ht)?ht[0]:ht,Mn=V=>{let P=Array.isArray(V)?V[0]:V;return P!==void 0&&/^[A-Za-z0-9._:/-]{1,128}$/.test(P)?P:void 0},Pe=Mn(h.headers["x-claude-code-session-i\
828
+ d"]),_e=Mn(h.headers["x-claude-code-agent-id"]),pe=Pe!==void 0||_e!==void 0?{...Pe!==void 0?{sessionId:Pe}:{},..._e!==void 0?{agentId:_e}:{}}:void 0;try{let V=[];for await(let w of h)V.push(w);let P=Buffer.
829
+ concat(V);$t=P,E=new URL(h.url??"/",r);let je=m!==null&&!H&&h.method==="POST"&&P.length>0,Ke=Cc(w=>{let _=h.headers[w];return Array.isArray(_)?_.join(", "):_}),sn=je?_c("POST",E.pathname+E.search,P,Ke):
830
+ "";if(je)if(m.tieneEnVuelo(sn)){let w=await m.esperar(sn);if(w){let _=Ee.signal.aborted||R.destroyed;_||R.writeHead(w.status,Lt(w.headers)),Ne=w.status;let Z=M(E.pathname)??new ze;for(let Bt of w.chunks)
831
+ _||R.write(Bt),Z.observar(Bt),be?.observar(Bt);be&&v.anotarRespuesta(N,be.valor()??_i(Buffer.concat(w.chunks))),_||R.end();let Xe=_?!1:await uh(R),De=Z.usageFinal()??wr(E.pathname,Buffer.concat(w.chunks));
832
+ if(De===null){if(f&&!Hc.test(E.pathname)){let Bt=String(w.headers["content-type"]??"").includes("text/event-stream");j(N,h.method??"POST",E.pathname,w.status,Bt,At(E.pathname)?Bt?se(Z,P,oe,null).motivo:
833
+ "the response carried no usage":"no usage dialect for this route",null);}return}let Ae=h.headers["anthropic-beta"],gt=pi(E.pathname,Array.isArray(Ae)?Ae.join(", "):Ae,r);re(N,P,De,!0,E.pathname,oe,pe,null,
834
+ null,U,null,gt,w.primaria??null,{entregada:Xe,tierServido:rc(E.pathname,Buffer.concat(w.chunks))},E.pathname==="/v1/messages"&&(Z instanceof ze&&Z.negativaNoCobrada()||di(E.pathname,Buffer.concat(w.chunks))));
835
+ return}}else We=m.registrar(sn);let an=h.headers.connection,mu=new Set((Array.isArray(an)?an.join(","):an??"").split(",").map(w=>w.trim().toLowerCase()).filter(w=>w!=="")),Je={};for(let[w,_]of Object.
836
+ entries(h.headers))w==="host"||w==="content-length"||_===void 0||lh.has(w)||mu.has(w)||w!==Tn&&(Je[w]=Array.isArray(_)?_.join(", "):_);let cn={...Je};me=pi(E.pathname,cn["anthropic-beta"],r);let Ce=P;
837
+ if(y&&!H&&e.dialesElision===!0&&h.method==="POST"&&E.pathname==="/v1/messages"&&S.tiene("context_elision"))try{let w=cs(P,oe);w!==null&&(Ce=w.cuerpo,K={nuestros:w.nuestros,triggerDelCliente:w.triggerDelCliente},
838
+ Je["anthropic-beta"]=us(Je["anthropic-beta"]));}catch{}if(h.method==="POST"&&E.pathname==="/v1/messages"&&(oe??"")==="")try{let w=Sc(P.toString("utf8")),_=Ec(w);_&&(Q("gateway-busqueda-herramientas",_),
839
+ Uc(h.headers)&&k.anotar("busquedaApagada",Pe)&&s(Ci("busquedaApagada",{sesion:Pe,definiciones:w.definiciones})));}catch{}let rs=y&&!H&&e.modeloHermano===!0&&h.method==="POST"&&(E.pathname==="/v1/messag\
840
+ es"||E.pathname==="/v1/messages/count_tokens");if(rs&&!S.tiene("sibling_model_routing")&&Q("gateway-hermano-sin-feature","[bvsala gateway] sibling model routing: the flag is set but your org's license\
841
+ does not include sibling_model_routing; the request is forwarded unchanged (fail-closed)."),rs&&S.tiene("sibling_model_routing"))try{let _=ao(Ce,Ce===P?oe:"identity",{betas:Je["anthropic-beta"]});_!==
842
+ null&&(Ce=_.cuerpo,Ie=_.cambio);}catch{}let Nn=!1;if(y&&!H&&oo(e.esfuerzo)&&h.method==="POST"&&E.pathname==="/v1/messages"&&S.tiene("per_turn_effort"))try{let w=Ce===P?oe:"identity",_=gs(Ce,e.esfuerzo,
843
+ w);_!==null&&(Ce=_.cuerpo,Je["anthropic-beta"]=bs(Je["anthropic-beta"]),Nn=!0);}catch{}let Nt=null;if(y&&!H&&h.method==="POST"&&E.pathname==="/v1/messages"&&S.tiene("cache_ttl_tuning"))try{let _=st(Ce,
844
+ Ce===P?oe:"identity");if(_!==null){let Z=Zr(_),Xe=`${pe?.sessionId??"sin-sesion"}:${Z.system}`,De=Date.now(),Ae=g.ultima(Xe,De);if(g.anotar(Xe,Z,De),eo({fraccionNueva:Qr(Ae,Z)})){let gt=no(_);gt!==null&&
845
+ (Ce=gt.cuerpo,Nt={rebajadas:gt.rebajadas,yaEran5m:gt.yaEran5m,herramientaDeServidor:gt.herramientaDeServidor},J=!0);}}}catch{}let zr=null;if(H&&e.elision!==!1&&h.method==="POST"&&E.pathname==="/v1/mess\
846
+ ages")try{let w=st(P,oe);if(w!==null){let _=Zr(w),Z=`${pe?.sessionId??"sin-sesion"}:${_.system}`,Xe=Date.now(),De=g.ultima(Z,Xe);if(g.anotar(Z,_,Xe),eo({fraccionNueva:Qr(De,_)})){let Ae=no(w);Ae!==null&&
847
+ (zr={rebajadas:Ae.rebajadas,yaEran5m:Ae.yaEran5m,herramientaDeServidor:Ae.herramientaDeServidor});}}}catch{}let jt=!1,jn=null;if(h.method==="POST"&&E.pathname.endsWith("/chat/completions")&&f&&e.usageInject===
848
+ !0&&!H)if(T)jn="rechazada-por-el-upstream";else try{let w=oc(P,oe);jn=w.motivo,w.cuerpo&&(Ce=w.cuerpo,jt=!0);}catch{}let z,Vr=Ce,qr=Je;try{z=await i(E,{method:h.method,headers:Je,body:["GET","HEAD"].includes(
849
+ h.method??"")?void 0:Ce,redirect:"manual",signal:Ee.signal});}catch(w){We?.abortar(),R.headersSent||(R.writeHead(502,{"content-type":"application/json"}),R.end(JSON.stringify({error:"bvsala gateway: up\
850
+ stream unreachable",detail:en(w)}))),s(`[gateway] ${h.method} ${E.pathname} \u2192 upstream unreachable: ${en(w)}`);return}if(((Vr!==P||!Gc(qr,cn))&&z.status===400||jt&&(z.status===400||z.status===422))&&
851
+ !Ee.signal.aborted){let w="";try{w=(await z.text()).slice(0,300).replace(/\s+/g," ");}catch{}let _=jt;s(_?`[gateway] the upstream rejected (${z.status}) the request with stream_options.include_usage ad\
852
+ ded; forwarding it unchanged \xB7 ${w}`:`[gateway] the upstream rejected (400) the rewritten request${Ie?` to ${Ie.servido}`:""}${Nn?" (per-turn effort)":""}${Nt?" (cache TTL)":""}${K?" (context editi\
853
+ ng dials)":""}; forwarding it unchanged \xB7 ${w}`),Ie=null,Nn=!1,Nt=null,J=!1,K=null,jt=!1,_&&(jn="rechazada-por-el-upstream"),Vr=P,qr=cn;try{z=await i(E,{method:h.method,headers:cn,body:P,redirect:"\
854
+ manual",signal:Ee.signal});}catch(Z){We?.abortar(),R.headersSent||(R.writeHead(502,{"content-type":"application/json"}),R.end(JSON.stringify({error:"bvsala gateway: upstream unreachable",detail:en(Z)}))),
855
+ s(`[gateway] ${h.method} ${E.pathname} \u2192 upstream unreachable on retry: ${en(Z)}`);return}_&&z.ok&&(T=!0,Q("gateway-sin-stream-options","[bvsala gateway] the upstream rejects stream_options, so u\
856
+ sage injection is off for the rest of this process: streamed /v1/chat/completions answers from it are forwarded but NOT metered (stream=false answers still are)."));}let Hr=Object.fromEntries(z.headers.
857
+ entries());for(let w of ch)delete Hr[w];R.writeHead(z.status,Lt(Hr)),Ne=z.status;let Bn=z.headers.get("content-type")??"",Un=Bn.includes("text/event-stream")||Bn===""&&z.ok&&M(E.pathname)!==null&&!E.pathname.
858
+ endsWith("/chat/completions");F=Un?M(E.pathname):null,on=z.ok;let Ye=!Un&&z.ok&&f!==void 0&&h.method==="POST"&&At(E.pathname)&&(z.headers.get("content-type")??"").includes("application/json")?[]:null,
859
+ os=0,is=!1;if(z.body)for await(let w of z.body){let _=Buffer.from(w);R.write(_),F?.observar(_),be?.observar(_),Ye&&(os+=_.length,os>xi?(Ye=null,is=!0):Ye.push(_)),We?.capturar(_);}if(R.end(),be&&v.anotarRespuesta(
860
+ N,be.valor()??(Ye?_i(Buffer.concat(Ye)):null)),We){let w=Ie===null&&!Nn&&K===null&&!jt&&Nt===null&&Vr===P&&Gc(qr,cn),_=Ye?Buffer.concat(Ye):null,Z=z.ok&&(F?F.usageFinal()!==null:_!==null&&wr(E.pathname,
861
+ _)!==null),Xe=F instanceof Jt&&F.estadoFinal()==="failed"||_!==null&&Za(E.pathname,_),De=F!==null&&F.negativa()||_!==null&&ec(E.pathname,_),Ae=!De&&nc(F!==null?F.textoInicial():_!==null?tc(E.pathname,
862
+ _):"");We.terminar(z.status,Hr,{requestId:N,at:Date.now(),intacta:w,proveedorOficial:o,conContador:Z,suscripcion:me,fallida:Xe,...De?{negativa:De}:{},...Ae?{negativaEnTexto:!0}:{}});}if(F&&z.ok){Mt=!0;
863
+ let w=F.usageFinal();if(w===null&&f){let _=se(F,P,oe,jt?"inyectado":jn);j(N,h.method??"POST",E.pathname,z.status,!0,_.motivo,_.aviso);}else {let _=he(F instanceof ze?F.elision():null,w),Z=E.pathname==="\
864
+ /v1/messages"&&F instanceof ze&&F.negativaNoCobrada();re(N,P,w,!1,E.pathname,oe,pe,_,Nt,U,Ie,me,void 0,void 0,Z,zr),xe(E.pathname,P,oe,w,J,Pe);}f||s(`[gateway] ${h.method} ${E.pathname} \u2192 ${z.status}\
865
+ (stream) \xB7 not metered: no BIVELIO_SERVICE_KEY`);}else if(Ye){let w=Buffer.concat(Ye),_=wr(E.pathname,w);if(_===null)j(N,h.method??"POST",E.pathname,z.status,!1,"the response carried no usage","uso");else {
866
+ let Z=E.pathname==="/v1/messages"?Ga(w):null;re(N,P,_,!1,E.pathname,oe,pe,he(Z,_),Nt,U,Ie,me,void 0,void 0,di(E.pathname,w),zr),xe(E.pathname,P,oe,_,J,Pe);}}else is?j(N,h.method??"POST",E.pathname,z.status,
867
+ !1,"the response was too large to read its usage",null):f&&h.method==="POST"&&z.ok&&At(E.pathname)?j(N,h.method,E.pathname,z.status,!1,`the response is neither JSON nor an event stream (content-type: ${Bn===
868
+ ""?"none":Bn.slice(0,80)})`,null):f&&h.method==="POST"&&z.ok&&!At(E.pathname)&&!Hc.test(E.pathname)?j(N,h.method,E.pathname,z.status,Un,"no usage dialect for this route",E.pathname.startsWith("/v1/")?
869
+ "dialecto":null):s(`[gateway] ${h.method} ${E.pathname} \u2192 ${z.status}${Un?" (stream)":""}`);}catch(V){if(We?.abortar(),Ee.signal.aborted){let P=!Mt&&F?F.usageFinal():null;if(P){s(`[gateway] ${h.method}\
870
+ ${E.pathname} \u2192 client closed after the final usage; metered anyway`);let je=he(F instanceof ze?F.elision():null,P),Ke=E.pathname==="/v1/messages"&&F instanceof ze&&F.negativaNoCobrada();re(N,$t,
871
+ P,false,E.pathname,oe,pe,je,void 0,U,Ie,me,void 0,void 0,Ke),xe(E.pathname,$t,oe,P,J,Pe);}else s(`[gateway] ${h.method} ${E.pathname} \u2192 client aborted; upstream cancelled`),F&&on&&!Mt&&x.noMedida("th\
872
+ e client closed the stream before the provider's final usage");}else if(s(`[gateway] ${h.method} ${E.pathname} \u2192 error while serving: ${en(V)}`),!R.headersSent){R.writeHead(502,{"content-type":"ap\
873
+ plication/json"}),R.end(JSON.stringify({error:"bvsala gateway: stream interrupted",detail:en(V)}));return}R.writableEnded||R.end();}finally{ee&&v.noMedido(N,Ee.signal.aborted?"the client closed the con\
874
+ nection before the provider's final usage":Ne===null?"the request did not get an answer from the provider":`no usage was read from the provider's answer (HTTP ${Ne})`);}});Se.on("upgrade",(h,R)=>{s(`[g\
875
+ ateway] ${h.method} ${new URL(h.url??"/","http://x").pathname} \u2192 426 (WebSocket not supported; the client falls back to HTTP)`),R.once("error",()=>{}),R.once("finish",()=>R.destroy()),R.end(`HTTP\
871
876
  /1.1 426 Upgrade Required\r
872
877
  connection: close\r
873
878
  content-length: 0\r
874
879
  \r
875
- `);});let We=e.puerto??8402;try{await new Promise((h,A)=>{Se.once("error",A),Se.listen(We,"127.0.0.1",()=>h());});}catch(h){f?.stop();let A=h?.code;throw new Ei(typeof A=="string"?A:"EUNKNOWN",We,h)}let it=Se.
876
- address().port;return l&&($=new bn({url:`${l}/licenses/revocations`,publicKeyPem:t,snapshot:p,getRefreshAfter:()=>u.gate.refreshAfter?.(),nowSeconds:()=>Math.floor(c()/1e3),...e.fetchImpl?{fetchImpl:e.
880
+ `);});let Ge=e.puerto??8402;try{await new Promise((h,R)=>{Se.once("error",R),Se.listen(Ge,"127.0.0.1",()=>h());});}catch(h){f?.stop();let R=h?.code;throw new Ri(typeof R=="string"?R:"EUNKNOWN",Ge,h)}let it=Se.
881
+ address().port;return l&&($=new Wt({url:`${l}/licenses/revocations`,publicKeyPem:t,snapshot:p,getRefreshAfter:()=>u.gate.refreshAfter?.(),nowSeconds:()=>Math.floor(c()/1e3),...e.fetchImpl?{fetchImpl:e.
877
882
  fetchImpl}:{},silenceWarnings:true,onEvent:h=>{h.type==="rejected"&&C(`poller:${h.reason}`,`[gateway] revocation list rejected (${h.reason}); known revocations still apply`);},...e.license.revocations??{}}),
878
- $.start(),e.serviceAccountKey&&(B=new Sr({licenseServerUrl:l,serviceAccountKey:e.serviceAccountKey,publicKey:t,revocation:p,current:()=>u.license,onAdopt:h=>{u=vi(h,t,p,c),s(`[gateway] renewed license\
883
+ $.start(),e.serviceAccountKey&&(B=new _r({licenseServerUrl:l,serviceAccountKey:e.serviceAccountKey,publicKey:t,revocation:p,current:()=>u.license,onAdopt:h=>{u=wi(h,t,p,c),s(`[gateway] renewed license\
879
884
  adopted (expires ${Me(h.payload.expires_at)})`),O(I());},onWarning:a,...e.fetchImpl?{fetchImpl:e.fetchImpl}:{},now:c,...e.license.renewal??{}}),B.start({checkNow:e.license.checkOnStart===true}))),{puerto:it,
880
- cerrar:async()=>{B?.stop(),$?.stop(),await f?.stopAndDrain(),await new Promise(h=>Se.close(()=>h()));},licenseStatus:()=>I().state,degradaciones:()=>k.contadores(),medicion:()=>x.estado()}}var _i=["claude","codex","goose","qwen","opencode","kilo","copilot","aider"];function Cn(e){return _i.includes(e??"")}function Ci(e,t={}){
885
+ cerrar:async()=>{B?.stop(),$?.stop(),await f?.stopAndDrain(),await new Promise(h=>Se.close(()=>h()));},licenseStatus:()=>I().state,degradaciones:()=>k.contadores(),medicion:()=>x.estado()}}var Ai=["claude","codex","goose","qwen","opencode","kilo","copilot","aider"];function In(e){return Ai.includes(e??"")}function Ti(e,t={}){
881
886
  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 [
882
- ".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 Wc(e={}){let n=(e.env??process.env).BVSALA_CODEX_AUTH?.toLowerCase();if(n===
887
+ ".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===
883
888
  "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.
884
- 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 ch={"api-key":{upstream:"\
885
- https://api.openai.com",prefijo:"/v1"},chatgpt:{upstream:"https://chatgpt.com",prefijo:"/backend-api/codex"}},qc="https://api.anthropic.com",Hc="https://api.openai.com",Gc={opencode:"OPENCODE_CONFIG_C\
886
- ONTENT",kilo:"KILO_CONFIG_CONTENT"};function Kc(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=
889
+ 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 ph={"api-key":{upstream:"\
890
+ https://api.openai.com",prefijo:"/v1"},chatgpt:{upstream:"https://chatgpt.com",prefijo:"/backend-api/codex"}},Yc="https://api.anthropic.com",Xc="https://api.openai.com",Qc={opencode:"OPENCODE_CONFIG_C\
891
+ ONTENT",kilo:"KILO_CONFIG_CONTENT"};function el(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=
887
892
  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(
888
- {...n,provider:{...o,anthropic:{...i,options:{...s,baseURL:t}}}})}function Jc(e){let t=e.COPILOT_PROVIDER_BASE_URL?.trim()??"";if(t==="")return {ok:false,error:"Copilot CLI goes through a base URL only wi\
893
+ {...n,provider:{...o,anthropic:{...i,options:{...s,baseURL:t}}}})}function tl(e){let t=e.COPILOT_PROVIDER_BASE_URL?.trim()??"";if(t==="")return {ok:false,error:"Copilot CLI goes through a base URL only wi\
889
894
  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\
890
895
  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.
891
896
  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\
892
897
  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\
893
898
  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\
894
899
  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\
895
- irst."}}return r.origin!==qc?{ok:false,error:`COPILOT_PROVIDER_BASE_URL does not point at ${qc}: the gateway prices only the provider's own API at its list price (a local model or a reseller bills differ\
896
- ently, or not at all), so it does not wrap it.`}:{ok:true,ruta:r.pathname.replace(/\/+$/,"")}}function Yc(e,t=process.env){if(e==="opencode"||e==="kilo"){let n=Gc[e];return Kc(t[n],"http://127.0.0.1:1/v\
900
+ irst."}}return r.origin!==Yc?{ok:false,error:`COPILOT_PROVIDER_BASE_URL does not point at ${Yc}: the gateway prices only the provider's own API at its list price (a local model or a reseller bills differ\
901
+ ently, or not at all), so it does not wrap it.`}:{ok:true,ruta:r.pathname.replace(/\/+$/,"")}}function nl(e,t=process.env){if(e==="opencode"||e==="kilo"){let n=Qc[e];return el(t[n],"http://127.0.0.1:1/v\
897
902
  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\
898
- se the manual recipe in \`bvsala doctor\`.`:null}if(e==="copilot"){let n=Jc(t);return n.ok?null:n.error}return null}function Pr(e,t,n,r={},o=process.env){let i=`http://127.0.0.1:${t}`;switch(e){case "c\
903
+ se the manual recipe in \`bvsala doctor\`.`:null}if(e==="copilot"){let n=tl(t);return n.ok?null:n.error}return null}function Or(e,t,n,r={},o=process.env){let i=`http://127.0.0.1:${t}`;switch(e){case "c\
899
904
  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",
900
- 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=Gc[e],
901
- a=Kc(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}: \
902
- 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=Jc(o);return s.ok?{bin:"copilot",args:n,
905
+ 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=Qc[e],
906
+ a=el(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}: \
907
+ 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=tl(o);return s.ok?{bin:"copilot",args:n,
903
908
  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\
904
- ider":{if(r.upstreamElegido===Hc){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:Hc,nota:"OpenAI models through \
909
+ ider":{if(r.upstreamElegido===Xc){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:Xc,nota:"OpenAI models through \
905
910
  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\
906
911
  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\
907
- 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=ch[s];return {
912
+ 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=ph[s];return {
908
913
  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\
909
914
  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\
910
- m/v1."}}}}var lh=["gateway","doctor","skill","init"],Zc=new Set(["help","--help","-h"]),Xc=new Set(["version","--version","-v"]);function el(e){let[t,...n]=e;return t===void 0||Zc.has(t)?{tipo:"ayuda",salida:0}:
911
- Xc.has(t)?{tipo:"version"}:Cn(t)?{tipo:"arrancar",comando:t,resto:n}:lh.includes(t)?n.some(r=>Zc.has(r))?{tipo:"ayuda",salida:0}:n.some(r=>Xc.has(r))?{tipo:"version"}:{tipo:"arrancar",comando:t,resto:n}:
912
- {tipo:"ayuda",salida:1}}function tl(e){return e.length===1&&(e[0]==="--help"||e[0]==="-h"||e[0]==="--version")}function nl(e,t,n){let r=e??{},o=typeof r.puerto=="number"?r.puerto:n;if(r.code==="EADDRI\
915
+ m/v1."}}}}var fh=["gateway","doctor","skill","init"],rl=new Set(["help","--help","-h"]),ol=new Set(["version","--version","-v"]);function sl(e){let[t,...n]=e;return t===void 0||rl.has(t)?{tipo:"ayuda",salida:0}:
916
+ ol.has(t)?{tipo:"version"}:In(t)?{tipo:"arrancar",comando:t,resto:n}:fh.includes(t)?n.some(r=>rl.has(r))?{tipo:"ayuda",salida:0}:n.some(r=>ol.has(r))?{tipo:"version"}:{tipo:"arrancar",comando:t,resto:n}:
917
+ {tipo:"ayuda",salida:1}}function al(e){return e.length===1&&(e[0]==="--help"||e[0]==="-h"||e[0]==="--version")}function cl(e,t,n){let r=e??{},o=typeof r.puerto=="number"?r.puerto:n;if(r.code==="EADDRI\
913
918
  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\
914
919
  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}`}
915
- var Qc={"--puerto":"--port","--proyecto":"--project","--forzar":"--force"},uh={BVSALA_GATEWAY_ESFUERZO:"BVSALA_GATEWAY_EFFORT",BVSALA_GATEWAY_MODELO_HERMANO:"BVSALA_GATEWAY_SIBLING_MODEL"},Ai="BVSALA_\
916
- SILENCE_DEPRECATIONS";function rl(e){let t=e[Ai]?.trim();return t!==void 0&&t!==""&&t!=="0"}function ol(e,t={}){let n=new Set,r=e.map(i=>{let s=Qc[i];return s===void 0?i:(n.add(i),s)}),o=rl(t)?[]:[...n].
917
- map(i=>`[bvsala] ${i} is deprecated: use ${Qc[i]} (it still works until 0.5; ${Ai}=1 silences this).`);return {resto:r,avisos:o}}function il(e){let t={...e},n=[];for(let[r,o]of Object.entries(uh)){let i=e[r];
918
- if(i===void 0)continue;let s=e[o];s===void 0&&(t[o]=i),n.push(`[bvsala] ${r} is deprecated: use ${o} (it still works until 0.5; ${Ai}=1 silences this).`+(s!==void 0?` Both are set: ${o} is the one in \
919
- use.`:""));}return {env:t,avisos:rl(e)?[]:n}}function dh(e){let t=Number.parseInt(e.slice(8,10),10);return Number.isFinite(t)&&t%2===0?"palanca":"control"}function sl(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.
920
- activo!==false,espia:r}}function al(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\
920
+ var il={"--puerto":"--port","--proyecto":"--project","--forzar":"--force"},mh={BVSALA_GATEWAY_ESFUERZO:"BVSALA_GATEWAY_EFFORT",BVSALA_GATEWAY_MODELO_HERMANO:"BVSALA_GATEWAY_SIBLING_MODEL"},Ii="BVSALA_\
921
+ SILENCE_DEPRECATIONS";function ll(e){let t=e[Ii]?.trim();return t!==void 0&&t!==""&&t!=="0"}function ul(e,t={}){let n=new Set,r=e.map(i=>{let s=il[i];return s===void 0?i:(n.add(i),s)}),o=ll(t)?[]:[...n].
922
+ map(i=>`[bvsala] ${i} is deprecated: use ${il[i]} (it still works until 0.5; ${Ii}=1 silences this).`);return {resto:r,avisos:o}}function dl(e){let t={...e},n=[];for(let[r,o]of Object.entries(mh)){let i=e[r];
923
+ if(i===void 0)continue;let s=e[o];s===void 0&&(t[o]=i),n.push(`[bvsala] ${r} is deprecated: use ${o} (it still works until 0.5; ${Ii}=1 silences this).`+(s!==void 0?` Both are set: ${o} is the one in \
924
+ use.`:""));}return {env:t,avisos:ll(e)?[]:n}}function hh(e){let t=Number.parseInt(e.slice(8,10),10);return Number.isFinite(t)&&t%2===0?"palanca":"control"}function pl(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.
925
+ activo!==false,espia:r}}function fl(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\
921
926
  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\
922
- 2:espia\`.`,aviso:true};let s=dh(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\
927
+ 2:espia\`.`,aviso:true};let s=hh(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\
923
928
  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 \
924
- 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 hh="check: the gateway log must show `[gateway] POST /v1/messages \u2026`; if you see `/v1/v1\
925
- /messages`, there is one /v1 too many; if you see a bare `POST /messages`, one is missing.",gh=[{id:"claude",nombre:"Claude Code",binario:"claude",configs:[],detectable:true,receta:({base:e})=>["use `bv\
929
+ 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 yh="check: the gateway log must show `[gateway] POST /v1/messages \u2026`; if you see `/v1/v1\
930
+ /messages`, there is one /v1 too many; if you see a bare `POST /messages`, one is missing.",kh=[{id:"claude",nombre:"Claude Code",binario:"claude",configs:[],detectable:true,receta:({base:e})=>["use `bv\
926
931
  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\
927
932
  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\
928
933
  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\
@@ -969,109 +974,109 @@ he stream is forwarded but NOT metered; the last chunk then has an empty choices
969
974
  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",
970
975
  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\
971
976
  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}" })`,
972
- "streamed and stream=False requests are both metered."]}];function bh(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(
973
- s=>t(join(i,o+s))))}async function cl(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??bh(t.
977
+ "streamed and stream=False requests are both metered."]}];function wh(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(
978
+ s=>t(join(i,o+s))))}async function ml(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??wh(t.
974
979
  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\
975
980
  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\
976
- y and does not start without one.",""];for(let l of gh){let p=l.configs.map(v=>join(n,v)),u=l.binario!==void 0&&o(l.binario),f=p.filter(v=>r(v)),m=u||f.length>0;m&&a.push(l.id);let b;l.detectable?m?b=`d\
981
+ y and does not start without one.",""];for(let l of kh){let p=l.configs.map(v=>join(n,v)),u=l.binario!==void 0&&o(l.binario),f=p.filter(v=>r(v)),m=u||f.length>0;m&&a.push(l.id);let b;l.detectable?m?b=`d\
977
982
  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(
978
- `\xBB ${l.id}: ${b}`),c.push(` ${l.nombre}`);for(let v of l.receta({base:i,baseV1:s,puerto:e,rutas:p}))c.push(` ${v}`);l.comprobar!==null&&c.push(` ${l.comprobar??hh}`),c.push("");}return c.push("BY\
983
+ `\xBB ${l.id}: ${b}`),c.push(` ${l.nombre}`);for(let v of l.receta({base:i,baseV1:s,puerto:e,rutas:p}))c.push(` ${v}`);l.comprobar!==null&&c.push(` ${l.comprobar??yh}`),c.push("");}return c.push("BY\
979
984
  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\
980
985
  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\
981
986
  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\
982
987
  ) 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 \
983
988
  license.","Per-terminal detail: docs/terminales/<terminal>.md"),{texto:c.join(`
984
- `),detectados:a}}var Ti=["ai-sdk","mastra","langchain","anthropic-sdk","sdk"],Tn={"ai-sdk":["openai","anthropic"],mastra:["openai","anthropic"],langchain:["openai","anthropic"],"anthropic-sdk":["anthropic"],sdk:["open\
985
- ai","anthropic"]},Rn={"ai-sdk":"Vercel AI SDK",mastra:"Mastra",langchain:"LangChain.js","anthropic-sdk":"Anthropic TypeScript SDK",sdk:"the SDK directly (no framework)"},Ri={"ai-sdk":"@bivelio/savings\
986
- -layer/ai-sdk",mastra:"@bivelio/savings-layer/mastra",langchain:"@bivelio/savings-layer/langchain","anthropic-sdk":"@bivelio/savings-layer/anthropic-sdk",sdk:"@bivelio/savings-layer"},vh={openai:"gpt-\
987
- 4o-mini",anthropic:"claude-haiku-4-5"},ll="What is 2 + 2 * 3?",An=["licenseKey: process.env.BIVELIO_LICENSE_KEY,",'licenseServerUrl: "https://savings.bivelio.com",',"serviceAccountKey: process.env.BIV\
988
- ELIO_SERVICE_KEY,"],yh=["onReport: (report) => {"," seen.calls += 1;"," seen.avoidedLlm = report.calls.avoidedLlm;"," seen.basis = report.cost.basis;","},"];function ul(e,t){switch(e){case "ai-sdk":
989
+ `),detectados:a}}var Pi=["ai-sdk","mastra","langchain","anthropic-sdk","sdk"],Dn={"ai-sdk":["openai","anthropic"],mastra:["openai","anthropic"],langchain:["openai","anthropic"],"anthropic-sdk":["anthropic"],sdk:["open\
990
+ ai","anthropic"]},On={"ai-sdk":"Vercel AI SDK",mastra:"Mastra",langchain:"LangChain.js","anthropic-sdk":"Anthropic TypeScript SDK",sdk:"the SDK directly (no framework)"},Di={"ai-sdk":"@bivelio/savings\
991
+ -layer/ai-sdk",mastra:"@bivelio/savings-layer/mastra",langchain:"@bivelio/savings-layer/langchain","anthropic-sdk":"@bivelio/savings-layer/anthropic-sdk",sdk:"@bivelio/savings-layer"},xh={openai:"gpt-\
992
+ 4o-mini",anthropic:"claude-haiku-4-5"},hl="What is 2 + 2 * 3?",Pn=["licenseKey: process.env.BIVELIO_LICENSE_KEY,",'licenseServerUrl: "https://savings.bivelio.com",',"serviceAccountKey: process.env.BIV\
993
+ ELIO_SERVICE_KEY,"],Sh=["onReport: (report) => {"," seen.calls += 1;"," seen.avoidedLlm = report.calls.avoidedLlm;"," seen.basis = report.cost.basis;","},"];function gl(e,t){switch(e){case "ai-sdk":
989
994
  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\
990
- hropic"];case "anthropic-sdk":return ["@anthropic-ai/sdk"];case "sdk":return []}}function qe(e,t){let n=" ".repeat(t);return e.map(r=>r===""?"":n+r)}function ot(e){return e?"export ":""}function Xt(e,t){let n=vh[t];
995
+ hropic"];case "anthropic-sdk":return ["@anthropic-ai/sdk"];case "sdk":return []}}function qe(e,t){let n=" ".repeat(t);return e.map(r=>r===""?"":n+r)}function ot(e){return e?"export ":""}function tn(e,t){let n=xh[t];
991
996
  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\
992
- velio/savings-layer/ai-sdk";'],adaptador:"savings",construir:(o,i)=>[`${ot(i)}const savings = savingsMiddleware({`,...qe([...An,...o],2),"});",...i?["","// Pass `model` wherever you pass a model today\
997
+ velio/savings-layer/ai-sdk";'],adaptador:"savings",construir:(o,i)=>[`${ot(i)}const savings = savingsMiddleware({`,...qe([...Pn,...o],2),"});",...i?["","// Pass `model` wherever you pass a model today\
993
998
  (generateText, streamText\u2026).","// `savings` goes LAST in the middleware list: nothing between it and the model."]:[],`${ot(i)}const model = wrapLanguageModel({ model: ${r}("${n}"), middleware: s\
994
999
  avings });`],exporta:["model"],importsDeUso:['import { generateText } from "ai";','import { getSavingsReport } from "@bivelio/savings-layer/ai-sdk";'],llamar:o=>[`const result = await generateText({ m\
995
1000
  odel, ${o==="prompt"?"prompt":`prompt: ${o}`} });`,"const text = result.text;","const basis = getSavingsReport(result)?.cost.basis;"],daBasis:true,importsDeComprobacion:['import { generateText } from "a\
996
1001
  i";'],preguntar:o=>[`const { text } = await generateText({ model, prompt: ${o} });`]}}case "mastra":return {imports:['import { Agent } from "@mastra/core/agent";','import { savingsProcessor } from "@biv\
997
- elio/savings-layer/mastra";'],adaptador:"bivelio",construir:(r,o)=>[`${ot(o)}const bivelio = savingsProcessor({`,...qe([...An,...r],2),"});",...o?["","// Add `bivelio` LAST to the inputProcessors of e\
1002
+ elio/savings-layer/mastra";'],adaptador:"bivelio",construir:(r,o)=>[`${ot(o)}const bivelio = savingsProcessor({`,...qe([...Pn,...r],2),"});",...o?["","// Add `bivelio` LAST to the inputProcessors of e\
998
1003
  ach agent you already have;","// this one shows where. Its reports go to `onReport` if you pass one above."]:[],`${ot(o)}const agent = new Agent({`,' id: "assistant",',' name: "Assistant",',' instr\
999
1004
  uctions: "Answer briefly.",',` model: "${t}/${n}",`," inputProcessors: [bivelio],","});"],exporta:["agent"],importsDeUso:[],llamar:r=>[`const result = await agent.generate(${r});`,"const text = resu\
1000
1005
  lt.text;"],daBasis:false,importsDeComprobacion:[],preguntar:r=>[`const { text } = await agent.generate(${r});`]};case "langchain":return {imports:['import { createAgent } from "langchain";','import { savin\
1001
- gsAgentMiddleware } from "@bivelio/savings-layer/langchain";'],adaptador:"savings",construir:(r,o)=>[`${ot(o)}const savings = savingsAgentMiddleware({`,...qe([...An,...r],2),"});",...o?["","// Add `sa\
1006
+ gsAgentMiddleware } from "@bivelio/savings-layer/langchain";'],adaptador:"savings",construir:(r,o)=>[`${ot(o)}const savings = savingsAgentMiddleware({`,...qe([...Pn,...r],2),"});",...o?["","// Add `sa\
1002
1007
  vings` LAST to the middleware of each agent you already have; this one shows where."]:[],`${ot(o)}const agent = createAgent({ model: "${t}:${n}", tools: [], middleware: [savings] });`],exporta:["agent"],
1003
1008
  importsDeUso:['import { getSavingsReportFromMessage } from "@bivelio/savings-layer/langchain";'],llamar:r=>[`const state = await agent.invoke({ messages: [{ role: "user", content: ${r} }] });`,"const \
1004
1009
  last = state.messages.at(-1);",'const text = last?.text ?? "";',"const basis = getSavingsReportFromMessage(last)?.cost.basis;"],daBasis:true,importsDeComprobacion:[],preguntar:r=>[`const state = await a\
1005
1010
  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: \
1006
1011
  "${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 \
1007
1012
  Anthropic from "@anthropic-ai/sdk";','import { anthropicSavings } from "@bivelio/savings-layer/anthropic-sdk";'],adaptador:"claudeSavings",construir:(i,s)=>[`${ot(s)}const claudeSavings = anthropicSav\
1008
- ings({`,...qe([...An,...i],2),"});",...s?["","// Use `client` for messages.create(); `claudeSavings.middleware` goes LAST in the list."]:[],`${ot(s)}const client = new Anthropic({ middleware: [claudeS\
1013
+ ings({`,...qe([...Pn,...i],2),"});",...s?["","// Use `client` for messages.create(); `claudeSavings.middleware` goes LAST in the list."]:[],`${ot(s)}const client = new Anthropic({ middleware: [claudeS\
1009
1014
  avings.middleware] });`],exporta:["client","claudeSavings"],importsDeUso:[],llamar:i=>[r(i),o,"const basis = claudeSavings.reportFor(message)?.cost.basis;"],daBasis:true,importsDeComprobacion:[],preguntar:i=>[
1010
1015
  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\
1011
1016
  vider({ apiKey: process.env.ANTHROPIC_API_KEY }),",i=t==="openai"?"OpenAICompatibleProvider":"AnthropicProvider";return {imports:[t==="openai"?`import { createSavingsLayer, ${i} } from "@bivelio/saving\
1012
1017
  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."]:
1013
- [],`${ot(c)}const layer = createSavingsLayer({`,...qe([o,...An,...a],2),"});"],exporta:["layer"],importsDeUso:[],llamar:a=>[`const { text, report } = await layer.generate({ model: "${r}", messages: [{\
1018
+ [],`${ot(c)}const layer = createSavingsLayer({`,...qe([o,...Pn,...a],2),"});"],exporta:["layer"],importsDeUso:[],llamar:a=>[`const { text, report } = await layer.generate({ model: "${r}", messages: [{\
1014
1019
  role: "user", content: ${a} }] });`,"const basis = report.cost.basis;"],daBasis:true,importsDeComprobacion:[],preguntar:a=>[`const { text, report } = await layer.generate({ model: "${r}", messages: [{ \
1015
- role: "user", content: ${a} }] });`]}}}}function Ii(e,t){let n=Xt(e,t);return ["// BiVelio Savings Layer: created once, when this module loads, and reused by every","// request. The exact cache lives i\
1020
+ role: "user", content: ${a} }] });`]}}}}function Oi(e,t){let n=tn(e,t);return ["// BiVelio Savings Layer: created once, when this module loads, and reused by every","// request. The exact cache lives i\
1016
1021
  n this instance, so do not create one per request.",...n.imports,"",...n.construir([],true),""].join(`
1017
- `)}var dl=["// 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 \
1022
+ `)}var bl=["// 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 \
1018
1023
  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\
1019
- ile once it says ok."];function pl(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\
1024
+ ile once it says ok."];function vl(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\
1020
1025
  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" \
1021
1026
  && 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\
1022
1027
  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\
1023
- .`;"]}function fl(e,t){let n=Xt(e,t),r=Pi([...n.importsDeComprobacion,...n.imports]),o=e==="sdk"?n.construir([],false):['const seen = { calls: 0, avoidedLlm: 0, basis: "" };',...n.construir(yh,false)];return {
1024
- imports:r,cuerpo:o}}function Pi(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=
1025
- 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 ml(e,t){
1026
- let n=Xt(e,t),{imports:r,cuerpo:o}=fl(e,t);return [...dl,...r,"",...o,"","try {",...qe([...n.preguntar(JSON.stringify(ll)),...pl(e),"console.log(line);","if (!ok) process.exitCode = 1;"],2),"} catch (e\
1028
+ .`;"]}function yl(e,t){let n=tn(e,t),r=Li([...n.importsDeComprobacion,...n.imports]),o=e==="sdk"?n.construir([],false):['const seen = { calls: 0, avoidedLlm: 0, basis: "" };',...n.construir(Sh,false)];return {
1029
+ imports:r,cuerpo:o}}function Li(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=
1030
+ 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 kl(e,t){
1031
+ let n=tn(e,t),{imports:r,cuerpo:o}=yl(e,t);return [...bl,...r,"",...o,"","try {",...qe([...n.preguntar(JSON.stringify(hl)),...vl(e),"console.log(line);","if (!ok) process.exitCode = 1;"],2),"} catch (e\
1027
1032
  rr) {"," console.log(`not ok: ${err instanceof Error ? err.message : String(err)}`);"," process.exitCode = 1;","} finally {",` ${n.adaptador}.close();`,"}",""].join(`
1028
- `)}function hl(e,t){let n=Xt(e,t),{imports:r,cuerpo:o}=fl(e,t);return [...dl,"// It answers only in development: in production it is a 404.",...r,"","// Run on each request, never at build time.",'expo\
1033
+ `)}function wl(e,t){let n=tn(e,t),{imports:r,cuerpo:o}=yl(e,t);return [...bl,"// It answers only in development: in production it is a 404.",...r,"","// Run on each request, never at build time.",'expo\
1029
1034
  rt const dynamic = "force-dynamic";',"","export async function GET() {",' if (process.env.NODE_ENV === "production") {',' return new Response("Not found", { status: 404 });'," }",...qe(o,2)," tr\
1030
- y {",...qe([...n.preguntar(JSON.stringify(ll)),...pl(e),"return Response.json({ ok, message: line }, { status: ok ? 200 : 500 });"],4)," } catch (err) {"," return Response.json({ ok: false, messag\
1035
+ y {",...qe([...n.preguntar(JSON.stringify(hl)),...vl(e),"return Response.json({ ok, message: line }, { status: ok ? 200 : 500 });"],4)," } catch (err) {"," return Response.json({ ok: false, messag\
1031
1036
  e: `not ok: ${err instanceof Error ? err.message : String(err)}` }, { status: 500 });"," } finally {",` ${n.adaptador}.close();`," }","}",""].join(`
1032
- `)}function gl(e,t,n){let r=Xt(e,t),o=r.daBasis?"{ text, basis }":"{ text }";return [...Pi(r.importsDeUso),`import { ${r.exporta.slice().sort().join(", ")} } from "${n.importeDelCableado}";`,"",`export\
1037
+ `)}function xl(e,t,n){let r=tn(e,t),o=r.daBasis?"{ text, basis }":"{ text }";return [...Li(r.importsDeUso),`import { ${r.exporta.slice().sort().join(", ")} } from "${n.importeDelCableado}";`,"",`export\
1033
1038
  async function POST(req${n.ts?": Request":""}) {`,` const { prompt } = ${n.ts?"(await req.json()) as { prompt: string }":"await req.json()"};`,...qe(r.llamar("prompt"),2),` return Response.json(${o}\
1034
1039
  );`,"}",""].join(`
1035
- `)}function bl(e,t){let n=Xt(e,t),r=n.daBasis?"{ text, basis }":"{ text }";return ['import express from "express";',...Pi([...n.imports,...n.importsDeUso]),"","// Created once, at startup, not inside t\
1040
+ `)}function Sl(e,t){let n=tn(e,t),r=n.daBasis?"{ text, basis }":"{ text }";return ['import express from "express";',...Li([...n.imports,...n.importsDeUso]),"","// Created once, at startup, not inside t\
1036
1041
  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 {",...qe(
1037
1042
  n.llamar('String(req.body?.prompt ?? "")'),4),` res.json(${r});`," } catch (err) {"," next(err);"," }","});","","app.listen(Number(process.env.PORT ?? 3000));",""].join(`
1038
- `)}var Dr="usage: bvsala init [--write [--yes]] [--json] [--stack ai-sdk|mastra|langchain|anthropic-sdk|sdk] [--provider openai|anthropic] [--cwd <dir>]";function xl(e,t){let n={cwd:t,escribir:false,si:false,json:false};
1043
+ `)}var Lr="usage: bvsala init [--write [--yes]] [--json] [--stack ai-sdk|mastra|langchain|anthropic-sdk|sdk] [--provider openai|anthropic] [--cwd <dir>]";function Al(e,t){let n={cwd:t,escribir:false,si:false,json:false};
1039
1044
  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.
1040
- json=true;else if(o==="--stack"){let s=i();if(!s||!Ti.includes(s))return {ok:false,mensaje:`--stack needs one of: ${Ti.join(", ")}.
1041
- ${Dr}`};n.capa=s;}else if(o==="--provider"){let s=i();if(s!=="openai"&&s!=="anthropic")return {ok:false,mensaje:`--provider needs openai or anthropic.
1042
- ${Dr}`};n.proveedor=s;}else if(o==="--cwd"){let s=i();if(!s)return {ok:false,mensaje:`--cwd needs a directory.
1043
- ${Dr}`};n.cwd=s.startsWith("/")||/^[A-Za-z]:[\\/]/.test(s)?s:join(t,s);}else return {ok:false,mensaje:`unknown option: ${o}
1044
- ${Dr}`}}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 \
1045
- --yes."}:n.capa&&n.proveedor&&!Tn[n.capa].includes(n.proveedor)?{ok:false,mensaje:`--stack ${n.capa} only works with --provider ${Tn[n.capa].join(" or ")}.`}:{ok:true,valor:n}}var kh=[["pnpm-lock.yaml","pn\
1046
- pm"],["yarn.lock","yarn"],["bun.lock","bun"],["bun.lockb","bun"],["package-lock.json","npm"]];function wh(e,t,n){if(typeof e.packageManager=="string"){let r=e.packageManager.split("@")[0];if(r==="pnpm"||
1047
- r==="yarn"||r==="bun"||r==="npm")return r}for(let r=t,o=0;o<20;o++){for(let[s,a]of kh)if(n.existe(join(r,s)))return a;let i=dirname(r);if(i===r)break;r=i;}return "npm"}function xh(e){let t={};for(let n of [e.devDependencies,
1048
- e.dependencies])if(n&&typeof n=="object")for(let[r,o]of Object.entries(n))typeof o=="string"&&(t[r]=o);return t}function Sh(e,t,n,r){let o=r.leer(join(n,"node_modules",...e.split("/"),"package.json"));if(o)
1045
+ json=true;else if(o==="--stack"){let s=i();if(!s||!Pi.includes(s))return {ok:false,mensaje:`--stack needs one of: ${Pi.join(", ")}.
1046
+ ${Lr}`};n.capa=s;}else if(o==="--provider"){let s=i();if(s!=="openai"&&s!=="anthropic")return {ok:false,mensaje:`--provider needs openai or anthropic.
1047
+ ${Lr}`};n.proveedor=s;}else if(o==="--cwd"){let s=i();if(!s)return {ok:false,mensaje:`--cwd needs a directory.
1048
+ ${Lr}`};n.cwd=s.startsWith("/")||/^[A-Za-z]:[\\/]/.test(s)?s:join(t,s);}else return {ok:false,mensaje:`unknown option: ${o}
1049
+ ${Lr}`}}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 \
1050
+ --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 Eh=[["pnpm-lock.yaml","pn\
1051
+ 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"||
1052
+ r==="yarn"||r==="bun"||r==="npm")return r}for(let r=t,o=0;o<20;o++){for(let[s,a]of Eh)if(n.existe(join(r,s)))return a;let i=dirname(r);if(i===r)break;r=i;}return "npm"}function Ch(e){let t={};for(let n of [e.devDependencies,
1053
+ e.dependencies])if(n&&typeof n=="object")for(let[r,o]of Object.entries(n))typeof o=="string"&&(t[r]=o);return t}function Rh(e,t,n,r){let o=r.leer(join(n,"node_modules",...e.split("/"),"package.json"));if(o)
1049
1054
  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(
1050
- t)))return `${i[1]}.${i[2]??0}.${i[3]??0}`}function Li(e){let[t=0,n=0,r=0]=e.split(/[.+-]/).map(o=>Number.parseInt(o,10)||0);return [t,n,r]}function $i(e,t){let n=Li(e),r=Li(t);for(let o=0;o<3;o++)if(n[o]!==
1051
- r[o])return n[o]>r[o];return true}var Sl=[{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\
1055
+ t)))return `${i[1]}.${i[2]??0}.${i[3]??0}`}function Ni(e){let[t=0,n=0,r=0]=e.split(/[.+-]/).map(o=>Number.parseInt(o,10)||0);return [t,n,r]}function ji(e,t){let n=Ni(e),r=Ni(t);for(let o=0;o<3;o++)if(n[o]!==
1056
+ r[o])return n[o]>r[o];return true}var Tl=[{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\
1052
1057
  \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\
1053
- 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"}],El=[["@mastra/core","mastra"],["langchain","\
1054
- langchain"],["ai","ai-sdk"],["@anthropic-ai/sdk","anthropic-sdk"],["openai","sdk"]];function _l(e,t){let n=t.leer(join(e,"package.json"));if(n===void 0){let u=["pyproject.toml","requirements.txt","setup\
1058
+ 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"}],Il=[["@mastra/core","mastra"],["langchain","\
1059
+ langchain"],["ai","ai-sdk"],["@anthropic-ai/sdk","anthropic-sdk"],["openai","sdk"]];function Pl(e,t){let n=t.leer(join(e,"package.json"));if(n===void 0){let u=["pyproject.toml","requirements.txt","setup\
1055
1060
  .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\
1056
1061
  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\
1057
1062
  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\
1058
1063
  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\
1059
- t a JSON object. Fix it and run init again.`};let o=xh(r),i={};for(let[u,f]of Object.entries(o))i[u]=Sh(u,f,e,t);let s=["app","src/app"].find(u=>t.existe(join(e,...u.split("/")))),a="next"in i?"next":"e\
1060
- xpress"in i?"express":"node",c=El.filter(([u])=>u in i).map(([,u])=>u),l={dir:e,gestor:wh(r,e,t),ts:"typescript"in i||t.existe(join(e,"tsconfig.json")),esm:r.type==="module",anfitrion:a,src:t.existe(join(
1064
+ t a JSON object. Fix it and run init again.`};let o=Ch(r),i={};for(let[u,f]of Object.entries(o))i[u]=Rh(u,f,e,t);let s=["app","src/app"].find(u=>t.existe(join(e,...u.split("/")))),a="next"in i?"next":"e\
1065
+ xpress"in i?"express":"node",c=Il.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(
1061
1066
  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"},
1062
1067
  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}}
1063
- var yl=(e,t)=>t.some(n=>n in e.deps),Eh=["openai","@ai-sdk/openai","@langchain/openai"],_h=["@anthropic-ai/sdk","@ai-sdk/anthropic","@langchain/anthropic"];function Ch(e,t){if(e==="anthropic-sdk")return "\
1068
+ var _l=(e,t)=>t.some(n=>n in e.deps),Ah=["openai","@ai-sdk/openai","@langchain/openai"],Th=["@anthropic-ai/sdk","@ai-sdk/anthropic","@langchain/anthropic"];function Ih(e,t){if(e==="anthropic-sdk")return "\
1064
1069
  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\
1065
- ain/anthropic"in t.deps)return "anthropic"}return yl(t,_h)&&!yl(t,Eh)?"anthropic":"openai"}function kl(e,t){for(let n of Sl){if(n.capa!==e)continue;let r=t.deps[n.paquete];if(r!==void 0&&(!$i(r,n.desde)||
1066
- $i(r,n.hasta)))return `${n.paquete} ${r} is outside what the adapter supports (${n.texto})`}}var Di={npm:"npm i",pnpm:"pnpm add",yarn:"yarn add",bun:"bun add"};function Ah(e){let t=e.ficherosEnv[0];return t?
1067
- `node --env-file=${t} bivelio-check.mjs`:"node bivelio-check.mjs"}function Cl(e,t,n){let[r=0]=Li(n.node);if(r<20)return {ok:false,mensaje:`Node ${n.node} is too old: @bivelio/savings-layer needs Node \u2265 20\
1068
- . Upgrade Node and run init again.`};let o=[],i=t.capa,s=[];if(i){let m=kl(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=kl(m,e);if(!b){
1070
+ ain/anthropic"in t.deps)return "anthropic"}return _l(t,Th)&&!_l(t,Ah)?"anthropic":"openai"}function Cl(e,t){for(let n of Tl){if(n.capa!==e)continue;let r=t.deps[n.paquete];if(r!==void 0&&(!ji(r,n.desde)||
1071
+ ji(r,n.hasta)))return `${n.paquete} ${r} is outside what the adapter supports (${n.texto})`}}var $i={npm:"npm i",pnpm:"pnpm add",yarn:"yarn add",bun:"bun add"};function Ph(e){let t=e.ficherosEnv[0];return t?
1072
+ `node --env-file=${t} bivelio-check.mjs`:"node bivelio-check.mjs"}function Dl(e,t,n){let[r=0]=Ni(n.node);if(r<20)return {ok:false,mensaje:`Node ${n.node} is too old: @bivelio/savings-layer needs Node \u2265 20\
1073
+ . Upgrade Node and run init again.`};let o=[],i=t.capa,s=[];if(i){let m=Cl(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=Cl(m,e);if(!b){
1069
1074
  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\
1070
1075
  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`."));
1071
- for(let m of s){let b=Sl.find(v=>v.capa===m.capa&&m.motivo.startsWith(`${v.paquete} `))?.paquete??"";o.push(`${m.motivo}: showing ${Rn[i]} instead. To use the ${Rn[m.capa]} adapter, upgrade it: ${Di[e.
1072
- gestor]} ${b}@latest`);}let a=t.proveedor??Ch(i,e);if(!Tn[i].includes(a))return {ok:false,mensaje:`--stack ${i} only works with --provider ${Tn[i].join(" or ")}.`};let c=[];e.yaInstalado||c.push("@bivelio/\
1073
- savings-layer");for(let m of ul(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&&!$i(l,
1074
- "0.4.25")&&o.push(`@bivelio/savings-layer ${l} has no framework adapters (they arrived in 0.4.25): ${Di[e.gestor]} @bivelio/savings-layer@latest`),r<22&&(i==="mastra"||i==="ai-sdk"&&(e.deps.ai??"7").startsWith(
1076
+ for(let m of s){let b=Tl.find(v=>v.capa===m.capa&&m.motivo.startsWith(`${v.paquete} `))?.paquete??"";o.push(`${m.motivo}: showing ${On[i]} instead. To use the ${On[m.capa]} adapter, upgrade it: ${$i[e.
1077
+ gestor]} ${b}@latest`);}let a=t.proveedor??Ih(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/\
1078
+ savings-layer");for(let m of gl(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&&!ji(l,
1079
+ "0.4.25")&&o.push(`@bivelio/savings-layer ${l} has no framework adapters (they arrived in 0.4.25): ${$i[e.gestor]} @bivelio/savings-layer@latest`),r<22&&(i==="mastra"||i==="ai-sdk"&&(e.deps.ai??"7").startsWith(
1075
1080
  "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\
1076
1081
  " 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\
1077
1082
  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\
@@ -1080,89 +1085,89 @@ est without credentials"});else {let m=a==="openai"?"OPENAI_API_KEY":"ANTHROPIC_
1080
1085
  "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\
1081
1086
  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\
1082
1087
  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};
1083
- return c.length>0&&(f.comandoDeInstalacion=`${Di[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",
1088
+ return c.length>0&&(f.comandoDeInstalacion=`${$i[e.gestor]} ${c.join(" ")}`),{ok:true,valor:f}}function Ol(e,t){let n=e.deteccion,{capa:r,proveedor:o}=e,i=n.ts?"ts":n.esm||n.anfitrion==="next"?"js":"mjs",
1084
1089
  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){
1085
- a.push({ruta:p,proposito:"wiring",contenido:Ii(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\
1086
- r (example: ${f})`,ruta:f,contenido:gl(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:hl(r,
1090
+ a.push({ruta:p,proposito:"wiring",contenido:Oi(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\
1091
+ r (example: ${f})`,ruta:f,contenido:xl(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:wl(r,
1087
1092
  o),existe:s(b)});let v=n.scriptDev?n.gestor==="npm"?"npm run dev":`${n.gestor} dev`:"next dev";l.push(`Start your dev server (${v}) and open http://localhost:3000/api/bivelio-check (or your dev port).`,
1088
1093
  '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\
1089
- ed once at startup, then used by the route",ruta:`server.${i}`,contenido:bl(r,o)}):a.push({ruta:p,proposito:"wiring",contenido:Ii(r,o),existe:s(p)}),a.push({ruta:"bivelio-check.mjs",proposito:"check",
1090
- contenido:ml(r,o),existe:s("bivelio-check.mjs")}),l.push(`Run it: ${Ah(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.
1094
+ ed once at startup, then used by the route",ruta:`server.${i}`,contenido:Sl(r,o)}):a.push({ruta:p,proposito:"wiring",contenido:Oi(r,o),existe:s(p)}),a.push({ruta:"bivelio-check.mjs",proposito:"check",
1095
+ contenido:kl(r,o),existe:s("bivelio-check.mjs")}),l.push(`Run it: ${Ph(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.
1091
1096
  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\
1092
1097
  (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\
1093
- ck once it says ok."),{...e,ficheros:a,usos:c,comoComprobar:l,avisos:u}}function Oi(e,t){let n="-".repeat(Math.max(8,Math.min(72,e.length+12)));return `----- ${e} -----
1098
+ ck once it says ok."),{...e,ficheros:a,usos:c,comoComprobar:l,avisos:u}}function Mi(e,t){let n="-".repeat(Math.max(8,Math.min(72,e.length+12)));return `----- ${e} -----
1094
1099
  ${t.replace(/\n$/,"")}
1095
- ${n}`}function Th(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.
1096
- 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 Rh(e){
1097
- let t=e.deteccion,n=El.find(([,s])=>s===e.capa)?.[0],r=n?t.deps[n]:void 0,o=t.capas.includes(e.capa);return `${`${Rn[e.capa]}${o&&r&&e.capa!=="sdk"?` ${r}`:""}`}${o||e.capa==="sdk"?"":" (not installed \
1098
- yet)"} with ${e.proveedor==="openai"?"OpenAI":"Anthropic"} models \u2192 ${Ri[e.capa]}`}function Tl(e,t,n,r={}){let o=e.deteccion,i=[t,"",`Detected in ${o.dir}`,` app: ${Th(o)}`,` LLM calls: \
1099
- ${Rh(e)}`];if(e.alternativas.length>0&&i.push(` also found: ${e.alternativas.map(u=>`${Rn[u]} (${n} --stack ${u})`).join(", ")}`),o.yaInstalado){let u=o.deps["@bivelio/savings-layer"];i.push(` inst\
1100
+ ${n}`}function Dh(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.
1101
+ 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 Oh(e){
1102
+ let t=e.deteccion,n=Il.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 \
1103
+ yet)"} with ${e.proveedor==="openai"?"OpenAI":"Anthropic"} models \u2192 ${Di[e.capa]}`}function Ll(e,t,n,r={}){let o=e.deteccion,i=[t,"",`Detected in ${o.dir}`,` app: ${Dh(o)}`,` LLM calls: \
1104
+ ${Oh(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\
1100
1105
  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}`:
1101
1106
  " 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.
1102
1107
  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/\
1103
1108
  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");
1104
- i.push("",`${s++} \xB7 Wire it`),c&&i.push(Oi(`${c.ruta} (new file${c.existe?"; it already exists, compare it":""})`,c.contenido));for(let u of e.usos)i.push(Oi(u.titulo,u.contenido));let l=e.ficheros.
1105
- find(u=>u.proposito==="check");i.push("",`${s++} \xB7 Check it, for free`),l&&i.push(Oi(`${l.ruta} (new file${l.existe?"; it already exists, compare it":""})`,l.contenido));for(let u of e.comoComprobar)
1109
+ i.push("",`${s++} \xB7 Wire it`),c&&i.push(Mi(`${c.ruta} (new file${c.existe?"; it already exists, compare it":""})`,c.contenido));for(let u of e.usos)i.push(Mi(u.titulo,u.contenido));let l=e.ficheros.
1110
+ find(u=>u.proposito==="check");i.push("",`${s++} \xB7 Check it, for free`),l&&i.push(Mi(`${l.ruta} (new file${l.existe?"; it already exists, compare it":""})`,l.contenido));for(let u of e.comoComprobar)
1106
1111
  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\
1107
1112
  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(`\
1108
1113
 
1109
- `)}function Rl(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.
1110
- gestor,stacks:n.capas,installed:n.yaInstalado?n.deps["@bivelio/savings-layer"]??n.yaInstalado:null},stack:e.capa,provider:e.proveedor,adapter:Ri[e.capa],install:e.comandoDeInstalacion??null,keys:e.claves.
1114
+ `)}function $l(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.
1115
+ gestor,stacks:n.capas,installed:n.yaInstalado?n.deps["@bivelio/savings-layer"]??n.yaInstalado:null},stack:e.capa,provider:e.proveedor,adapter:Di[e.capa],install:e.comandoDeInstalacion??null,keys:e.claves.
1111
1116
  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.
1112
- contenido})),check:e.comoComprobar,notes:e.avisos},null,2)}async function Il(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}\
1117
+ contenido})),check:e.comoComprobar,notes:e.avisos},null,2)}async function Ml(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}\
1113
1118
  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\
1114
1119
  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(
1115
1120
  "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\
1116
1121
  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(
1117
1122
  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(`\
1118
- could not create ${a.ruta}: ${l instanceof Error?l.message:String(l)}`));}}return {salida:s,lineas:n,creados:r}}var Pl="savings-mode";function Dl(e,t){for(let n of e){let r=join(n,"skills",Pl,"SKILL.md");if(t.existe(r))return r}return null}var Ol="<!-- bvsala:savings-mode:inicio -->",
1119
- Or="<!-- bvsala:savings-mode:fin -->";function Ih(e){let t=e.replace(/^---\n[\s\S]*?\n---\n*/,"").trim();return `${Ol}
1123
+ could not create ${a.ruta}: ${l instanceof Error?l.message:String(l)}`));}}return {salida:s,lineas:n,creados:r}}var Nl="savings-mode";function jl(e,t){for(let n of e){let r=join(n,"skills",Nl,"SKILL.md");if(t.existe(r))return r}return null}var Bl="<!-- bvsala:savings-mode:inicio -->",
1124
+ $r="<!-- bvsala:savings-mode:fin -->";function Lh(e){let t=e.replace(/^---\n[\s\S]*?\n---\n*/,"").trim();return `${Bl}
1120
1125
  ${t}
1121
1126
 
1122
1127
  _Always on (AGENTS.md has no activation step). Delete this block to turn it off; \`bvsala skill --codex --force\` restores it._
1123
- ${Or}`}function Ll(e){let t=Dl(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=Ih(e.fs.leer(t)),
1128
+ ${$r}`}function Ul(e){let t=jl(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=Lh(e.fs.leer(t)),
1124
1129
  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+`
1125
- `),{ok:true,destino:o,mensaje:Mi(o,"installed")};let i=e.fs.leer(o),s=i.indexOf(Ol),a=i.indexOf(Or);return s===-1||a===-1||a<s?(e.fs.escribir(o,i.trimEnd()+`
1130
+ `),{ok:true,destino:o,mensaje:Bi(o,"installed")};let i=e.fs.leer(o),s=i.indexOf(Bl),a=i.indexOf($r);return s===-1||a===-1||a<s?(e.fs.escribir(o,i.trimEnd()+`
1126
1131
 
1127
1132
  `+n+`
1128
- `),{ok:true,destino:o,mensaje:Mi(o,"appended to the existing AGENTS.md")}):i.slice(s,a+Or.length)===n?{ok:true,destino:o,mensaje:`[bvsala skill] already installed and up to date: ${o}`}:e.forzar?(e.fs.escribir(
1129
- o,i.slice(0,s)+n+i.slice(a+Or.length)),{ok:true,destino:o,mensaje:Mi(o,"block updated")}):{ok:false,destino:o,mensaje:`[bvsala skill] the savings-mode block in ${o} has DIFFERENT content \u2014 not overwriting \
1130
- it; use --force to update it`}}function Mi(e,t){return `[bvsala skill] ${t}: ${e}
1133
+ `),{ok:true,destino:o,mensaje:Bi(o,"appended to the existing AGENTS.md")}):i.slice(s,a+$r.length)===n?{ok:true,destino:o,mensaje:`[bvsala skill] already installed and up to date: ${o}`}:e.forzar?(e.fs.escribir(
1134
+ o,i.slice(0,s)+n+i.slice(a+$r.length)),{ok:true,destino:o,mensaje:Bi(o,"block updated")}):{ok:false,destino:o,mensaje:`[bvsala skill] the savings-mode block in ${o} has DIFFERENT content \u2014 not overwriting \
1135
+ it; use --force to update it`}}function Bi(e,t){return `[bvsala skill] ${t}: ${e}
1131
1136
  [bvsala skill] AGENTS.md is ALWAYS active in Codex (there is no activation step); delete the block to turn it off.
1132
- [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 $l(e){let t=Dl(e.origenes,e.fs);if(!t)return {ok:false,destino:"",
1133
- 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,Pl),o=join(r,"SKILL.\
1137
+ [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 Fl(e){let t=jl(e.origenes,e.fs);if(!t)return {ok:false,destino:"",
1138
+ 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,Nl),o=join(r,"SKILL.\
1134
1139
  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\
1135
1140
  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}
1136
1141
  [bvsala skill] start (or restart) Claude Code and ask for "savings mode" \u2014 or let it activate on its own when you mention limits.
1137
- [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 Ni=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.
1142
+ [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 Fi=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.
1138
1143
  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,
1139
- Math.ceil(t.length/4))}},ji=new Ni;var Bi=class{estimators=new Map;modelToTokenizer=new Map;fallbackId;constructor(t=ji){this.fallbackId=t.id,this.estimators.set(t.id,t);}register(t){return this.estimators.set(t.id,t),this}mapModel(t,n){
1144
+ Math.ceil(t.length/4))}},zi=new Fi;var Vi=class{estimators=new Map;modelToTokenizer=new Map;fallbackId;constructor(t=zi){this.fallbackId=t.id,this.estimators.set(t.id,t);}register(t){return this.estimators.set(t.id,t),this}mapModel(t,n){
1140
1145
  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.
1141
- get(r);if(o)return o}}return this.estimators.get(this.fallbackId)}count(t,n){return this.resolve(n).count(t)}};new Bi;var Nl={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",
1142
- "text-embedding-3-large"]};var Mh=new Map;function T(e,t){for(let n of e.split(/\s+/).filter(Boolean))Mh.set(n,t);}var Nh=["zero","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen",
1143
- "fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"];Nh.forEach((e,t)=>T(e,{k:"unidad",v:t}));["twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"].forEach((e,t)=>T(e,{k:"\
1144
- decena",v:20+10*t}));T("hundred hundreds",{k:"cien"});T("thousand thousands",{k:"escala",v:1e3});T("million millions",{k:"escala",v:1e6});T("billion billions",{k:"escala",v:1e9});var jh=["","first","s\
1145
- econd","third","fourth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelfth","thirteenth","fourteenth","fifteenth","sixteenth","seventeenth","eighteenth","nineteenth"];jh.forEach((e,t)=>{
1146
- e&&(T(e,{k:"ordinal",v:t}),t>=3&&T(`${e}s`,{k:"ordinal",v:t}));});["twentieth","thirtieth","fortieth","fiftieth","sixtieth","seventieth","eightieth","ninetieth"].forEach((e,t)=>{T(e,{k:"ordinal",v:20+10*
1147
- t}),T(`${e}s`,{k:"ordinal",v:20+10*t});});T("hundredth hundredths",{k:"ordinal",v:100});T("thousandth thousandths",{k:"ordinal",v:1e3});T("millionth millionths",{k:"ordinal",v:1e6});T("half halves",{k:"\
1148
- token",t:"f:1/2"});T("quarter quarters",{k:"token",t:"f:1/4"});T("once single",{k:"token",t:"m:1"});T("twice double doubled doubles doubling",{k:"token",t:"m:2"});T("thrice triple tripled triples trip\
1149
- ling",{k:"token",t:"m:3"});T("quadruple quadrupled quadruples quadrupling",{k:"token",t:"m:4"});T("dozen dozens",{k:"token",t:"c:12"});T("pair pairs",{k:"token",t:"c:2"});T("times time",{k:"veces"});T(
1150
- "and",{k:"conector"});var Bh=["cero","uno","dos","tres","cuatro","cinco","seis","siete","ocho","nueve","diez","","doce","trece","catorce","quince","dieciseis","diecisiete","dieciocho","diecinueve"];Bh.
1151
- forEach((e,t)=>e&&T(e,{k:"unidad",v:t}));T("veinte",{k:"decena",v:20});["veintiuno","veintidos","veintitres","veinticuatro","veinticinco","veintiseis","veintisiete","veintiocho","veintinueve"].forEach(
1152
- (e,t)=>T(e,{k:"unidad",v:21+t}));["treinta","cuarenta","cincuenta","sesenta","setenta","ochenta","noventa"].forEach((e,t)=>T(e,{k:"decena",v:30+10*t}));T("cien ciento",{k:"centena",v:100});[["doscient\
1146
+ get(r);if(o)return o}}return this.estimators.get(this.fallbackId)}count(t,n){return this.resolve(n).count(t)}};new Vi;var zl={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",
1147
+ "text-embedding-3-large"]};var Fh=new Map;function A(e,t){for(let n of e.split(/\s+/).filter(Boolean))Fh.set(n,t);}var zh=["zero","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen",
1148
+ "fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"];zh.forEach((e,t)=>A(e,{k:"unidad",v:t}));["twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"].forEach((e,t)=>A(e,{k:"\
1149
+ 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 Vh=["","first","s\
1150
+ econd","third","fourth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelfth","thirteenth","fourteenth","fifteenth","sixteenth","seventeenth","eighteenth","nineteenth"];Vh.forEach((e,t)=>{
1151
+ 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*
1152
+ 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:"\
1153
+ 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\
1154
+ 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(
1155
+ "and",{k:"conector"});var qh=["cero","uno","dos","tres","cuatro","cinco","seis","siete","ocho","nueve","diez","","doce","trece","catorce","quince","dieciseis","diecisiete","dieciocho","diecinueve"];qh.
1156
+ 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(
1157
+ (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\
1153
1158
  os doscientas",200],["trescientos trescientas",300],["cuatrocientos cuatrocientas",400],["quinientos quinientas",500],["seiscientos seiscientas",600],["setecientos setecientas",700],["ochocientos ocho\
1154
- cientas",800],["novecientos novecientas",900]].forEach(([e,t])=>T(e,{k:"centena",v:t}));T("mil miles",{k:"escala",v:1e3});T("millon millones",{k:"escala",v:1e6});T("billon billones",{k:"escala",v:1e12});
1159
+ 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});
1155
1160
  [["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\
1156
1161
  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]].
1157
- forEach(([e,t])=>T(e,{k:"ordinal",v:t}));T("mitad mitades medio media medios medias",{k:"token",t:"f:1/2"});T("doble dobles",{k:"token",t:"m:2"});T("cuadruple",{k:"token",t:"m:4"});T("docena docenas",
1158
- {k:"token",t:"c:12"});T("par pares",{k:"token",t:"c:2"});T("veces vez",{k:"veces"});T("y",{k:"conector"});[["zero",0],["dues",2],["quatre",4],["cinc",5],["sis",6],["set",7],["vuit",8],["nou",9],["deu",
1159
- 10],["onze",11],["dotze",12],["tretze",13],["catorze",14],["quinze",15],["setze",16],["disset",17],["divuit",18],["dinou",19]].forEach(([e,t])=>T(e,{k:"unidad",v:t}));["vint","trenta","quaranta","cinq\
1160
- uanta","seixanta","setanta","vuitanta","noranta"].forEach((e,t)=>T(e,{k:"decena",v:20+10*t}));T("cent",{k:"centena",v:100});T("cents centes",{k:"cien"});T("milio milions",{k:"escala",v:1e6});[["segon \
1162
+ 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",
1163
+ {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",
1164
+ 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\
1165
+ 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 \
1161
1166
  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(
1162
- ([e,t])=>T(e,{k:"ordinal",v:t}));T("meitat meitats mig mitja",{k:"token",t:"f:1/2"});T("dotzena dotzenes",{k:"token",t:"c:12"});T("parell parells",{k:"token",t:"c:2"});T("vegades vegada",{k:"veces"});
1163
- T("i",{k:"conector"});var ng={"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}};
1164
- ro(ng);new Set(Object.values(Nl).flatMap(e=>e.flatMap(t=>[t,`openai/${t}`])));function xg(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 en=el(process.
1165
- argv.slice(2));function Sg(){console.log(`bvsala ${ye} \u2014 BiVelio Savings Layer
1167
+ ([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"});
1168
+ A("i",{k:"conector"});var mg={"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}};
1169
+ so(mg);new Set(Object.values(zl).flatMap(e=>e.flatMap(t=>[t,`openai/${t}`])));function Kg(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 rn=sl(process.
1170
+ argv.slice(2));function Jg(){console.log(`bvsala ${ye} \u2014 BiVelio Savings Layer
1166
1171
 
1167
1172
  Commands:
1168
1173
  gateway [--port N] [--upstream U]
@@ -1288,49 +1293,49 @@ forwards and warns. On a Claude or ChatGPT subscription there is no per-token in
1288
1293
  traffic is metered at list-price equivalent and never carries commission.
1289
1294
  Your prompts, completions and provider keys never reach BiVelio: what it receives is per-request
1290
1295
  usage (token counts, cost, the model id and opaque ids); LICENSE \xA75 lists every field.
1291
- More: savings.bivelio.com`);}en.tipo==="ayuda"&&(Sg(),process.exit(en.salida));en.tipo==="version"&&(console.log(ye),process.exit(0));var{comando:Y}=en,It=Cn(Y),iu=It?{resto:en.resto,avisos:[]}:ol(en.resto,
1292
- process.env),Ae=iu.resto,Zi=il(process.env);for(let e of [...iu.avisos,...Zi.avisos])console.error(e);var Gi=Zi.env.BVSALA_GATEWAY_EFFORT,su=Zi.env.BVSALA_GATEWAY_SIBLING_MODEL;if(Y==="init"){let e=xl(
1293
- Ae,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=_l(t.cwd,n);r.ok||(console.error(`[b\
1294
- vsala init] ${r.mensaje}`),process.exit(1));let o=Cl(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(
1295
- o.valor,n);t.json&&(console.log(Rl(i,ye)),process.exit(0)),console.log(Tl(i,`bvsala init \xB7 BiVelio Savings Layer ${ye}`,"npx @bivelio/savings-layer@latest init",{escribira:t.escribir})),t.escribir||
1296
- process.exit(0),console.log("");let{createInterface:s}=await import('readline/promises'),a=await Il(i,{si:t.si,esTerminal:!!process.stdin.isTTY,preguntar:async c=>{let l=s({input:process.stdin,output:process.
1296
+ More: savings.bivelio.com`);}rn.tipo==="ayuda"&&(Jg(),process.exit(rn.salida));rn.tipo==="version"&&(console.log(ye),process.exit(0));var{comando:Y}=rn,Ot=In(Y),cu=Ot?{resto:rn.resto,avisos:[]}:ul(rn.resto,
1297
+ process.env),Re=cu.resto,ns=dl(process.env);for(let e of [...cu.avisos,...ns.avisos])console.error(e);var Zi=ns.env.BVSALA_GATEWAY_EFFORT,lu=ns.env.BVSALA_GATEWAY_SIBLING_MODEL;if(Y==="init"){let e=Al(
1298
+ Re,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=Pl(t.cwd,n);r.ok||(console.error(`[b\
1299
+ vsala init] ${r.mensaje}`),process.exit(1));let o=Dl(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=Ol(
1300
+ o.valor,n);t.json&&(console.log($l(i,ye)),process.exit(0)),console.log(Ll(i,`bvsala init \xB7 BiVelio Savings Layer ${ye}`,"npx @bivelio/savings-layer@latest init",{escribira:t.escribir})),t.escribir||
1301
+ process.exit(0),console.log("");let{createInterface:s}=await import('readline/promises'),a=await Ml(i,{si:t.si,esTerminal:!!process.stdin.isTTY,preguntar:async c=>{let l=s({input:process.stdin,output:process.
1297
1302
  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)(
1298
- c);process.exit(a.salida);}if(Y==="skill"){let e=dirname(fileURLToPath(import.meta.url)),t={origenes:[join(e,"..",".."),join(e,"..")],home:homedir(),cwd:process.cwd(),proyecto:Ae.includes("--project"),forzar:Ae.includes("--for\
1299
- ce"),fs:{existe:existsSync,leer:r=>readFileSync(r,"utf8"),escribir:(r,o)=>writeFileSync(r,o),crearDir:r=>mkdirSync(r,{recursive:true})}},n=Ae.includes("--codex")?Ll(t):$l(t);console.log(n.mensaje),process.exit(n.ok?0:1);}var Ki=Ae.indexOf(
1300
- "--port"),Tt=It?0:Ki>=0?Number(Ae[Ki+1]):8402;(!Number.isInteger(Tt)||(Y==="doctor"?Tt<1:Tt<0)||Tt>65535)&&(console.error(`[bvsala ${Y}] invalid port: ${Ae[Ki+1]}`),process.exit(1));if(Y==="doctor"){Ae.
1301
- 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 cl(Tt);console.log(e.texto),process.exit(
1302
- 0);}function Eg(e,t){Cn(e)||process.exit(1);let n=Pr(e,0,[],{}).bin;if(process.platform==="win32"){let o=Ci(n);o.tipo==="exe"?n=o.ruta:o.tipo==="solo-shim"&&(console.error(`[bvsala ${e}] \`${n}\` is ins\
1303
+ c);process.exit(a.salida);}if(Y==="skill"){let e=dirname(fileURLToPath(import.meta.url)),t={origenes:[join(e,"..",".."),join(e,"..")],home:homedir(),cwd:process.cwd(),proyecto:Re.includes("--project"),forzar:Re.includes("--for\
1304
+ ce"),fs:{existe:existsSync,leer:r=>readFileSync(r,"utf8"),escribir:(r,o)=>writeFileSync(r,o),crearDir:r=>mkdirSync(r,{recursive:true})}},n=Re.includes("--codex")?Ul(t):Fl(t);console.log(n.mensaje),process.exit(n.ok?0:1);}var Qi=Re.indexOf(
1305
+ "--port"),Pt=Ot?0:Qi>=0?Number(Re[Qi+1]):8402;(!Number.isInteger(Pt)||(Y==="doctor"?Pt<1:Pt<0)||Pt>65535)&&(console.error(`[bvsala ${Y}] invalid port: ${Re[Qi+1]}`),process.exit(1));if(Y==="doctor"){Re.
1306
+ 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 ml(Pt);console.log(e.texto),process.exit(
1307
+ 0);}function Yg(e,t){In(e)||process.exit(1);let n=Or(e,0,[],{}).bin;if(process.platform==="win32"){let o=Ti(n);o.tipo==="exe"?n=o.ruta:o.tipo==="solo-shim"&&(console.error(`[bvsala ${e}] \`${n}\` is ins\
1303
1308
  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\
1304
1309
  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\
1305
- TH?`),process.exit(127);}),r.on("exit",(o,i)=>process.exit(o??(i?1:0))),new Promise(()=>{})}It&&tl(Ae)&&await Eg(Y,Ae);if(It){let e=Yc(Y);e&&(console.error(`[bvsala ${Y}] ${e}`),process.exit(1));}var _g=Y===
1306
- "gateway"?Sc(Ae):void 0,fe=Ec({flag:_g,env:process.env.BVSALA_GATEWAY_UPSTREAM});fe.ok||(console.error(fe.error),process.exit(1));var au=process.env.BIVELIO_SERVICE_KEY?.trim()||void 0,Rt=await mc({serviceAccountKey:au,
1307
- licenseKey:process.env.BIVELIO_LICENSE_KEY,licenseServerUrl:hi});Rt.ok||(console.error(`[bvsala ${Y}] ${Rt.message}`),process.exit(1));var He=It?Pr(Y,0,Ae,{modoCodex:Y==="codex"?Wc({leerAuth:()=>readFileSync(
1308
- join(homedir(),".codex","auth.json"),"utf8")}):void 0,...fe.upstream?{upstreamElegido:fe.upstream}:{}}):null,Cg=It&&process.env.BVSALA_GATEWAY_LOG!=="1",Wi=He?.upstream?null:sl(()=>readFileSync(process.env.BVSALA_ANILLO2_FICHERO??
1309
- join(homedir(),".bvsala","anillo2.json"),"utf8")),Pn=al({enrolamiento:Wi,espiaVivo:Wi!==null&&await xg(Wi.espia),upstreamEnv:fe.upstream,...fe.origen!=="none"?{upstreamOrigen:fe.origen}:{},elisionEnv:process.
1310
- env.BVSALA_GATEWAY_ELISION,hoyUtcIso:new Date().toISOString().slice(0,10)}),Ji=fe.upstream??Pn.upstream,Mr=process.env.BVSALA_GATEWAY_ELISION??Pn.elision,Re;try{Re=await Fc({puerto:Tt,...Cg?{log:()=>{},
1311
- avisosDeNoMedido:!1}:{},license:{token:Rt.license.token,publicKey:wt,licenseServerUrl:hi,checkOnStart:Rt.source==="offline"},warn:e=>console.error(e),serviceAccountKey:au,...process.env.BVSALA_SEAT_ID?
1312
- {seatId:process.env.BVSALA_SEAT_ID}:{},...Ji?{upstream:Ji}:He?.upstream?{upstream:He.upstream}:{},...process.env.BVSALA_GATEWAY_COALESCE==="1"?{coalescer:!0}:{},...process.env.BVSALA_GATEWAY_USAGE_INJECT===
1313
- "1"?{usageInject:!0}:{},...process.env.BVSALA_GATEWAY_SHADOW==="1"?{sombra:!0}:{},elision:Mr!=="0",...process.env.BVSALA_GATEWAY_DIALES_ELISION==="1"?{dialesElision:!0}:{},...su==="1"?{modeloHermano:!0}:
1314
- {},...Gi?{esfuerzo:Gi}:{},...process.env.BVSALA_METERING_URL?{meteringUrl:process.env.BVSALA_METERING_URL}:{}});}catch(e){console.error(`[bvsala ${Y}] ${nl(e,Y,Tt)}`),process.exit(1);}var cu=Ji??He?.upstream??
1315
- "https://api.anthropic.com";console.log(`[bvsala gateway] v${ye} listening on http://127.0.0.1:${Re.puerto} \u2192 ${cu}`);(Rt.lineIsWarning?console.error:console.log)(`[bvsala gateway] ${Rt.line}`);for(let e of Rt.
1310
+ TH?`),process.exit(127);}),r.on("exit",(o,i)=>process.exit(o??(i?1:0))),new Promise(()=>{})}Ot&&al(Re)&&await Yg(Y,Re);if(Ot){let e=nl(Y);e&&(console.error(`[bvsala ${Y}] ${e}`),process.exit(1));}var Xg=Y===
1311
+ "gateway"?Tc(Re):void 0,fe=Ic({flag:Xg,env:process.env.BVSALA_GATEWAY_UPSTREAM});fe.ok||(console.error(fe.error),process.exit(1));var uu=process.env.BIVELIO_SERVICE_KEY?.trim()||void 0,Dt=await kc({serviceAccountKey:uu,
1312
+ licenseKey:process.env.BIVELIO_LICENSE_KEY,licenseServerUrl:vi});Dt.ok||(console.error(`[bvsala ${Y}] ${Dt.message}`),process.exit(1));var He=Ot?Or(Y,0,Re,{modoCodex:Y==="codex"?Zc({leerAuth:()=>readFileSync(
1313
+ join(homedir(),".codex","auth.json"),"utf8")}):void 0,...fe.upstream?{upstreamElegido:fe.upstream}:{}}):null,Zg=Ot&&process.env.BVSALA_GATEWAY_LOG!=="1",Xi=He?.upstream?null:pl(()=>readFileSync(process.env.BVSALA_ANILLO2_FICHERO??
1314
+ join(homedir(),".bvsala","anillo2.json"),"utf8")),$n=fl({enrolamiento:Xi,espiaVivo:Xi!==null&&await Kg(Xi.espia),upstreamEnv:fe.upstream,...fe.origen!=="none"?{upstreamOrigen:fe.origen}:{},elisionEnv:process.
1315
+ env.BVSALA_GATEWAY_ELISION,hoyUtcIso:new Date().toISOString().slice(0,10)}),es=fe.upstream??$n.upstream,Br=process.env.BVSALA_GATEWAY_ELISION??$n.elision,Te;try{Te=await Kc({puerto:Pt,...Zg?{log:()=>{},
1316
+ avisosDeNoMedido:!1}:{},license:{token:Dt.license.token,publicKey:ft,licenseServerUrl:vi,checkOnStart:Dt.source==="offline"},warn:e=>console.error(e),serviceAccountKey:uu,...process.env.BVSALA_SEAT_ID?
1317
+ {seatId:process.env.BVSALA_SEAT_ID}:{},...es?{upstream:es}:He?.upstream?{upstream:He.upstream}:{},...process.env.BVSALA_GATEWAY_COALESCE==="1"?{coalescer:!0}:{},...process.env.BVSALA_GATEWAY_USAGE_INJECT===
1318
+ "1"?{usageInject:!0}:{},...process.env.BVSALA_GATEWAY_SHADOW==="1"?{sombra:!0}:{},elision:Br!=="0",...process.env.BVSALA_GATEWAY_DIALES_ELISION==="1"?{dialesElision:!0}:{},...lu==="1"?{modeloHermano:!0}:
1319
+ {},...Zi?{esfuerzo:Zi}:{},...process.env.BVSALA_METERING_URL?{meteringUrl:process.env.BVSALA_METERING_URL}:{}});}catch(e){console.error(`[bvsala ${Y}] ${cl(e,Y,Pt)}`),process.exit(1);}var du=es??He?.upstream??
1320
+ "https://api.anthropic.com";console.log(`[bvsala gateway] v${ye} listening on http://127.0.0.1:${Te.puerto} \u2192 ${du}`);(Dt.lineIsWarning?console.error:console.log)(`[bvsala gateway] ${Dt.line}`);for(let e of Dt.
1316
1321
  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\
1317
1322
  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\
1318
1323
  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\
1319
- treamed chat completions without stream_options get include_usage; their last chunk has an empty choices list.");{let e=os(Mr,true,process.env.BVSALA_GATEWAY_DIALES_ELISION==="1");(e.aviso?console.error:
1320
- console.log)(`[bvsala gateway] ${e.linea}`);let t=vs(su,true,Mr!=="0");(t.aviso?console.error:console.log)(`[bvsala gateway] ${t.linea}`);let n=fs(Gi,true,Mr!=="0");(n.aviso?console.error:console.log)(`[b\
1321
- vsala gateway] ${n.linea}`),Pn.linea&&(Pn.aviso?console.error:console.log)(`[bvsala gateway] ${Pn.linea}`);}fe.upstream&&He?.upstream&&fe.upstream!==He.upstream&&console.error(`[bvsala ${Y}] WARNING: B\
1322
- VSALA_GATEWAY_UPSTREAM=${fe.upstream} overrides this terminal's upstream (${He.upstream}). If that is not what you want, unset the variable.`);Y==="codex"&&!Ha()&&console.error(`[bvsala codex] WARNING\
1323
- : 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 eu=false;function lu(){if(eu)return;eu=true;let e=jc(
1324
- Re.degradaciones());e&&console.error(e),console.error(_c(Re.medicion(),Y));}if(He&&It){let e=Pr(Y,Re.puerto,Ae,{...He.upstream?{modoCodex:He.upstream.includes("chatgpt.com")?"chatgpt":"api-key"}:{},...fe.
1325
- upstream?{upstreamElegido:fe.upstream}:{}});e.nota&&console.log(`[bvsala ${Y}] ${e.nota}`);let t=e.bin;if(process.platform==="win32"){let r=Ci(e.bin);r.tipo==="exe"?t=r.ruta:r.tipo==="solo-shim"&&(console.
1324
+ treamed chat completions without stream_options get include_usage; their last chunk has an empty choices list.");{let e=ls(Br,true,process.env.BVSALA_GATEWAY_DIALES_ELISION==="1");(e.aviso?console.error:
1325
+ console.log)(`[bvsala gateway] ${e.linea}`);let t=Ss(lu,true,Br!=="0");(t.aviso?console.error:console.log)(`[bvsala gateway] ${t.linea}`);let n=vs(Zi,true,Br!=="0");(n.aviso?console.error:console.log)(`[b\
1326
+ vsala gateway] ${n.linea}`),$n.linea&&($n.aviso?console.error:console.log)(`[bvsala gateway] ${$n.linea}`);}fe.upstream&&He?.upstream&&fe.upstream!==He.upstream&&console.error(`[bvsala ${Y}] WARNING: B\
1327
+ VSALA_GATEWAY_UPSTREAM=${fe.upstream} overrides this terminal's upstream (${He.upstream}). If that is not what you want, unset the variable.`);Y==="codex"&&!Xa()&&console.error(`[bvsala codex] WARNING\
1328
+ : 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 ru=false;function pu(){if(ru)return;ru=true;let e=qc(
1329
+ Te.degradaciones());e&&console.error(e),console.error(Pc(Te.medicion(),Y));}if(He&&Ot){let e=Or(Y,Te.puerto,Re,{...He.upstream?{modoCodex:He.upstream.includes("chatgpt.com")?"chatgpt":"api-key"}:{},...fe.
1330
+ upstream?{upstreamElegido:fe.upstream}:{}});e.nota&&console.log(`[bvsala ${Y}] ${e.nota}`);let t=e.bin;if(process.platform==="win32"){let r=Ti(e.bin);r.tipo==="exe"?t=r.ruta:r.tipo==="solo-shim"&&(console.
1326
1331
  error(`[bvsala ${Y}] \`${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.
1327
- bin}.exe on the PATH) or use the manual recipe in docs/terminales/.`),await Re.cerrar(),process.exit(127));}let n=spawn(t,e.args,{stdio:"inherit",env:{...process.env,...e.env}});n.on("error",r=>{console.error(
1328
- `[bvsala ${Y}] could not launch \`${e.bin}\`: ${String(r)}. Is it installed and on the PATH?`),Re.cerrar().then(()=>process.exit(127));}),n.on("exit",(r,o)=>{lu(),Re.cerrar().then(()=>process.exit(r??(o?
1329
- 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:${Re.puerto}/v1 (OpenAI SDKs) \xB7 streamed chat completions ar\
1332
+ bin}.exe on the PATH) or use the manual recipe in docs/terminales/.`),await Te.cerrar(),process.exit(127));}let n=spawn(t,e.args,{stdio:"inherit",env:{...process.env,...e.env}});n.on("error",r=>{console.error(
1333
+ `[bvsala ${Y}] could not launch \`${e.bin}\`: ${String(r)}. Is it installed and on the PATH?`),Te.cerrar().then(()=>process.exit(127));}),n.on("exit",(r,o)=>{pu(),Te.cerrar().then(()=>process.exit(r??(o?
1334
+ 1:0)));});}else {let e=new URL(du).hostname;e==="api.openai.com"?console.log(`[bvsala gateway] point your SDK at it: base_url=http://127.0.0.1:${Te.puerto}/v1 (OpenAI SDKs) \xB7 streamed chat completions ar\
1330
1335
  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 \
1331
- use \`bvsala ${_i.join("|")}\`): ANTHROPIC_BASE_URL=http://127.0.0.1:${Re.puerto} claude \xB7 bvsala doctor for the others`):console.log(`[bvsala gateway] point your client at http://127.0.0.1:${Re.
1332
- puerto} plus the path prefix it already uses (for example /v1) \xB7 bvsala doctor for recipes`);}var uu=async()=>{lu(),await Re.cerrar(),process.exit(0);};process.on("SIGINT",()=>{uu();});process.on("SIG\
1333
- TERM",()=>{uu();});
1336
+ use \`bvsala ${Ai.join("|")}\`): ANTHROPIC_BASE_URL=http://127.0.0.1:${Te.puerto} claude \xB7 bvsala doctor for the others`):console.log(`[bvsala gateway] point your client at http://127.0.0.1:${Te.
1337
+ puerto} plus the path prefix it already uses (for example /v1) \xB7 bvsala doctor for recipes`);}var fu=async()=>{pu(),await Te.cerrar(),process.exit(0);};process.on("SIGINT",()=>{fu();});process.on("SIG\
1338
+ TERM",()=>{fu();});
1334
1339
  /*! Bundled license information:
1335
1340
 
1336
1341
  @noble/curves/utils.js: