@bivelio/savings-layer 0.4.31 → 0.4.32
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.
- package/README.md +117 -12
- package/dist/adapters/anthropic-sdk.js +75 -69
- package/dist/gateway/bin.js +846 -725
- package/dist/index.d.ts +101 -6
- package/dist/index.js +1552 -1387
- package/package.json +6 -2
package/dist/gateway/bin.js
CHANGED
|
@@ -1,47 +1,47 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {spawn}from'child_process';import {existsSync,writeFileSync,mkdirSync,readFileSync}from'fs';import {homedir}from'os';import {join,dirname,posix,delimiter}from'path';import {fileURLToPath}from'url';import {randomUUID,createHash}from'crypto';import {createServer}from'http';import*as
|
|
3
|
-
return e===32||e===10||e===13||e===9}function
|
|
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&&
|
|
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(
|
|
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
|
|
7
|
-
if(t!==void 0&&t!==""&&t!=="identity")return null;let n=
|
|
8
|
-
return n.context_management=
|
|
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===
|
|
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===
|
|
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
|
|
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
|
|
13
|
-
let t=
|
|
14
|
-
s=>s.type
|
|
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 Ze from'zlib';import {connect}from'net';var On="context-management-2025-06-27";function Nr(){return {edits:[{type:"clear_tool_uses_20250919",trigger:{type:"input_tokens",value:5e4},keep:{type:"tool_uses",value:8},clear_at_least:{type:"input_tokens",value:5e3}}]}}var Bl=new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});function Ul(e){try{return Bl.decode(e)}catch{return null}}function zl(e){return /^(?:0|[1-9]\d{0,9})$/.test(e)&&Number(e)<4294967295}function Fl(e){
|
|
3
|
+
return e===32||e===10||e===13||e===9}function Vl(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&&Fl(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(zl(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 Ln(e,t){
|
|
7
|
+
if(t!==void 0&&t!==""&&t!=="identity")return null;let n=Ul(e);if(n===null)return null;let r;try{r=JSON.parse(n);}catch{return null}return Vl(n)?r:null}function Mi(e,t){try{let n=Ln(e,t);if(n===null||typeof n!="object"||Array.isArray(n)||typeof n.model!="string"||!Array.isArray(n.messages))return null;let r=Hl(n.context_management),o=Wl(n.context_management);
|
|
8
|
+
return n.context_management=Gl(n.context_management),{cuerpo:Buffer.from(JSON.stringify(n),"utf8"),nuestros:r,triggerDelCliente:o}}catch{return null}}function Hl(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===jr);return Li(n)!==Li([Nr().edits[0]])}function Wl(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===jr);if(n.length===0)return null;let r=Number.POSITIVE_INFINITY;
|
|
11
|
+
for(let o of n){let i=o.trigger,s=i!==null&&typeof i=="object"&&i.type==="input_tokens"&&typeof i.value=="number"&&Number.isFinite(i.value)&&i.value>0?i.value:1e5;s<r&&(r=s);}return r}function Li(e){return JSON.
|
|
12
|
+
stringify(e,(t,n)=>n!==null&&typeof n=="object"&&!Array.isArray(n)?Object.fromEntries(Object.keys(n).sort().map(r=>[r,n[r]])):n)}var jr="clear_tool_uses_20250919",$i="clear_thinking_20251015";function Gl(e){
|
|
13
|
+
let t=Nr().edits[0],n=e!==null&&typeof e=="object"&&!Array.isArray(e)?{...e}:{},r=(Array.isArray(n.edits)?n.edits:[]).filter(s=>s!==null&&typeof s=="object"&&!Array.isArray(s)&&s.type!==jr),o=r.filter(
|
|
14
|
+
s=>s.type===$i),i=r.filter(s=>s.type!==$i);return {...n,edits:[...o,...i,t]}}function Ni(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
|
|
18
|
-
n=>n.length>0).includes(
|
|
19
|
-
Number(t[2]);return n>5||n===5&&r>=6}function
|
|
20
|
-
typeof t=="object"?t.type:void 0;return typeof n=="string"&&!
|
|
21
|
-
return Array.isArray(e)?e.filter(t=>!(t!==null&&typeof t=="object"&&t.defer_loading===true)):e}function
|
|
22
|
-
null||typeof n!="object"||Array.isArray(n))return null;let r=n;return typeof r.model!="string"||!Array.isArray(r.messages)?null:r}function
|
|
23
|
-
messages)?e.messages.slice(0,
|
|
24
|
-
t,"utf8")+Buffer.byteLength(n,"utf8")}}function
|
|
25
|
-
length&&r<t.mensajes.length&&e.mensajes[r]===t.mensajes[r];)r++;let o=0;for(let i=r;i<t.bytes.length;i++)o+=t.bytes[i]??0;return o/n}function
|
|
26
|
-
e.ttl==="1h"?(e.ttl="5m",t.rebajadas++):(e.ttl==="5m"||e.ttl===void 0)&&t.yaEran5m++;}var
|
|
27
|
-
function
|
|
28
|
-
isArray(s.content)&&
|
|
29
|
-
e.messages)){let r=e.messages.length-1;e.messages.forEach((o,i)=>{
|
|
30
|
-
try{let r={rebajadas:0,yaEran5m:0};return
|
|
31
|
-
return null}}var
|
|
17
|
+
ce channel: OPEN by default (=0 turns the levers off)")+r+o,aviso:n}}function ji(e){return e===void 0||e.trim()===""?On:e.split(",").map(n=>n.trim()).filter(
|
|
18
|
+
n=>n.length>0).includes(On)?e:`${e},${On}`}function Bi(e){let t=e.toLowerCase(),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Kl(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 Te(e){let t=Bi(e);return t.startsWith("gpt-")||t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4")?Kl(t)?1.25:1:t.startsWith("gemini")?1:1.25}function $n(e){let t=e.toLowerCase();return t.startsWith("claude")||t.startsWith("anthropic/")||Bi(t).startsWith("claude")?2:Te(e)}var Yl=.3,Zl=/^(custom|bash_|text_editor_|computer_|browser_|memory_)/;function Vr(e){return Array.isArray(e.mcp_servers)&&e.mcp_servers.length>0?true:Array.isArray(e.tools)?e.tools.some(t=>{let n=t!==null&&
|
|
20
|
+
typeof t=="object"?t.type:void 0;return typeof n=="string"&&!Zl.test(n)}):false}var Xl=4096,Ql=(e,t)=>e==="cache_control"?void 0:t;function Br(e){return e===void 0?"":JSON.stringify(e,Ql)??""}function eu(e){
|
|
21
|
+
return Array.isArray(e)?e.filter(t=>!(t!==null&&typeof t=="object"&&t.defer_loading===true)):e}function Ur(e){return createHash("sha1").update(e).digest("base64url").slice(0,16)}function pt(e,t){let n=Ln(e,t);if(n===
|
|
22
|
+
null||typeof n!="object"||Array.isArray(n))return null;let r=n;return typeof r.model!="string"||!Array.isArray(r.messages)?null:r}function Ui(e){let t=Br(e.system),n=Br(eu(e.tools)),r=Array.isArray(e.
|
|
23
|
+
messages)?e.messages.slice(0,Xl):[],o=[],i=[];for(let s of r){let a=Br(s);o.push(Ur(a)),i.push(Buffer.byteLength(a,"utf8"));}return {system:Ur(t),tools:Ur(n),mensajes:o,bytes:i,bytesFijos:Buffer.byteLength(
|
|
24
|
+
t,"utf8")+Buffer.byteLength(n,"utf8")}}function zi(e,t){if(e===void 0||e.system!==t.system||e.tools!==t.tools)return 1;let n=t.bytesFijos;for(let i of t.bytes)n+=i;if(n<=0)return 1;let r=0;for(;r<e.mensajes.
|
|
25
|
+
length&&r<t.mensajes.length&&e.mensajes[r]===t.mensajes[r];)r++;let o=0;for(let i=r;i<t.bytes.length;i++)o+=t.bytes[i]??0;return o/n}function Fi(e){let{fraccionNueva:t,umbral:n=Yl}=e;return t>=n}function tu(e,t){
|
|
26
|
+
e.ttl==="1h"?(e.ttl="5m",t.rebajadas++):(e.ttl==="5m"||e.ttl===void 0)&&t.yaEran5m++;}var tn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),zr=e=>tn(e)&&tn(e.cache_control)?e.cache_control:null,nu=8;
|
|
27
|
+
function Mn(e,t,n,r){if(!(!Array.isArray(e)||r>nu))for(let o of e){let i=zr(o);if(i&&n(i,t),!tn(o))continue;Array.isArray(o.content)&&Mn(o.content,t,n,r+1);let s=o.source;tn(s)&&s.type==="content"&&Array.
|
|
28
|
+
isArray(s.content)&&Mn(s.content,t,n,r+1);}}function qr(e,t){let n=zr(e);if(n&&t(n,"raiz"),Mn(e.system,"system",t,0),Array.isArray(e.tools))for(let r of e.tools){let o=zr(r);o&&t(o,"tools");}if(Array.isArray(
|
|
29
|
+
e.messages)){let r=e.messages.length-1;e.messages.forEach((o,i)=>{tn(o)&&Mn(o.content,i===r?"ultimoMensaje":"mensaje",t,0);});}}function Vi(e,t){let n=Buffer.isBuffer(e)?pt(e,t):e;if(n===null)return null;
|
|
30
|
+
try{let r={rebajadas:0,yaEran5m:0};return qr(n,o=>tu(o,r)),r.rebajadas===0?null:{cuerpo:Buffer.from(JSON.stringify(n),"utf8"),rebajadas:r.rebajadas,yaEran5m:r.yaEran5m,herramientaDeServidor:Vr(n)}}catch{
|
|
31
|
+
return null}}var Nn=class{constructor(t=512,n=3600*1e3){this.maxEntradas=t;this.maxEdadMs=n;}maxEntradas;maxEdadMs;visto=new Map;ultima(t,n){let r=this.visto.get(t);if(r!==void 0){if(n-r.vistoMs>this.maxEdadMs){this.
|
|
32
32
|
visto.delete(t);return}return r.huella}}anotar(t,n,r){for(this.visto.delete(t),this.visto.set(t,{huella:n,vistoMs:r});this.visto.size>this.maxEntradas;){let o=this.visto.keys().next();if(o.done===true)break;
|
|
33
|
-
this.visto.delete(o.value);}}get tamano(){return this.visto.size}};var
|
|
34
|
-
high","claude-mythos-5-1":"high","claude-opus-5-5":"medium","claude-opus-5":"high"};function
|
|
35
|
-
var
|
|
36
|
-
function
|
|
37
|
-
let r=
|
|
38
|
-
r),"utf8"),nivel:t}):null}function
|
|
39
|
-
ort: OFF (BVSALA_GATEWAY_ESFUERZO=${
|
|
33
|
+
this.visto.delete(o.value);}}get tamano(){return this.visto.size}};var Hr="mid-conversation-output-config-2026-07-01",Un=["low","medium","high","xhigh","max"],ru=new Set(["claude-fable-5-1","claude-mythos-5-1","claude-opus-5-5","claude-opus-5"]),qi={"claude-fable-5-1":"\
|
|
34
|
+
high","claude-mythos-5-1":"high","claude-opus-5-5":"medium","claude-opus-5":"high"};function ou(e){return Wi(e)?qi[e]:void 0}function Hi(e,t){let n=ou(e);return n!==void 0&&Un.indexOf(t)<Un.indexOf(n)}
|
|
35
|
+
var Bn=Un.filter(e=>Object.keys(qi).some(t=>Hi(t,e)));function Wi(e){return ru.has(e)}function Wr(e){return e!==void 0&&Un.includes(e)}function iu(e){return {role:"system",content:[],output_config:{effort:e}}}
|
|
36
|
+
function su(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 Gi(e,t,n){
|
|
37
|
+
let r=pt(e,n);if(r===null||typeof r.model!="string"||!Wi(r.model)||!Hi(r.model,t)||su(r))return null;let o=r.messages;return Array.isArray(o)?(r.messages=[...o,iu(t)],{cuerpo:Buffer.from(JSON.stringify(
|
|
38
|
+
r),"utf8"),nivel:t}):null}function Ki(e){return e===void 0||e.trim()===""?Hr:e.split(",").map(n=>n.trim()).includes(Hr)?e:`${e},${Hr}`}function Ji(e,t,n){return e===void 0||e===""?{linea:`per-turn eff\
|
|
39
|
+
ort: OFF (BVSALA_GATEWAY_ESFUERZO=${Bn.join("|")} turns it on)`,aviso:false}:Wr(e)?Bn.includes(e)?n?{linea:`per-turn effort: ARMED at "${e}" (ON if your licence includes per_turn_effort; fail-closed). \
|
|
40
40
|
Only fable-5-1, mythos-5-1, opus-5-5 and opus-5, and only below the model's default effort (high; medium on opus-5-5${e==="medium"?", so opus-5-5 passes through unchanged at this level":""}); every ot\
|
|
41
41
|
her request passes through unchanged. Does NOT reset the prefix cache: the dial is appended at the end and nothing earlier is rewritten. Not yet verified against the quality gate`,aviso:false}:{linea:"pe\
|
|
42
42
|
r-turn effort: NOT ARMED - BVSALA_GATEWAY_ELISION=0 turns off the levers",aviso:true}:{linea:`per-turn effort: NOT ARMED \u2014 "${e}" is not below any supported model's default effort (high; medium on claude-opus-5-5),\
|
|
43
|
-
so it could only leave the bill as it is or raise it. This lever only lowers effort: use ${
|
|
44
|
-
join(", ")}`,aviso:true}}var
|
|
43
|
+
so it could only leave the bill as it is or raise it. This lever only lowers effort: use ${Bn.join(" or ")}`,aviso:true}:{linea:`per-turn effort: NOT ARMED \u2014 "${e}" is not a level. Use one of: ${Bn.
|
|
44
|
+
join(", ")}`,aviso:true}}var nn={"gpt-4.1":{inputPer1k:.002,outputPer1k:.008,cachedInputPer1k:5e-4},"gpt-4.1-mini":{inputPer1k:4e-4,outputPer1k:.0016,cachedInputPer1k:1e-4},"gpt-4.1-nano":{inputPer1k:1e-4,outputPer1k:4e-4,cachedInputPer1k:25e-6},
|
|
45
45
|
"gpt-4o":{inputPer1k:.0025,outputPer1k:.01,cachedInputPer1k:.00125},"gpt-4o-mini":{inputPer1k:15e-5,outputPer1k:6e-4,cachedInputPer1k:75e-6},"gpt-4-turbo":{inputPer1k:.01,outputPer1k:.03},"gpt-4":{inputPer1k:.03,
|
|
46
46
|
outputPer1k:.06},"gpt-3.5-turbo":{inputPer1k:5e-4,outputPer1k:.0015},"gpt-5":{inputPer1k:.00125,outputPer1k:.01,cachedInputPer1k:125e-6},"gpt-5-codex":{inputPer1k:.00125,outputPer1k:.01,cachedInputPer1k:125e-6},
|
|
47
47
|
"gpt-5-mini":{inputPer1k:25e-5,outputPer1k:.002,cachedInputPer1k:25e-6},"gpt-5-nano":{inputPer1k:5e-5,outputPer1k:4e-4,cachedInputPer1k:5e-6},"gpt-5.1-codex":{inputPer1k:.00125,outputPer1k:.01,cachedInputPer1k:125e-6},
|
|
@@ -55,38 +55,38 @@ t-5.6-sol":{inputPer1k:.004,outputPer1k:.02,cachedInputPer1k:4e-4},"gpt-5.6-terr
|
|
|
55
55
|
inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},"claude-opus-4-6":{inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},"claude-opus-4-7":{inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},
|
|
56
56
|
"claude-opus-4-8":{inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},"claude-opus-5":{inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},"claude-opus-5-5":{inputPer1k:.004,outputPer1k:.02,cachedInputPer1k:2e-4},
|
|
57
57
|
"claude-opus-4":{inputPer1k:.015,outputPer1k:.075,cachedInputPer1k:.0015},"claude-sonnet-4-5":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-sonnet-4-6":{inputPer1k:.003,outputPer1k:.015,
|
|
58
|
-
cachedInputPer1k:3e-4},"claude-sonnet-5":{inputPer1k:.002,outputPer1k:.01,cachedInputPer1k:2e-4},"claude-
|
|
59
|
-
outputPer1k:.05,cachedInputPer1k
|
|
60
|
-
|
|
61
|
-
"claude-3-5-
|
|
62
|
-
cachedInputPer1k
|
|
63
|
-
h
|
|
64
|
-
cachedInputPer1k:
|
|
65
|
-
pro":{inputPer1k:.00125,outputPer1k:.01,cachedInputPer1k:125e-6},"gemini-2.5-flash":{inputPer1k:3e-4,outputPer1k:.0025,cachedInputPer1k:3e-5}},
|
|
66
|
-
|
|
67
|
-
"gemini-3.7-flash":[{vigenteDesde:"2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}],"gemini-3.6-flash":[{vigenteDesde:"
|
|
68
|
-
cachedInputPer1k:15e-5}}]},
|
|
69
|
-
for(let n of
|
|
70
|
-
""&&c!=="-"&&c!=="."&&c!=="_")continue;let l=i.slice(a.length+1);if(!(/^\d/.test(l)&&!/^\d{4}/.test(l)))return e[a]}}function
|
|
71
|
-
p-research","o4-mini-deep-research","gpt-5.5-pro","gpt-5.4-pro","gpt-5.2-pro","gpt-5-pro","gpt-5.5-cyber","gemini-3.8-flash-tts","gemini-3.8-flash-lite-tts","gemini-3.1-flash-lite-image"],
|
|
72
|
-
fromEntries(
|
|
73
|
-
return
|
|
74
|
-
1))))return
|
|
75
|
-
cachedInputPer1k??n.inputPer1k;return (r.cachedInputPer1k??r.inputPer1k)<o}function
|
|
76
|
-
servido:n}}var
|
|
77
|
-
|
|
78
|
-
let r=Object.entries(
|
|
58
|
+
cachedInputPer1k:3e-4},"claude-sonnet-5":{inputPer1k:.002,outputPer1k:.01,cachedInputPer1k:2e-4},"claude-sonnet-5-5":{inputPer1k:.002,outputPer1k:.01,cachedInputPer1k:2e-4},"claude-fable-5":{inputPer1k:.01,
|
|
59
|
+
outputPer1k:.05,cachedInputPer1k:.001},"claude-fable-5-1":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:25e-5},"claude-mythos-5-1":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:25e-5},"claude-my\
|
|
60
|
+
thos-5":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:.001},"claude-sonnet-4":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-haiku-4-5":{inputPer1k:.001,outputPer1k:.005,cachedInputPer1k:1e-4},
|
|
61
|
+
"claude-3-5-sonnet":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-3-5-haiku":{inputPer1k:8e-4,outputPer1k:.004,cachedInputPer1k:8e-5},"claude-3-opus":{inputPer1k:.015,outputPer1k:.075,
|
|
62
|
+
cachedInputPer1k:.0015},"gemini-3.8-flash":{inputPer1k:75e-5,outputPer1k:.00375,cachedInputPer1k:75e-6},"gemini-3.7-flash":{inputPer1k:75e-5,outputPer1k:.00375,cachedInputPer1k:75e-6},"gemini-3.6-flas\
|
|
63
|
+
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,
|
|
64
|
+
cachedInputPer1k:5e-5},"gemini-3.5-flash":{inputPer1k:.0015,outputPer1k:.009,cachedInputPer1k:15e-5},"gemini-3.5-flash-lite":{inputPer1k:3e-4,outputPer1k:.0025,cachedInputPer1k:3e-5},"gemini-3.1-pro-p\
|
|
65
|
+
review":{inputPer1k:.002,outputPer1k:.012,cachedInputPer1k:2e-4},"gemini-2.5-pro":{inputPer1k:.00125,outputPer1k:.01,cachedInputPer1k:125e-6},"gemini-2.5-flash":{inputPer1k:3e-4,outputPer1k:.0025,cachedInputPer1k:3e-5}},
|
|
66
|
+
au={"gemini-3.8-flash":{vigenteHasta:"2027-01-01"},"gemini-3.7-flash":{vigenteHasta:"2027-01-01"},"gemini-3.6-flash":{vigenteHasta:"2027-01-01"}},cu={"gemini-3.8-flash":[{vigenteDesde:"2027-01-01",precio:{
|
|
67
|
+
inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}],"gemini-3.7-flash":[{vigenteDesde:"2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}],"gemini-3.6-flash":[{vigenteDesde:"\
|
|
68
|
+
2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}]},lu=Object.fromEntries(Object.keys(nn).map(e=>[e,[{...au[e],precio:nn[e]},...cu[e]??[]]]));var uu=864e13;function Yi(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 Zi(e,t){
|
|
69
|
+
for(let n of lu[e]??[])if(!(n.vigenteDesde!==void 0&&t<n.vigenteDesde)&&!(n.vigenteHasta!==void 0&&t>=n.vigenteHasta))return n.precio}function Xi(e,t,n){if(!n)return;let r=e[n];if(r)return r;let o=n.lastIndexOf("/"),i=o>=0?n.slice(o+1):n,s=e[i];if(s)return s;for(let a of t){if(!i.startsWith(a))continue;let c=i.charAt(a.length);if(c!==
|
|
70
|
+
""&&c!=="-"&&c!=="."&&c!=="_")continue;let l=i.slice(a.length+1);if(!(/^\d/.test(l)&&!/^\d{4}/.test(l)))return e[a]}}function Kr(e){return Object.keys(e).sort((t,n)=>n.length-t.length)}var du=["o3-dee\
|
|
71
|
+
p-research","o4-mini-deep-research","gpt-5.5-pro","gpt-5.4-pro","gpt-5.2-pro","gpt-5-pro","gpt-5.5-cyber","gemini-3.8-flash-tts","gemini-3.8-flash-lite-tts","gemini-3.1-flash-lite-image"],Gr={...nn,...Object.
|
|
72
|
+
fromEntries(du.map(e=>[e,null]))},pu=Kr(Gr);function Re(e,t){let n=ft(e);return n===void 0?void 0:Zi(n,Yi(t))}var fu=Object.fromEntries(Object.keys(Gr).map(e=>[e,Gr[e]===null?null:e]));function ft(e){
|
|
73
|
+
return Xi(fu,pu,e)??void 0}var mu=/^\d{4}-?\d{2}-?\d{2}$/;function Pt(e,t){let n=ft(e);if(n===void 0)return;let r=e.lastIndexOf("/"),o=r>=0?e.slice(r+1):e;if(!(n!==e&&n!==o&&!mu.test(o.slice(n.length+
|
|
74
|
+
1))))return Zi(n,Yi(t))}var Qi={"claude-fable-5":"claude-fable-5-1"};function hu(e,t){let n=Re(e),r=Re(t);if(n===void 0||r===void 0||n.inputPer1k!==r.inputPer1k||n.outputPer1k!==r.outputPer1k||Te(e)!==Te(t))return false;let o=n.
|
|
75
|
+
cachedInputPer1k??n.inputPer1k;return (r.cachedInputPer1k??r.inputPer1k)<o}function gu(e){let t=ft(e);if(t===void 0||t!==e)return null;let n=Qi[t];return n===void 0||n===t||!hu(t,n)?null:{solicitado:e,
|
|
76
|
+
servido:n}}var bu=/(^|,)\s*context-1m/i;function vu(e){let t=e.tool_choice;if(t===null||typeof t!="object")return false;let n=t.type;return n==="any"||n==="tool"}function es(e,t,n={}){if(n.betas!==void 0&&
|
|
77
|
+
bu.test(n.betas))return null;let r=pt(e,t);if(r===null||vu(r))return null;let o=gu(r.model);return o===null?null:(r.model=o.servido,{cuerpo:Buffer.from(JSON.stringify(r),"utf8"),cambio:o})}function ts(e,t,n){
|
|
78
|
+
let r=Object.entries(Qi).map(([o,i])=>`${o}\u2192${i}`).join(", ");return e!=="1"?{linea:"sibling model routing: OFF (BVSALA_GATEWAY_MODELO_HERMANO=1 turns it on)",aviso:false}:n?{linea:`sibling model \
|
|
79
79
|
routing: ARMED (${r}; ON if your licence includes sibling_model_routing; fail-closed). Changes the model you see in the response; cache reads cost 0.025\xD7 instead of 0.1\xD7 (list price). Turning it on mi\
|
|
80
80
|
d-conversation pays one cold prefix write, once. If the provider rejects the rewritten request (400), it is re-sent unchanged once`,aviso:false}:{linea:"sibling model routing: NOT ARMED - BVSALA_GATEWAY_\
|
|
81
|
-
ELISION=0 turns off the levers",aviso:true}}var
|
|
81
|
+
ELISION=0 turns off the levers",aviso:true}}var ns=new Set;function Z(e,t){ns.has(e)||(ns.add(e),console.warn(t));}var be="0.4.32",Jr="x-bvsala-version";var Dt=class{options;now;flushIntervalMs;maxBatch;maxBuffer;buffer=[];seatId;ci;timer;inflight=null;fallosSeguidos=0;constructor(t){this.options=t,this.now=t.now??(()=>Date.now()),this.flushIntervalMs=
|
|
82
82
|
t.flushIntervalMs??15e3,this.maxBatch=t.maxBatch??50,this.maxBuffer=t.maxBuffer??1e3,this.ci=t.ci??false;}setSeat(t,n){t&&(this.seatId=t),this.ci=n;}record(t){this.buffer.push({report:t,at:this.now()}),this.
|
|
83
83
|
buffer.length>this.maxBuffer&&this.buffer.splice(0,this.buffer.length-this.maxBuffer),this.buffer.length>=this.maxBatch&&this.flush();}start(){this.timer||(this.timer=setInterval(()=>{this.flush();},this.
|
|
84
84
|
flushIntervalMs),this.timer.unref?.());}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0),this.flush();}async stopAndDrain(t){this.timer&&(clearInterval(this.timer),this.timer=void 0);let n=t??
|
|
85
85
|
Math.ceil(this.maxBuffer/this.maxBatch)+4,r=0;for(let o=0;o<n&&this.buffer.length>0;o++){let i=this.buffer.length;if(await this.flush(),r=this.buffer.length>=i?r+1:0,r>=2)break}}async flush(){if(this.
|
|
86
86
|
inflight)return this.inflight;if(this.buffer.length!==0){this.inflight=this.hacerFlush();try{await this.inflight;}finally{this.inflight=null;}}}async hacerFlush(){let t=this.options.fetchImpl??globalThis.
|
|
87
87
|
fetch;if(!t)return;let n=this.buffer.splice(0,this.maxBatch);try{let r=n.map(i=>this.toWire(i)),o=await t(this.options.url,{method:"POST",headers:{"content-type":"application/json",authorization:`Bear\
|
|
88
|
-
er ${this.options.serviceAccountKey}`,[
|
|
89
|
-
`the server responded ${o.status}`)):o.status===401||o.status===403?(
|
|
88
|
+
er ${this.options.serviceAccountKey}`,[Jr]:`${this.options.surface??"sdk"}/${be}`},body:JSON.stringify(r)});o.ok?this.fallosSeguidos=0:o.status>=500?(this.fallosSeguidos++,this.requeue(n),this.avisarDeFallo(
|
|
89
|
+
`the server responded ${o.status}`)):o.status===401||o.status===403?(Z(`metering-auth-${o.status}`,`[bv-sala] usage reporting is being rejected with HTTP ${o.status} at ${this.options.url}. Check 'ser\
|
|
90
90
|
viceAccountKey' (rotated? revoked? from another organization?). Until it works, no usage is reported: the dashboard will say it sees no traffic and billable seats will show zero.`),this.options.onAuthError?.(
|
|
91
91
|
o.status)):(this.fallosSeguidos++,this.avisarDeFallo(o.status===404||o.status===405?`HTTP ${o.status}: the reporting URL looks wrong`:`the server rejected the batch with HTTP ${o.status}`));}catch(r){this.
|
|
92
92
|
fallosSeguidos++,this.requeue(n),this.avisarDeFallo(r instanceof Error?r.message:"network error");}}avisarDeFallo(t){if(this.options.silenceWarnings)return;let n=this.fallosSeguidos;n<3||(n-3)%12!==0||
|
|
@@ -98,34 +98,34 @@ tokens.compressedInput,baselineOutputTokens:n.tokens.baselineOutput,actualOutput
|
|
|
98
98
|
eliminatedInputFloorCost!==void 0&&Number.isFinite(n.cost.eliminatedInputFloorCost)&&n.cost.eliminatedInputFloorCost>0&&n.tokens.eliminatedInput>0?{eliminatedInputFloorCost:n.cost.eliminatedInputFloorCost}:
|
|
99
99
|
{},baselineCost:n.cost.baselineEstimate,actualCost:n.cost.actual,netSavings:n.cost.netSavings,...n.cost.basis?{basis:n.cost.basis}:{},...n.cost.basis==="reference"&&n.cache.reference&&/^[A-Za-z0-9._:/-]{1,128}$/.
|
|
100
100
|
test(n.cache.reference.requestId)&&Number.isInteger(n.cache.reference.at)?{referenceRequestId:n.cache.reference.requestId,referenceAt:n.cache.reference.at}:{},...n.attribution?.sessionId?{sessionId:n.
|
|
101
|
-
attribution.sessionId}:{},...n.attribution?.agentId?{agentId:n.attribution.agentId}:{}}}};function
|
|
102
|
-
]";return new RegExp(`-${t}{8,10}-${t}{5}$`).test(e)}function
|
|
103
|
-
e.NETLIFY)}async function
|
|
104
|
-
if(e.KUBERNETES_SERVICE_HOST||
|
|
105
|
-
e.arch,e.execPath,n,t.USER??t.USERNAME??t.LOGNAME,t.HOME??t.USERPROFILE].filter(o=>typeof o=="string"&&o.length>0);return r.length?r.join("|"):void 0}var
|
|
106
|
-
ONS","GITLAB_CI","CIRCLECI","TRAVIS","JENKINS_URL","BUILDKITE","TF_BUILD","TEAMCITY_VERSION","BITBUCKET_BUILD_NUMBER","CODEBUILD_BUILD_ID","HEROKU_TEST_RUN_ID","DRONE"];function
|
|
107
|
-
return false;for(let t of
|
|
101
|
+
attribution.sessionId}:{},...n.attribution?.agentId?{agentId:n.attribution.agentId}:{}}}};function zn(){return globalThis.process}function yu(e){if(/^[0-9a-f]{12}$/.test(e)||/^\d{1,3}(\.\d{1,3}){3}$/.test(e)||/^ip-\d{1,3}(-\d{1,3}){3}$/i.test(e))return true;let t="[bcdfghjklmnpqrstvwxz2456789\
|
|
102
|
+
]";return new RegExp(`-${t}{8,10}-${t}{5}$`).test(e)}function ku(e){return !!(e.AWS_LAMBDA_FUNCTION_NAME??e.LAMBDA_TASK_ROOT??e.VERCEL??e.VERCEL_ENV??e.K_SERVICE??e.FUNCTION_TARGET??e.FUNCTIONS_WORKER_RUNTIME??
|
|
103
|
+
e.NETLIFY)}async function wu(){if(zn()?.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 xu(e,t=wu){
|
|
104
|
+
if(e.KUBERNETES_SERVICE_HOST||ku(e))return;let n=e.HOSTNAME??e.COMPUTERNAME??await t();if(!(!n||yu(n)))return n}async function Su(){let e=zn();if(!e||!e.env)return;let t=e.env,n=await xu(t),r=[e.platform,
|
|
105
|
+
e.arch,e.execPath,n,t.USER??t.USERNAME??t.LOGNAME,t.HOME??t.USERPROFILE].filter(o=>typeof o=="string"&&o.length>0);return r.length?r.join("|"):void 0}var Eu=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTI\
|
|
106
|
+
ONS","GITLAB_CI","CIRCLECI","TRAVIS","JENKINS_URL","BUILDKITE","TF_BUILD","TEAMCITY_VERSION","BITBUCKET_BUILD_NUMBER","CODEBUILD_BUILD_ID","HEROKU_TEST_RUN_ID","DRONE"];function Fn(){let e=zn()?.env;if(!e)
|
|
107
|
+
return false;for(let t of Eu){let n=e[t];if(n&&n!=="false"&&n!=="0")return true}return false}async function _u(e,t){let n=globalThis.crypto,r=new TextEncoder;if(n?.subtle)try{let s=await n.subtle.importKey("raw",
|
|
108
108
|
r.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await n.subtle.sign("HMAC",s,r.encode(t));return [...new Uint8Array(a)].map(c=>c.toString(16).padStart(2,"0")).join("")}catch{}let o=2166136261,i=`${e}\
|
|
109
|
-
|${t}`;for(let s=0;s<i.length;s++)o^=i.charCodeAt(s),o=Math.imul(o,16777619);return (o>>>0).toString(16).padStart(8,"0")}async function
|
|
110
|
-
if(!r)return;let o=await
|
|
111
|
-
`"${t}" `;throw new TypeError(`${n}expected number, got ${typeof e}`)}if(!Number.isSafeInteger(e)||e<0){let n=t&&`"${t}" `;throw new RangeError(`${n}expected integer >= 0, got ${e}`)}}function
|
|
112
|
-
let r=
|
|
113
|
-
new TypeError(l)}return e}function
|
|
114
|
-
o() output");let n=t.outputLen;if(e.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function
|
|
115
|
-
let t="";for(let n=0;n<e.length;n++)t+=
|
|
116
|
-
e<=
|
|
117
|
-
new RangeError(o.message):o}let t=e.length,n=t/2;if(t%2)throw new RangeError("hex string expected, got unpadded hex of length "+t);let r=new Uint8Array(n);for(let o=0,i=0;o<n;o++,i+=2){let s=
|
|
118
|
-
i)),a=
|
|
119
|
-
|
|
120
|
-
`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}var
|
|
121
|
-
new Uint8Array(t),this.view=
|
|
122
|
-
o)this.process(c,s);continue}r.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(n,0),this.pos=0);}return this.length+=t.length,this.roundClean(),this}digestInto(t){
|
|
123
|
-
|
|
124
|
-
o-8,BigInt(this.length*8),i),this.process(r,0);let a=
|
|
125
|
-
ha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,
|
|
126
|
-
constructor,t.set(...this.get());let{blockLen:n,buffer:r,length:o,finished:i,destroyed:s,pos:a}=this;return t.destroyed=s,t.finished=i,t.length=o,t.pos=a,o%n&&t.buffer.set(r),t}clone(){return this._cloneInto()}};var
|
|
127
|
-
o=new Uint32Array(n);for(let i=0;i<n;i++){let{h:s,l:a}=
|
|
128
|
-
n+r+o+(e/2**32|0)|0,
|
|
109
|
+
|${t}`;for(let s=0;s<i.length;s++)o^=i.charCodeAt(s),o=Math.imul(o,16777619);return (o>>>0).toString(16).padStart(8,"0")}async function Vn(e){let n=zn()?.env?.BVSALA_SEAT_ID;if(n&&Tu.test(n))return n;let r=await Su();
|
|
110
|
+
if(!r)return;let o=await _u(e,r);if(o)return `m-${o.slice(0,32)}`}var Tu=/^[A-Za-z0-9._:/-]{1,128}$/;function Yr(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function qn(e,t=""){if(typeof e!="number"){let n=t&&
|
|
111
|
+
`"${t}" `;throw new TypeError(`${n}expected number, got ${typeof e}`)}if(!Number.isSafeInteger(e)||e<0){let n=t&&`"${t}" `;throw new RangeError(`${n}expected integer >= 0, got ${e}`)}}function Ie(e,t,n=""){
|
|
112
|
+
let r=Yr(e),o=e?.length,i=t!==void 0;if(!r||i&&o!==t){let s=n&&`"${n}" `,a=i?` of length ${t}`:"",c=r?`length=${o}`:`type=${typeof e}`,l=s+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):
|
|
113
|
+
new TypeError(l)}return e}function Zr(e,t=true){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function os(e,t){Ie(e,void 0,"digestInt\
|
|
114
|
+
o() output");let n=t.outputLen;if(e.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function rn(...e){for(let t=0;t<e.length;t++)e[t].fill(0);}function Hn(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var is=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Au=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Wn(e){if(Ie(e),is)return e.toHex();
|
|
115
|
+
let t="";for(let n=0;n<e.length;n++)t+=Au[e[n]];return t}var We={_0:48,_9:57,A:65,F:70,a:97,f:102};function rs(e){if(e>=We._0&&e<=We._9)return e-We._0;if(e>=We.A&&e<=We.F)return e-(We.A-10);if(e>=We.a&&
|
|
116
|
+
e<=We.f)return e-(We.a-10)}function on(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);if(is)try{return Uint8Array.fromHex(e)}catch(o){throw o instanceof SyntaxError?
|
|
117
|
+
new RangeError(o.message):o}let t=e.length,n=t/2;if(t%2)throw new RangeError("hex string expected, got unpadded hex of length "+t);let r=new Uint8Array(n);for(let o=0,i=0;o<n;o++,i+=2){let s=rs(e.charCodeAt(
|
|
118
|
+
i)),a=rs(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 Xr(...e){let t=0;for(let r=0;r<e.length;r++){let o=e[r];Ie(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 as(e=32){
|
|
119
|
+
qn(e,"bytesLength");let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(e>65536)throw new RangeError(
|
|
120
|
+
`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}var cs=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});var Gn=class{blockLen;outputLen;canXOF=false;padOffset;isLE;buffer;view;finished=false;length=0;pos=0;destroyed=false;constructor(t,n,r,o){this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=
|
|
121
|
+
new Uint8Array(t),this.view=Hn(this.buffer);}update(t){Zr(this),Ie(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=Hn(t);for(;o<=i-s;s+=
|
|
122
|
+
o)this.process(c,s);continue}r.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(n,0),this.pos=0);}return this.length+=t.length,this.roundClean(),this}digestInto(t){Zr(this),
|
|
123
|
+
os(t,this),this.finished=true;let{buffer:n,view:r,blockLen:o,isLE:i}=this,{pos:s}=this;n[s++]=128,rn(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(r,0),s=0);for(let u=s;u<o;u++)n[u]=0;r.setBigUint64(
|
|
124
|
+
o-8,BigInt(this.length*8),i),this.process(r,0);let a=Hn(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\
|
|
125
|
+
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.
|
|
126
|
+
constructor,t.set(...this.get());let{blockLen:n,buffer:r,length:o,finished:i,destroyed:s,pos:a}=this;return t.destroyed=s,t.finished=i,t.length=o,t.pos=a,o%n&&t.buffer.set(r),t}clone(){return this._cloneInto()}};var ue=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Kn=BigInt(4294967295),ls=BigInt(32);function Cu(e,t=false){return t?{h:Number(e&Kn),l:Number(e>>ls&Kn)}:{h:Number(e>>ls&Kn)|0,l:Number(e&Kn)|0}}function us(e,t=false){let n=e.length,r=new Uint32Array(n),
|
|
127
|
+
o=new Uint32Array(n);for(let i=0;i<n;i++){let{h:s,l:a}=Cu(e[i],t);[r[i],o[i]]=[s,a];}return [r,o]}var Qr=(e,t,n)=>e>>>n,eo=(e,t,n)=>e<<32-n|t>>>n,mt=(e,t,n)=>e>>>n|t<<32-n,ht=(e,t,n)=>e<<32-n|t>>>n,sn=(e,t,n)=>e<<64-n|t>>>n-32,an=(e,t,n)=>e>>>n-32|t<<64-n;function Le(e,t,n,r){let o=(t>>>0)+(r>>>0);return {h:e+n+(o/2**32|0)|0,l:o|0}}var ds=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),ps=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,fs=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),ms=(e,t,n,r,o)=>t+
|
|
128
|
+
n+r+o+(e/2**32|0)|0,hs=(e,t,n,r,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(o>>>0),gs=(e,t,n,r,o,i)=>t+n+r+o+i+(e/2**32|0)|0;var bs=us(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242",
|
|
129
129
|
"0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc6\
|
|
130
130
|
8b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","\
|
|
131
131
|
0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3\
|
|
@@ -133,150 +133,150 @@ c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a6
|
|
|
133
133
|
x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5d\
|
|
134
134
|
efb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0x\
|
|
135
135
|
eada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c1\
|
|
136
|
-
00d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),
|
|
137
|
-
super(128,t,16,false);}get(){let{Ah:t,Al:n,Bh:r,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:l,El:
|
|
138
|
-
t|0,this.Al=n|0,this.Bh=r|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=
|
|
139
|
-
16;x++,n+=4)
|
|
140
|
-
L,B,19)^
|
|
141
|
-
Gh:
|
|
142
|
-
|
|
143
|
-
let j=
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
0;Dh=
|
|
147
|
-
expected boolean, got type="+typeof e)}return e}function
|
|
148
|
-
"number"){let n=t&&`"${t}" `;throw new TypeError(n+"expected number, got type="+typeof e)}if(!Number.isSafeInteger(e)){let n=t&&`"${t}" `;throw new RangeError(n+"expected safe integer, got "+e)}}function
|
|
149
|
-
function
|
|
150
|
-
return
|
|
151
|
-
"expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function
|
|
136
|
+
00d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),Iu=bs[0],Pu=bs[1],tt=new Uint32Array(80),nt=new Uint32Array(80),to=class extends Gn{constructor(t){
|
|
137
|
+
super(128,t,16,false);}get(){let{Ah:t,Al:n,Bh:r,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:l,El: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=
|
|
138
|
+
t|0,this.Al=n|0,this.Bh=r|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=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 x=0;x<
|
|
139
|
+
16;x++,n+=4)tt[x]=t.getUint32(n),nt[x]=t.getUint32(n+=4);for(let x=16;x<80;x++){let k=tt[x-15]|0,I=nt[x-15]|0,P=mt(k,I,1)^mt(k,I,8)^Qr(k,I,7),D=ht(k,I,1)^ht(k,I,8)^eo(k,I,7),L=tt[x-2]|0,B=nt[x-2]|0,K=mt(
|
|
140
|
+
L,B,19)^sn(L,B,61)^Qr(L,B,6),Q=ht(L,B,19)^an(L,B,61)^eo(L,B,6),_=fs(D,Q,nt[x-7],nt[x-16]),R=ms(_,P,K,tt[x-7],tt[x-16]);tt[x]=R|0,nt[x]=_|0;}let{Ah:r,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:p,Eh:u,El:f,Fh:m,Fl:b,
|
|
141
|
+
Gh:v,Gl:g,Hh:y,Hl:w}=this;for(let x=0;x<80;x++){let k=mt(u,f,14)^mt(u,f,18)^sn(u,f,41),I=ht(u,f,14)^ht(u,f,18)^an(u,f,41),P=u&m^~u&v,D=f&b^~f&g,L=hs(w,I,D,Pu[x],nt[x]),B=gs(L,y,k,P,Iu[x],tt[x]),K=L|0,
|
|
142
|
+
Q=mt(r,o,28)^sn(r,o,34)^sn(r,o,39),_=ht(r,o,28)^an(r,o,34)^an(r,o,39),R=r&i^r&a^i&a,$=o&s^o&c^s&c;y=v|0,w=g|0,v=m|0,g=b|0,m=u|0,b=f|0,{h:u,l:f}=Le(l|0,p|0,B|0,K|0),l=a|0,p=c|0,a=i|0,c=s|0,i=r|0,s=o|0;
|
|
143
|
+
let j=ds(K,_,$);r=ps(j,B,Q,R),o=j|0;}(({h:r,l:o}=Le(this.Ah|0,this.Al|0,r|0,o|0))),{h:i,l:s}=Le(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Le(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:p}=Le(this.Dh|0,this.Dl|0,l|0,
|
|
144
|
+
p|0),{h:u,l:f}=Le(this.Eh|0,this.El|0,u|0,f|0),{h:m,l:b}=Le(this.Fh|0,this.Fl|0,m|0,b|0),{h:v,l:g}=Le(this.Gh|0,this.Gl|0,v|0,g|0),{h:y,l:w}=Le(this.Hh|0,this.Hl|0,y|0,w|0),this.set(r,o,i,s,a,c,l,p,u,
|
|
145
|
+
f,m,b,v,g,y,w);}roundClean(){rn(tt,nt);}destroy(){this.destroyed=true,rn(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}},no=class extends to{Ah=ue[0]|0;Al=ue[1]|0;Bh=ue[2]|0;Bl=ue[3]|0;Ch=ue[4]|0;Cl=ue[5]|
|
|
146
|
+
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 Jn=ss(()=>new no,cs(3));var te=(e,t,n)=>Ie(e,t,n),oo=qn,io=Wn,$e=(...e)=>Xr(...e),vs=e=>on(e),Xn=Yr,ys=e=>as(e),Zn=BigInt(0),ro=BigInt(1);function Ot(e,t=""){if(typeof e!="boolean"){let n=t&&`"${t}" `;throw new TypeError(n+"\
|
|
147
|
+
expected boolean, got type="+typeof e)}return e}function Du(e){if(typeof e=="bigint"){if(!Yn(e))throw new RangeError("positive bigint expected, got "+e)}else oo(e);return e}function Ge(e,t=""){if(typeof e!=
|
|
148
|
+
"number"){let n=t&&`"${t}" `;throw new TypeError(n+"expected number, got type="+typeof e)}if(!Number.isSafeInteger(e)){let n=t&&`"${t}" `;throw new RangeError(n+"expected safe integer, got "+e)}}function ks(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);return e===""?Zn:BigInt("0x"+e)}function so(e){return ks(Wn(e))}function Ke(e){return ks(Wn(cn(Ie(e)).reverse()))}
|
|
149
|
+
function ao(e,t){if(qn(t),t===0)throw new RangeError("zero length");e=Du(e);let n=e.toString(16);if(n.length>t*2)throw new RangeError("number too large");return on(n.padStart(t*2,"0"))}function ws(e,t){
|
|
150
|
+
return ao(e,t).reverse()}function xs(e,t){if(e=te(e),t=te(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 cn(e){return Uint8Array.from(te(e))}var Yn=e=>typeof e=="bigint"&&Zn<=e;function Ou(e,t,n){return Yn(e)&&Yn(t)&&Yn(n)&&t<=e&&e<n}function co(e,t,n,r){if(!Ou(t,n,r))throw new RangeError(
|
|
151
|
+
"expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function lo(e){if(e<Zn)throw new Error("expected non-negative bigint, got "+e);let t;for(t=0;e>Zn;e>>=ro,t+=1);return t}var Ss=e=>(ro<<BigInt(e))-ro;function gt(e,t={},n={}){if(Object.prototype.toString.call(e)!=="[object Object]")throw new TypeError("expected valid options object");function r(i,s,a){if(!a&&s!=="function"&&!Object.hasOwn(e,i))throw new TypeError(
|
|
152
152
|
`param "${i}" is invalid: expected own property`);let c=e[i];if(a&&c===void 0)return;let l=typeof c;if(l!==s||c===null)throw new TypeError(`param "${i}" is invalid: expected ${s}, got ${l}`)}let o=(i,s)=>Object.
|
|
153
|
-
entries(i).forEach(([a,c])=>r(a,c,s));o(t,false),o(n,true);}var
|
|
154
|
-
modulus, got "+t);let n=e%t;return n>=
|
|
155
|
-
o number");if(t<=
|
|
156
|
-
throw new Error("invert: does not exist");return
|
|
157
|
-
r);return
|
|
158
|
-
n=
|
|
159
|
-
cmov(f,
|
|
160
|
-
o=
|
|
161
|
-
if(
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
BYTES:"number",BITS:"number"},n=
|
|
165
|
-
ORDER<=
|
|
166
|
-
if(n===
|
|
167
|
-
a,r.mul(a,c)),r.ONE),s=r.inv(i);return t.reduceRight((a,c,l)=>r.is0(c)?a:(o[l]=r.mul(a,o[l]),r.mul(a,c)),s),o}function
|
|
168
|
-
let n=
|
|
169
|
-
|
|
153
|
+
entries(i).forEach(([a,c])=>r(a,c,s));o(t,false),o(n,true);}var uo=()=>{throw new Error("not implemented")};var de=BigInt(0),se=BigInt(1),bt=BigInt(2),As=BigInt(3),Cs=BigInt(4),Rs=BigInt(5),Lu=BigInt(7),Is=BigInt(8),$u=BigInt(9),Ps=BigInt(16);function X(e,t){if(t<=de)throw new Error("mod: expected positive \
|
|
154
|
+
modulus, got "+t);let n=e%t;return n>=de?n:t+n}function Pe(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 Es(e,t){if(e===de)throw new Error("invert: expected non-zer\
|
|
155
|
+
o number");if(t<=de)throw new Error("invert: expected positive modulus, got "+t);let n=X(e,t),r=t,o=de,s=se;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!==se)
|
|
156
|
+
throw new Error("invert: does not exist");return X(o,t)}function po(e,t,n){let r=e;if(!r.eql(r.sqr(t),n))throw new Error("Cannot find square root")}function Ds(e,t){let n=e,r=(n.ORDER+se)/Cs,o=n.pow(t,
|
|
157
|
+
r);return po(n,o,t),o}function Mu(e,t){let n=e,r=(n.ORDER-Rs)/Is,o=n.mul(t,bt),i=n.pow(o,r),s=n.mul(t,i),a=n.mul(n.mul(s,bt),i),c=n.mul(s,n.sub(a,n.ONE));return po(n,c,t),c}function Nu(e){let t=nr(e),
|
|
158
|
+
n=Os(e),r=n(t,t.neg(t.ONE)),o=n(t,r),i=n(t,t.neg(r)),s=(e+Lu)/Ps;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.
|
|
159
|
+
cmov(m,f,v);let g=l.eql(l.sqr(u),c),y=l.cmov(p,u,g);return po(l,y,c),y})}function Os(e){if(e<As)throw new Error("sqrt is not defined for small field");let t=e-se,n=0;for(;t%bt===de;)t/=bt,n++;let r=bt,
|
|
160
|
+
o=nr(e);for(;_s(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Ds;let i=o.pow(r,t),s=(t+se)/bt;return function(c,l){let p=c;if(p.is0(l))return l;
|
|
161
|
+
if(_s(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++,
|
|
162
|
+
g=p.sqr(g),v===u)throw new Error("Cannot find square root");let y=se<<BigInt(u-v-1),w=p.pow(f,y);u=v,f=p.sqr(w),m=p.mul(m,f),b=p.mul(b,w);}return b}}function ju(e){return e%Cs===As?Ds:e%Is===Rs?Mu:e%Ps===
|
|
163
|
+
$u?Nu(e):Os(e)}var Je=(e,t)=>(X(e,t)&se)===se,Bu=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ls(e){let t={ORDER:"bigint",
|
|
164
|
+
BYTES:"number",BITS:"number"},n=Bu.reduce((r,o)=>(r[o]="function",r),t);if(gt(e,n),Ge(e.BYTES,"BYTES"),Ge(e.BITS,"BITS"),e.BYTES<1||e.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(e.
|
|
165
|
+
ORDER<=se)throw new Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function Uu(e,t,n){let r=e;if(n<de)throw new Error("invalid exponent, negatives unsupported");if(n===de)return r.ONE;
|
|
166
|
+
if(n===se)return t;let o=r.ONE,i=t;for(;n>de;)n&se&&(o=r.mul(o,i)),i=r.sqr(i),n>>=se;return o}function tr(e,t,n=false){let r=e,o=new Array(t.length).fill(n?r.ZERO:void 0),i=t.reduce((a,c,l)=>r.is0(c)?a:(o[l]=
|
|
167
|
+
a,r.mul(a,c)),r.ONE),s=r.inv(i);return t.reduceRight((a,c,l)=>r.is0(c)?a:(o[l]=r.mul(a,o[l]),r.mul(a,c)),s),o}function _s(e,t){let n=e,r=(n.ORDER-se)/bt,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 zu(e,t){if(t!==void 0&&oo(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);
|
|
168
|
+
let n=lo(e);if(t!==void 0&&t<n)throw new Error(`invalid n length: expected bit length (${n}) >= n.length (${t})`);let r=t!==void 0?t:n,o=Math.ceil(r/8);return {nBitLength:r,nByteLength:o}}var Ts=new WeakMap,
|
|
169
|
+
er=class{ORDER;BITS;BYTES;isLE;ZERO=de;ONE=se;_lengths;_mod;constructor(t,n={}){if(t<=se)throw new Error("invalid field: expected ORDER > 1, got "+t);let r;this.isLE=false,n!=null&&typeof n=="object"&&(typeof n.
|
|
170
170
|
BITS=="number"&&(r=n.BITS),typeof n.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:n.sqrt,enumerable:true}),typeof n.isLE=="boolean"&&(this.isLE=n.isLE),n.allowedLengths&&(this._lengths=Object.
|
|
171
|
-
freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:i}=
|
|
172
|
-
048 bytes");this.ORDER=t,this.BITS=o,this.BYTES=i,Object.freeze(this);}create(t){return
|
|
173
|
-
"+typeof t);return
|
|
174
|
-
t*t,this.ORDER)}add(t,n){return
|
|
175
|
-
return t*t}addN(t,n){return t+n}subN(t,n){return t-n}mulN(t,n){return t*n}inv(t){return
|
|
176
|
-
isLE?
|
|
171
|
+
freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:i}=zu(t,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2\
|
|
172
|
+
048 bytes");this.ORDER=t,this.BITS=o,this.BYTES=i,Object.freeze(this);}create(t){return X(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new TypeError("invalid field element: expected bigint, got\
|
|
173
|
+
"+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&se)===se}neg(t){return X(-t,this.ORDER)}eql(t,n){return t===n}sqr(t){return X(
|
|
174
|
+
t*t,this.ORDER)}add(t,n){return X(t+n,this.ORDER)}sub(t,n){return X(t-n,this.ORDER)}mul(t,n){return X(t*n,this.ORDER)}pow(t,n){return Uu(this,t,n)}div(t,n){return X(t*Es(n,this.ORDER),this.ORDER)}sqrN(t){
|
|
175
|
+
return t*t}addN(t,n){return t+n}subN(t,n){return t-n}mulN(t,n){return t*n}inv(t){return Es(t,this.ORDER)}sqrt(t){let n=Ts.get(this);return n||Ts.set(this,n=ju(this.ORDER)),n(this,t)}toBytes(t){return this.
|
|
176
|
+
isLE?ws(t,this.BYTES):ao(t,this.BYTES)}fromBytes(t,n=false){te(t);let{_lengths:r,BYTES:o,isLE:i,ORDER:s,_mod:a}=this;if(r){if(t.length<1||!r.includes(t.length)||t.length>o)throw new Error("Field.fromByte\
|
|
177
177
|
s: expected "+r+" bytes, got "+t.length);let l=new Uint8Array(o);l.set(t,i?0:l.length-t.length),t=l;}if(t.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);let c=i?Ke(t):
|
|
178
|
-
|
|
179
|
-
freeze(
|
|
180
|
-
throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function
|
|
181
|
-
shiftBy:s}}function
|
|
182
|
-
isNeg:
|
|
183
|
-
t.ZERO,this.Fn=t.Fn,this.bits=n;}_unsafeLadder(t,n,r=this.ZERO){let o=t;for(;n>
|
|
178
|
+
so(t);if(a&&(c=X(c,s)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return tr(this,t)}cmov(t,n,r){return Ot(r,"condition"),r?n:t}};Object.
|
|
179
|
+
freeze(er.prototype);function nr(e,t={}){return new er(e,t)}var rr=BigInt(0),go=BigInt(1);function $s(e,t){let n=t.negate();return e?n:t}function ir(e,t){let n=tr(e.Fp,t.map(r=>r.Z));return t.map((r,o)=>e.fromAffine(r.toAffine(n[o])))}function Bs(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)
|
|
180
|
+
throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function fo(e,t){Bs(e,t);let n=Math.ceil(t/e)+1,r=2**(e-1),o=2**e,i=Ss(e),s=BigInt(e);return {windows:n,windowSize:r,mask:i,maxNumber:o,
|
|
181
|
+
shiftBy:s}}function Ms(e,t,n){let{windowSize:r,mask:o,maxNumber:i,shiftBy:s}=n,a=Number(e&o),c=e>>s;a>r&&(a-=i,c+=go);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,
|
|
182
|
+
isNeg:f,isNegF:m,offsetF:l}}var mo=new WeakMap,Us=new WeakMap;function ho(e){return Us.get(e)||1}function Ns(e){if(e!==rr)throw new Error("invalid wNAF")}var or=class{BASE;ZERO;Fn;bits;constructor(t,n){this.BASE=t.BASE,this.ZERO=
|
|
183
|
+
t.ZERO,this.Fn=t.Fn,this.bits=n;}_unsafeLadder(t,n,r=this.ZERO){let o=t;for(;n>rr;)n&go&&(r=r.add(o)),o=o.double(),n>>=go;return r}precomputeWindow(t,n){let{windows:r,windowSize:o}=fo(n,this.bits),i=[],
|
|
184
184
|
s=t,a=s;for(let c=0;c<r;c++){a=s,i.push(a);for(let l=1;l<o;l++)a=a.add(s),i.push(a);s=a.double();}return i}wNAF(t,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,i=this.BASE,
|
|
185
|
-
s=
|
|
186
|
-
ZERO){let i=
|
|
187
|
-
get(n);return o||(o=this.precomputeWindow(n,t),t!==1&&(typeof r=="function"&&(o=r(o)),
|
|
188
|
-
t);return i===1?this._unsafeLadder(t,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,t,r),n,o)}createCache(t,n){
|
|
189
|
-
ds"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(let c of ["p","n","h"]){let l=t[c];if(!(typeof l=="bigint"&&l>
|
|
190
|
-
let o=
|
|
191
|
-
freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:i}}function
|
|
192
|
-
let n=t,r=
|
|
193
|
-
sqrt(o.div(
|
|
194
|
-
|
|
195
|
-
this.X=u("x",
|
|
196
|
-
x:
|
|
197
|
-
c:o.ORDER;
|
|
198
|
-
"bad point: x=0 and x_0=1");return j
|
|
199
|
-
return
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
let{a:
|
|
203
|
-
X:x,Y:
|
|
204
|
-
return
|
|
205
|
-
if(!i.isValid(
|
|
206
|
-
is0()}isTorsionFree(){return
|
|
207
|
-
throw new Error("invZ was invalid");return {x:D,y:L}}clearCofactor(){return a===
|
|
208
|
-
return
|
|
209
|
-
this.ep=t;}static fromBytes(t){
|
|
210
|
-
return this.ep.toAffine(t)}toHex(){return
|
|
185
|
+
s=fo(t,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:l,isZero:p,isNeg:u,isNegF:f,offsetF:m}=Ms(r,a,s);r=c,p?i=i.add($s(f,n[m])):o=o.add($s(u,n[l]));}return Ns(r),{p:o,f:i}}wNAFUnsafe(t,n,r,o=this.
|
|
186
|
+
ZERO){let i=fo(t,this.bits);for(let s=0;s<i.windows&&r!==rr;s++){let{nextN:a,offset:c,isZero:l,isNeg:p}=Ms(r,s,i);if(r=a,!l){let u=n[c];o=o.add(p?u.negate():u);}}return Ns(r),o}getPrecomputes(t,n,r){let o=mo.
|
|
187
|
+
get(n);return o||(o=this.precomputeWindow(n,t),t!==1&&(typeof r=="function"&&(o=r(o)),mo.set(n,o))),o}cached(t,n,r){let o=ho(t);return this.wNAF(o,this.getPrecomputes(o,t,r),n)}unsafe(t,n,r,o){let i=ho(
|
|
188
|
+
t);return i===1?this._unsafeLadder(t,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,t,r),n,o)}createCache(t,n){Bs(n,this.bits),Us.set(t,n),mo.delete(t);}hasCache(t){return ho(t)!==1}};function js(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ls(t),t}else return nr(e,{isLE:n})}function zs(e,t,n={},r){if(r===void 0&&(r=e==="edwar\
|
|
189
|
+
ds"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(let c of ["p","n","h"]){let l=t[c];if(!(typeof l=="bigint"&&l>rr))throw new Error(`CURVE.${c} must be positive bigint`)}
|
|
190
|
+
let o=js(t.p,n.Fp,r),i=js(t.n,n.Fn,r),a=["Gx","Gy","a","d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.
|
|
191
|
+
freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:i}}function Fs(e,t){return function(r){let o=e(r);return {secretKey:o,publicKey:t(o)}}}var rt=BigInt(0),ae=BigInt(1),bo=BigInt(2),Fu=BigInt(8);function Vu(e,t,n,r){let o=e.sqr(n),i=e.sqr(r),s=e.add(e.mul(t.a,o),i),a=e.add(e.ONE,e.mul(t.d,e.mul(o,i)));return e.eql(s,a)}function Vs(e,t={}){
|
|
192
|
+
let n=t,r=zs("edwards",e,n,n.FpFnLE),{Fp:o,Fn:i}=r,s=r.CURVE,{h:a}=s;gt(n,{},{uvRatio:"function"});let c=bo<<BigInt(i.BYTES*8)-ae,l=v=>o.create(v),p=n.uvRatio===void 0?(v,g)=>{try{return {isValid:!0,value:o.
|
|
193
|
+
sqrt(o.div(v,g))}}catch{return {isValid:false,value:rt}}}:n.uvRatio;if(!Vu(o,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function u(v,g,y=false){let w=y?ae:rt;return co("coordinate "+v,
|
|
194
|
+
g,w,c),g}function f(v){if(!(v instanceof m))throw new Error("EdwardsPoint expected")}class m{static BASE=new m(s.Gx,s.Gy,ae,l(s.Gx*s.Gy));static ZERO=new m(rt,ae,ae,rt);static Fp=o;static Fn=i;X;Y;Z;T;constructor(g,y,w,x){
|
|
195
|
+
this.X=u("x",g),this.Y=u("y",y),this.Z=u("z",w,true),this.T=u("t",x),Object.freeze(this);}static CURVE(){return s}static fromAffine(g){if(g instanceof m)throw new Error("extended point not allowed");let{
|
|
196
|
+
x:y,y:w}=g||{};return u("x",y),u("y",w),new m(y,w,ae,l(y*w))}static fromBytes(g,y=false){let w=o.BYTES,{a:x,d:k}=s;g=cn(te(g,w,"point")),Ot(y,"zip215");let I=cn(g),P=g[w-1];I[w-1]=P&-129;let D=Ke(I),L=y?
|
|
197
|
+
c:o.ORDER;co("point.y",D,rt,L);let B=l(D*D),K=l(B-ae),Q=l(k*B-x),{isValid:_,value:R}=p(K,Q);if(!_)throw new Error("bad point: invalid y coordinate");let $=(R&ae)===ae,j=(P&128)!==0;if(!y&&R===rt&&j)throw new Error(
|
|
198
|
+
"bad point: x=0 and x_0=1");return j!==$&&(R=l(-R)),m.fromAffine({x:R,y:D})}static fromHex(g,y=false){return m.fromBytes(vs(g),y)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,y=true){
|
|
199
|
+
return b.createCache(this,g),y||this.multiply(bo),this}assertValidity(){let g=this,{a:y,d:w}=s;if(g.is0())throw new Error("bad point: ZERO");let{X:x,Y:k,Z:I,T:P}=g,D=l(x*x),L=l(k*k),B=l(I*I),K=l(B*B),
|
|
200
|
+
Q=l(D*y),_=l(B*l(Q+L)),R=l(K+l(w*l(D*L)));if(_!==R)throw new Error("bad point: equation left != right (1)");let $=l(x*k),j=l(I*P);if($!==j)throw new Error("bad point: equation left != right (2)")}equals(g){
|
|
201
|
+
f(g);let{X:y,Y:w,Z:x}=this,{X:k,Y:I,Z:P}=g,D=l(y*P),L=l(k*x),B=l(w*P),K=l(I*x);return D===L&&B===K}is0(){return this.equals(m.ZERO)}negate(){return new m(l(-this.X),this.Y,this.Z,l(-this.T))}double(){
|
|
202
|
+
let{a:g}=s,{X:y,Y:w,Z:x}=this,k=l(y*y),I=l(w*w),P=l(bo*l(x*x)),D=l(g*k),L=y+w,B=l(l(L*L)-k-I),K=D+I,Q=K-P,_=D-I,R=l(B*Q),$=l(K*_),j=l(B*_),ne=l(Q*K);return new m(R,$,ne,j)}add(g){f(g);let{a:y,d:w}=s,{
|
|
203
|
+
X:x,Y:k,Z:I,T:P}=this,{X:D,Y:L,Z:B,T:K}=g,Q=l(x*D),_=l(k*L),R=l(P*w*K),$=l(I*B),j=l((x+k)*(D+L)-Q-_),ne=$-R,ee=$+R,ke=l(_-y*Q),we=l(j*ne),ze=l(ee*ke),Qe=l(j*ke),h=l(ne*ee);return new m(we,ze,h,Qe)}subtract(g){
|
|
204
|
+
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:y,f:w}=b.cached(this,g,x=>ir(m,x));return ir(m,[y,w])[0]}multiplyUnsafe(g){
|
|
205
|
+
if(!i.isValid(g))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return g===rt?m.ZERO:this.is0()||g===ae?this:b.unsafe(this,g,y=>ir(m,y))}isSmallOrder(){return this.clearCofactor().
|
|
206
|
+
is0()}isTorsionFree(){return b.unsafe(this,s.n).is0()}toAffine(g){let y=this,w=g,{X:x,Y:k,Z:I}=y,P=y.is0();w==null&&(w=P?Fu:o.inv(I));let D=l(x*w),L=l(k*w),B=o.mul(I,w);if(P)return {x:rt,y:ae};if(B!==ae)
|
|
207
|
+
throw new Error("invZ was invalid");return {x:D,y:L}}clearCofactor(){return a===ae?this:this.multiplyUnsafe(a)}toBytes(){let{x:g,y}=this.toAffine(),w=o.toBytes(y);return w[w.length-1]|=g&ae?128:0,w}toHex(){
|
|
208
|
+
return io(this.toBytes())}toString(){return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let b=new or(m,i.BITS);return i.BITS>=8&&m.BASE.precompute(8),Object.freeze(m.prototype),Object.freeze(m),m}var sr=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(t){
|
|
209
|
+
this.ep=t;}static fromBytes(t){uo();}static fromHex(t){uo();}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity();}toAffine(t){
|
|
210
|
+
return this.ep.toAffine(t)}toHex(){return io(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return true}isSmallOrder(){return false}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){
|
|
211
211
|
return this.assertSame(t),this.init(this.ep.subtract(t.ep))}multiply(t){return this.init(this.ep.multiply(t))}multiplyUnsafe(t){return this.init(this.ep.multiplyUnsafe(t))}double(){return this.init(this.
|
|
212
|
-
ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,n){return this.ep.precompute(t,n),this}};function
|
|
213
|
-
equired');let r=t,o=n;
|
|
214
|
-
outputLen,
|
|
215
|
-
|
|
216
|
-
let
|
|
217
|
-
|
|
218
|
-
"context"),!!i)))}function x(
|
|
219
|
-
|
|
220
|
-
void 0?!!
|
|
221
|
-
subarray(ke
|
|
222
|
-
clearCofactor().is0()}let P=a.BYTES,D={secretKey:P,publicKey:P,signature:2*P,seed:P};function L(
|
|
223
|
-
function K(
|
|
224
|
-
|
|
225
|
-
|
|
212
|
+
ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,n){return this.ep.precompute(t,n),this}};function qs(e,t,n={}){if(typeof t!="function")throw new Error('"hash" function param is r\
|
|
213
|
+
equired');let r=t,o=n;gt(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:i}=o,{BASE:s,Fp:a,Fn:c}=e,l=r.
|
|
214
|
+
outputLen,p=2*a.BYTES;if(l!==void 0&&(Ge(l,"hash.outputLen"),l!==p))throw new Error(`hash.outputLen must be ${p}, got ${l}`);let u=o.randomBytes===void 0?ys:o.randomBytes,f=o.adjustScalarBytes===void 0?
|
|
215
|
+
_=>_:o.adjustScalarBytes,m=o.domain===void 0?(_,R,$)=>{if(Ot($,"phflag"),R.length||$)throw new Error("Contexts/pre-hash are not supported");return _}:o.domain;function b(_){return c.create(Ke(_))}function v(_){
|
|
216
|
+
let R=D.secretKey;te(_,D.secretKey,"secretKey");let $=te(r(_),2*R,"hashedSecretKey"),j=f($.slice(0,R)),ne=$.slice(R,2*R),ee=b(j);return {head:j,prefix:ne,scalar:ee}}function g(_){let{head:R,prefix:$,scalar:j}=v(
|
|
217
|
+
_),ne=s.multiply(j),ee=ne.toBytes();return {head:R,prefix:$,scalar:j,point:ne,pointBytes:ee}}function y(_){return g(_).pointBytes}function w(_=Uint8Array.of(),...R){let $=$e(...R);return b(r(m($,te(_,void 0,
|
|
218
|
+
"context"),!!i)))}function x(_,R,$={}){_=te(_,void 0,"message"),i&&(_=i(_));let{prefix:j,scalar:ne,pointBytes:ee}=g(R),ke=w($.context,j,_),we=s.multiply(ke).toBytes(),ze=w($.context,we,ee,_),Qe=c.create(
|
|
219
|
+
ke+ze*ne);if(!c.isValid(Qe))throw new Error("sign failed: invalid s");let h=$e(we,c.toBytes(Qe));return te(h,D.signature,"result")}let k={zip215:o.zip215};function I(_,R,$,j=k){let{context:ne}=j,ee=j.
|
|
220
|
+
zip215===void 0?!!k.zip215:j.zip215,ke=D.signature;_=te(_,ke,"signature"),R=te(R,void 0,"message"),$=te($,D.publicKey,"publicKey"),ee!==void 0&&Ot(ee,"zip215"),i&&(R=i(R));let we=ke/2,ze=_.subarray(0,
|
|
221
|
+
we),Qe=Ke(_.subarray(we,ke)),h,T,M;try{h=e.fromBytes($,ee),T=e.fromBytes(ze,ee),M=s.multiplyUnsafe(Qe);}catch{return false}if(!ee&&h.isSmallOrder())return false;let z=w(ne,ze,$,R);return T.add(h.multiplyUnsafe(
|
|
222
|
+
z)).subtract(M).clearCofactor().is0()}let P=a.BYTES,D={secretKey:P,publicKey:P,signature:2*P,seed:P};function L(_){return _=_===void 0?u(D.seed):_,te(_,D.seed,"seed")}function B(_){return Xn(_)&&_.length===
|
|
223
|
+
D.secretKey}function K(_,R){try{return !!e.fromBytes(_,R===void 0?k.zip215:R)}catch{return false}}let Q={getExtendedPublicKey:g,randomSecretKey:L,isValidSecretKey:B,isValidPublicKey:K,toMontgomery(_){let{y:R}=e.
|
|
224
|
+
fromBytes(_),$=D.publicKey,j=$===32;if(!j&&$!==57)throw new Error("only defined for 25519 and 448");let ne=j?a.div(ae+R,ae-R):a.div(R-ae,R+ae);return a.toBytes(ne)},toMontgomerySecret(_){let R=D.secretKey;
|
|
225
|
+
te(_,R);let $=r(_.subarray(0,R));return f($).subarray(0,R)}};return Object.freeze(D),Object.freeze(Q),Object.freeze({keygen:Fs(L,y),getPublicKey:y,sign:x,verify:I,utils:Q,Point:e,lengths:D})}var Wu=BigInt(0),Ye=BigInt(1),Ws=BigInt(2);var Gu=BigInt(5),Ku=BigInt(8),Lt=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),xo={p:Lt,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Ku,
|
|
226
226
|
a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6d\
|
|
227
|
-
c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function
|
|
228
|
-
i*e%i,c=
|
|
229
|
-
return e[0]&=248,e[31]&=127,e[31]|=64,e}var
|
|
230
|
-
s=
|
|
231
|
-
"1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var
|
|
232
|
-
fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),
|
|
233
|
-
|
|
234
|
-
oint expected")}init(t){return new e(t)}static fromBytes(t){
|
|
235
|
-
let a=i(s*s),c=i(
|
|
236
|
-
"invalid ristretto255 encoding 2");return new e(new
|
|
237
|
-
l=s(c*c),{value:
|
|
238
|
-
|
|
239
|
-
|
|
227
|
+
c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Ju(e){let t=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),i=Lt,a=e*e%
|
|
228
|
+
i*e%i,c=Pe(a,Ws,i)*a%i,l=Pe(c,Ye,i)*e%i,p=Pe(l,Gu,i)*l%i,u=Pe(p,t,i)*p%i,f=Pe(u,n,i)*u%i,m=Pe(f,r,i)*f%i,b=Pe(m,o,i)*m%i,v=Pe(b,o,i)*m%i,g=Pe(v,t,i)*p%i;return {pow_p_5_8:Pe(g,Ws,i)*e%i,b2:a}}function Yu(e){
|
|
229
|
+
return e[0]&=248,e[31]&=127,e[31]|=64,e}var yo=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function So(e,t){let n=Lt,r=X(t*t*t,n),o=X(r*r*t,n),i=Ju(e*o).pow_p_5_8,
|
|
230
|
+
s=X(e*r*i,n),a=X(t*s*s,n),c=s,l=X(s*yo,n),p=a===e,u=a===X(-e,n),f=a===X(-e*yo,n);return p&&(s=c),(u||f)&&(s=l),Je(s,n)&&(s=X(-s,n)),{isValid:p||u,value:s}}var it=Vs(xo,{uvRatio:So}),ot=it.Fp,Js=it.Fn;function Zu(e){return qs(it,Jn,Object.assign({adjustScalarBytes:Yu,zip215:true},e))}var Ys=Zu({});var ko=yo;BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");var Qu=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt(
|
|
231
|
+
"1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var Gs=e=>So(Ye,e),nd=BigInt("0x7\
|
|
232
|
+
fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),wo=e=>ot.create(Ke(e)&nd);var st=class e extends sr{static BASE=new e(
|
|
233
|
+
it.BASE);static ZERO=new e(it.ZERO);static Fp=ot;static Fn=Js;constructor(t){super(t);}static fromAffine(t){return new e(it.fromAffine(t))}assertSame(t){if(!(t instanceof e))throw new Error("RistrettoP\
|
|
234
|
+
oint expected")}init(t){return new e(t)}static fromBytes(t){Ie(t,32);let{a:n,d:r}=xo,o=Lt,i=k=>ot.create(k),s=wo(t);if(!xs(ot.toBytes(s),t)||Je(s,o))throw new Error("invalid ristretto255 encoding 1");
|
|
235
|
+
let a=i(s*s),c=i(Ye+n*a),l=i(Ye-n*a),p=i(c*c),u=i(l*l),f=i(n*r*p-u),{isValid:m,value:b}=Gs(i(f*u)),v=i(b*l),g=i(b*v*f),y=i((s+s)*v);Je(y,o)&&(y=i(-y));let w=i(c*g),x=i(y*w);if(!m||Je(x,o)||w===Wu)throw new Error(
|
|
236
|
+
"invalid ristretto255 encoding 2");return new e(new it(y,w,Ye,x))}static fromHex(t){return e.fromBytes(on(t))}toBytes(){let{X:t,Y:n,Z:r,T:o}=this.ep,i=Lt,s=g=>ot.create(g),a=s(s(r+n)*s(r-n)),c=s(t*n),
|
|
237
|
+
l=s(c*c),{value:p}=Gs(s(a*l)),u=s(p*a),f=s(p*c),m=s(u*f*o),b;if(Je(o*m,i)){let g=s(n*ko),y=s(t*ko);t=g,n=y,b=s(u*Qu);}else b=f;Je(t*m,i)&&(n=s(-n));let v=s((r-n)*b);return Je(v,i)&&(v=s(-v)),ot.toBytes(
|
|
238
|
+
v)}equals(t){this.assertSame(t);let{X:n,Y:r}=this.ep,{X:o,Y:i}=t.ep,s=l=>ot.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(st.BASE);Object.freeze(
|
|
239
|
+
st.ZERO);Object.freeze(st.prototype);Object.freeze(st);var vt=`-----BEGIN PUBLIC KEY-----
|
|
240
240
|
MCowBQYDK2VwAyEAWBiklf0kmDIVmM7nMiCxwiEAkwQIiqWGuRiRDJonsFY=
|
|
241
|
-
-----END PUBLIC KEY-----`;function
|
|
242
|
-
length%4?"=".repeat(4-t.length%4):"";return
|
|
243
|
-
function
|
|
244
|
-
function
|
|
245
|
-
oken"};let n=e.split("."),r=n[0],o=n[1],i=n[2],s;try{s=JSON.parse(
|
|
246
|
-
u=t.keys[
|
|
247
|
-
return {ok:false,reason:"invalid public key"}}let l=false;try{l=
|
|
248
|
-
{ok:false,reason:"bad signature"}}function
|
|
249
|
-
n.payloadBytes))}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function
|
|
250
|
-
active":t<=r?"grace":"expired"}var
|
|
251
|
-
if(o.header?.typ!==
|
|
241
|
+
-----END PUBLIC KEY-----`;function Zs(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 Eo(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.
|
|
242
|
+
length%4?"=".repeat(4-t.length%4):"";return Zs(t+n)}function od(e){let t=e.replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=Zs(t);return n.subarray(n.length-32)}var id=new TextEncoder,Xs=new TextDecoder;
|
|
243
|
+
function _o(e){return typeof e=="object"&&e!==null&&"keys"in e}function $t(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 sd=/^[A-Za-z0-9_-]+$/;
|
|
244
|
+
function Qs(e){let t=e.split(".");return t.length===3&&t.every(n=>sd.test(n))}function un(e){return e===""?"empty":Qs(e)?"token":"malformed"}function dn(e,t){if(!Qs(e))return {ok:false,reason:"malformed t\
|
|
245
|
+
oken"};let n=e.split("."),r=n[0],o=n[1],i=n[2],s;try{s=JSON.parse(Xs.decode(Eo(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,
|
|
246
|
+
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=od(a),c.length!==32)return {ok:!1,reason:"invalid public key"}}catch{
|
|
247
|
+
return {ok:false,reason:"invalid public key"}}let l=false;try{l=Ys.verify(Eo(i),id.encode(`${r}.${o}`),c);}catch{return {ok:false,reason:"signature verification error"}}return l?{ok:true,header:s,payloadBytes:Eo(o)}:
|
|
248
|
+
{ok:false,reason:"bad signature"}}function To(e,t){let n=dn(e,t);if(!n.ok||!n.payloadBytes)return {signatureValid:false,...n.reason?{reason:n.reason}:{}};try{return {signatureValid:!0,payload:JSON.parse(Xs.decode(
|
|
249
|
+
n.payloadBytes))}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function ar(e,t,n){if(n?.has(e.jti))return "revoked";let r=e.expires_at+e.grace_days*86400;return t<=e.expires_at?"\
|
|
250
|
+
active":t<=r?"grace":"expired"}var ea="BVSALA-REVOC",ad=300,cd=new TextDecoder;function ta(e,t,n={}){let r=l=>({ok:false,seq:-1,asOf:0,revoked:new Set,reason:l}),o=dn(e,t);if(!o.ok||!o.payloadBytes)return r(o.reason??"bad signature");
|
|
251
|
+
if(o.header?.typ!==ea)return r(`unexpected token type "${String(o.header?.typ??"")}" (want ${ea})`);let i;try{i=JSON.parse(cd.decode(o.payloadBytes));}catch{return r("payload is not valid JSON")}if(typeof i.
|
|
252
252
|
seq!="number"||typeof i.asOf!="number"||!Array.isArray(i.revoked))return r("malformed revocation payload");let s=n.minSeq??0;if(i.seq<s)return r(`stale/rolled-back list (seq ${i.seq} < ${s})`);let a=n.
|
|
253
|
-
nowSeconds??Math.floor(Date.now()/1e3),c=n.maxSkewSeconds??
|
|
253
|
+
nowSeconds??Math.floor(Date.now()/1e3),c=n.maxSkewSeconds??ad;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 Mt=class{_seq=-1;_asOf=0;_lastContactAt=0;set=new Set;get seq(){
|
|
254
254
|
return this._seq}get asOf(){return this._asOf}get lastContactAt(){return this._lastContactAt}markContact(t){t>this._lastContactAt&&(this._lastContactAt=t);}has(t){return this.set.has(t)}snapshot(){return this.
|
|
255
255
|
set}apply(t){if(t.seq<this._seq)return false;let n=this.set.size;for(let i of t.revoked)this.set.add(i);let r=this.set.size>n,o=t.seq>this._seq;return t.seq>this._seq&&(this._seq=t.seq),t.asOf>this._asOf&&
|
|
256
|
-
(this._asOf=t.asOf),r||o}};function
|
|
257
|
-
c?.features??[]),
|
|
258
|
-
86400,
|
|
259
|
-
|
|
256
|
+
(this._asOf=t.asOf),r||o}};function cr(e,t,n){let r=()=>Math.floor((n.now?n.now():Date.now())/1e3),o=n.startedAt??r(),i=$t(e),s=un(i),a=s==="token"?To(i,t):{signatureValid:false,reason:s},c=a.signatureValid?a.payload:void 0,l=new Set(
|
|
257
|
+
c?.features??[]),p=()=>{if(s==="empty")return "none";if(!c)return "invalid";let f=ar(c,r(),n.revocation.snapshot());if(n.maxStalenessSeconds!=null&&(f==="active"||f==="grace")){let m=c.expires_at+c.grace_days*
|
|
258
|
+
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 {isEntitled:f=>u()&&l.has(
|
|
259
|
+
f),isActive:()=>u(),status:p,reason:()=>c?void 0:a.reason,refreshAfter:()=>{if(c)return Math.min(c.expires_at,r()+86400)}}}var Nt={pollIntervalSeconds:900,floorSeconds:300,maxIntervalSeconds:3600,jitterRatio:.1,maxSkewSeconds:300,requestTimeoutMs:3e4},na=3,ld=12;function ud(e){let t=e.random??Math.random,n;if(e.consecutiveFailures>
|
|
260
260
|
0){let o=Math.pow(2,Math.min(e.consecutiveFailures,4));n=Math.min(e.maxIntervalSeconds,e.floorSeconds*o);}else {let o=e.refreshAfter!=null?e.refreshAfter-e.nowSeconds:e.pollIntervalSeconds,i=o<0?e.pollIntervalSeconds:
|
|
261
|
-
o;n=Math.min(e.pollIntervalSeconds,Math.max(e.floorSeconds,i));}let r=1+(t()*2-1)*e.jitterRatio;return Math.max(e.floorSeconds,n*r)}var
|
|
261
|
+
o;n=Math.min(e.pollIntervalSeconds,Math.max(e.floorSeconds,i));}let r=1+(t()*2-1)*e.jitterRatio;return Math.max(e.floorSeconds,n*r)}var dd=10,pn=class{constructor(t){this.opts=t;}opts;timer=null;controller=null;consecutiveFailures=0;stopped=false;started=false;lastEtag=null;consecutive304=0;now(){
|
|
262
262
|
return this.opts.nowSeconds?this.opts.nowSeconds():Math.floor(Date.now()/1e3)}resolveFetch(){return this.opts.fetchImpl?this.opts.fetchImpl:typeof fetch<"u"?fetch:void 0}async pollOnce(){let t=this.resolveFetch();
|
|
263
263
|
if(!t){this.avisar("sin-fetch","[bv-sala] no global fetch available; revocation call-home disabled (offline). License expiry is still enforced from the token."),this.opts.onEvent?.({type:"no-fetch"});
|
|
264
|
-
return}let n=new AbortController;this.controller=n;let r=this.opts.requestTimeoutMs??
|
|
264
|
+
return}let n=new AbortController;this.controller=n;let r=this.opts.requestTimeoutMs??Nt.requestTimeoutMs,o=setTimeout(()=>n.abort(),r);o.unref?.();let i={accept:"application/json"};this.lastEtag&&(i["\
|
|
265
265
|
if-none-match"]=this.lastEtag);try{let s=await t(this.opts.url,{signal:n.signal,headers:i});if(s.status===304){this.consecutiveFailures=0,this.opts.snapshot.markContact(this.now()),this.opts.onEvent?.(
|
|
266
|
-
{type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=
|
|
267
|
-
ions HTTP ${s.status}`);let a=s.headers.get("etag"),c=await s.json();if(!c.list)throw new Error("response missing `list`");this.consecutiveFailures=0;let l=
|
|
268
|
-
opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??
|
|
266
|
+
{type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=dd&&(this.consecutive304=0,this.lastEtag=null);return}if(this.consecutive304=0,!s.ok)throw new Error(`revocat\
|
|
267
|
+
ions HTTP ${s.status}`);let a=s.headers.get("etag"),c=await s.json();if(!c.list)throw new Error("response missing `list`");this.consecutiveFailures=0;let l=ta(c.list,this.opts.publicKeyPem,{minSeq:this.
|
|
268
|
+
opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??Nt.maxSkewSeconds});if(!l.ok){let u=l.reason??"rejected";this.opts.onEvent?.({type:"rejected",reason:u}),this.avisar(`r\
|
|
269
269
|
echazada:${u}`,`[bv-sala] the revocation list does NOT verify (${u}). The last known-good list is kept, so revocations ALREADY known still apply, but new ones are not arriving. Check ${this.opts.url}.`);
|
|
270
|
-
return}a&&(this.lastEtag=a),this.opts.snapshot.markContact(this.now());let
|
|
270
|
+
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:"\
|
|
271
271
|
unchanged",seq:l.seq});}catch(s){this.consecutiveFailures++,this.opts.onEvent?.({type:"error",error:s}),this.avisarFalloDeRed(s);}finally{clearTimeout(o),this.controller=null;}}callado(){return !!(this.opts.
|
|
272
|
-
silenceWarnings??this.opts.silenciarAvisos)}avisar(t,n){this.callado()||
|
|
273
|
-
|
|
272
|
+
silenceWarnings??this.opts.silenciarAvisos)}avisar(t,n){this.callado()||Z(`poller:${this.opts.url}:${t}`,n);}avisarFalloDeRed(t){if(this.callado())return;let n=this.consecutiveFailures;if(n<na||(n-na)%
|
|
273
|
+
ld!==0)return;let r=t instanceof Error?t.message:String(t);console.warn(`[bv-sala] could not reach the revocation server ${n} times in a row (${r}). The license KEEPS working and known revocations sti\
|
|
274
274
|
ll apply, but NEW ones are not arriving. Check egress to ${this.opts.url}.`);}start(){this.started||this.stopped||(this.started=true,this.pollOnce().finally(()=>this.schedule()));}schedule(){if(this.stopped)
|
|
275
|
-
return;let t=
|
|
276
|
-
opts.pollIntervalSeconds??
|
|
275
|
+
return;let t=ud({refreshAfter:this.opts.getRefreshAfter?.(),nowSeconds:this.now(),consecutiveFailures:this.consecutiveFailures,floorSeconds:this.opts.floorSeconds??Nt.floorSeconds,pollIntervalSeconds:this.
|
|
276
|
+
opts.pollIntervalSeconds??Nt.pollIntervalSeconds,maxIntervalSeconds:this.opts.maxIntervalSeconds??Nt.maxIntervalSeconds,jitterRatio:this.opts.jitterRatio??Nt.jitterRatio,...this.opts.random?{random:this.
|
|
277
277
|
opts.random}:{}});this.timer=setTimeout(()=>{this.pollOnce().finally(()=>this.schedule());},t*1e3),this.timer.unref?.();}stop(){this.stopped=true,this.timer&&(clearTimeout(this.timer),this.timer=null),this.
|
|
278
|
-
controller?.abort();}};var
|
|
279
|
-
|
|
278
|
+
controller?.abort();}};var pd="https://developers.openai.com/api/docs/pricing",fd="https://ai.google.dev/gemini-api/docs/pricing",Ao="2026-09-27",O=e=>({...e,fuente:pd,consultado:Ao}),Me=e=>({...e,fuente:fd,consultado:Ao}),
|
|
279
|
+
md="https://platform.claude.com/docs/en/about-claude/pricing",ce=e=>({...e,fuente:md,consultado:Ao});({openai:{flex:{"gpt-5":O({inputPer1k:625e-6,cachedInputPer1k:625e-7,outputPer1k:.005}),"gpt-5-mi\
|
|
280
280
|
ni":O({inputPer1k:125e-6,cachedInputPer1k:125e-7,outputPer1k:.001}),"gpt-5-nano":O({inputPer1k:25e-6,cachedInputPer1k:25e-7,outputPer1k:2e-4}),"gpt-5.2":O({inputPer1k:875e-6,cachedInputPer1k:875e-7,outputPer1k:.007}),
|
|
281
281
|
"gpt-5.4":O({inputPer1k:.00125,cachedInputPer1k:13e-5,outputPer1k:.0075,largo:{estandar:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225},tier:{inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.01125}}}),
|
|
282
282
|
"gpt-5.4-mini":O({inputPer1k:375e-6,cachedInputPer1k:375e-7,outputPer1k:.00225}),"gpt-5.4-nano":O({inputPer1k:1e-4,cachedInputPer1k:1e-5,outputPer1k:625e-6}),"gpt-5.5":O({inputPer1k:.0025,cachedInputPer1k:25e-5,
|
|
@@ -304,472 +304,593 @@ outputPer1k:.00225}),"gpt-5.4-nano":O({inputPer1k:1e-4,cachedInputPer1k:1e-5,out
|
|
|
304
304
|
cachedInputPer1k:625e-7,outputPer1k:.005}),"gpt-5-mini":O({inputPer1k:125e-6,cachedInputPer1k:125e-7,outputPer1k:.001}),"gpt-5-nano":O({inputPer1k:25e-6,cachedInputPer1k:25e-7,outputPer1k:2e-4}),"gpt-\
|
|
305
305
|
4.1":O({inputPer1k:.001,outputPer1k:.004}),"gpt-4.1-mini":O({inputPer1k:2e-4,outputPer1k:8e-4}),"gpt-4.1-nano":O({inputPer1k:5e-5,outputPer1k:2e-4}),"gpt-4o":O({inputPer1k:.00125,outputPer1k:.005}),"g\
|
|
306
306
|
pt-4o-mini":O({inputPer1k:75e-6,outputPer1k:3e-4}),o3:O({inputPer1k:.001,outputPer1k:.004}),"o4-mini":O({inputPer1k:55e-5,outputPer1k:.0022}),"o3-mini":O({inputPer1k:55e-5,outputPer1k:.0022}),"o3-pro":O(
|
|
307
|
-
{inputPer1k:.01,outputPer1k:.04})}},anthropic:{batch:{"claude-fable-5-1":
|
|
308
|
-
cacheWritePer1k:.00625,outputPer1k:.025}),"claude-fable-5":
|
|
309
|
-
cacheWritePer1k:.00625,outputPer1k:.025}),"claude-opus-5-5":
|
|
310
|
-
cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-8":
|
|
311
|
-
cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-6":
|
|
312
|
-
cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4":
|
|
313
|
-
cacheWritePer1k:.00125,outputPer1k:.005}),"claude-sonnet-
|
|
314
|
-
cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-sonnet-4":
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
cachedInputPer1k:
|
|
318
|
-
outputPer1k:.
|
|
319
|
-
inputPer1k:.
|
|
320
|
-
|
|
321
|
-
|
|
307
|
+
{inputPer1k:.01,outputPer1k:.04})}},anthropic:{batch:{"claude-fable-5-1":ce({inputPer1k:.005,cachedInputPer1k:125e-6,cacheWritePer1k:.00625,outputPer1k:.025}),"claude-mythos-5-1":ce({inputPer1k:.005,cachedInputPer1k:125e-6,
|
|
308
|
+
cacheWritePer1k:.00625,outputPer1k:.025}),"claude-fable-5":ce({inputPer1k:.005,cachedInputPer1k:5e-4,cacheWritePer1k:.00625,outputPer1k:.025}),"claude-mythos-5":ce({inputPer1k:.005,cachedInputPer1k:5e-4,
|
|
309
|
+
cacheWritePer1k:.00625,outputPer1k:.025}),"claude-opus-5-5":ce({inputPer1k:.002,cachedInputPer1k:1e-4,cacheWritePer1k:.0025,outputPer1k:.01}),"claude-opus-5":ce({inputPer1k:.0025,cachedInputPer1k:25e-5,
|
|
310
|
+
cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-8":ce({inputPer1k:.0025,cachedInputPer1k:25e-5,cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-7":ce({inputPer1k:.0025,cachedInputPer1k:25e-5,
|
|
311
|
+
cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-6":ce({inputPer1k:.0025,cachedInputPer1k:25e-5,cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-5":ce({inputPer1k:.0025,cachedInputPer1k:25e-5,
|
|
312
|
+
cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4":ce({inputPer1k:.0075,cachedInputPer1k:75e-5,cacheWritePer1k:.009375,outputPer1k:.0375}),"claude-sonnet-5":ce({inputPer1k:.001,cachedInputPer1k:1e-4,
|
|
313
|
+
cacheWritePer1k:.00125,outputPer1k:.005}),"claude-sonnet-5-5":{...ce({inputPer1k:.001,cachedInputPer1k:1e-4,cacheWritePer1k:.00125,outputPer1k:.005})},"claude-sonnet-4-6":ce({inputPer1k:.0015,
|
|
314
|
+
cachedInputPer1k:15e-5,cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-sonnet-4-5":ce({inputPer1k:.0015,cachedInputPer1k:15e-5,cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-sonnet-4":ce({inputPer1k:.0015,
|
|
315
|
+
cachedInputPer1k:15e-5,cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-haiku-4-5":ce({inputPer1k:5e-4,cachedInputPer1k:5e-5,cacheWritePer1k:625e-6,outputPer1k:.0025}),"claude-3-5-haiku":ce({inputPer1k:4e-4,
|
|
316
|
+
cachedInputPer1k:4e-5,cacheWritePer1k:5e-4,outputPer1k:.002})}},google:{flex:{"gemini-3.7-flash":Me({inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3\
|
|
317
|
+
.5-flash":Me({inputPer1k:75e-5,outputPer1k:.0045,cachedInputPer1k:8e-5}),"gemini-3.5-flash-lite":Me({inputPer1k:15e-5,outputPer1k:.00125,cachedInputPer1k:2e-5}),"gemini-3.1-pro-preview":Me({inputPer1k:.001,
|
|
318
|
+
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":Me({inputPer1k:625e-6,
|
|
319
|
+
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\
|
|
320
|
+
sh":Me({inputPer1k:15e-5,outputPer1k:.00125,cachedInputPer1k:3e-5}),"gemini-3.8-flash":Me({inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.6-flash":Me(
|
|
321
|
+
{inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.1-flash-lite":Me({inputPer1k:125e-6,outputPer1k:75e-5,cachedInputPer1k:125e-7}),"gemini-3-flash-pre\
|
|
322
|
+
view":Me({inputPer1k:25e-5,outputPer1k:.0015,cachedInputPer1k:5e-5})}}});var ra={flex:.5,default:1,auto:1,priority:1,fast:1,scale:1,standard:1,batch:.5};Math.min(...Object.values(ra).filter(e=>e<1));function lr(e){if(e==null||e==="")return null;let t=ra[e];return t==null?{servido:e,factor:null,conDescuento:false}:{servido:e,factor:t,conDescuento:t<1}}var kd={"gpt-4.1":false,"gpt-4.1-mini":false,"gpt-4.1-nano":false,"gpt-4o":false,"gpt-4o-mini":false,"gpt-4-turbo":false,"gpt-4":false,"gpt-3.5-turbo":false,"gpt-5":true,"gpt-5-codex":true,"gpt-5-mini":true,"gpt-5-nano":true,"gpt-5.\
|
|
322
323
|
1-codex":true,"gpt-5.1-codex-max":true,"gpt-5.1-codex-mini":true,"gpt-5.1-thinking":true,"gpt-5.2":true,"gpt-5.2-codex":true,"gpt-5.3-codex":true,"gpt-5.4":true,"gpt-5.4-mini":true,"gpt-5.4-nano":true,"gpt-5.5":true,"gpt-5\
|
|
323
324
|
.6-luna":true,"gpt-5.6-sol":true,"gpt-5.6-terra":true,"gpt-6-astra":true,"gpt-6-sol":true,"gpt-6-luna":true,o3:true,"o3-mini":true,"o3-pro":true,"o4-mini":true,"claude-opus-4-5":false,"claude-opus-4-6":false,"claude-opus-4-7":false,
|
|
324
|
-
"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-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
-opus-4-7","claude-opus-4-8"]),
|
|
328
|
-
/^qwq/,/^qwen3/,/^glm-(4\.[5-9]|[5-9])/,/magistral/];function
|
|
329
|
-
return "unclassified-model";let o=
|
|
330
|
-
if(n===null||typeof n!="object")continue;let r=n;if(r.type!=="compaction")continue;t.iteraciones++,t.input+=
|
|
331
|
-
let o=r.cache_creation,i=
|
|
332
|
-
Math.min(s,a);}return t.iteraciones>0?t:null}var
|
|
333
|
-
efusal"||!("category"in n))return false;let r=n.category;return !(r!==null&&typeof r!="string"||!
|
|
334
|
-
able","do not feel comfortable","'d rather not","would rather not","don't think i can","do not think i can"].join("|")+")",
|
|
335
|
-
|
|
336
|
-
|
|
|
337
|
-
|
|
338
|
-
|
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
325
|
+
"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\
|
|
326
|
+
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\
|
|
327
|
+
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},
|
|
328
|
+
wd=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($|[-_.])/,
|
|
329
|
+
/^qwq/,/^qwen3/,/^glm-(4\.[5-9]|[5-9])/,/magistral/];function Co(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=ft(e);if(r===void 0)
|
|
330
|
+
return "unclassified-model";let o=kd[r];if(o===true)return "reasoning-model";if(o!==false)return "unclassified-model";if(wd.has(r))return "temperature-ignored"}var jt=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0;function Ro(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){
|
|
331
|
+
if(n===null||typeof n!="object")continue;let r=n;if(r.type!=="compaction")continue;t.iteraciones++,t.input+=jt(r.input_tokens),t.output+=jt(r.output_tokens),t.cacheRead+=jt(r.cache_read_input_tokens);
|
|
332
|
+
let o=r.cache_creation,i=jt(o?.ephemeral_5m_input_tokens),s=jt(o?.ephemeral_1h_input_tokens),a=typeof r.cache_creation_input_tokens=="number"?jt(r.cache_creation_input_tokens):i+s;t.cacheWrite+=a,t.cacheWrite1h+=
|
|
333
|
+
Math.min(s,a);}return t.iteraciones>0?t:null}var Sd=new Set([null,"cyber","general_harms"]);function ur(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\
|
|
334
|
+
efusal"||!("category"in n))return false;let r=n.category;return !(r!==null&&typeof r!="string"||!Sd.has(r)||e.bloques!==0||e.outputTokens!==0||Array.isArray(e.iterations)&&e.iterations.length>1)}var sa="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\
|
|
335
|
+
able","do not feel comfortable","'d rather not","would rather not","don't think i can","do not think i can"].join("|")+")",Io="(?:much|many times|happy|glad|grateful|excited|thankful|proud|sorry|impor\
|
|
336
|
+
tant|good|great|amazing|nice|relieved|pleased|delighted|impressed|helpful|useful|valuable|lucky|blessed|thrilled|fun|cool|beautiful|wonderful)",Ed=`(?:help(?! but| feeling| thinking| noticing| wonderi\
|
|
337
|
+
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\
|
|
338
|
+
itate|contribute|go along|go into|walk you through|explain how|describe how(?! ${Io})|tell you how(?! ${Io})|teach|instruct|encourage|condone|endorse|promote|role-?play|pretend|do that|do this|do so|w\
|
|
339
|
+
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\
|
|
340
|
+
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\
|
|
341
|
+
s|evaluate|comment on|speak to|give out|dox|tell (?:you )?(?:whether|if))`,_d="i(?:'ll| will| must| need to|'d| would)?(?: have to)? ?(?:respectfully |politely )?decline",Td="(?:(?:that|this|it)(?:'s|\
|
|
342
|
+
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\
|
|
343
|
+
sure (?:that )?it(?:'s| is| would be) appropriate)",Ad="(?:(?: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\
|
|
344
|
+
|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}*",aa="no (?:puedo|voy a|me es posible|est\
|
|
345
|
+
oy en condiciones de|me siento c\xF3mod[oa])",Cd=`(?:ayudar${d}|asistir${d}|proporcionar${d}|facilitar${d}|dar${d}|ofrecer${d}|crear${d}|escribir${d}|generar${d}|compartir${d}|cumplir|responder${d}|co\
|
|
346
|
+
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\
|
|
347
|
+
r${d}|rastrear${d}|adivinar${d}|predecir${d}|diagnosticar${d}|recomendar${d}(?![^.!?]{0,60}suficiente)|recetar${d}|aconsejar${d})`,Rd="(?:lo siento|lo lamento|siento|lamento|disculpa|disculpe|perd\xF3n|p\
|
|
348
|
+
erdona|lamentablemente|desafortunadamente|me temo que|como (?:una )?(?:ia|inteligencia artificial|modelo de lenguaje|asistente)|entiendo)",ca="no (?:puc|et puc|us puc|em sento c\xF2mod[ea]|estic en condi\
|
|
349
|
+
cions de)",Id=`(?: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\
|
|
350
|
+
-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\
|
|
351
|
+
nosticar${d}|recomanar${d}(?![^.!?]{0,60}prou)|receptar${d}|aconsellar${d})`,Pd="(?:ho sento|ho lamento|em sap greu|disculpa|disculpeu|perdona|malauradament|lamentablement|dissortadament|com a (?:ia|i\
|
|
352
|
+
ntel\xB7lig\xE8ncia artificial|model de llenguatge|assistent)|entenc)",la="(?:je ne (?:peux|pourrai|pourrais|vais|souhaite)(?: malheureusement)? pas|je ne suis pas en mesure d[e']|je refuse d[e'])",Dd="\
|
|
353
|
+
(?: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\
|
|
354
|
+
\xE9v\xE9ler|v\xE9rifier|confirmer|localiser|retrouver|deviner|pr\xE9dire|diagnostiquer|prescrire|conseiller|recommander(?![^.!?]{0,60}assez))",Od="(?:d\xE9sol\xE9e?|je suis d\xE9sol\xE9e?|je regrette|malheureuse\
|
|
355
|
+
ment|h\xE9las|je comprends|en tant qu'(?:ia|intelligence artificielle|mod\xE8le de langage|assistant))",ua="(?:ich (?:kann|werde|darf|m\xF6chte)|(?:kann|werde|darf|m\xF6chte) ich)(?: \\p{L}+){0,4}? (?:nicht|\
|
|
356
|
+
keine\\p{L}*)(?: \\p{L}+){0,3}?",Ld="(?:helfen|unterst\xFCtzen|bereitstellen|geben|erstellen|schreiben|generieren|beantworten|liefern|nachkommen|teilen|anbieten|erkl\xE4ren|behilflich sein|bestimmen|festste\
|
|
357
|
+
llen|identifizieren|wissen|zugreifen|preisgeben|offenlegen|verraten|\xFCberpr\xFCfen|best\xE4tigen|ausfindig machen|orten|verfolgen|erraten|vorhersagen|diagnostizieren|verschreiben|raten|sagen, ob)",$d="\
|
|
358
|
+
(?:es tut mir leid|tut mir leid|entschuldigung|entschuldige|leider|bedauerlicherweise|ich verstehe|als (?:eine )?(?:ki|k\xFCnstliche intelligenz|sprachmodell|assistent))",da="non (?:posso|sono in grad\
|
|
359
|
+
o di|riesco a|mi sento a mio agio (?:a|nel))",Md=`(?:aiutar${d}|assister${d}|fornir${d}|crear${d}|scriver${d}|generar${d}|condivider${d}|risponder${d}|dar${d}|offrir${d}|soddisfare|partecipare|farlo|f\
|
|
360
|
+
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\
|
|
361
|
+
car${d}|prescriver${d}|consigliar${d}(?![^.!?]{0,60}abbastanza))`,Nd="(?:mi dispiace|spiacente|purtroppo|sfortunatamente|capisco|come (?:un'?\\s?)?(?:ia|intelligenza artificiale|modello linguistico|ass\
|
|
362
|
+
istente))",pa="n\xE3o (?:posso|consigo|vou|sou capaz de|estou em condi\xE7\xF5es de|me sinto confort\xE1vel (?:em|a))",jd=`(?:ajudar${d}|auxiliar${d}|assistir${d}|fornecer${d}|criar${d}|escrever${d}|g\
|
|
363
|
+
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|\
|
|
364
|
+
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))`,Bd="(\
|
|
365
|
+
?:desculpe|desculpa|sinto muito|lamento|infelizmente|entendo|compreendo|como (?:uma? )?(?:ia|intelig\xEAncia artificial|modelo de linguagem|assistente))",Bt="(?:[\\s,]+[\\p{L}'\u2019-]+){0,4}?[\\s,]+",
|
|
366
|
+
fa=[`${sa}${Bt}${Ed}`,_d,Td,`${aa}${Bt}${Cd}`,"lamento no poder",`${ca}${Bt}${Id}`,`${la}${Bt}${Dd}`,`${ua} ${Ld}`,`${da}${Bt}${Md}`,`${pa}${Bt}${jd}`].join("|"),Ud=[Ad,Rd,Pd,Od,$d,Nd,Bd].join("|"),zd=new RegExp(
|
|
367
|
+
`^(?:${fa})(?![\\p{L}])`,"u"),Fd=new RegExp(`^(?:${Ud})(?![\\p{L}])`,"u"),oa=new RegExp(`(?:^|[^\\p{L}'])(?:${fa})(?![\\p{L}])`,"u"),Vd="(?:really|even|honestly|quite|possibly|truly|personally|actuall\
|
|
368
|
+
y|simply|just|ever|always)",ma="i(?:'m| am)? ?(?:can't|cannot|can not|won't|will not|not going to|not able to|unable to)",qd=["wait","believe","imagine (?:how|what|why|anything|anyone|anybody|life|liv\
|
|
369
|
+
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)[^.\
|
|
370
|
+
!?]{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) ${Io}`,
|
|
371
|
+
"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 \
|
|
372
|
+
(?: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 (?\
|
|
373
|
+
: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))",
|
|
374
|
+
"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","remember (?:a time|the last time|wh\
|
|
375
|
+
en i)","stop (?:thinking|smiling|laughing|listening|reading|talking about)"],Hd="(?:be (?:100% |completely |entirely |absolutely |totally |fully |one hundred percent )?(?:sure|certain)|say (?:for (?:s\
|
|
376
|
+
ure|certain)|with (?:certainty|confidence)|definitively|exactly|precisely|for a fact)|know (?:for (?:sure|certain)|exactly|precisely)|guarantee|promise|speak for|vouch for|recall|remember|run|test|exe\
|
|
377
|
+
cute|see (?:your|the) (?:screen|code|file|image|output|logs?))[^.!?]{0,160}?(?:,|\\s)(?:but|however)(?![\\p{L}])",Po=`(?:${Vd} ){0,2}(?:(?:${qd.join("|")})(?![\\p{L}])|${Hd})`,ha="no (?:(?:te|le|les|o\
|
|
378
|
+
s|lo|la|me|se) )?(?:puedo|voy a)",Wd=["esperar",`creer${d}`,`imaginar${d}`,"dejar de",`evitar${d}`,`agradecer${d}`,`negar${d}`,`mentir${d}`,`quejar${d}`,"estar m\xE1s",`(?:encontrar|ver|detectar|ident\
|
|
379
|
+
ificar|notar)${d} (?:ning\xFAn|ninguna|ningun|nada|ni un|motivo para no|raz\xF3n para no)`,`recomendar${d}[^.!?]{0,60}(?:suficiente|bastante)`,`(?:enfatizar|recalcar|subrayar|insistir|exagerar|pondera\
|
|
380
|
+
r)${d}`,`(?:decir|expresar)${d} (?:lo|cu\xE1nto|cuanto|c\xF3mo de|como de)`,`resistir${d}`,"m\xE1s que","sino","pedir m\xE1s"],Gd=`(?:estar (?:100 ?% |completamente |totalmente |del todo )?segur[oa]|a\
|
|
381
|
+
segurar${d}|garantizar${d}|prometer${d}|(?:decir|saber|afirmar)${d} con (?:certeza|seguridad|exactitud)|ejecutar${d}|probar${d}|recordar${d}|ver (?:tu|la|el) (?:pantalla|c\xF3digo|archivo))[^.!?]{0,160}?\
|
|
382
|
+
(?:,|\\s)(?:pero|aunque|sin embargo)(?![\\p{L}])`,Do=`(?:(?:${Wd.join("|")})(?![\\p{L}])|${Gd})`,ga="no (?:(?:et|us|el|la|ho|em|li|els|les) )?(?:puc|penso|podr\xE9)",Kd=[`esperar${d}`,`creure${d}`,`im\
|
|
383
|
+
aginar${d}`,"deixar de",`evitar${d}`,`agrair${d}`,`negar${d}`,`mentir${d}`,`queixar${d}`,"estar m\xE9s",`(?:trobar|veure|detectar|identificar)${d} (?:cap|res|ni un|ni una)`,`recomanar${d}[^.!?]{0,60}p\
|
|
384
|
+
rou`,`(?:emfatitzar|remarcar|subratllar|insistir|exagerar)${d}`,`dir${d} (?:com de|quant|prou)`,`resistir${d}`,"m\xE9s que","sin\xF3","fer altra cosa que"],Jd=`(?:estar (?:100 ?% |completament |del to\
|
|
385
|
+
t )?segura?|assegurar${d}|garantir${d}|prometre${d}|(?:dir|saber|afirmar)${d} amb (?:certesa|seguretat)|executar${d}|provar${d}|recordar${d})[^.!?]{0,160}?(?:,|\\s)(?:per\xF2|pero|tot i que)(?![\\p{L}])`,
|
|
386
|
+
Oo=`(?:(?:${Kd.join("|")})(?![\\p{L}])|${Jd})`,ba="je ne (?:peux|pourrai|pourrais|vais)(?: malheureusement)? pas",Yd="(?:vous |te |t'|me |m'|le |la |les |l'|lui |leur |y |en |se |s')",Zd=["attendre","\
|
|
387
|
+
croire","imaginer","emp\xEAcher","remercier","(?:trop |assez )?(?:insister|souligner|exag\xE9rer)","mentir","nier","plaindre","\xEAtre plus","(?:trouver|voir|d\xE9tecter|identifier|rep\xE9rer) (?:aucun|aucu\
|
|
388
|
+
ne|rien|de (?:probl\xE8me|raison|souci))","dire (?:\xE0 quel point|combien|assez)","recommander[^.!?]{0,60}assez","r\xE9sister","faire autrement que"],Xd="(?:\xEAtre (?:(?:tout \xE0 fait|absolument|enti\xE8rem\
|
|
389
|
+
ent|100 ?%) )?(?:s\xFBre?|certaine?)|garantir|promettre|affirmer|dire avec certitude|ex\xE9cuter|tester|souvenir|rappeler|voir (?:votre|ton|ta|le|la) (?:\xE9cran|code|fichier))[^.!?]{0,160}?(?:,|\\s)(?:mais|cep\
|
|
390
|
+
endant|toutefois)(?![\\p{L}])",Lo=`${Yd}*(?:(?:${Zd.join("|")})(?![\\p{L}])|${Xd})`,va="non (?:(?:ti|vi|la|lo|le|gli|ne|mi|ci) )?(?:posso|riesco a|sono in grado di|ho intenzione di)",Qd=[`aspettar${d}`,
|
|
391
|
+
`creder${d}`,`immaginar${d}`,"fare a meno",`ringraziar${d}`,"che","non",`negar${d}`,`mentir${d}`,`lamentar${d}`,"(?:essere|esser) pi\xF9",`(?:trovare|vedere|notare|individuare|rilevare) (?:nessun${d}|\
|
|
392
|
+
niente|alcun${d}|un solo)`,`consigliar${d}[^.!?]{0,60}abbastanza`,`(?:sottolinear|enfatizzar|insister|esagerar)${d}`,`dir${d} (?:quanto|abbastanza)`,`resister${d}`],ep=`(?:(?:esserne|essere) (?:del tu\
|
|
393
|
+
tto |completamente |al 100 ?% )?(?:sicur[oa]|cert[oa])|garantir${d}|prometter${d}|(?:dir|affermar)${d} con certezza|eseguir${d}|testar${d}|ricordar${d})[^.!?]{0,160}?(?:,|\\s)(?:ma|per\xF2|tuttavia)(?![\\p\
|
|
394
|
+
{L}])`,$o=`(?:(?:${Qd.join("|")})(?![\\p{L}])|${ep})`,ya="n\xE3o (?:(?:te|lhe|lhes|vos|o|a|me) )?(?:posso|consigo|vou|sou capaz de)",tp=["esperar","acreditar",`imaginar${d}`,"deixar de",`evitar${d}`,`\
|
|
395
|
+
agradecer${d}`,`negar${d}`,`mentir${d}`,`(?:me )?(?:queixar|reclamar)${d}`,"concordar mais","estar mais","sen\xE3o","(?:fazer )?mais (?:do )?que",`(?:encontrar|ver|identificar|detetar|detectar|notar) \
|
|
396
|
+
(?:nenhum${d}|nada|um \xFAnico|uma \xFAnica)`,`recomendar${d}[^.!?]{0,60}(?:o )?suficiente`,`(?:enfatizar|sublinhar|ressaltar|insistir|exagerar)${d}`,`dizer${d} (?:o quanto|quanto|como|o suficiente)`,
|
|
397
|
+
`resistir${d}`],np=`(?:ter (?:a )?certeza|estar (?:100 ?% |completamente |totalmente )?(?:segur[oa]|cert[oa])|garantir${d}|prometer${d}|(?:dizer|afirmar|saber)${d} com (?:certeza|seguran\xE7a)|executar${d}\
|
|
398
|
+
|testar${d}|lembrar${d})[^.!?]{0,160}?(?:,|\\s)(?:mas|por\xE9m|contudo)(?![\\p{L}])`,Mo=`(?:(?:${tp.join("|")})(?![\\p{L}])|${np})`,ka="(?:ich (?:kann|werde|darf)|kann ich|werde ich)",rp=["(?:kaum|nic\
|
|
399
|
+
ht) erwarten","glauben","vorstellen","genug (?:danken|betonen|empfehlen|loben|sagen|hervorheben)","oft genug","\\p{L}*l\xFCgen","leugnen","bestreiten","beschweren","beklagen","(?:mehr|besser) zustimme\
|
|
400
|
+
n","widerstehen","keine?n? (?:fehler|probleme?|grund|haken|m\xE4ngel|bugs?|nachteile?|einw\xE4nde?)","sagen, wie (?:sehr|froh|dankbar|gl\xFCcklich)"],op="(?:(?:mit )?sicherheit|genau|garantieren|versp\
|
|
401
|
+
rechen|100 ?%|ausf\xFChren|testen|erinnern)[^.!?]{0,160}?(?:,|\\s)(?:aber|jedoch|allerdings)(?![\\p{L}])",wa=`[^.!?]*?(?<![\\p{L}])(?:(?:${rp.join("|")})(?![\\p{L}])|${op})`,xa="(?:no[,.!]? |non[,.!]?\
|
|
402
|
+
|n\xE3o[,.!]? |nein[,.!]? )?",ip=new RegExp("^"+xa+"(?:"+[`${ma}\\s(?!${Po})\\p{L}`,`${ha}\\s(?!${Do})\\p{L}`,`${ga}\\s(?!${Oo})\\p{L}`,`${ba}\\s?(?!${Lo})\\p{L}`,`${va}\\s(?!${$o})\\p{L}`,`${ya}\\s(?\
|
|
403
|
+
!${Mo})\\p{L}`,`${ka}(?!${wa})(?:\\s[\\p{L}\\p{N}'-]+){0,6}?\\s(?:nicht|keine?\\p{L}*)(?![\\p{L}])(?!\\s(?:nur|mehr als|anders|umhin))`].join("|")+")","u"),sp=new RegExp("^"+xa+"(?:"+[`${ma}\\s(?=${Po}\
|
|
404
|
+
)`,`${ha}\\s(?=${Do})`,`${ga}\\s(?=${Oo})`,`${ba}\\s?(?=${Lo})`,`${va}\\s(?=${$o})`,`${ya}\\s(?=${Mo})`,`${ka}(?=${wa})`].join("|")+")","u"),ap="(?:(?:i'm |i am )?(?:really |so |very |truly |terribly \
|
|
405
|
+
)?sorry|i apologi[sz]e|my apologies|apologies|unfortunately|regrettably|i'm afraid|i am afraid)",cp="(?:lo siento(?: mucho)?|lo lamento|disculpa|disculpe|perd\xF3n|perdona|lamentablemente|desafortunadame\
|
|
406
|
+
nte|me temo que)",lp="(?:ho sento(?: molt)?|em sap greu|disculpa|disculpeu|perdona|malauradament|lamentablement|dissortadament)",up="(?:(?:je suis )?(?:vraiment )?d\xE9sol\xE9e?|je regrette|pardon|malheureu\
|
|
407
|
+
sement|h\xE9las)",dp="(?:es tut mir (?:sehr |wirklich )?leid|tut mir leid|entschuldigung|leider|bedauerlicherweise)",pp="(?:mi dispiace(?: molto)?|spiacente|scusa|scusami|mi scuso|purtroppo|sfortunata\
|
|
408
|
+
mente)",fp="(?:desculpe|desculpa|sinto muito|lamento|pe\xE7o desculpa|infelizmente)",mp=Po,hp=Do,gp=Oo,bp=Lo,vp=$o,yp=Mo,yt=e=>`[,.!:;]?\\s(?:(?:${e})\\s)?`,kp="\\s\\p{L}",wp=[`${ap}${yt("but|however,\
|
|
409
|
+
?")}(?:as an ai(?: language model| assistant)?,?\\s)?${sa}\\s(?!${mp})\\p{L}`,`${cp}${yt("pero")}${aa}(?:\\s(?:te|le|les|os))?\\s(?!${hp})\\p{L}`,`${lp}${yt("per\xF2|pero")}${ca}\\s(?!${gp})\\p{L}`,`${up}${yt(
|
|
410
|
+
"mais")}${la}(?:\\s(?:vous|te))?\\s?(?!${bp})\\p{L}`,`${dp}${yt("aber")}${ua}${kp}`,`${pp}${yt("ma")}${da}\\s(?!${vp})\\p{L}`,`${fp}${yt("mas")}${pa}\\s(?!${yp})\\p{L}`].join("|"),xp="(?:(?:i'm |i am \
|
|
411
|
+
)?(?:really |so |very |truly |terribly )?sorry|i apologi[sz]e|my apologies|apologies)",Sp="(?:(?:is|are|was|would be|could be|may be|might be|it's|that's|this is|it is|that is)(?: considered| generall\
|
|
412
|
+
y| strictly| both)? (?:illegal|unlawful|unethical|against|a violation|a serious violation|a breach|an invasion|prohibited|not (?:something|appropriate|possible|allowed|permitted|legal|ethical|safe|adv\
|
|
413
|
+
isable|ok|okay))|violates?|goes against|go against|infringes?)",Ep="(?:(?:es|son|ser\xEDa|ser\xEDan|est\xE1|estar\xEDa|resulta)(?: considerado)? (?:ilegal|poco \xE9tic[oa]|inapropiad[oa]|contrari[oa] a|una violaci\xF3n\
|
|
414
|
+
|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 en contra)",_p="(?:(?:\xE9s|s\xF3n|seria|serien)\
|
|
415
|
+
(?:il\xB7legal|ilegal|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)",
|
|
416
|
+
Tp="(?:(?: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 \
|
|
417
|
+
\xE0 l'encontre)",Ap="(?:(?: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))\
|
|
418
|
+
|verst\xF6\xDFt|verletzt)",Cp="(?:(?:\xE8|sono|sarebbe|sarebbero) (?:illegale|illecito|non etico|contrario a|una violazione|vietato|inappropriato)|non (?:\xE8|sarebbe) (?:appropriato|possibile|etico|legale|\
|
|
419
|
+
consentito)|viola|va contro)",Rp="(?:(?:\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\
|
|
420
|
+
)|viola|vai contra)",kt="(?:[\\p{L}\\p{N}'\u2019-]+[\\s,]+){0,14}?",Ip=[`${xp},?\\sbut\\s${kt}${Sp}`,`(?:lo siento(?: mucho)?|lo lamento|disculpa|disculpe|perd\xF3n|perdona),?\\spero\\s${kt}${Ep}`,`(?\
|
|
421
|
+
:ho sento(?: molt)?|em sap greu|disculpa|perdona),?\\s(?:per\xF2|pero)\\s${kt}${_p}`,`(?:(?:je suis )?(?:vraiment )?d\xE9sol\xE9e?|pardon),?\\smais\\s${kt}${Tp}`,`(?:es tut mir (?:sehr |wirklich )?lei\
|
|
422
|
+
d|tut mir leid|entschuldigung),?\\saber\\s${kt}${Ap}`,`(?:mi dispiace(?: molto)?|spiacente|scusa|scusami|mi scuso),?\\sma\\s${kt}${Cp}`,`(?:desculpe|desculpa|sinto muito|lamento|pe\xE7o desculpa),?\\smas\\\
|
|
423
|
+
s${kt}${Rp}`].join("|"),Pp=new RegExp(`^(?:${wp}|(?:${Ip})(?![\\p{L}]))`,"u"),Dp="(?:(?:i'm |i am )?(?:really |so |very |truly |deeply |terribly )?sorry (?:to hear|to read|that you|you(?:'re| are)|you\
|
|
424
|
+
feel|for what 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 )?(?\
|
|
425
|
+
:concerned|worried) (?: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)",Op="(?:mental health (?:professional|provider|expe\
|
|
426
|
+
rt|specialist|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)|(\
|
|
427
|
+
?:suicide|crisis) (?:prevention|hotline|helpline|lifeline)|hotline|helpline|lifeline|samaritans|emergency services|emergency number|call (?:911|988|999|112|000|emergency)|988|someone you trust|people \
|
|
428
|
+
you trust|(?:a )?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\
|
|
429
|
+
|loved ones)|professional (?:help|support)|seek (?:immediate|urgent|professional) (?:help|support))",Lp="(?:(?:lo )?(?:siento|lamento) (?:mucho |much\xEDsimo )?(?:que (?:te sientas|est\xE9s|estes|te encuent\
|
|
430
|
+
res|pases|est\xE9s pasando)|escuchar|o\xEDr|leer|saber)|parece que (?:est\xE1s|estas) (?:pasando|atravesando)|me preocupa)",$p="(?:profesional(?:es)? de (?:la )?salud mental|psic\xF3log[oa]|psiquiatra|te\
|
|
431
|
+
rapeuta|l\xEDnea (?: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\
|
|
432
|
+
de (?:tu )?confianza|ayuda profesional)",Mp="(?:em sap (?:molt )?greu (?:que (?:et sentis|estiguis|passis)|sentir|llegir|saber)|ho sento (?:molt|molt\xEDssim)|sembla que (?:est\xE0s|passes) (?:passant|trav\
|
|
433
|
+
essant)?)",Np="(?: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|(\
|
|
434
|
+
?:truca|trucar|truquis) al (?:112|024)|alg\xFA de (?:la teva )?confian\xE7a|(?:una )?persona de confian\xE7a|ajuda professional)",jp="(?:(?:je suis )?(?:vraiment |sinc\xE8rement |tellement |profond\xE9ment \
|
|
435
|
+
)?d\xE9sol\xE9e? (?: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))",Bp="(?:professionnel(?:le)?s?\
|
|
436
|
+
de (?:la )?sant\xE9 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|\
|
|
437
|
+
911)|3114|personne de confiance|quelqu'un en qui (?:tu as|vous avez) confiance|aide professionnelle|sos amiti\xE9)",Up="(?:es tut mir (?:sehr |wirklich |so )?leid,? (?:dass|zu h\xF6ren|das zu h\xF6ren|zu le\
|
|
438
|
+
sen|das zu lesen)|das klingt (?:sehr |wirklich )?(?:schwer|belastend|schmerzhaft)|ich mache mir sorgen)",zp="(?:psychotherapeut\\p{L}*|psycholog\\p{L}*|psychiater\\p{L}*|therapeut\\p{L}*|fachkraft f\xFCr psy\
|
|
439
|
+
chische|telefonseelsorge|krisendienst|krisentelefon|notruf\\p{L}*|notdienst|rettungsdienst|vertrauensperson|jemandem,? dem (?:du|sie) vertrau\\p{L}*|professionelle hilfe|professionelle unterst\xFCtzung)",
|
|
440
|
+
Fp="(?:mi dispiace (?:molto |davvero |tanto )?(?:sentire|leggere|sapere|che tu|che ti|che stia)|sembra che (?:tu stia|stai) (?:passando|attraversando))",Vp="(?:professionista della salute mentale|psic\
|
|
441
|
+
olog[oa]|psichiatra|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)|perso\
|
|
442
|
+
na di fiducia|qualcuno di cui ti fidi|aiuto professionale)",qp="(?: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 \
|
|
443
|
+
voc\xEA (?:est\xE1|esteja) (?:passando|a passar))",Hp="(?:profissional de sa\xFAde mental|profissionais de sa\xFAde mental|psic\xF3log[oa]|psiquiatra|terapeuta|cvv|linha de (?:apoio|crise|ajuda)|servi\xE7os de em\
|
|
444
|
+
erg\xEAncia|(?:ligue|liga|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)",Wp=new RegExp(`^(\
|
|
445
|
+
?:${[Dp,Lp,Mp,jp,Up,Fp,qp].join("|")})(?![\\p{L}])`,"u"),Gp=new RegExp(`(?<![\\p{L}\\p{N}])(?:${[Op,$p,Np,Bp,zp,Vp,Hp].join("|")})(?![\\p{L}\\p{N}])`,"u");function Kp(e){return e.slice(0,4*300).replace(
|
|
446
|
+
/[‘’ʼ`´]/g,"'").toLowerCase().replace(/\s+/g," ").trim().replace(/^[\s*#>_"'«“¿¡(\[-]+/u,"").trim()}function Jp(e){let t=[...e.matchAll(/[.!?。](?:\s|$)/g)],n=t.length>=2?t[1].index+1:e.length;
|
|
447
|
+
return e.slice(0,Math.min(n,240))}function ia(e){let t=/[.!?。:;](?:\s|$)/.exec(e);return t?e.slice(t.index+1).trim():""}function No(e){if(typeof e!="string"||e==="")return null;let t=Kp(e);if(t==="")
|
|
448
|
+
return null;let n=Jp(t),r=sp.test(n);if(!r&&(zd.test(n)||ip.test(n)))return "opens-with-refusal";let o=r?ia(n):n;return Fd.test(n)&&oa.test(o)||Pp.test(n)?"apology-then-refusal":t.length<=300&&oa.test(
|
|
449
|
+
r?ia(t):t)?"short-refusal":Wp.test(n)&&Gp.test(n)?"redirection":null}var Yp=/^content_filter(?:\s*:\s*(.*?))?\s*$/;function jo(e){return typeof e=="string"&&Yp.test(e)}function Bo(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function Uo(e){if(!e)return 0;let{prompt_tokens:t,completion_tokens:n,total_tokens:r}=e;return !Bo(t)||!Bo(n)||!Bo(r)?0:Math.max(0,r-
|
|
450
|
+
t-n)}var V="\\p{L}*",Zp=[`suicid${V}`,`self[- ]?harm${V}`,`self[- ]?injur${V}`,`self[- ]?mutilat${V}`,"(?:kill|killing|hang|hanging|drown|drowning|cut|cutting|hurt|hurting|harm|harming|shoot|poison|stab|st\
|
|
451
|
+
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\
|
|
452
|
+
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",
|
|
453
|
+
"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\
|
|
454
|
+
ms|skin|leg|legs|wrist|wrists)",`overdos${V}`,"autolesi\\p{L}*","(?:matarme|ahorcarme|ahogarme|envenenarme|lastimarme|hacerme da\xF1o|quitarme la vida)","cortarme (?:las venas|los brazos|las mu\xF1ecas)",
|
|
455
|
+
"acabar con mi vida","quiero morir(?:me)?","no quiero (?:seguir viviendo|vivir m\xE1s)","sobredosis",`su\xEFcid${V}`,"(?:matar-me|penjar-me|ofegar-me|fer-me mal|treure'm la vida)","acabar amb la meva \
|
|
456
|
+
vida","vull morir","no vull (?:seguir vivint|viure m\xE9s)","sobredosi","automutil\\p{L}*","(?:me tuer|me pendre|me noyer|me faire du mal|me mutiler|m'ouvrir les veines|me couper les veines)","mettre \
|
|
457
|
+
fin \xE0 (?:mes jours|ma vie)","en finir avec la vie","(?:je veux|j'ai envie de) mourir","surdose",`suizid${V}`,`selbstmord${V}`,"freitod",`selbstverletz${V}`,"mich (?:umbringen|t\xF6ten|erh\xE4ngen|ertr\xE4nk\
|
|
458
|
+
en|ritzen|verletzen)","mir das leben nehmen","mein leben beenden","(?:ich will|ich m\xF6chte) (?:nicht mehr leben|sterben)","\xFCberdosis",`autolesion${V}`,"(?:uccidermi|ammazzarmi|impiccarmi|annegarm\
|
|
459
|
+
i|tagliarmi le vene|farmi del male|togliermi la vita)","(?:voglio|vorrei) morire","non voglio pi\xF9 vivere",`suic\xEDd${V}`,`automutila${V}`,"autoles\xE3o|autoles\xF5es","(?:me matar|matar-me|me enfo\
|
|
460
|
+
rcar|enforcar-me|me afogar|me machucar)","tirar a (?:minha )?(?:pr\xF3pria )?vida","acabar com a minha vida","quero morrer","n\xE3o quero mais viver",`zelfmoord${V}`,`zelfbeschadig${V}`,"mezelf (?:dod\
|
|
461
|
+
en|ophangen|verdrinken|snijden|iets aandoen|van kant maken)","ik wil dood","overdosis",`samob\xF3j${V}`,`samookalecz${V}`,"(?:zabi\u0107 si\u0119|powiesi\u0107 si\u0119|utopi\u0107 si\u0119|poci\u0105\u0107 si\u0119|skrzywdzi\u0107 si\u0119|odebra\u0107 sobie \
|
|
462
|
+
\u017Cycie)","chc\u0119 umrze\u0107","nie chc\u0119 ju\u017C \u017Cy\u0107",`przedawkowa${V}`,`intihar${V}`,"kendime zarar",`kendimi \xF6ld\xFCr${V}`,"\xF6lmek istiyorum","art\u0131k ya\u015Famak istemiyorum",
|
|
463
|
+
"a\u015F\u0131r\u0131 doz","bunuh diri",`menyakiti diri${V}`,"(?: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"],
|
|
464
|
+
Xp=["panic attacks?","(?:mental|nervous) breakdown","psychotic (?:episode|break)","hearing voices","mental health crisis","feel(?:ing)? (?:so |really |very |completely )?(?:hopeless|worthless|suicidal\
|
|
465
|
+
|empty inside)","i(?:'m| am) (?:so |really |very )?(?:depressed|hopeless|worthless)","eating disorder",`anorexi${V}`,`bulimi${V}`,"ataques? de (?:p\xE1nico|panico|ansiedad)","crisis de (?:p\xE1nico|panic\
|
|
466
|
+
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\
|
|
467
|
+
esperada)","crises? (?:de panique|d'angoisse)","attaques? de panique","je suis (?:tr\xE8s )?d\xE9prim\xE9e?",`panikattacke${V}`,"ich bin (?:so |sehr )?(?:depressiv|verzweifelt)","attacc(?:o|hi) di pan\
|
|
468
|
+
ico","(?:sono|mi sento) (?:molto )?(?:depress[oa]|disperat[oa])","(?:ataques?|crises?) de (?:p\xE2nico|ansiedade)","(?:estou|me sinto) (?:muito )?(?:deprimid[oa]|desesperad[oa])",`paniekaanval${V}`,"a\
|
|
469
|
+
tak(?:i)? paniki",`panik atak${V}`,"serangan panik","c\u01A1n ho\u1EA3ng lo\u1EA1n"],Qp=["heart attack","having a stroke","(?:can't|cannot|can not) breathe","(?:not|stopped) breathing","chest pains?",
|
|
470
|
+
`anaphyla${V}`,"(?: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\
|
|
471
|
+
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\
|
|
472
|
+
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\
|
|
473
|
+
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",
|
|
474
|
+
"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"],
|
|
475
|
+
ef=/(?<![\p{L}\p{N}])(?:suicide (?:squad|doors?|burn|king|linux|slide|bid)|shoot myself in the foot)(?![\p{L}\p{N}])/gu,zo=e=>new RegExp(`(?<![\\p{L}\\p{N}])(?:${e.join("|")})(?![\\p{L}\\p{N}])`,"u"),
|
|
476
|
+
tf=zo(Zp),nf=zo(Xp),rf=zo(Qp);function of(e){return e.normalize("NFC").replace(/[‘’ʼ`´]/g,"'").toLowerCase().replace(/\s+/g," ").replace(ef," ")}function sf(e){if(typeof e!="string"||e==="")return null;
|
|
477
|
+
let t=of(e);return tf.test(t)?"self-harm":nf.test(t)?"mental-health-crisis":rf.test(t)?"medical-emergency":null}function Fo(e){for(let t of e){let n=sf(t);if(n!==null)return n}return null}var dr=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(
|
|
360
478
|
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,
|
|
361
479
|
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(
|
|
362
480
|
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.
|
|
363
481
|
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),
|
|
364
482
|
i=t.slice(r+1),i.charCodeAt(0)===32&&(i=i.slice(1))),o){case "data":this.datos+=i+`
|
|
365
483
|
`;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":
|
|
366
|
-
this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};var
|
|
484
|
+
this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};var Ne=class{resto="";uso=null;elisionObservada=null;paradaFinal=null;detallesDeParada=void 0;texto=new mn;eventos={};observar(t){this.resto+=typeof t=="string"?t:t.toString("utf8");let n;for(;(n=this.
|
|
367
485
|
resto.indexOf(`
|
|
368
486
|
|
|
369
487
|
`))>=0;){let r=this.resto.slice(0,n);this.resto=this.resto.slice(n+2);let o=/^event: (.+)$/m.exec(r)?.[1];if(o&&(this.eventos[o]=(this.eventos[o]??0)+1),o==="content_block_delta"&&!this.texto.lleno()){
|
|
370
488
|
let s=/^data: (.+)$/m.exec(r)?.[1];try{let a=s?JSON.parse(s):null;a?.delta?.type==="text_delta"&&this.texto.sumar(a.delta.text);}catch{}continue}if(o!=="message_start"&&o!=="message_delta")continue;let i=/^data: (.+)$/m.
|
|
371
489
|
exec(r)?.[1];if(i)try{let s=JSON.parse(i);o==="message_delta"&&typeof s.delta?.stop_reason=="string"&&(this.paradaFinal=s.delta.stop_reason),o==="message_delta"&&s.delta&&"stop_details"in s.delta&&(this.
|
|
372
|
-
detallesDeParada=s.delta.stop_details);let a=
|
|
490
|
+
detallesDeParada=s.delta.stop_details);let a=_a(s.context_management);a&&(this.elisionObservada=a);let c=s.usage??s.message?.usage;if(c){let l=c.cache_creation||this.uso?.cache_creation?{...this.uso?.
|
|
373
491
|
cache_creation,...c.cache_creation}:void 0;this.uso={...this.uso,...c,...l?{cache_creation:l}:{}};}}catch{}}}usage(){return this.uso}usageFinal(){return (this.eventos.message_delta??0)>0?this.uso:null}elision(){
|
|
374
|
-
return this.elisionObservada}negativa(){return this.paradaFinal==="refusal"}textoInicial(){return this.texto.valor()}negativaNoCobrada(){let t=this.usageFinal();return t!==null&&
|
|
375
|
-
stopDetails:this.detallesDeParada,bloques:this.eventos.content_block_start??0,outputTokens:t.output_tokens,iterations:t.iterations})}};function
|
|
376
|
-
0))return 0;let n=e.cachedInputPer1k;return typeof n!="number"||!Number.isFinite(n)||n<=0?0:t.tokensLimpiadosToolUses/1e3*n}function
|
|
492
|
+
return this.elisionObservada}negativa(){return this.paradaFinal==="refusal"}textoInicial(){return this.texto.valor()}negativaNoCobrada(){let t=this.usageFinal();return t!==null&&ur({stopReason:this.paradaFinal,
|
|
493
|
+
stopDetails:this.detallesDeParada,bloques:this.eventos.content_block_start??0,outputTokens:t.output_tokens,iterations:t.iterations})}};function af(e,t){if(!t||t.atribuible!==true||!(t.tokensLimpiadosToolUses>
|
|
494
|
+
0))return 0;let n=e.cachedInputPer1k;return typeof n!="number"||!Number.isFinite(n)||n<=0?0:t.tokensLimpiadosToolUses/1e3*n}function _a(e){if(e===null||typeof e!="object")return null;let t=e.applied_edits;
|
|
377
495
|
if(!Array.isArray(t)||t.length===0)return null;let n=0,r=0;for(let o of t){let i=o.cleared_input_tokens;typeof i=="number"&&Number.isFinite(i)&&i>0&&(n+=i,o.type==="clear_tool_uses_20250919"&&(r+=i));}
|
|
378
|
-
return {borrados:t.length,tokensLimpiados:n,tokensLimpiadosToolUses:r}}function
|
|
496
|
+
return {borrados:t.length,tokensLimpiados:n,tokensLimpiadosToolUses:r}}function Ta(e){try{let t=JSON.parse(typeof e=="string"?e:e.toString("utf8"));return _a(t.context_management)}catch{return null}}var Ut=class{resto="";uso=null;final=null;negada=false;texto=new mn;eventos={};observar(t){
|
|
379
497
|
this.resto+=typeof t=="string"?t:t.toString("utf8");let n;for(;(n=this.resto.indexOf(`
|
|
380
498
|
|
|
381
499
|
`))>=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.
|
|
382
|
-
parse(i),a=o??s.type;
|
|
383
|
-
response?.usage;if(!l)continue;c==="completed"?this.uso=
|
|
384
|
-
uso}estadoFinal(){return this.final}negativa(){return this.negada}textoInicial(){return this.texto.valor()}};function
|
|
385
|
-
null||typeof t!="object")return false;let n=t;return
|
|
386
|
-
type==="refusal"}function
|
|
387
|
-
ed","response.incomplete":"incomplete","response.failed":"failed"};function
|
|
388
|
-
max(0,e.input_tokens_details?.cache_write_tokens??0),t-n);return {input_tokens:t-n-r,output_tokens:Math.max(0,e.output_tokens??0),cache_read_input_tokens:n,cache_creation_input_tokens:r}}function
|
|
389
|
-
return !e||typeof e.prompt_tokens!="number"||typeof e.completion_tokens!="number"?null:
|
|
500
|
+
parse(i),a=o??s.type;cf(a,s)&&(this.negada=!0),a==="response.output_text.delta"&&this.texto.sumar(s.delta);let c=a!==void 0&&Object.hasOwn(Sa,a)?Sa[a]:void 0;if(c===void 0)continue;this.final=c;let l=s.
|
|
501
|
+
response?.usage;if(!l)continue;c==="completed"?this.uso=pr(l):typeof l.input_tokens=="number"&&typeof l.output_tokens=="number"&&(this.uso=pr(l));}catch{}}}usage(){return this.uso}usageFinal(){return this.
|
|
502
|
+
uso}estadoFinal(){return this.final}negativa(){return this.negada}textoInicial(){return this.texto.valor()}};function cf(e,t){if(e==="response.refusal.delta"||e==="response.refusal.done")return true;if(t===
|
|
503
|
+
null||typeof t!="object")return false;let n=t;return Aa(n.part)||qo([n.item])?true:n.response!==null&&typeof n.response=="object"&&qo(n.response.output)}function Aa(e){return e!==null&&typeof e=="object"&&e.
|
|
504
|
+
type==="refusal"}function qo(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(Aa)})}var Sa={"response.completed":"complet\
|
|
505
|
+
ed","response.incomplete":"incomplete","response.failed":"failed"};function pr(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.
|
|
506
|
+
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 Ca(e){
|
|
507
|
+
return !e||typeof e.prompt_tokens!="number"||typeof e.completion_tokens!="number"?null:pr({input_tokens:e.prompt_tokens,output_tokens:e.completion_tokens+Uo(e),input_tokens_details:{...e.prompt_tokens_details?.
|
|
390
508
|
cached_tokens!==void 0?{cached_tokens:e.prompt_tokens_details.cached_tokens}:{},...e.prompt_tokens_details?.cache_write_tokens!==void 0?{cache_write_tokens:e.prompt_tokens_details.cache_write_tokens}:
|
|
391
|
-
{}}})}var
|
|
509
|
+
{}}})}var fn=class{parser=new dr;ultimoUso=null;vioUsoFinal=false;vioDone=false;filtrada=false;texto=new mn;eventos={};observar(t){for(let n of this.parser.push(t))this.mensaje(n);}textoInicial(){for(let t of this.
|
|
392
510
|
parser.end())this.mensaje(t);return this.texto.valor()}negativa(){return this.filtrada}usage(){return this.vioUsoFinal||this.vioDone?this.ultimoUso:null}usageFinal(){for(let t of this.parser.end())this.
|
|
393
511
|
mensaje(t);return this.usage()}mensaje(t){if(t.data==="[DONE]"){this.vioDone=true,this.eventos.done=(this.eventos.done??0)+1;return}let n;try{n=JSON.parse(t.data);}catch{return}if(n===null||typeof n!="ob\
|
|
394
|
-
ject")return;if(this.eventos.chunk=(this.eventos.chunk??0)+1,
|
|
395
|
-
usage===null||typeof n.usage!="object")return;let r=
|
|
396
|
-
e.inputPer1k;return t.entrada/1e3*e.inputPer1k+t.cacheLeida/1e3*r+(t.cacheEscrita-t.cacheEscrita1h)/1e3*e.inputPer1k*
|
|
397
|
-
let r=n??Date.now(),o=
|
|
398
|
-
cache_creation,
|
|
399
|
-
0),u),
|
|
400
|
-
try{let n=e,r={maxOutputLength:
|
|
401
|
-
e,r);break;case "zstd":{let o=
|
|
402
|
-
return typeof
|
|
403
|
-
t);if(!
|
|
404
|
-
typeof r.input_tokens=="number"&&typeof r.output_tokens=="number"?
|
|
405
|
-
"utf8"));return n!==null&&typeof n=="object"&&n.status==="failed"}catch{return false}}function
|
|
406
|
-
isArray(e)&&e.some(n=>{if(n===null||typeof n!="object")return false;let r=n;return r.finish_reason
|
|
407
|
-
|
|
408
|
-
"
|
|
409
|
-
return this.t}};function
|
|
512
|
+
ject")return;if(this.eventos.chunk=(this.eventos.chunk??0)+1,La(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.
|
|
513
|
+
usage===null||typeof n.usage!="object")return;let r=Ca(n.usage);r!==null&&(this.ultimoUso=r,Array.isArray(n.choices)&&n.choices.length===0&&(this.vioUsoFinal=true));}};function Ra(e,t,n){let r=e.cachedInputPer1k??
|
|
514
|
+
e.inputPer1k;return t.entrada/1e3*e.inputPer1k+t.cacheLeida/1e3*r+(t.cacheEscrita-t.cacheEscrita1h)/1e3*e.inputPer1k*Te(n)+t.cacheEscrita1h/1e3*e.inputPer1k*2+t.salida/1e3*e.outputPer1k}function Ia(e,t,n){
|
|
515
|
+
let r=n??Date.now(),o=Re(e,r);if(!o)return null;let i=Ro(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.
|
|
516
|
+
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??
|
|
517
|
+
0),u),m={entrada:s,salida:a,cacheLeida:c,cacheEscrita:u,cacheEscrita1h:f};return {costeUsd:Ra(o,m,e),precio:o,tokens:m,instante:r}}function Pa(e,t){let r=zt(e,t)?.model;return typeof r=="string"?r:""}function zt(e,t){
|
|
518
|
+
try{let n=e,r={maxOutputLength:lf};switch((t??"").trim().toLowerCase()){case "gzip":case "x-gzip":n=Ze.gunzipSync(e,r);break;case "deflate":n=Ze.inflateSync(e,r);break;case "br":n=Ze.brotliDecompressSync(
|
|
519
|
+
e,r);break;case "zstd":{let o=Ze.zstdDecompressSync;if(typeof o!="function")return null;n=o(e,r);break}default:break}return JSON.parse(n.toString("utf8"))}catch{return null}}var lf=5*1024*1024;function Da(){
|
|
520
|
+
return typeof Ze.zstdDecompressSync=="function"}function uf(e){try{return JSON.parse(typeof e=="string"?e:e.toString("utf8")).usage??null}catch{return null}}function fr(e,t){if(e==="/v1/messages")return uf(
|
|
521
|
+
t);if(!wt(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 Ca(n.usage);let r=n.usage;return r&&
|
|
522
|
+
typeof r.input_tokens=="number"&&typeof r.output_tokens=="number"?pr(r):null}catch{return null}}function Oa(e,t){if(!e.endsWith("/responses"))return false;try{let n=JSON.parse(typeof t=="string"?t:t.toString(
|
|
523
|
+
"utf8"));return n!==null&&typeof n=="object"&&n.status==="failed"}catch{return false}}function La(e){let t=n=>{let r=n!==null&&typeof n=="object"?n.refusal:void 0;return typeof r=="string"&&r!==""};return Array.
|
|
524
|
+
isArray(e)&&e.some(n=>{if(n===null||typeof n!="object")return false;let r=n;return jo(r.finish_reason)||t(r.message)||t(r.delta)})}function $a(e,t){if(e!=="/v1/messages"&&!e.endsWith("/chat/completions")&&
|
|
525
|
+
!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\
|
|
526
|
+
ompletions")?La(n.choices):qo(n.output)}catch{return false}}var Vo=1200,mn=class{t="";sumar(t){typeof t=="string"&&this.t.length<Vo&&(this.t=(this.t+t).slice(0,Vo));}lleno(){return this.t.length>=Vo}valor(){
|
|
527
|
+
return this.t}};function Ma(e,t){try{let n=JSON.parse(typeof t=="string"?t:t.toString("utf8"));if(n===null||typeof n!="object")return "";let r=(o,i,s)=>Array.isArray(o)?o.filter(a=>a!==null&&typeof a==
|
|
410
528
|
"object"&&a.type===i).map(a=>a[s]).filter(a=>typeof a=="string").join(""):"";if(e==="/v1/messages")return r(n.content,"text","text");if(e.endsWith("/chat/completions")){let i=(Array.isArray(n.choices)?
|
|
411
529
|
n.choices[0]:void 0)?.message?.content;return typeof i=="string"?i:r(i,"text","text")}return e.endsWith("/responses")&&Array.isArray(n.output)?n.output.map(o=>o!==null&&typeof o=="object"?r(o.content,
|
|
412
|
-
"output_text","text"):"").join(""):""}catch{return ""}}function
|
|
413
|
-
null||typeof n!="object"?!1:
|
|
414
|
-
return false}}function
|
|
530
|
+
"output_text","text"):"").join(""):""}catch{return ""}}function Na(e){return No(e)!==null}function Ho(e,t){if(e!=="/v1/messages")return false;try{let n=JSON.parse(typeof t=="string"?t:t.toString("utf8"));return n===
|
|
531
|
+
null||typeof n!="object"?!1:ur({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{
|
|
532
|
+
return false}}function ja(e,t){let n=typeof t=="string"?t:t.toString("utf8"),r=i=>{if(i===null||typeof i!="object")return;let s=i,a=l=>l!==null&&typeof l=="object"?l.service_tier:void 0,c;return e==="/v1/\
|
|
415
533
|
messages"?(c=a(s.usage),c===void 0&&s.message!==null&&typeof s.message=="object"&&(c=a(s.message.usage))):e.endsWith("/chat/completions")?c=s.service_tier:e.endsWith("/responses")&&(c=s.service_tier,c===
|
|
416
534
|
void 0&&s.response!==null&&typeof s.response=="object"&&(c=s.response.service_tier)),typeof c=="string"&&c!==""?c:void 0};try{return r(JSON.parse(n))}catch{}let o;for(let i of n.split(`
|
|
417
|
-
`)){if(!i.startsWith("data:"))continue;let s=i.slice(5).trim();if(!(s===""||s==="[DONE]"))try{o=r(JSON.parse(s))??o;}catch{}}return o}function
|
|
418
|
-
ions")||e.endsWith("/responses")}var
|
|
535
|
+
`)){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 wt(e){return e==="/v1/messages"||e.endsWith("/chat/complet\
|
|
536
|
+
ions")||e.endsWith("/responses")}var df=Buffer.from('"stream_options":{"include_usage":true},',"utf8");function Ba(e,t){let n=(t??"").trim().toLowerCase();if(n!==""&&n!=="identity")return {cuerpo:null,
|
|
419
537
|
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:"\
|
|
420
538
|
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,
|
|
421
539
|
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,
|
|
422
|
-
motivo:"ilegible"}:{cuerpo:Buffer.concat([e.subarray(0,i+1),
|
|
423
|
-
true?null:r.stream_options?.include_usage===true}function
|
|
424
|
-
return r==="chatgpt.com"||r.endsWith(".chatgpt.com")}catch{return false}}function
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
return
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
540
|
+
motivo:"ilegible"}:{cuerpo:Buffer.concat([e.subarray(0,i+1),df,e.subarray(i+1)]),motivo:"inyectado"}}function Ua(e,t){let n=zt(e,t);if(n===null||typeof n!="object")return null;let r=n;return r.stream!==
|
|
541
|
+
true?null:r.stream_options?.include_usage===true}function Wo(e,t,n){if((t??"").split(",").some(r=>r.trim().startsWith("oauth-"))||e.startsWith("/backend-api/"))return true;try{let r=new URL(n).hostname.toLowerCase();
|
|
542
|
+
return r==="chatgpt.com"||r.endsWith(".chatgpt.com")}catch{return false}}function za(e,t,n,r,o,i,s,a,c,l){return Ha(e,t,n,false,r,o,i,s,a,c,l===true)}function pf(e){if(e===null||typeof e!="object"||Array.isArray(
|
|
543
|
+
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"):
|
|
544
|
+
[],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 ff(e){
|
|
545
|
+
return Fo(pf(e))}var mf=new Set(["auto","default","priority","standard_only"]);function hf(e){if(e==null)return 1;if(typeof e!="string")return null;if(mf.has(e))return 1;let t=lr(e);return t!==null&&t.
|
|
546
|
+
conDescuento&&t.factor!==null?t.factor:null}function gf(e){if(e===void 0)return 1;if(e==="scale")return null;let t=lr(e);return t!==null&&t.factor!==null?t.factor:null}function Fa(e,t,n,r,o){if(!n||!n.
|
|
547
|
+
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)
|
|
548
|
+
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:"\
|
|
549
|
+
primary-text-refusal"};if(ff(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=hf(
|
|
550
|
+
i.service_tier),a=gf(o.tierServido);if(s===null||a===null)return {ok:false,reason:"service-tier"};let c=Math.min(s,a),l=Pt(e,t.instante),p=l?.cachedInputPer1k;if(!l||typeof p!="number"||!Number.isFinite(p)||
|
|
551
|
+
!(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.
|
|
552
|
+
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&&Co(e)===void 0;return {ok:true,credit:{requestId:n.
|
|
553
|
+
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 Go(e){
|
|
554
|
+
return e.tierFactor*(e.creditedInputTokens/1e3*e.cachedInputPer1k+e.creditedOutputTokens/1e3*e.outputPer1k)}function Va(e,t,n,r,o,i){let s=o?Go(o):0;return i===true||!o||!(s>0)||!Number.isFinite(s)?Ha(e,
|
|
555
|
+
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,
|
|
556
|
+
eliminatedInput:0,compressedInput:0,baselineOutput:o.creditedOutputTokens,actualOutput:0,providerCachedInput:0},cache:{result:"singleflight",reference:o},cost:{baselineEstimate:s,actual:0,netSavings:1,
|
|
557
|
+
basis:"reference"}}}function qa(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,
|
|
558
|
+
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 bf(e,t){
|
|
559
|
+
let n=Re(e.solicitado,t.instante);return n===void 0?0:Math.max(0,Ra(n,t.tokens,e.solicitado)-t.costeUsd)}function Ha(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.
|
|
560
|
+
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):
|
|
561
|
+
0,g=m&&a?bf(a,n):0,y=n.costeUsd+v+g,w=v+g,x=r||l||p?0:af(n.precio,i);return {requestId:e,model:t,...o&&(o.sessionId||o.agentId)?{attribution:o}:{},calls:r?{avoidedLlm:1,actualLlm:0}:{avoidedLlm:0,actualLlm:1},
|
|
562
|
+
tokens:{baselineInput:u,actualInput:r?0:u,eliminatedInput:r?0:i?.tokensLimpiados??0,compressedInput:0,baselineOutput:n.tokens.salida,actualOutput:r?0:n.tokens.salida,providerCachedInput:r?0:n.tokens.cacheLeida},
|
|
563
|
+
cache:{result:r?"singleflight":"miss"},cost:r?{baselineEstimate:n.costeUsd,actual:0,netSavings:p?0:1,basis:"estimated"}:{baselineEstimate:y,actual:n.costeUsd,netSavings:y>0?Math.max(-100,Math.min(1,w/
|
|
564
|
+
y)):0,basis:"measured",...x>0?{eliminatedInputFloorCost:x}:{}}}}var vf=1024,hn=120,yf=8,kf=256*1024,wf=/error|exception|traceback|warn|fatal|fail|panic|assert|denied|refused|timeout|\bat\s+\S+:\d+/i,Ka=/^\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)/;
|
|
565
|
+
function xf(e){return Buffer.byteLength(typeof e=="string"?e:JSON.stringify(e??""))}function Sf(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t&&typeof t=="object"&&typeof t.text=="string"?
|
|
445
566
|
t.text:"").join(`
|
|
446
|
-
`):""}var
|
|
447
|
-
`),n=Math.max(1,t.length),r=0,o=0,i=0;for(let s of t){let a=
|
|
448
|
-
test(a)||/\b(INFO|DEBUG|TRACE|WARN|ERROR)\b/.test(a))&&(i+=1);}return r/n>.25?"diff":i/n>.3?"log":o/n>.08?"codigo":"otro"}function
|
|
567
|
+
`):""}var Ef=/^\s*\d+[\t→]/;function Ja(e){return e.replace(Ef,"")}function _f(e){if(!e)return "otro";let t=e.split(`
|
|
568
|
+
`),n=Math.max(1,t.length),r=0,o=0,i=0;for(let s of t){let a=Ja(s);(/^[+-](?![+-])/.test(a)||a.startsWith("@@")||a.startsWith("diff --git"))&&(r+=1),Ka.test(a)&&(o+=1),(/^\s*(\d{4}-\d{2}-\d{2}|\[\d|\d{2}:\d{2}:\d{2})/.
|
|
569
|
+
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 Tf(e,t){if(t==="diff"||t==="otro")return Buffer.byteLength(e);let n=e.
|
|
449
570
|
split(`
|
|
450
|
-
`),r=new Set;for(let i=0;i<n.length;i++){let s=
|
|
451
|
-
n[i])+1;return Math.min(o,Buffer.byteLength(e))}var
|
|
452
|
-
n:${JSON.stringify(e??"")}`;let t=e;return t.type==="text"&&typeof t.text=="string"&&Object.keys(t).every(n=>n==="type"||n==="text"||n==="cache_control")?`text:${t.text}`:`json:${JSON.stringify(t,
|
|
453
|
-
function
|
|
454
|
-
t.ttl==="1h"?"1h":"5m"}function
|
|
455
|
-
let a=o;s.esError=a.is_error===true;let c=
|
|
571
|
+
`),r=new Set;for(let i=0;i<n.length;i++){let s=Ja(n[i]);(t==="log"?wf.test(s):Ka.test(s))&&(r.add(i),t==="log"&&(i>0&&r.add(i-1),i<n.length-1&&r.add(i+1)));}let o=hn;for(let i of r)o+=Buffer.byteLength(
|
|
572
|
+
n[i])+1;return Math.min(o,Buffer.byteLength(e))}var Af=(e,t)=>e==="cache_control"?void 0:t;function Cf(e){if(typeof e=="string")return `text:${e}`;if(!e||typeof e!="object"||Array.isArray(e))return `jso\
|
|
573
|
+
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,Af)}`}
|
|
574
|
+
function Rf(e){return createHash("sha256").update(Cf(e)).digest("hex").slice(0,16)}function If(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.cache_control;return !t||typeof t!="object"?null:
|
|
575
|
+
t.ttl==="1h"?"1h":"5m"}function Ya(e){let t=[],n=(r,o)=>{let i=xf(o),s={clave:Rf(o),tipo:r,marca:If(o),bytes:i,bytesV1:i,clase:"otro",esError:false};if(r.endsWith(":tool_result")&&o&&typeof o=="object"){
|
|
576
|
+
let a=o;s.esError=a.is_error===true;let c=Sf(a.content);s.clase=_f(c);let l=i-Buffer.byteLength(c);s.bytesV1=Math.min(i,Math.max(0,l)+Tf(c,s.clase));}t.push(s);};if(Array.isArray(e.tools))for(let r of e.tools)
|
|
456
577
|
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!=
|
|
457
578
|
"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}\
|
|
458
|
-
:${s?.type??"?"}`,s);}return t}function
|
|
459
|
-
return n}function
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
var
|
|
463
|
-
r:null}escribir(t,n,r){this.entradas.delete(t),this.entradas.set(t,{expira:n+
|
|
464
|
-
t),this.entradas.set(t,{expira:n+
|
|
465
|
-
value;if(n===void 0)break;this.entradas.delete(n);}}};function
|
|
466
|
-
"|").update(t[o]).digest("hex").slice(0,32),n[o]=r;return n}function
|
|
467
|
-
t");s&&i===r||(n+=1),r=s?i:"",t[o]=n;}return t}function
|
|
468
|
-
5m";hayPrevio=false;atPrevio=0;acumulado=
|
|
469
|
-
previo=i,this.previoUltimoBp=-1,this.previoTtl="5m",this.hayPrevio=true,this.atPrevio=t.at,n;let s=i.map((
|
|
470
|
-
|
|
471
|
-
n.tokensEntrada+=
|
|
472
|
-
n.tokensEntrada,this.acumulado.entradaUsd+=n.entradaUsd,this.acumulado.totalUsd+=n.totalUsd,n}let
|
|
473
|
-
|
|
474
|
-
[]:this.previo.slice(
|
|
475
|
-
P/1e3*o.inputPer1k;continue}for(;
|
|
476
|
-
|
|
579
|
+
:${s?.type??"?"}`,s);}return t}function Pf(){return {nacimiento:new Map,turno:0,elididosV2m:new Set}}function Df(e,t){let n=e.turno++;for(let r of t)e.nacimiento.has(r.clave)||e.nacimiento.set(r.clave,n);
|
|
580
|
+
return n}function Za(e,t,n,r,o=kf){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>=vf&&f!==i;return t.map((u,f)=>{if(!s(u,
|
|
581
|
+
f))return {clave:u.clave,bytes:u.bytes};let m=r-(n.nacimiento.get(u.clave)??r);return m>=2&&m*u.bytes/1024>=yf?{clave:`${u.clave}:e`,bytes:hn}:{clave:u.clave,bytes:u.bytes}});}function Of(e,t){let n=Re(e,t);return n?{inputPer1k:n.inputPer1k,lecturaPer1k:n.cachedInputPer1k??n.inputPer1k,escrituraPer1k:n.inputPer1k*
|
|
582
|
+
Te(e),escritura1hPer1k:n.inputPer1k*$n(e)}:null}function Wa(){return {lecturaUsd:0,escrituraUsd:0,entradaUsd:0,totalUsd:0,tokensLeidos:0,tokensEscritos:0,tokensEntrada:0,tokensInvalidados:0,invalidacionUsd:0}}
|
|
583
|
+
var Jo={"1h":36e5,"5m":3e5},Lf=20,$f=6e3,Mf=2e4,Ft=class{constructor(t=Mf){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?
|
|
584
|
+
r:null}escribir(t,n,r){this.entradas.delete(t),this.entradas.set(t,{expira:n+Jo[r],ttl:r}),this.entradas.size>this.tope&&this.podar(n);}refrescar(t,n){let r=this.entradas.get(t);r&&(this.entradas.delete(
|
|
585
|
+
t),this.entradas.set(t,{expira:n+Jo[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().
|
|
586
|
+
value;if(n===void 0)break;this.entradas.delete(n);}}};function Nf(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(
|
|
587
|
+
"|").update(t[o]).digest("hex").slice(0,32),n[o]=r;return n}function jf(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\
|
|
588
|
+
t");s&&i===r||(n+=1),r=s?i:"",t[o]=n;}return t}function Ga(e,t){return e.endsWith(":image")?Math.min(t,$f):t}var gn=class{constructor(t,n){this.transformar=t;this.cache=n??new Ft;}transformar;estado=Pf();cache;previo=[];previoUltimoBp=-1;previoTtl="\
|
|
589
|
+
5m";hayPrevio=false;atPrevio=0;acumulado=Wa();paso(t){let n=Wa(),r=Df(this.estado,t.bloques),o=Of(t.model,t.at),i=this.transformar(t.bloques,this.estado,r);if(!o||t.entradaReal<=0||i.length===0)return this.
|
|
590
|
+
previo=i,this.previoUltimoBp=-1,this.previoTtl="5m",this.hayPrevio=true,this.atPrevio=t.at,n;let s=i.map((k,I)=>t.bloques[I]?.tipo??""),a=i.map((k,I)=>t.bloques[I]?.marca??null),c=t.bloques.reduce((k,I)=>k+
|
|
591
|
+
Ga(I.tipo,I.bytes),0),l=c>0?t.entradaReal/c:0,p=i.map((k,I)=>Ga(s[I],k.bytes)*l),u=Nf(t.model,i.map(k=>k.clave)),f=jf(s),m=a.map((k,I)=>k?I:-1).filter(k=>k>=0);if(m.length===0){for(let k=0;k<i.length;k++)
|
|
592
|
+
n.tokensEntrada+=p[k],n.entradaUsd+=p[k]/1e3*o.inputPer1k;return n.totalUsd=n.entradaUsd,this.previo=i,this.previoUltimoBp=-1,this.previoTtl="5m",this.hayPrevio=true,this.atPrevio=t.at,this.acumulado.tokensEntrada+=
|
|
593
|
+
n.tokensEntrada,this.acumulado.entradaUsd+=n.entradaUsd,this.acumulado.totalUsd+=n.totalUsd,n}let b=-1;for(let k of m){let I=f[k]-(Lf-1);for(let P=k;P>=0&&f[P]>=I;P--)if(this.cache.viva(u[P],t.at)){P>
|
|
594
|
+
b&&(b=P);break}}for(let k=0;k<=b;k++)this.cache.refrescar(u[k],t.at);let v=m[m.length-1];for(let k of m)k>b&&this.cache.escribir(u[k],t.at,a[k]);let g=0,w=this.hayPrevio&&t.at-this.atPrevio>Jo[this.previoTtl]?
|
|
595
|
+
[]:this.previo.slice(b+1,this.previoUltimoBp+1),x=0;for(let k=0;k<i.length;k++){let I=i[k],P=p[k];if(k<=b){n.tokensLeidos+=P,n.lecturaUsd+=P/1e3*o.lecturaPer1k;continue}if(k>v){n.tokensEntrada+=P,n.entradaUsd+=
|
|
596
|
+
P/1e3*o.inputPer1k;continue}for(;m[g]<k;)g+=1;let D=a[m[g]]==="1h"?o.escritura1hPer1k:o.escrituraPer1k;n.tokensEscritos+=P,n.escrituraUsd+=P/1e3*D;let L=x;for(;L<w.length&&w[L].clave!==I.clave;)L+=1;L<
|
|
597
|
+
w.length&&(w[L].bytes===I.bytes&&(n.tokensInvalidados+=P,n.invalidacionUsd+=P/1e3*(D-o.lecturaPer1k)),x=L+1);}return this.previo=i,this.previoUltimoBp=v,this.previoTtl=a[v]??"5m",this.hayPrevio=true,this.
|
|
477
598
|
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.
|
|
478
599
|
totalUsd+=n.totalUsd,this.acumulado.tokensLeidos+=n.tokensLeidos,this.acumulado.tokensEscritos+=n.tokensEscritos,this.acumulado.tokensEntrada+=n.tokensEntrada,this.acumulado.tokensInvalidados+=n.tokensInvalidados,
|
|
479
|
-
this.acumulado.invalidacionUsd+=n.invalidacionUsd,n}};function
|
|
480
|
-
0),r=(t.uso.input_tokens??0)+(t.uso.cache_read_input_tokens??0)+n;if(r<=0)return null;let o={bloques:
|
|
600
|
+
this.acumulado.invalidacionUsd+=n.invalidacionUsd,n}};function Xa(e){return e.map(t=>({clave:t.clave,bytes:t.bytes}))}var Uf=64,mr=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??
|
|
601
|
+
0),r=(t.uso.input_tokens??0)+(t.uso.cache_read_input_tokens??0)+n;if(r<=0)return null;let o={bloques:Ya(t.cuerpo),at:t.at,model:t.model,entradaReal:r,escritura1h:(t.uso.cache_creation?.ephemeral_1h_input_tokens??
|
|
481
602
|
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){
|
|
482
603
|
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(
|
|
483
|
-
"hex").slice(0,16)}\xB7${t.model}`}cachesDe(t){let n=this.cachesPorModelo.get(t);return n||(n={base:new
|
|
484
|
-
let o=this.cachesDe(n);if(r={base:new
|
|
485
|
-
c.ultimoUso<s&&(s=c.ultimoUso,i=a);i!==null&&this.cadenas.delete(i);}}return r.ultimoUso=Date.now(),r}};var
|
|
486
|
-
oard/install and relaunch",
|
|
604
|
+
"hex").slice(0,16)}\xB7${t.model}`}cachesDe(t){let n=this.cachesPorModelo.get(t);return n||(n={base:new Ft,v0:new Ft},this.cachesPorModelo.set(t,n)),n}cadenaPara(t,n){let r=this.cadenas.get(t);if(!r){
|
|
605
|
+
let o=this.cachesDe(n);if(r={base:new gn(i=>Xa(i),o.base),v0:new gn((i,s,a)=>Za("v0",i,s,a),o.v0),ultimoUso:0},this.cadenas.set(t,r),this.cadenas.size>Uf){let i=null,s=1/0;for(let[a,c]of this.cadenas)
|
|
606
|
+
c.ultimoUso<s&&(s=c.ultimoUso,i=a);i!==null&&this.cadenas.delete(i);}}return r.ultimoUso=Date.now(),r}};var zf="[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\
|
|
607
|
+
oard/install and relaunch",hr=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,
|
|
487
608
|
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(),
|
|
488
609
|
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===
|
|
489
610
|
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(
|
|
490
|
-
"entitlements HTTP 401",
|
|
611
|
+
"entitlements HTTP 401",zf);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(
|
|
491
612
|
"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==
|
|
492
613
|
"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,
|
|
493
614
|
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\
|
|
494
|
-
ing`));}};var
|
|
495
|
-
VL";function
|
|
496
|
-
isFinite(e);function
|
|
497
|
-
t.grace_days>=0&&Array.isArray(t.features)&&t.features.every(n=>typeof n=="string")}function
|
|
498
|
-
ty"};if(r==="malformed")return {ok:!1,shape:"malformed",reason:"malformed"};let o=
|
|
499
|
-
if(i!==
|
|
500
|
-
payload is not valid JSON"}}return
|
|
501
|
-
cation error: ${
|
|
502
|
-
slice(0,t)}...`:n}function
|
|
503
|
-
r.code:r&&typeof r.message=="string"?r.message:void 0;return o?`${n} (${o})`:n}async function
|
|
615
|
+
ing`));}};var Zo="https://savings.bivelio.com",ge="https://savings.bivelio.com/dashboard/account",xt="https://savings.bivelio.com/dashboard/install",Ff=1e4,Vf=3e3,ec=6e4,qf=36e5,Hf=7*86400,Wf=3e4,Gf=86400,Kf="B\
|
|
616
|
+
VL";function Xo(e){return vt}function Jf(e){return _o(e)?Object.keys(e.keys??{}).length===0:e.trim()===""}var Yo=e=>typeof e=="string"&&e.trim()!=="",gr=e=>typeof e=="number"&&Number.
|
|
617
|
+
isFinite(e);function Yf(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let t=e;return Yo(t.jti)&&Yo(t.org_id)&&Yo(t.plan)&&gr(t.seats)&&gr(t.issued_at)&&gr(t.expires_at)&&gr(t.grace_days)&&
|
|
618
|
+
t.grace_days>=0&&Array.isArray(t.features)&&t.features.every(n=>typeof n=="string")}function vr(e,t){try{let n=$t(typeof e=="string"?e:""),r=un(n);if(r==="empty")return {ok:!1,shape:"empty",reason:"emp\
|
|
619
|
+
ty"};if(r==="malformed")return {ok:!1,shape:"malformed",reason:"malformed"};let o=dn(n,t);if(!o.ok||!o.payloadBytes)return {ok:!1,shape:"token",reason:vn(o.reason??"bad signature")};let i=o.header?.typ;
|
|
620
|
+
if(i!==Kf)return {ok:!1,shape:"token",reason:`not a license token (typ ${vn(String(i??"none"))})`};let s;try{s=JSON.parse(new TextDecoder().decode(o.payloadBytes));}catch{return {ok:!1,shape:"token",reason:"\
|
|
621
|
+
payload is not valid JSON"}}return Yf(s)?{ok:!0,license:{token:n,payload:s}}:{ok:!1,shape:"token",reason:"license payload has the wrong field types"}}catch(n){return {ok:false,shape:"token",reason:`verifi\
|
|
622
|
+
cation error: ${vn(String(n))}`}}}function Vt(e,t,n){return ar(e,Math.floor(t/1e3),n)}var qt=e=>e==="active"||e==="grace";function vn(e,t=200){let n=e.replace(/[^\x20-\x7E]/g,"?");return n.length>t?`${n.
|
|
623
|
+
slice(0,t)}...`:n}function Zf(e){return `${Number((e/1e3).toFixed(3))} s`}function Xf(e){let t=e,n=typeof t?.message=="string"&&t.message!==""?t.message:String(e),r=t?.cause,o=r&&typeof r.code=="string"?
|
|
624
|
+
r.code:r&&typeof r.message=="string"?r.message:void 0;return o?`${n} (${o})`:n}async function tc(e){let t=`${e.licenseServerUrl.replace(/\/+$/,"")}/api/license/current`,n=c=>e.serviceAccountKey?c.split(
|
|
504
625
|
e.serviceAccountKey).join("[service key]"):c,r=new AbortController,o=false,i=setTimeout(()=>{o=true,r.abort();},e.timeoutMs);i.unref?.();let s=()=>r.abort();e.signal&&(e.signal.aborted?r.abort():e.signal.addEventListener(
|
|
505
|
-
"abort",s,{once:true}));let a=c=>o?{kind:"unreachable",cause:`timed out after ${
|
|
506
|
-
l=await c(t,{method:"GET",headers:{authorization:`Bearer ${e.serviceAccountKey}`,accept:"application/json"},signal:r.signal});}catch(
|
|
507
|
-
404)return {kind:"no-license"};if(!l.ok)return {kind:"unreachable",cause:`HTTP ${l.status}`};let
|
|
508
|
-
ponse (no license token)"}}let u=
|
|
509
|
-
n",license:
|
|
510
|
-
slice(0,10)}catch{return "an unknown date"}}var
|
|
511
|
-
key's organization is used. Unset BIVELIO_LICENSE_KEY or replace it with this organization's license key.",
|
|
512
|
-
's BiVelio key (${e}); starting with BIVELIO_LICENSE_KEY. Update @bivelio/savings-layer (npm i -g @bivelio/savings-layer).`;function
|
|
626
|
+
"abort",s,{once:true}));let a=c=>o?{kind:"unreachable",cause:`timed out after ${Zf(e.timeoutMs)}`}:{kind:"unreachable",cause:vn(n(`network error: ${Xf(c)}`))};try{let c=e.fetchImpl??globalThis.fetch,l;try{
|
|
627
|
+
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-unknown"};if(l.status===
|
|
628
|
+
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:"unexpected res\
|
|
629
|
+
ponse (no license token)"}}let u=p?.token;if(typeof u!="string"||u.trim()==="")return {kind:"unreachable",cause:"unexpected response (no license token)"};let f=vr(u,e.publicKey);return f.ok?{kind:"toke\
|
|
630
|
+
n",license:f.license}:{kind:"not-verifying",reason:vn(f.reason)}}catch(c){return a(c)}finally{clearTimeout(i),e.signal?.removeEventListener("abort",s);}}function De(e){try{return new Date(e*1e3).toISOString().
|
|
631
|
+
slice(0,10)}catch{return "an unknown date"}}var yn=(e,t)=>e+t*Gf,Qf="WARNING: BIVELIO_LICENSE_KEY belongs to a different organization than BIVELIO_SERVICE_KEY and is ignored; the license of the service\
|
|
632
|
+
key's organization is used. Unset BIVELIO_LICENSE_KEY or replace it with this organization's license key.",em=e=>`WARNING: the license served by savings.bivelio.com does not verify against this build\
|
|
633
|
+
's BiVelio key (${e}); starting with BIVELIO_LICENSE_KEY. Update @bivelio/savings-layer (npm i -g @bivelio/savings-layer).`;function tm(e,t={}){switch(e){case "no-public-key":return "this build has no e\
|
|
513
634
|
mbedded BiVelio verification key (it is running from source): install the published package (npm i -g @bivelio/savings-layer) or run pnpm build first.";case "service-key-missing":return `BIVELIO_SERVICE\
|
|
514
|
-
_KEY is not set. The gateway needs two things and does not start without them: an active BiVelio subscription (${
|
|
635
|
+
_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 ${xt}, step 2). Export the key and relaun\
|
|
515
636
|
ch: the license is collected with it automatically.`;case "service-key-malformed":return "BIVELIO_SERVICE_KEY does not look like a service key (service keys start with bvk_)."+(t.keyLooksLikeLicense?" I\
|
|
516
|
-
t looks like a license key: that one goes in BIVELIO_LICENSE_KEY.":"")+` Create a service key at ${
|
|
517
|
-
not recognised by savings.bivelio.com (HTTP 401): it was deleted or rotated, or it was copied incompletely. Create a new one at ${
|
|
518
|
-
rganization has no active BiVelio license, and the gateway does not start without one: there is no free tier. Subscribe at ${
|
|
519
|
-
key.`;case "license-expired":{let n=t.expiresAt??0;return `your BiVelio license expired on ${
|
|
637
|
+
t looks like a license key: that one goes in BIVELIO_LICENSE_KEY.":"")+` Create a service key at ${xt} (step 2), export it and relaunch.`;case "service-key-not-recognised":return `BIVELIO_SERVICE_KEY is\
|
|
638
|
+
not recognised by savings.bivelio.com (HTTP 401): it was deleted or rotated, or it was copied incompletely. Create a new one at ${xt} (step 2), export it and relaunch.`;case "no-license":return `your o\
|
|
639
|
+
rganization has no active BiVelio license, and the gateway does not start without one: there is no free tier. Subscribe at ${ge} and relaunch; the license is collected automatically with your service \
|
|
640
|
+
key.`;case "license-expired":{let n=t.expiresAt??0;return `your BiVelio license expired on ${De(n)} and its grace period ended on ${De(yn(n,t.graceDays??0))}. Renew at ${ge} and relaunch.`+(t.cause?` (s\
|
|
520
641
|
avings.bivelio.com could not be reached to look for a renewed license: ${t.cause})`:"")}case "license-invalid":{let n=t.reason??"bad signature";return t.tokenSource==="savings.bivelio.com"?`the license\
|
|
521
642
|
served by savings.bivelio.com does not verify against this build's BiVelio key (${n}). Update @bivelio/savings-layer (npm i -g @bivelio/savings-layer); if it persists, write to support@bivelio.com.`:
|
|
522
643
|
t.shape==="malformed"?`BIVELIO_LICENSE_KEY is not a license key: a license key has three dot-separated parts and several hundred characters. Did you paste the bvk_ service key by mistake? That one goe\
|
|
523
|
-
s in BIVELIO_SERVICE_KEY; the license key is the other value on ${
|
|
524
|
-
is build's BiVelio key (${n}). Copy the WHOLE key again from ${
|
|
644
|
+
s in BIVELIO_SERVICE_KEY; the license key is the other value on ${xt}. Or unset BIVELIO_LICENSE_KEY: the gateway collects the license online by itself.`:`BIVELIO_LICENSE_KEY does not verify against th\
|
|
645
|
+
is build's BiVelio key (${n}). Copy the WHOLE key again from ${xt}, or unset BIVELIO_LICENSE_KEY to collect it online; if it persists, update @bivelio/savings-layer or write to support@bivelio.com.`}case "\
|
|
525
646
|
unreachable":return `could not collect your license from savings.bivelio.com (${t.cause??"unknown cause"}). The gateway does not start without a verified license. Check your connection and relaunch. If\
|
|
526
|
-
savings.bivelio.com is down, export BIVELIO_LICENSE_KEY=<your license key> (from ${
|
|
527
|
-
must be replaced by hand every billing period.`}}function
|
|
528
|
-
machine":r?`from BIVELIO_LICENSE_KEY, verified on this machine (savings.bivelio.com unreachable: ${r})`:"from BIVELIO_LICENSE_KEY, verified on this machine";if(n==="grace"){let c=
|
|
529
|
-
return `license: ${o}, IN GRACE: expired on ${s}, keeps working until ${c}. Renew at ${
|
|
530
|
-
code:e,message:
|
|
531
|
-
startsWith("bvk_"))return
|
|
532
|
-
ty")return
|
|
533
|
-
publicKey:n,timeoutMs:e.timeoutMs??(i?
|
|
534
|
-
fline",
|
|
535
|
-
y-not-recognised");case "no-license":return
|
|
536
|
-
ne",status:l,line:
|
|
537
|
-
[
|
|
538
|
-
"no-license","blocked","invalid"]);function
|
|
647
|
+
savings.bivelio.com is down, export BIVELIO_LICENSE_KEY=<your license key> (from ${xt}) as a fallback: it is verified on this machine and used only when savings.bivelio.com cannot be reached, and it \
|
|
648
|
+
must be replaced by hand every billing period.`}}function Qa(e,t,n,r){let o=e.plan.toUpperCase(),i=e.grace_days,s=De(e.expires_at),a=t==="online"?"collected with your service key and verified on this \
|
|
649
|
+
machine":r?`from BIVELIO_LICENSE_KEY, verified on this machine (savings.bivelio.com unreachable: ${r})`:"from BIVELIO_LICENSE_KEY, verified on this machine";if(n==="grace"){let c=De(yn(e.expires_at,i));
|
|
650
|
+
return `license: ${o}, IN GRACE: expired on ${s}, keeps working until ${c}. Renew at ${ge} (${a})`}return `license: ${o}, active until ${s} (+${i} ${i===1?"day":"days"} grace), ${a}`}var je=(e,t)=>({ok:false,
|
|
651
|
+
code:e,message:tm(e,t)});async function nc(e){let t=e.now??Date.now,n=Xo();if(Jf(n))return je("no-public-key");let r=e.serviceAccountKey?.trim();if(!r)return je("service-key-missing");if(!r.
|
|
652
|
+
startsWith("bvk_"))return je("service-key-malformed",{keyLooksLikeLicense:un($t(r))==="token"});let o=null;if(e.licenseKey!==void 0){let c=vr(e.licenseKey,n);if(c.ok)o=c.license;else if(c.shape!=="emp\
|
|
653
|
+
ty")return je("license-invalid",{tokenSource:"BIVELIO_LICENSE_KEY",shape:c.shape,reason:c.reason})}let i=o!==null&&qt(Vt(o.payload,t())),s=await tc({licenseServerUrl:e.licenseServerUrl,serviceAccountKey:r,
|
|
654
|
+
publicKey:n,timeoutMs:e.timeoutMs??(i?Vf:Ff),...e.fetchImpl?{fetchImpl:e.fetchImpl}:{}}),a=(c,l)=>{let p=Vt(o.payload,t());return qt(p)?{ok:true,license:o,source:"offline",status:p,line:Qa(o.payload,"of\
|
|
655
|
+
fline",p,c),lineIsWarning:true,warnings:l}:je("license-expired",{expiresAt:o.payload.expires_at,graceDays:o.payload.grace_days,...c?{cause:c}:{}})};switch(s.kind){case "key-unknown":return je("service-ke\
|
|
656
|
+
y-not-recognised");case "no-license":return je("no-license");case "token":{let c=s.license,l=Vt(c.payload,t()),p=o&&o.payload.org_id!==c.payload.org_id?[Qf]:[];return qt(l)?{ok:true,license:c,source:"onli\
|
|
657
|
+
ne",status:l,line:Qa(c.payload,"online",l),lineIsWarning:l==="grace",warnings:p}:je("license-expired",{expiresAt:c.payload.expires_at,graceDays:c.payload.grace_days})}case "not-verifying":return i?a(void 0,
|
|
658
|
+
[em(s.reason)]):je("license-invalid",{tokenSource:"savings.bivelio.com",reason:s.reason});case "unreachable":return o?a(s.cause,[]):je("unreachable",{cause:s.cause})}}var nm=new Set(["expired","revoked",
|
|
659
|
+
"no-license","blocked","invalid"]);function Qo(e,t,n){let r=typeof t=="string"?t.trim():"";if(r!==""){let i="reported by savings.bivelio.com";return r==="license-revoked"?{serve:false,state:"revoked",detail:i}:
|
|
539
660
|
r==="license-expired"?{serve:false,state:"expired",detail:i}:r==="no-license"?{serve:false,state:"no-license",detail:i}:{serve:false,state:"blocked",detail:i}}let o=e.status();return o==="active"||o==="grace"?
|
|
540
|
-
{serve:true,state:o}:o==="expired"?{serve:false,state:"expired",detail:n?`grace period ended ${
|
|
541
|
-
nse id revoked"}:{serve:false,state:"invalid",detail:"license no longer verifies"}}var
|
|
542
|
-
he BiVelio license for this organization has expired. New requests are refused until it is renewed at ${
|
|
543
|
-
o longer active (revoked or cancelled). New requests are refused; ${
|
|
544
|
-
icense. New requests are refused until you subscribe at ${
|
|
545
|
-
uests are refused; ${
|
|
546
|
-
ts, write to support@bivelio.com.`}}function
|
|
547
|
-
ite to support@bivelio.com`,"no-license":`Subscribe at ${
|
|
548
|
-
t.state?null:`[bvsala gateway] license ${t.state} (${t.detail}): new requests are refused with HTTP 402; requests in flight are not touched. ${
|
|
549
|
-
n.grace_days));return e!==null&&
|
|
550
|
-
ateway] license ${t.state} again (expires ${r}): serving new requests`:t.state==="grace"&&e!=="grace"?`[bvsala gateway] license in grace: it expired on ${r} and keeps working until ${o}. Renew at ${
|
|
551
|
-
null}function
|
|
552
|
-
return this.o.now?this.o.now():Date.now()}start(t={}){this.parado||this.timer!==null||(this.timer=setInterval(()=>{this.check();},this.o.intervalMs??
|
|
661
|
+
{serve:true,state:o}:o==="expired"?{serve:false,state:"expired",detail:n?`grace period ended ${De(yn(n.expires_at,n.grace_days))}`:"grace period ended"}:o==="revoked"?{serve:false,state:"revoked",detail:"lice\
|
|
662
|
+
nse id revoked"}:{serve:false,state:"invalid",detail:"license no longer verifies"}}var bn="requests already in flight were not interrupted";function rm(e){switch(e){case "expired":return `bvsala gateway: t\
|
|
663
|
+
he BiVelio license for this organization has expired. New requests are refused until it is renewed at ${ge}; ${bn}.`;case "revoked":return `bvsala gateway: the BiVelio license for this organization is n\
|
|
664
|
+
o longer active (revoked or cancelled). New requests are refused; ${bn}. Check ${ge} or write to support@bivelio.com.`;case "no-license":return `bvsala gateway: this organization has no active BiVelio l\
|
|
665
|
+
icense. New requests are refused until you subscribe at ${ge}; ${bn}.`;case "blocked":return `bvsala gateway: savings.bivelio.com reports the BiVelio license for this organization as not active. New req\
|
|
666
|
+
uests are refused; ${bn}. Check ${ge}.`;case "invalid":return `bvsala gateway: the license loaded by this gateway no longer verifies. New requests are refused; ${bn}. Relaunch the terminal; if it persis\
|
|
667
|
+
ts, write to support@bivelio.com.`}}function rc(e){return JSON.stringify({type:"error",error:{type:"license_error",status:e,message:rm(e)}})}var om={expired:`Renew at ${ge}`,revoked:`Check ${ge} or wr\
|
|
668
|
+
ite to support@bivelio.com`,"no-license":`Subscribe at ${ge}`,blocked:`Check ${ge}`,invalid:"Relaunch the terminal; if it persists, write to support@bivelio.com"};function oc(e,t,n){if(!t.serve)return e===
|
|
669
|
+
t.state?null:`[bvsala gateway] license ${t.state} (${t.detail}): new requests are refused with HTTP 402; requests in flight are not touched. ${om[t.state]}`;let r=De(n.expires_at),o=De(yn(n.expires_at,
|
|
670
|
+
n.grace_days));return e!==null&&nm.has(e)?t.state==="grace"?`[bvsala gateway] license in grace again (it expired on ${r} and keeps working until ${o}): serving new requests. Renew at ${ge}`:`[bvsala g\
|
|
671
|
+
ateway] license ${t.state} again (expires ${r}): serving new requests`:t.state==="grace"&&e!=="grace"?`[bvsala gateway] license in grace: it expired on ${r} and keeps working until ${o}. Renew at ${ge}`:
|
|
672
|
+
null}function ei(e,t,n,r){return {license:e,gate:cr(e.token,t,{revocation:n,...r?{now:r}:{}})}}var br=class{constructor(t){this.o=t;}o;timer=null;enVuelo=false;parado=false;ctrl=null;avisados=new Set;ahora(){
|
|
673
|
+
return this.o.now?this.o.now():Date.now()}start(t={}){this.parado||this.timer!==null||(this.timer=setInterval(()=>{this.check();},this.o.intervalMs??qf),this.timer.unref?.(),t.checkNow&&this.check({force:true}));}stop(){
|
|
553
674
|
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.
|
|
554
|
-
enVuelo||this.parado)return false;let n=this.o.current(),r=Vt(
|
|
555
|
-
|
|
556
|
-
o.timeoutMs??
|
|
557
|
-
license.payload,l=this.o.revocation.snapshot();if(c.jti===n.payload.jti||this.o.revocation.has(c.jti)||!Vt(
|
|
558
|
-
org_id,
|
|
559
|
-
s no longer recognised (HTTP 401). This session keeps its current license until ${a}; create a new key at ${
|
|
560
|
-
cense renewal: savings.bivelio.com reports no active license for this organization (HTTP 404). This session keeps its current license until ${a}; subscribe or renew at ${
|
|
675
|
+
enVuelo||this.parado)return false;let n=this.o.current(),r=qt(Vt(n.payload,this.ahora(),this.o.revocation.snapshot())),o=n.payload.expires_at-Math.floor(this.ahora()/1e3);if(!t.force&&r&&o>(this.o.leadSeconds??
|
|
676
|
+
Hf))return false;this.enVuelo=true;let i=new AbortController;this.ctrl=i;try{let s=await tc({licenseServerUrl:this.o.licenseServerUrl,serviceAccountKey:this.o.serviceAccountKey,publicKey:this.o.publicKey,timeoutMs:this.
|
|
677
|
+
o.timeoutMs??Wf,signal:i.signal,...this.o.fetchImpl?{fetchImpl:this.o.fetchImpl}:{}});if(this.parado)return !1;let a=De(yn(n.payload.expires_at,n.payload.grace_days));switch(s.kind){case "token":{let c=s.
|
|
678
|
+
license.payload,l=this.o.revocation.snapshot();if(c.jti===n.payload.jti||this.o.revocation.has(c.jti)||!qt(Vt(c,this.ahora(),l)))return !1;let p=qt(Vt(n.payload,this.ahora(),l)),u=c.org_id!==n.payload.
|
|
679
|
+
org_id,f=c.expires_at>n.payload.expires_at;return !u&&!f&&p?!1:(this.o.onAdopt(s.license),!0)}case "key-unknown":return this.avisar("key-unknown",`[bvsala gateway] license renewal: BIVELIO_SERVICE_KEY i\
|
|
680
|
+
s no longer recognised (HTTP 401). This session keeps its current license until ${a}; create a new key at ${xt} and relaunch.`),!1;case "no-license":return this.avisar("no-license",`[bvsala gateway] li\
|
|
681
|
+
cense renewal: savings.bivelio.com reports no active license for this organization (HTTP 404). This session keeps its current license until ${a}; subscribe or renew at ${ge}.`),!1;case "not-verifying":
|
|
561
682
|
return this.avisar(`not-verifying:${s.reason}`,`[bvsala gateway] license renewal: the license served by savings.bivelio.com does not verify against this build's BiVelio key (${s.reason}); update @bive\
|
|
562
|
-
lio/savings-layer.`),!1;case "unreachable":return !1}return !1}catch{return false}finally{this.ctrl===i&&(this.ctrl=null),this.enVuelo=false;}}};function
|
|
563
|
-
length??0;return {definiciones:t,referencias:r,diferidas:o}}var
|
|
683
|
+
lio/savings-layer.`),!1;case "unreachable":return !1}return !1}catch{return false}finally{this.ctrl===i&&(this.ctrl=null),this.enVuelo=false;}}};function ic(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)?.
|
|
684
|
+
length??0;return {definiciones:t,referencias:r,diferidas:o}}var im=40;function sc(e){return e.referencias>0||(e.diferidas??0)>0||e.definiciones<im?null:`[bvsala gateway] your client sends ${e.definiciones}\
|
|
564
685
|
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\
|
|
565
|
-
f you launched the terminal by hand, export ENABLE_TOOL_SEARCH=true. In our own corpus that block was 24.5% of input spend.`}var
|
|
686
|
+
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 ti=5*1024*1024,am=["authorization","x-api-key","anthropic-version","anthropic-beta","api-key","openai-organization","openai-project"];function ac(e,t,n,r=""){return createHash(
|
|
566
687
|
"sha256").update(e).update(`
|
|
567
688
|
`).update(t).update(`
|
|
568
689
|
`).update(r).update(`
|
|
569
|
-
`).update(n).digest("hex")}function
|
|
570
|
-
`)}var
|
|
571
|
-
i=0,s=false;return {capturar:a=>{if(!s){if(i+=a.length,i>
|
|
690
|
+
`).update(n).digest("hex")}function cc(e){return am.map(t=>`${t}=${e(t)??""}`).join(`
|
|
691
|
+
`)}var yr=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=[],
|
|
692
|
+
i=0,s=false;return {capturar:a=>{if(!s){if(i+=a.length,i>ti){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?
|
|
572
693
|
{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;
|
|
573
|
-
return r&&(this.gemelas+=1),r}tieneEnVuelo(t){return this.enVuelo.has(t)}};var
|
|
574
|
-
e.length;t++){let n=e[t];if(n==="--upstream"){let r=e[t+1];return r!==void 0&&!r.startsWith("--")?r:null}if(n.startsWith("--upstream=")){let r=n.slice(11);return r.trim()!==""?r:null}}}function
|
|
575
|
-
let t=e.trim();return /^(sk-|sk_|bvk_|rk_|pk_|key-)/i.test(t)||t.length>=32&&!/[\s:/.]/.test(t)?"(value hidden: it looks like a key)":`"${t.length>80?`${t.slice(0,80)}\u2026`:t}"`}function
|
|
694
|
+
return r&&(this.gemelas+=1),r}tieneEnVuelo(t){return this.enVuelo.has(t)}};var lc={openai:"https://api.openai.com",anthropic:"https://api.anthropic.com"};function uc(e){let t;try{t=new URL(e).origin;}catch{return false}return Object.values(lc).includes(t)}function dc(e){for(let t=0;t<
|
|
695
|
+
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 cm(e){
|
|
696
|
+
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 pc(e){if(e.flag===
|
|
576
697
|
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&&
|
|
577
|
-
e.env.trim()!=="")t=e.env,n="env";else return {ok:true,upstream:void 0,origen:"none"};let r=
|
|
578
|
-
invalid upstream ${
|
|
698
|
+
e.env.trim()!=="")t=e.env,n="env";else return {ok:true,upstream:void 0,origen:"none"};let r=lc[t.trim().toLowerCase()];if(r!==void 0)return {ok:true,upstream:r,origen:n};let o={ok:false,error:`[bvsala gateway]\
|
|
699
|
+
invalid upstream ${cm(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!==
|
|
579
700
|
""||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\
|
|
580
|
-
ns), so put that prefix in the client's base URL instead.`}:{ok:true,upstream:i.origin,origen:n}}var
|
|
581
|
-
set(n,(this.noMedidas.get(n)??0)+1);}estado(){return {medidas:this.medidas,replicas:this.replicas,noMedidas:Object.fromEntries(this.noMedidas)}}};function
|
|
701
|
+
ns), so put that prefix in the client's base URL instead.`}:{ok:true,upstream:i.origin,origen:n}}var lm="other reasons",kr=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:lm;this.noMedidas.
|
|
702
|
+
set(n,(this.noMedidas.get(n)??0)+1);}estado(){return {medidas:this.medidas,replicas:this.replicas,noMedidas:Object.fromEntries(this.noMedidas)}}};function fc(e,t){let n=`[bvsala ${t}] metering in this r\
|
|
582
703
|
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\
|
|
583
704
|
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\
|
|
584
705
|
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(
|
|
585
|
-
"; ");return `${n} ${i} \xB7 ${o} forwarded but NOT metered (nothing is estimated in their place): ${s}. What each reason means and what to do: docs/terminales/README.md.`}var
|
|
706
|
+
"; ");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 kn="x-bvsala-report",ri="x-bvsala-request-id",um="/_bvsala/",dm="bvsala.gateway.report/1",mc="bvsala.gateway.status/1";var wr=/^[A-Za-z0-9._:-]{1,200}$/;function hc(e){let t=(Array.isArray(e)?e[0]:e)?.trim().toLowerCase();return t==="1"||t==="true"}var xr=class{entradas=new Map;porRespuestaId=new Map;oyentes=new Set;capacidad;now;constructor(t={}){
|
|
586
707
|
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>=
|
|
587
|
-
this.capacidad;){let r=this.entradas.keys().next().value;if(r===void 0)break;this.quitar(r);}this.entradas.set(t,{informe:{schema:
|
|
588
|
-
abiertaMs:this.now()}),this.avisar();}anotarRespuesta(t,n){let r=this.entradas.get(t);!r||r.informe.responseId!==null||!n||!
|
|
708
|
+
this.capacidad;){let r=this.entradas.keys().next().value;if(r===void 0)break;this.quitar(r);}this.entradas.set(t,{informe:{schema:dm,requestId:t,responseId:null,path:n,status:"pending",reason:null,report:null},
|
|
709
|
+
abiertaMs:this.now()}),this.avisar();}anotarRespuesta(t,n){let r=this.entradas.get(t);!r||r.informe.responseId!==null||!n||!wr.test(n)||(r.informe.responseId=n,this.porRespuestaId.set(n,t),this.avisar());}medido(t,n){
|
|
589
710
|
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.
|
|
590
711
|
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=()=>{
|
|
591
|
-
a||(a=true,clearTimeout(
|
|
712
|
+
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){
|
|
592
713
|
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);
|
|
593
714
|
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;
|
|
594
|
-
this.quitar(n);}}avisar(){for(let t of [...this.oyentes])t();}};function
|
|
595
|
-
"string"&&
|
|
715
|
+
this.quitar(n);}}avisar(){for(let t of [...this.oyentes])t();}};function gc(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==
|
|
716
|
+
"string"&&wr.test(n))return n;return null}function oi(e){try{return gc(JSON.parse(e.toString("utf8")))}catch{return null}}var Sr=class{resto="";leidos=0;id=null;observar(t){if(this.id!==null||this.leidos>
|
|
596
717
|
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(`
|
|
597
|
-
`))>=0;){let o=this.resto.slice(0,r).replace(/\r$/,"");if(this.resto=this.resto.slice(r+1),!o.startsWith("data:"))continue;let i=o.slice(5).trim();if(!(i===""||i==="[DONE]"))try{let s=
|
|
598
|
-
if(s!==null){this.id=s,this.resto="";return}}catch{}}this.leidos>262144&&(this.resto="");}valor(){return this.id}};function
|
|
599
|
-
try{t=new URL(e??"/","http://127.0.0.1");}catch{return null}return t.pathname.startsWith(
|
|
600
|
-
try{t=new URL(`http://${e}`).hostname.toLowerCase();}catch{return false}return
|
|
601
|
-
n));}function
|
|
602
|
-
127.0.0.1 or localhost");return}if(e.method!=="GET"){t.setHeader("allow","GET"),
|
|
603
|
-
s"){
|
|
718
|
+
`))>=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=gc(JSON.parse(i));
|
|
719
|
+
if(s!==null){this.id=s,this.resto="";return}}catch{}}this.leidos>262144&&(this.resto="");}valor(){return this.id}};function bc(e){try{return new URL(e).origin}catch{return "unknown"}}function vc(e){let t;
|
|
720
|
+
try{t=new URL(e??"/","http://127.0.0.1");}catch{return null}return t.pathname.startsWith(um)?t:null}var pm=new Set(["127.0.0.1","localhost","[::1]"]);function fm(e){if(e===void 0||e==="")return true;let t;
|
|
721
|
+
try{t=new URL(`http://${e}`).hostname.toLowerCase();}catch{return false}return pm.has(t)}function ni(e,t,n){e.writeHead(t,{"content-type":"application/json","cache-control":"no-store"}),e.end(JSON.stringify(
|
|
722
|
+
n));}function St(e,t,n,r){ni(e,t,{type:"error",error:{type:n,message:r}});}async function yc(e,t,n,r){if(e.resume(),!fm(e.headers.host)){St(t,403,"forbidden","bvsala gateway: local routes answer only to\
|
|
723
|
+
127.0.0.1 or localhost");return}if(e.method!=="GET"){t.setHeader("allow","GET"),St(t,405,"method_not_allowed","bvsala gateway: local routes only answer GET");return}if(n.pathname==="/_bvsala/v1/statu\
|
|
724
|
+
s"){ni(t,200,r.estado());return}let o=Number(n.searchParams.get("wait_ms")??"0");if(!Number.isFinite(o)||o<0){St(t,400,"invalid_request","bvsala gateway: wait_ms must be a non-negative number of milli\
|
|
604
725
|
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(
|
|
605
|
-
l[1]);}catch{u="";}if(!
|
|
606
|
-
let u=n.searchParams.get("response_id")??"";if(!
|
|
607
|
-
response id ${u}`;}if(a===null){
|
|
608
|
-
`bvsala gateway: no report for ${c}. Reports exist only for requests sent with the header "${
|
|
609
|
-
t,200,
|
|
610
|
-
(t.enLaCola=true);}),t.herramientaDeServidor=
|
|
611
|
-
"string"&&n.startsWith("claude-cli/")}var
|
|
612
|
-
0)===0&&
|
|
613
|
-
ttlReescritoPorLaCapa:r}=e;if(t.marcas===0)return null;if((n.cache_read_input_tokens??0)===0&&
|
|
614
|
-
0&&t.deOtroTtl===0&&!t.herramientaDeServidor&&i!==void 0&&(i.ephemeral_1h_input_tokens??0)===0&&(i.ephemeral_5m_input_tokens??0)>0?"ttlAcortado":null}function
|
|
726
|
+
l[1]);}catch{u="";}if(!wr.test(u)){St(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"){
|
|
727
|
+
let u=n.searchParams.get("response_id")??"";if(!wr.test(u)){St(t,400,"invalid_request","bvsala gateway: pass ?response_id=<the id of the provider's response>");return}a=()=>r.buzon.porRespuesta(u),c=`\
|
|
728
|
+
response id ${u}`;}if(a===null){St(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){St(t,404,"not_found",
|
|
729
|
+
`bvsala gateway: no report for ${c}. Reports exist only for requests sent with the header "${kn}: 1", while this gateway process keeps them (the last ${r.buzon.limite}, one hour at most).`);return}ni(
|
|
730
|
+
t,200,p);}}var kc=4096;function wc(e){let t={marcas:0,de1h:0,deOtroTtl:0,enLaCola:false,herramientaDeServidor:false};return qr(e,(n,r)=>{t.marcas++,n.ttl==="1h"?t.de1h++:t.deOtroTtl++,(r==="raiz"||r==="ultimoMensaje")&&
|
|
731
|
+
(t.enLaCola=true);}),t.herramientaDeServidor=Vr(e),t}function xc(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==
|
|
732
|
+
"string"&&n.startsWith("claude-cli/")}var Sc=e=>e.cache_creation_input_tokens??(e.cache_creation?.ephemeral_5m_input_tokens??0)+(e.cache_creation?.ephemeral_1h_input_tokens??0);function Ec(e){if((e.cache_read_input_tokens??
|
|
733
|
+
0)===0&&Sc(e)===0&&(e.input_tokens??0)>=kc)return true;let n=e.cache_creation;return n!==void 0&&(n.ephemeral_5m_input_tokens??0)>0&&(n.ephemeral_1h_input_tokens??0)===0}function _c(e){let{vista:t,uso:n,
|
|
734
|
+
ttlReescritoPorLaCapa:r}=e;if(t.marcas===0)return null;if((n.cache_read_input_tokens??0)===0&&Sc(n)===0&&t.enLaCola&&(n.input_tokens??0)>=kc)return "cacheIgnorada";let i=n.cache_creation;return !r&&t.de1h>
|
|
735
|
+
0&&t.deOtroTtl===0&&!t.herramientaDeServidor&&i!==void 0&&(i.ephemeral_1h_input_tokens??0)===0&&(i.ephemeral_5m_input_tokens??0)>0?"ttlAcortado":null}function ii(e,t){let n=`[gateway] degraded traffic${t.
|
|
615
736
|
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 \
|
|
616
737
|
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\
|
|
617
738
|
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 \
|
|
618
739
|
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\
|
|
619
740
|
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 \
|
|
620
741
|
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\
|
|
621
|
-
y hand.`+r}var
|
|
742
|
+
y hand.`+r}var Er=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??""}`;
|
|
622
743
|
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.
|
|
623
|
-
cuentas}}};function
|
|
744
|
+
cuentas}}};function Tc(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) \
|
|
624
745
|
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\
|
|
625
|
-
his run: ${t.join(" \xB7 ")}. What each one means and what to do: "What the gateway guarantees" in docs/terminales/README.md of the package.`}var
|
|
626
|
-
o the call (Node: stream_options: { include_usage: true }); its last chunk then has an empty choices list.',
|
|
627
|
-
nnot change.",
|
|
628
|
-
red without the provider's final usage, so it was forwarded but NOT metered. Nothing is estimated in its place.`,
|
|
629
|
-
from /v1/messages, \u2026/chat/completions and \u2026/responses only.`,
|
|
630
|
-
alive","proxy-connection","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","expect"]);function
|
|
631
|
-
AggregateError&&t.errors.length>0?t.errors.map(r=>String(r)).join("; "):String(t);return `${String(e)} \xB7 cause: ${n}`}var
|
|
746
|
+
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 Rc='[bvsala gateway] streamed /v1/chat/completions requests without stream_options.include_usage carry no usage, so they are forwarded but NOT metered. Add stream_options={"include_usage": True} t\
|
|
747
|
+
o the call (Node: stream_options: { include_usage: true }); its last chunk then has an empty choices list.',gm=Rc+" Or start the gateway with BVSALA_GATEWAY_USAGE_INJECT=1 to add it for clients you ca\
|
|
748
|
+
nnot change.",bm=Rc+" 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.",vm=e=>`[bvsala gateway] POST ${e} answe\
|
|
749
|
+
red without the provider's final usage, so it was forwarded but NOT metered. Nothing is estimated in its place.`,ym=e=>`[bvsala gateway] POST ${e} is forwarded but NOT metered: the gateway reads usage\
|
|
750
|
+
from /v1/messages, \u2026/chat/completions and \u2026/responses only.`,Ac=/\/(count_tokens|input_tokens)$/,km=["content-encoding","content-length","transfer-encoding"],wm=new Set(["connection","keep-\
|
|
751
|
+
alive","proxy-connection","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","expect"]);function Ht(e){let t=e?.cause;if(t==null)return String(e);let n=t instanceof
|
|
752
|
+
AggregateError&&t.errors.length>0?t.errors.map(r=>String(r)).join("; "):String(t);return `${String(e)} \xB7 cause: ${n}`}var si=class extends Error{code;puerto;constructor(t,n,r){super(t==="EADDRINUSE"?
|
|
632
753
|
`port ${n} is already in use: the gateway could not start`:t==="EACCES"?`port ${n} cannot be opened: permission denied`:`could not listen on 127.0.0.1:${n} (${t})`,{cause:r}),this.name="ErrorDeEscucha",
|
|
633
|
-
this.code=t,this.puerto=n;}};function
|
|
634
|
-
Promise.resolve(true):e.destroyed?Promise.resolve(false):new Promise(t=>{let n=()=>o(true),r=()=>o(e.writableFinished),o=i=>{e.off("finish",n),e.off("close",r),t(i);};e.once("finish",n),e.once("close",r);})}async function
|
|
635
|
-
if(!e?.license)throw new Error("arrancarGateway: a verified BiVelio license is required (LICENSE section 2)");let t=
|
|
636
|
-
teway: the license token does not verify (${n.reason})`);let r=(e.upstream??"https://api.anthropic.com").replace(/\/+$/,""),o=
|
|
637
|
-
error(
|
|
638
|
-
api/metering/usage",serviceAccountKey:e.serviceAccountKey,surface:"gateway",...e.fetchImpl?{fetchImpl:e.fetchImpl}:{},onAuthError:
|
|
639
|
-
ting the credential (${
|
|
640
|
-
let
|
|
641
|
-
gateway forwards traffic but does not meter it (the bvsala CLI refuses to start without the key).");let
|
|
642
|
-
new
|
|
643
|
-
{fetchImpl:e.fetchImpl}:{},...e.entitlementsTtlMs!==void 0?{ttlMs:e.entitlementsTtlMs}:{},log:s}):null,
|
|
644
|
-
u.gate,null,u.license.payload);
|
|
645
|
-
"/v1/messages"?new
|
|
646
|
-
red: ${
|
|
647
|
-
inyeccion",
|
|
648
|
-
return {motivo:`the response ended as response.${
|
|
649
|
-
vent",aviso:"uso"};let q="the request did not ask for usage (stream_options.include_usage)";return
|
|
650
|
-
"comprimido"?{motivo:`${q}; usage injection skips compressed request bodies`,aviso:"chat-con-inyeccion"}:
|
|
651
|
-
if(!
|
|
652
|
-
ided)":""}`;if(!
|
|
653
|
-
from the request body"),
|
|
654
|
-
return}let
|
|
655
|
-
null,
|
|
656
|
-
d)":""} \xB7 ${
|
|
657
|
-
cacheEscrita1h})`:""} cache\u2193${
|
|
658
|
-
$${
|
|
659
|
-
|
|
660
|
-
cription traffic: lever applied, saving not credited (no per-token invoice)":"")+(!o&&!
|
|
661
|
-
d at the provider's own API)":"")+(
|
|
662
|
-
at temperature 0`:", no output credited"})`:` \xB7 estimated, not by reference: ${
|
|
663
|
-
let
|
|
664
|
-
{}});if(!
|
|
665
|
-
|
|
666
|
-
no list price in the catalog`),s(`${Ce} \xB7 not metered: model "${
|
|
667
|
-
bvsala gateway] model "${
|
|
668
|
-
!
|
|
669
|
-
entrada:
|
|
670
|
-
|
|
671
|
-
"/","http://x").pathname;}catch{}s(`[gateway] ${
|
|
672
|
-
upstream:
|
|
673
|
-
return}let q=
|
|
674
|
-
()=>{
|
|
675
|
-
cache_creation,
|
|
676
|
-
triggerDelCliente!==null&&
|
|
677
|
-
test(N)?N:void 0},
|
|
678
|
-
void 0;try{let
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
isArray(
|
|
684
|
-
|
|
685
|
-
trim().toLowerCase()).filter(
|
|
686
|
-
|
|
687
|
-
(
|
|
688
|
-
N.toString("utf8")),
|
|
689
|
-
modeloHermano===!0&&
|
|
690
|
-
y] sibling model routing: the flag is set but your org's license does not include sibling_model_routing; the request is forwarded unchanged (fail-closed)."),
|
|
691
|
-
|
|
692
|
-
t"))try{let
|
|
693
|
-
ges"&&x.tiene("cache_ttl_tuning"))try{let
|
|
694
|
-
|
|
695
|
-
method==="POST"&&
|
|
696
|
-
|
|
697
|
-
tent-type":"application/json"}),
|
|
698
|
-
if(((
|
|
699
|
-
upstream rejected (${U.status}) the request with stream_options.include_usage added; forwarding it unchanged \xB7 ${
|
|
700
|
-
""}${
|
|
701
|
-
m"),
|
|
702
|
-
JSON.stringify({error:"bvsala gateway: upstream unreachable",detail:
|
|
754
|
+
this.code=t,this.puerto=n;}};function Cc(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 xm(e){return e.writableFinished?
|
|
755
|
+
Promise.resolve(true):e.destroyed?Promise.resolve(false):new Promise(t=>{let n=()=>o(true),r=()=>o(e.writableFinished),o=i=>{e.off("finish",n),e.off("close",r),t(i);};e.once("finish",n),e.once("close",r);})}async function Ic(e){
|
|
756
|
+
if(!e?.license)throw new Error("arrancarGateway: a verified BiVelio license is required (LICENSE section 2)");let t=Xo(e.license.publicKey),n=vr(e.license.token,t);if(!n.ok)throw new Error(`arrancarGa\
|
|
757
|
+
teway: the license token does not verify (${n.reason})`);let r=(e.upstream??"https://api.anthropic.com").replace(/\/+$/,""),o=uc(r),i=e.fetchImpl??fetch,s=e.log??(h=>console.log(h)),a=e.warn??(h=>console.
|
|
758
|
+
error(h)),c=e.license.now??Date.now,l=e.license.licenseServerUrl?.replace(/\/+$/,""),p=new Mt,u=ei(n.license,t,p,c),f;if(e.serviceAccountKey){f=new Dt({url:e.meteringUrl??"https://savings.bivelio.com/\
|
|
759
|
+
api/metering/usage",serviceAccountKey:e.serviceAccountKey,surface:"gateway",...e.fetchImpl?{fetchImpl:e.fetchImpl}:{},onAuthError:T=>Z("gateway-ingest-auth",`[bvsala gateway] the usage ingest is rejec\
|
|
760
|
+
ting the credential (${T}). 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.`)});
|
|
761
|
+
let h=Fn();e.seatId?f.setSeat(e.seatId,h):Vn(e.serviceAccountKey).then(T=>f?.setSeat(T,h)).catch(()=>{}),f.start();}else Z("gateway-sin-clave","[bvsala gateway] no BIVELIO_SERVICE_KEY: this in-process \
|
|
762
|
+
gateway forwards traffic but does not meter it (the bvsala CLI refuses to start without the key).");let m=e.coalescer?new yr:null,b=e.sombra&&f?new mr:null,v=new xr,g=new Nn,y=new Er,w=new kr,x=e.serviceAccountKey?
|
|
763
|
+
new hr({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?
|
|
764
|
+
{fetchImpl:e.fetchImpl}:{},...e.entitlementsTtlMs!==void 0?{ttlMs:e.entitlementsTtlMs}:{},log:s}):null,k=x!==null&&e.elision!==false,I=()=>Qo(u.gate,x?.blockReason()??null,u.license.payload),P=null;{let h=Qo(
|
|
765
|
+
u.gate,null,u.license.payload);h.serve&&(P=h.state);}let D=h=>{let T=oc(P,h,u.license.payload);P=h.state,T&&a(T);},L,B,K=Number.NEGATIVE_INFINITY,Q=new Set,_=(h,T)=>{Q.has(h)||(Q.add(h),s(T));},R=false,$=h=>h===
|
|
766
|
+
"/v1/messages"?new Ne:h.endsWith("/responses")?new Ut:h.endsWith("/chat/completions")?new fn:null,j=(h,T,M,z,J,re,q)=>{v.noMedido(h,re),s(`[gateway] ${T} ${M} \u2192 ${z}${J?" (stream)":""} \xB7 not mete\
|
|
767
|
+
red: ${re}`),(wt(M)||M.startsWith("/v1/"))&&w.noMedida(re),e.avisosDeNoMedido!==false&&(q==="chat"&&Z("gateway-chat-sin-include-usage",gm),q==="chat-con-inyeccion"&&Z("gateway-chat-sin-include-usage-con-\
|
|
768
|
+
inyeccion",bm),q==="uso"&&Z(`gateway-sin-usage:${M}`,vm(M)),q==="dialecto"&&Z(`gateway-sin-dialecto:${M}`,ym(M)));},ne=(h,T,M,z)=>{let J=h instanceof Ut?h.estadoFinal():null;if(J!==null&&J!=="completed")
|
|
769
|
+
return {motivo:`the response ended as response.${J} without usage`,aviso:"uso"};if(!(h instanceof fn&&z!=="inyectado"&&Ua(T,M)!==true))return {motivo:"the stream ended without the provider's final usage e\
|
|
770
|
+
vent",aviso:"uso"};let q="the request did not ask for usage (stream_options.include_usage)";return z==="rechazada-por-el-upstream"?{motivo:`${q}, and the upstream rejects that option`,aviso:null}:z===
|
|
771
|
+
"comprimido"?{motivo:`${q}; usage injection skips compressed request bodies`,aviso:"chat-con-inyeccion"}:z!==null?{motivo:q,aviso:"chat-con-inyeccion"}:{motivo:q,aviso:"chat"}},ee=(h,T,M,z,J,re,q,W,Oe,at,xe,Ee,E,F,et)=>{
|
|
772
|
+
if(!f||!M){v.noMedido(h,f?"the provider reported no usage":"metering is off: the gateway has no BIVELIO_SERVICE_KEY");return}let Jt=f,An=M,Y=Pa(T,re),Ce=`[gateway] POST ${J}${z?" \xB7 COALESCED (call avo\
|
|
773
|
+
ided)":""}`;if(!Y){let he=`could not read the model from the request body${re?` (content-encoding: ${re})`:""}`;s(`${Ce} \xB7 not metered: ${he}`),w.noMedida(he),v.noMedido(h,"could not read the model\
|
|
774
|
+
from the request body"),Z(`gateway-sin-modelo:${J}`,`[bvsala gateway] could not read the model from the ${J} request body (content-encoding: ${re??"none"}); its usage is forwarded but not metered.`);
|
|
775
|
+
return}let me=!z&&xe?xe.servido:Y,le=Ia(me,M,at);if(le){let he=z?Fa(Y,le,E,zt(T,re),{suscripcion:Ee===true,entregada:F?.entregada===true,tierServido:F?.tierServido}):null,ct=z?Va(h,Y,le,q,he?.ok?he.credit:
|
|
776
|
+
null,et===true):za(h,me,le,q,W,Oe,xe,Ee===true,!o,et===true);f.record(ct),z?w.replica():w.medida(),v.medido(h,ct);let oe=ct.cost.eliminatedInputFloorCost;s(`[gateway] POST ${J} ${z?"\xB7 COALESCED (call avoide\
|
|
777
|
+
d)":""} \xB7 ${me!==Y?`${Y}\u2192${me} (sibling model)`:Y} \xB7 $${(et?0:le.costeUsd).toFixed(6)} (in ${le.tokens.entrada}, cache\u2191${le.tokens.cacheEscrita}${le.tokens.cacheEscrita1h?` (1h ${le.tokens.
|
|
778
|
+
cacheEscrita1h})`:""} cache\u2193${le.tokens.cacheLeida}, out ${le.tokens.salida})`+(W?` \xB7 elision: ${W.borrados} clear(s), ${W.tokensLimpiados} tok cleared by the provider`+(oe!==void 0?` \xB7 floor \
|
|
779
|
+
$${oe.toFixed(6)} (cache read price)`:W.tokensLimpiadosToolUses>0?W.atribuible?" \xB7 no cache read price in the catalog: no floor":" \xB7 your own context_management settings: counted, not credited":
|
|
780
|
+
W.tokensLimpiados>0?" \xB7 thinking only (your config): counted, not credited":""):"")+(et?" \xB7 refusal the provider does not bill: measured at $0, no saving credited":"")+(Ee&&!z&&(Oe||xe)?" \xB7 subs\
|
|
781
|
+
cription traffic: lever applied, saving not credited (no per-token invoice)":"")+(!o&&!Ee&&!z&&(Oe||xe||W?.atribuible)?" \xB7 unofficial upstream: lever applied, saving not credited (list prices only hol\
|
|
782
|
+
d at the provider's own API)":"")+(he?he.ok?` \xB7 by reference: floor $${Go(he.credit).toFixed(6)} (cache read price${he.credit.creditedOutputTokens>0?`, ${he.credit.creditedOutputTokens} output tok \
|
|
783
|
+
at temperature 0`:", no output credited"})`:` \xB7 estimated, not by reference: ${he.reason}`:""));let Cn=W?.atribuible===true&&W.tokensLimpiadosToolUses>0;b&&!z&&J==="/v1/messages"&&setImmediate(()=>{try{
|
|
784
|
+
let _e=zt(T,re);if(!_e||typeof _e!="object")return;let Fe=b.observar({cuerpo:_e,uso:An,model:Y,at:at??Date.now(),...q?.sessionId!==void 0?{sessionId:q.sessionId}:{},...q?.agentId!==void 0?{agentId:q.agentId}:
|
|
785
|
+
{}});if(!Fe)return;if(Cn){s(`[gateway] shadow estimate \xB7 ${Y} \xB7 the provider already cleared context via our settings: chain advances, nothing emitted`);return}Jt.record(qa(`${h}:shadow`,Y,Fe.baselineUsd,
|
|
786
|
+
Fe.politicaUsd,q)),s(`[gateway] shadow estimate \xB7 ${Y} \xB7 baseline $${Fe.baselineUsd.toFixed(6)} \u2192 with elision $${Fe.politicaUsd.toFixed(6)}`);}catch{}});}else v.noMedido(h,`model "${me}" has\
|
|
787
|
+
no list price in the catalog`),s(`${Ce} \xB7 not metered: model "${me}" has no list price in the catalog`),w.noMedida(`model "${me}" has no list price in the catalog`),Z(`gateway-sin-precio:${me}`,`[\
|
|
788
|
+
bvsala gateway] model "${me}" is not in the price catalog; its usage is forwarded but not metered.`);},ke=(h,T,M,z,J,re)=>{if(!(h!=="/v1/messages"||z===null||!Ec(z)||(M===void 0||M===""||M==="identity")&&
|
|
789
|
+
!T.includes('"cache_control"')))try{let W=zt(T,M);if(W===null||typeof W!="object"||Array.isArray(W))return;let Oe=_c({vista:wc(W),uso:z,ttlReescritoPorLaCapa:J});Oe!==null&&y.anotar(Oe,re)&&s(ii(Oe,{sesion:re,
|
|
790
|
+
entrada:z.input_tokens??0,escrita5m:z.cache_creation?.ephemeral_5m_input_tokens??0}));}catch{}},we=createServer(async(h,T)=>{let M=randomUUID(),z=Date.now(),J=I();if(D(J),!J.serve){let H=c();B&&H-K>=ec&&(K=H,B.check({force:true})),
|
|
791
|
+
h.resume(),T.writeHead(402,{"content-type":"application/json","cache-control":"no-store","x-bvsala-license-status":J.state}),T.end(h.method==="HEAD"?void 0:rc(J.state));let N="/";try{N=new URL(h.url??
|
|
792
|
+
"/","http://x").pathname;}catch{}s(`[gateway] ${h.method} ${N} \u2192 402 (license ${J.state})`);return}let re=vc(h.url);if(re!==null){await yc(h,T,re,{buzon:v,estado:()=>({schema:mc,gateway:"bvsala",version:be,
|
|
793
|
+
upstream:bc(r),license:{state:J.state,plan:u.license.payload.plan??null,expiresAt:De(u.license.payload.expires_at)},metering:f!==void 0,reports:{requestHeader:kn,responseHeader:ri,capacity:v.limite}})});
|
|
794
|
+
return}let q=hc(h.headers[kn]),W=q?new Sr:null;if(q){let H="/";try{H=new URL(h.url??"/","http://x").pathname;}catch{}v.abrir(M,H);}let Oe=H=>q?{...H,[ri]:M}:H,at=null,xe=new AbortController;T.on("close",
|
|
795
|
+
()=>{T.writableEnded||xe.abort();});let Ee=null,E=new URL(h.url??"/",r),F=null,et=Buffer.alloc(0),Jt=false,An=false,Y=null,Ce=null,me=false,le=false,he=(H,N)=>{if(H===null||Y===null||!Y.nuestros)return H;let lt=N?.
|
|
796
|
+
cache_creation,Zt=N?.cache_creation_input_tokens??(lt?.ephemeral_5m_input_tokens??0)+(lt?.ephemeral_1h_input_tokens??0),Xt=(N?.input_tokens??0)+(N?.cache_read_input_tokens??0)+Zt+H.tokensLimpiados,Qt=Y.
|
|
797
|
+
triggerDelCliente!==null&&Xt>=Y.triggerDelCliente;return {...H,atribuible:!Qt}},ct=h.headers["content-encoding"],oe=Array.isArray(ct)?ct[0]:ct,Cn=H=>{let N=Array.isArray(H)?H[0]:H;return N!==void 0&&/^[A-Za-z0-9._:/-]{1,128}$/.
|
|
798
|
+
test(N)?N:void 0},_e=Cn(h.headers["x-claude-code-session-id"]),Fe=Cn(h.headers["x-claude-code-agent-id"]),Yt=_e!==void 0||Fe!==void 0?{..._e!==void 0?{sessionId:_e}:{},...Fe!==void 0?{agentId:Fe}:{}}:
|
|
799
|
+
void 0;try{let H=[];for await(let S of h)H.push(S);let N=Buffer.concat(H);et=N,E=new URL(h.url??"/",r);let lt=m!==null&&h.method==="POST"&&N.length>0,Zt=cc(S=>{let A=h.headers[S];return Array.isArray(
|
|
800
|
+
A)?A.join(", "):A}),Xt=lt?ac("POST",E.pathname+E.search,N,Zt):"";if(lt)if(m.tieneEnVuelo(Xt)){let S=await m.esperar(Xt);if(S){let A=xe.signal.aborted||T.destroyed;A||T.writeHead(S.status,Oe(S.headers)),
|
|
801
|
+
at=S.status;let ie=$(E.pathname)??new Ne;for(let It of S.chunks)A||T.write(It),ie.observar(It),W?.observar(It);W&&v.anotarRespuesta(M,W.valor()??oi(Buffer.concat(S.chunks))),A||T.end();let Rt=A?!1:await xm(
|
|
802
|
+
T),He=ie.usageFinal()??fr(E.pathname,Buffer.concat(S.chunks));if(He===null){if(f&&!Ac.test(E.pathname)){let It=String(S.headers["content-type"]??"").includes("text/event-stream");j(M,h.method??"POST",
|
|
803
|
+
E.pathname,S.status,It,wt(E.pathname)?It?ne(ie,N,oe,null).motivo:"the response carried no usage":"no usage dialect for this route",null);}return}let ut=h.headers["anthropic-beta"],dt=Wo(E.pathname,Array.
|
|
804
|
+
isArray(ut)?ut.join(", "):ut,r);ee(M,N,He,!0,E.pathname,oe,Yt,null,null,z,null,dt,S.primaria??null,{entregada:Rt,tierServido:ja(E.pathname,Buffer.concat(S.chunks))},E.pathname==="/v1/messages"&&(ie instanceof
|
|
805
|
+
Ne&&ie.negativaNoCobrada()||Ho(E.pathname,Buffer.concat(S.chunks))));return}}else Ee=m.registrar(Xt);let Qt=h.headers.connection,jl=new Set((Array.isArray(Qt)?Qt.join(","):Qt??"").split(",").map(S=>S.
|
|
806
|
+
trim().toLowerCase()).filter(S=>S!=="")),Ve={};for(let[S,A]of Object.entries(h.headers))S==="host"||S==="content-length"||A===void 0||wm.has(S)||jl.has(S)||S!==kn&&(Ve[S]=Array.isArray(A)?A.join(", "):
|
|
807
|
+
A);let en={...Ve};me=Wo(E.pathname,en["anthropic-beta"],r);let Se=N;if(k&&e.dialesElision===!0&&h.method==="POST"&&E.pathname==="/v1/messages"&&x.tiene("context_elision"))try{let S=Mi(N,oe);S!==null&&
|
|
808
|
+
(Se=S.cuerpo,Y={nuestros:S.nuestros,triggerDelCliente:S.triggerDelCliente},Ve["anthropic-beta"]=ji(Ve["anthropic-beta"]));}catch{}if(h.method==="POST"&&E.pathname==="/v1/messages"&&(oe??"")==="")try{let S=ic(
|
|
809
|
+
N.toString("utf8")),A=sc(S);A&&(Z("gateway-busqueda-herramientas",A),xc(h.headers)&&y.anotar("busquedaApagada",_e)&&s(ii("busquedaApagada",{sesion:_e,definiciones:S.definiciones})));}catch{}let Pi=k&&e.
|
|
810
|
+
modeloHermano===!0&&h.method==="POST"&&(E.pathname==="/v1/messages"||E.pathname==="/v1/messages/count_tokens");if(Pi&&!x.tiene("sibling_model_routing")&&Z("gateway-hermano-sin-feature","[bvsala gatewa\
|
|
811
|
+
y] sibling model routing: the flag is set but your org's license does not include sibling_model_routing; the request is forwarded unchanged (fail-closed)."),Pi&&x.tiene("sibling_model_routing"))try{let A=es(
|
|
812
|
+
Se,Se===N?oe:"identity",{betas:Ve["anthropic-beta"]});A!==null&&(Se=A.cuerpo,Ce=A.cambio);}catch{}let Rn=!1;if(k&&Wr(e.esfuerzo)&&h.method==="POST"&&E.pathname==="/v1/messages"&&x.tiene("per_turn_effor\
|
|
813
|
+
t"))try{let S=Se===N?oe:"identity",A=Gi(Se,e.esfuerzo,S);A!==null&&(Se=A.cuerpo,Ve["anthropic-beta"]=Ki(Ve["anthropic-beta"]),Rn=!0);}catch{}let At=null;if(k&&h.method==="POST"&&E.pathname==="/v1/messa\
|
|
814
|
+
ges"&&x.tiene("cache_ttl_tuning"))try{let A=pt(Se,Se===N?oe:"identity");if(A!==null){let ie=Ui(A),Rt=`${Yt?.sessionId??"sin-sesion"}:${ie.system}`,He=Date.now(),ut=g.ultima(Rt,He);if(g.anotar(Rt,ie,He),
|
|
815
|
+
Fi({fraccionNueva:zi(ut,ie)})){let dt=Vi(A);dt!==null&&(Se=dt.cuerpo,At={rebajadas:dt.rebajadas,yaEran5m:dt.yaEran5m,herramientaDeServidor:dt.herramientaDeServidor},le=!0);}}}catch{}let Ct=!1,In=null;if(h.
|
|
816
|
+
method==="POST"&&E.pathname.endsWith("/chat/completions")&&f&&e.usageInject===!0)if(R)In="rechazada-por-el-upstream";else try{let S=Ba(N,oe);In=S.motivo,S.cuerpo&&(Se=S.cuerpo,Ct=!0);}catch{}let U,Lr=Se,
|
|
817
|
+
$r=Ve;try{U=await i(E,{method:h.method,headers:Ve,body:["GET","HEAD"].includes(h.method??"")?void 0:Se,redirect:"manual",signal:xe.signal});}catch(S){Ee?.abortar(),T.headersSent||(T.writeHead(502,{"con\
|
|
818
|
+
tent-type":"application/json"}),T.end(JSON.stringify({error:"bvsala gateway: upstream unreachable",detail:Ht(S)}))),s(`[gateway] ${h.method} ${E.pathname} \u2192 upstream unreachable: ${Ht(S)}`);return}
|
|
819
|
+
if(((Lr!==N||!Cc($r,en))&&U.status===400||Ct&&(U.status===400||U.status===422))&&!xe.signal.aborted){let S="";try{S=(await U.text()).slice(0,300).replace(/\s+/g," ");}catch{}let A=Ct;s(A?`[gateway] the\
|
|
820
|
+
upstream rejected (${U.status}) the request with stream_options.include_usage added; forwarding it unchanged \xB7 ${S}`:`[gateway] the upstream rejected (400) the rewritten request${Ce?` to ${Ce.servido}`:
|
|
821
|
+
""}${Rn?" (per-turn effort)":""}${At?" (cache TTL)":""}${Y?" (context editing dials)":""}; forwarding it unchanged \xB7 ${S}`),Ce=null,Rn=!1,At=null,le=!1,Y=null,Ct=!1,A&&(In="rechazada-por-el-upstrea\
|
|
822
|
+
m"),Lr=N,$r=en;try{U=await i(E,{method:h.method,headers:en,body:N,redirect:"manual",signal:xe.signal});}catch(ie){Ee?.abortar(),T.headersSent||(T.writeHead(502,{"content-type":"application/json"}),T.end(
|
|
823
|
+
JSON.stringify({error:"bvsala gateway: upstream unreachable",detail:Ht(ie)}))),s(`[gateway] ${h.method} ${E.pathname} \u2192 upstream unreachable on retry: ${Ht(ie)}`);return}A&&U.ok&&(R=!0,Z("gateway\
|
|
703
824
|
-sin-stream-options","[bvsala gateway] the upstream rejects stream_options, so usage injection is off for the rest of this process: streamed /v1/chat/completions answers from it are forwarded but NOT \
|
|
704
|
-
metered (stream=false answers still are)."));}let
|
|
705
|
-
"",
|
|
706
|
-
|
|
707
|
-
(
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
fallida:
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
null)j(
|
|
714
|
-
|
|
715
|
-
method,
|
|
716
|
-
j(
|
|
717
|
-
if(
|
|
718
|
-
F.elision():null,N),
|
|
719
|
-
|
|
720
|
-
\u2192 error while serving: ${
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
)`),
|
|
825
|
+
metered (stream=false answers still are)."));}let Mr=Object.fromEntries(U.headers.entries());for(let S of km)delete Mr[S];T.writeHead(U.status,Oe(Mr)),at=U.status;let Pn=U.headers.get("content-type")??
|
|
826
|
+
"",Dn=Pn.includes("text/event-stream")||Pn===""&&U.ok&&$(E.pathname)!==null&&!E.pathname.endsWith("/chat/completions");F=Dn?$(E.pathname):null,An=U.ok;let qe=!Dn&&U.ok&&f!==void 0&&h.method==="POST"&&
|
|
827
|
+
wt(E.pathname)&&(U.headers.get("content-type")??"").includes("application/json")?[]:null,Di=0,Oi=!1;if(U.body)for await(let S of U.body){let A=Buffer.from(S);T.write(A),F?.observar(A),W?.observar(A),qe&&
|
|
828
|
+
(Di+=A.length,Di>ti?(qe=null,Oi=!0):qe.push(A)),Ee?.capturar(A);}if(T.end(),W&&v.anotarRespuesta(M,W.valor()??(qe?oi(Buffer.concat(qe)):null)),Ee){let S=Ce===null&&!Rn&&Y===null&&!Ct&&At===null&&Lr===N&&
|
|
829
|
+
Cc($r,en),A=qe?Buffer.concat(qe):null,ie=U.ok&&(F?F.usageFinal()!==null:A!==null&&fr(E.pathname,A)!==null),Rt=F instanceof Ut&&F.estadoFinal()==="failed"||A!==null&&Oa(E.pathname,A),He=F!==null&&F.negativa()||
|
|
830
|
+
A!==null&&$a(E.pathname,A),ut=!He&&Na(F!==null?F.textoInicial():A!==null?Ma(E.pathname,A):"");Ee.terminar(U.status,Mr,{requestId:M,at:Date.now(),intacta:S,proveedorOficial:o,conContador:ie,suscripcion:me,
|
|
831
|
+
fallida:Rt,...He?{negativa:He}:{},...ut?{negativaEnTexto:!0}:{}});}if(F&&U.ok){Jt=!0;let S=F.usageFinal();if(S===null&&f){let A=ne(F,N,oe,Ct?"inyectado":In);j(M,h.method??"POST",E.pathname,U.status,!0,
|
|
832
|
+
A.motivo,A.aviso);}else {let A=he(F instanceof Ne?F.elision():null,S),ie=E.pathname==="/v1/messages"&&F instanceof Ne&&F.negativaNoCobrada();ee(M,N,S,!1,E.pathname,oe,Yt,A,At,z,Ce,me,void 0,void 0,ie),ke(
|
|
833
|
+
E.pathname,N,oe,S,le,_e);}f||s(`[gateway] ${h.method} ${E.pathname} \u2192 ${U.status} (stream) \xB7 not metered: no BIVELIO_SERVICE_KEY`);}else if(qe){let S=Buffer.concat(qe),A=fr(E.pathname,S);if(A===
|
|
834
|
+
null)j(M,h.method??"POST",E.pathname,U.status,!1,"the response carried no usage","uso");else {let ie=E.pathname==="/v1/messages"?Ta(S):null;ee(M,N,A,!1,E.pathname,oe,Yt,he(ie,A),At,z,Ce,me,void 0,void 0,
|
|
835
|
+
Ho(E.pathname,S)),ke(E.pathname,N,oe,A,le,_e);}}else Oi?j(M,h.method??"POST",E.pathname,U.status,!1,"the response was too large to read its usage",null):f&&h.method==="POST"&&U.ok&&wt(E.pathname)?j(M,h.
|
|
836
|
+
method,E.pathname,U.status,!1,`the response is neither JSON nor an event stream (content-type: ${Pn===""?"none":Pn.slice(0,80)})`,null):f&&h.method==="POST"&&U.ok&&!wt(E.pathname)&&!Ac.test(E.pathname)?
|
|
837
|
+
j(M,h.method,E.pathname,U.status,Dn,"no usage dialect for this route",E.pathname.startsWith("/v1/")?"dialecto":null):s(`[gateway] ${h.method} ${E.pathname} \u2192 ${U.status}${Dn?" (stream)":""}`);}catch(H){
|
|
838
|
+
if(Ee?.abortar(),xe.signal.aborted){let N=!Jt&&F?F.usageFinal():null;if(N){s(`[gateway] ${h.method} ${E.pathname} \u2192 client closed after the final usage; metered anyway`);let lt=he(F instanceof Ne?
|
|
839
|
+
F.elision():null,N),Zt=E.pathname==="/v1/messages"&&F instanceof Ne&&F.negativaNoCobrada();ee(M,et,N,false,E.pathname,oe,Yt,lt,void 0,z,Ce,me,void 0,void 0,Zt),ke(E.pathname,et,oe,N,le,_e);}else s(`[gatew\
|
|
840
|
+
ay] ${h.method} ${E.pathname} \u2192 client aborted; upstream cancelled`),F&&An&&!Jt&&w.noMedida("the client closed the stream before the provider's final usage");}else if(s(`[gateway] ${h.method} ${E.
|
|
841
|
+
pathname} \u2192 error while serving: ${Ht(H)}`),!T.headersSent){T.writeHead(502,{"content-type":"application/json"}),T.end(JSON.stringify({error:"bvsala gateway: stream interrupted",detail:Ht(H)}));return}
|
|
842
|
+
T.writableEnded||T.end();}finally{q&&v.noMedido(M,xe.signal.aborted?"the client closed the connection before the provider's final usage":at===null?"the request did not get an answer from the provider":
|
|
843
|
+
`no usage was read from the provider's answer (HTTP ${at})`);}});we.on("upgrade",(h,T)=>{s(`[gateway] ${h.method} ${new URL(h.url??"/","http://x").pathname} \u2192 426 (WebSocket not supported; the client f\
|
|
844
|
+
alls back to HTTP)`),T.once("error",()=>{}),T.once("finish",()=>T.destroy()),T.end(`HTTP/1.1 426 Upgrade Required\r
|
|
724
845
|
connection: close\r
|
|
725
846
|
content-length: 0\r
|
|
726
847
|
\r
|
|
727
|
-
`);});let
|
|
728
|
-
address().port;return l&&(L=new
|
|
729
|
-
fetchImpl}:{},silenceWarnings:true,onEvent:
|
|
730
|
-
L.start(),e.serviceAccountKey&&(B=new
|
|
731
|
-
adopted (expires ${
|
|
732
|
-
cerrar:async()=>{B?.stop(),L?.stop(),await
|
|
848
|
+
`);});let ze=e.puerto??8402;try{await new Promise((h,T)=>{we.once("error",T),we.listen(ze,"127.0.0.1",()=>h());});}catch(h){f?.stop();let T=h?.code;throw new si(typeof T=="string"?T:"EUNKNOWN",ze,h)}let Qe=we.
|
|
849
|
+
address().port;return l&&(L=new pn({url:`${l}/licenses/revocations`,publicKeyPem:t,snapshot:p,getRefreshAfter:()=>u.gate.refreshAfter?.(),nowSeconds:()=>Math.floor(c()/1e3),...e.fetchImpl?{fetchImpl:e.
|
|
850
|
+
fetchImpl}:{},silenceWarnings:true,onEvent:h=>{h.type==="rejected"&&_(`poller:${h.reason}`,`[gateway] revocation list rejected (${h.reason}); known revocations still apply`);},...e.license.revocations??{}}),
|
|
851
|
+
L.start(),e.serviceAccountKey&&(B=new br({licenseServerUrl:l,serviceAccountKey:e.serviceAccountKey,publicKey:t,revocation:p,current:()=>u.license,onAdopt:h=>{u=ei(h,t,p,c),s(`[gateway] renewed license\
|
|
852
|
+
adopted (expires ${De(h.payload.expires_at)})`),D(I());},onWarning:a,...e.fetchImpl?{fetchImpl:e.fetchImpl}:{},now:c,...e.license.renewal??{}}),B.start({checkNow:e.license.checkOnStart===true}))),{puerto:Qe,
|
|
853
|
+
cerrar:async()=>{B?.stop(),L?.stop(),await f?.stopAndDrain(),await new Promise(h=>we.close(()=>h()));},licenseStatus:()=>I().state,degradaciones:()=>y.contadores(),medicion:()=>w.estado()}}var ai=["claude","codex","goose","qwen","opencode","kilo","copilot","aider"];function wn(e){return ai.includes(e??"")}function ci(e,t={}){
|
|
733
854
|
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 [
|
|
734
|
-
".cmd",".bat"]){let a=join(i,e+s);if(r(a)){o=a;break}}}return o!==null?{tipo:"solo-shim",ruta:o}:{tipo:"no-encontrado"}}function
|
|
855
|
+
".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 Lc(e={}){let n=(e.env??process.env).BVSALA_CODEX_AUTH?.toLowerCase();if(n===
|
|
735
856
|
"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.
|
|
736
|
-
auth_mode=="string"?o.auth_mode.toLowerCase().replace(/[^a-z]/g,"")==="apikey"?"api-key":"chatgpt":o.tokens!==void 0&&o.tokens!==null?"chatgpt":"api-key"}catch{return "api-key"}}var
|
|
737
|
-
https://api.openai.com",prefijo:"/v1"},chatgpt:{upstream:"https://chatgpt.com",prefijo:"/backend-api/codex"}},
|
|
738
|
-
ONTENT",kilo:"KILO_CONFIG_CONTENT"};function
|
|
857
|
+
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 Em={"api-key":{upstream:"\
|
|
858
|
+
https://api.openai.com",prefijo:"/v1"},chatgpt:{upstream:"https://chatgpt.com",prefijo:"/backend-api/codex"}},Dc="https://api.anthropic.com",Oc="https://api.openai.com",$c={opencode:"OPENCODE_CONFIG_C\
|
|
859
|
+
ONTENT",kilo:"KILO_CONFIG_CONTENT"};function Mc(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=
|
|
739
860
|
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(
|
|
740
|
-
{...n,provider:{...o,anthropic:{...i,options:{...s,baseURL:t}}}})}function
|
|
861
|
+
{...n,provider:{...o,anthropic:{...i,options:{...s,baseURL:t}}}})}function Nc(e){let t=e.COPILOT_PROVIDER_BASE_URL?.trim()??"";if(t==="")return {ok:false,error:"Copilot CLI goes through a base URL only wi\
|
|
741
862
|
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\
|
|
742
863
|
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.
|
|
743
864
|
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\
|
|
744
865
|
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\
|
|
745
866
|
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\
|
|
746
867
|
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\
|
|
747
|
-
irst."}}return r.origin!==
|
|
748
|
-
ently, or not at all), so it does not wrap it.`}:{ok:true,ruta:r.pathname.replace(/\/+$/,"")}}function
|
|
868
|
+
irst."}}return r.origin!==Dc?{ok:false,error:`COPILOT_PROVIDER_BASE_URL does not point at ${Dc}: the gateway prices only the provider's own API at its list price (a local model or a reseller bills differ\
|
|
869
|
+
ently, or not at all), so it does not wrap it.`}:{ok:true,ruta:r.pathname.replace(/\/+$/,"")}}function jc(e,t=process.env){if(e==="opencode"||e==="kilo"){let n=$c[e];return Mc(t[n],"http://127.0.0.1:1/v\
|
|
749
870
|
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\
|
|
750
|
-
se the manual recipe in \`bvsala doctor\`.`:null}if(e==="copilot"){let n=
|
|
871
|
+
se the manual recipe in \`bvsala doctor\`.`:null}if(e==="copilot"){let n=Nc(t);return n.ok?null:n.error}return null}function _r(e,t,n,r={},o=process.env){let i=`http://127.0.0.1:${t}`;switch(e){case "c\
|
|
751
872
|
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",
|
|
752
|
-
args:n,env:{ANTHROPIC_BASE_URL:i},nota:'Qwen Code only routes through here with `security.auth.selectedType: "anthropic"` in ~/.qwen/settings.json (see `bvsala doctor`).'};case "opencode":case "kilo":{let s
|
|
753
|
-
a=
|
|
754
|
-
nothing is written to disk. Other providers`+(e==="kilo"?", the Kilo Gateway included,":"")+" go straight to their API and are not metered."}}case "copilot":{let s=
|
|
873
|
+
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=$c[e],
|
|
874
|
+
a=Mc(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}: \
|
|
875
|
+
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=Nc(o);return s.ok?{bin:"copilot",args:n,
|
|
755
876
|
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\
|
|
756
|
-
ider":{if(r.upstreamElegido===
|
|
877
|
+
ider":{if(r.upstreamElegido===Oc){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:Oc,nota:"OpenAI models through \
|
|
757
878
|
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\
|
|
758
879
|
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\
|
|
759
|
-
through the gateway; OpenAI and other providers go direct and are not metered (for OpenAI models: BVSALA_GATEWAY_UPSTREAM=openai bvsala aider)."}}case "codex":{let s=r.modoCodex??"api-key",a=
|
|
880
|
+
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=Em[s];return {
|
|
760
881
|
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\
|
|
761
882
|
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\
|
|
762
|
-
m/v1."}}}}var
|
|
763
|
-
|
|
764
|
-
{tipo:"ayuda",salida:1}}function
|
|
883
|
+
m/v1."}}}}var _m=["gateway","doctor","skill","init"],Bc=new Set(["help","--help","-h"]),Uc=new Set(["version","--version","-v"]);function zc(e){let[t,...n]=e;return t===void 0||Bc.has(t)?{tipo:"ayuda",salida:0}:
|
|
884
|
+
Uc.has(t)?{tipo:"version"}:wn(t)?{tipo:"arrancar",comando:t,resto:n}:_m.includes(t)?n.some(r=>Bc.has(r))?{tipo:"ayuda",salida:0}:n.some(r=>Uc.has(r))?{tipo:"version"}:{tipo:"arrancar",comando:t,resto:n}:
|
|
885
|
+
{tipo:"ayuda",salida:1}}function Fc(e){return e.length===1&&(e[0]==="--help"||e[0]==="-h"||e[0]==="--version")}function Vc(e,t,n){let r=e??{},o=typeof r.puerto=="number"?r.puerto:n;if(r.code==="EADDRI\
|
|
765
886
|
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\
|
|
766
|
-
sion denied (EACCES; ports below 1024 need privileges): use --port ${Math.max(1024,o)} or higher`;let i=e instanceof Error?e.message:String(e);return `could not start the gateway for \`bvsala ${t}\`: ${i}`}function
|
|
767
|
-
activo!==false,espia:r}}function
|
|
887
|
+
sion denied (EACCES; ports below 1024 need privileges): use --port ${Math.max(1024,o)} or higher`;let i=e instanceof Error?e.message:String(e);return `could not start the gateway for \`bvsala ${t}\`: ${i}`}function Tm(e){let t=Number.parseInt(e.slice(8,10),10);return Number.isFinite(t)&&t%2===0?"palanca":"control"}function qc(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.
|
|
888
|
+
activo!==false,espia:r}}function Hc(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\
|
|
768
889
|
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\
|
|
769
|
-
2:espia\`.`,aviso:true};let s=
|
|
770
|
-
ag"?"--upstream":"the environment";return
|
|
771
|
-
OFF (2026-09-09): the arm no longer turns them on"),
|
|
772
|
-
/messages`, there is one /v1 too many; if you see a bare `POST /messages`, one is missing.",
|
|
890
|
+
2:espia\`.`,aviso:true};let s=Tm(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\
|
|
891
|
+
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 \
|
|
892
|
+
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 Im="check: the gateway log must show `[gateway] POST /v1/messages \u2026`; if you see `/v1/v1\
|
|
893
|
+
/messages`, there is one /v1 too many; if you see a bare `POST /messages`, one is missing.",Pm=[{id:"claude",nombre:"Claude Code",binario:"claude",configs:[],detectable:true,receta:({base:e})=>["use `bv\
|
|
773
894
|
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\
|
|
774
895
|
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\
|
|
775
896
|
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\
|
|
@@ -816,185 +937,185 @@ he stream is forwarded but NOT metered; the last chunk then has an empty choices
|
|
|
816
937
|
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",
|
|
817
938
|
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\
|
|
818
939
|
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}" })`,
|
|
819
|
-
"streamed and stream=False requests are both metered."]}];function
|
|
820
|
-
s=>t(join(i,o+s))))}async function
|
|
940
|
+
"streamed and stream=False requests are both metered."]}];function Dm(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(
|
|
941
|
+
s=>t(join(i,o+s))))}async function Wc(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??Dm(t.
|
|
821
942
|
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\
|
|
822
943
|
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\
|
|
823
|
-
y and does not start without one.",""];for(let l of
|
|
824
|
-
etected \u2014 ${[...u?[`binary \`${l.binario}\` on PATH`]:[],...
|
|
825
|
-
`\xBB ${l.id}: ${
|
|
944
|
+
y and does not start without one.",""];for(let l of Pm){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\
|
|
945
|
+
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(
|
|
946
|
+
`\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??Im}`),c.push("");}return c.push("BY\
|
|
826
947
|
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\
|
|
827
948
|
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\
|
|
828
949
|
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\
|
|
829
950
|
) 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 \
|
|
830
951
|
license.","Per-terminal detail: docs/terminales/<terminal>.md"),{texto:c.join(`
|
|
831
|
-
`),detectados:a}}var
|
|
832
|
-
ai","anthropic"]},
|
|
833
|
-
-layer/ai-sdk",mastra:"@bivelio/savings-layer/mastra",langchain:"@bivelio/savings-layer/langchain","anthropic-sdk":"@bivelio/savings-layer/anthropic-sdk",sdk:"@bivelio/savings-layer"},
|
|
834
|
-
4o-mini",anthropic:"claude-haiku-4-5"},
|
|
835
|
-
ELIO_SERVICE_KEY,"],
|
|
952
|
+
`),detectados:a}}var li=["ai-sdk","mastra","langchain","anthropic-sdk","sdk"],Sn={"ai-sdk":["openai","anthropic"],mastra:["openai","anthropic"],langchain:["openai","anthropic"],"anthropic-sdk":["anthropic"],sdk:["open\
|
|
953
|
+
ai","anthropic"]},En={"ai-sdk":"Vercel AI SDK",mastra:"Mastra",langchain:"LangChain.js","anthropic-sdk":"Anthropic TypeScript SDK",sdk:"the SDK directly (no framework)"},ui={"ai-sdk":"@bivelio/savings\
|
|
954
|
+
-layer/ai-sdk",mastra:"@bivelio/savings-layer/mastra",langchain:"@bivelio/savings-layer/langchain","anthropic-sdk":"@bivelio/savings-layer/anthropic-sdk",sdk:"@bivelio/savings-layer"},Om={openai:"gpt-\
|
|
955
|
+
4o-mini",anthropic:"claude-haiku-4-5"},Gc="What is 2 + 2 * 3?",xn=["licenseKey: process.env.BIVELIO_LICENSE_KEY,",'licenseServerUrl: "https://savings.bivelio.com",',"serviceAccountKey: process.env.BIV\
|
|
956
|
+
ELIO_SERVICE_KEY,"],Lm=["onReport: (report) => {"," seen.calls += 1;"," seen.avoidedLlm = report.calls.avoidedLlm;"," seen.basis = report.cost.basis;","},"];function Kc(e,t){switch(e){case "ai-sdk":
|
|
836
957
|
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\
|
|
837
|
-
hropic"];case "anthropic-sdk":return ["@anthropic-ai/sdk"];case "sdk":return []}}function
|
|
958
|
+
hropic"];case "anthropic-sdk":return ["@anthropic-ai/sdk"];case "sdk":return []}}function Be(e,t){let n=" ".repeat(t);return e.map(r=>r===""?"":n+r)}function Xe(e){return e?"export ":""}function Wt(e,t){let n=Om[t];
|
|
838
959
|
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\
|
|
839
|
-
velio/savings-layer/ai-sdk";'],adaptador:"savings",construir:(o,i)=>[`${
|
|
840
|
-
(generateText, streamText\u2026).","// `savings` goes LAST in the middleware list: nothing between it and the model."]:[],`${
|
|
960
|
+
velio/savings-layer/ai-sdk";'],adaptador:"savings",construir:(o,i)=>[`${Xe(i)}const savings = savingsMiddleware({`,...Be([...xn,...o],2),"});",...i?["","// Pass `model` wherever you pass a model today\
|
|
961
|
+
(generateText, streamText\u2026).","// `savings` goes LAST in the middleware list: nothing between it and the model."]:[],`${Xe(i)}const model = wrapLanguageModel({ model: ${r}("${n}"), middleware: s\
|
|
841
962
|
avings });`],exporta:["model"],importsDeUso:['import { generateText } from "ai";','import { getSavingsReport } from "@bivelio/savings-layer/ai-sdk";'],llamar:o=>[`const result = await generateText({ m\
|
|
842
963
|
odel, ${o==="prompt"?"prompt":`prompt: ${o}`} });`,"const text = result.text;","const basis = getSavingsReport(result)?.cost.basis;"],daBasis:true,importsDeComprobacion:['import { generateText } from "a\
|
|
843
964
|
i";'],preguntar:o=>[`const { text } = await generateText({ model, prompt: ${o} });`]}}case "mastra":return {imports:['import { Agent } from "@mastra/core/agent";','import { savingsProcessor } from "@biv\
|
|
844
|
-
elio/savings-layer/mastra";'],adaptador:"bivelio",construir:(r,o)=>[`${
|
|
845
|
-
ach agent you already have;","// this one shows where. Its reports go to `onReport` if you pass one above."]:[],`${
|
|
965
|
+
elio/savings-layer/mastra";'],adaptador:"bivelio",construir:(r,o)=>[`${Xe(o)}const bivelio = savingsProcessor({`,...Be([...xn,...r],2),"});",...o?["","// Add `bivelio` LAST to the inputProcessors of e\
|
|
966
|
+
ach agent you already have;","// this one shows where. Its reports go to `onReport` if you pass one above."]:[],`${Xe(o)}const agent = new Agent({`,' id: "assistant",',' name: "Assistant",',' instr\
|
|
846
967
|
uctions: "Answer briefly.",',` model: "${t}/${n}",`," inputProcessors: [bivelio],","});"],exporta:["agent"],importsDeUso:[],llamar:r=>[`const result = await agent.generate(${r});`,"const text = resu\
|
|
847
968
|
lt.text;"],daBasis:false,importsDeComprobacion:[],preguntar:r=>[`const { text } = await agent.generate(${r});`]};case "langchain":return {imports:['import { createAgent } from "langchain";','import { savin\
|
|
848
|
-
gsAgentMiddleware } from "@bivelio/savings-layer/langchain";'],adaptador:"savings",construir:(r,o)=>[`${
|
|
849
|
-
vings` LAST to the middleware of each agent you already have; this one shows where."]:[],`${
|
|
969
|
+
gsAgentMiddleware } from "@bivelio/savings-layer/langchain";'],adaptador:"savings",construir:(r,o)=>[`${Xe(o)}const savings = savingsAgentMiddleware({`,...Be([...xn,...r],2),"});",...o?["","// Add `sa\
|
|
970
|
+
vings` LAST to the middleware of each agent you already have; this one shows where."]:[],`${Xe(o)}const agent = createAgent({ model: "${t}:${n}", tools: [], middleware: [savings] });`],exporta:["agent"],
|
|
850
971
|
importsDeUso:['import { getSavingsReportFromMessage } from "@bivelio/savings-layer/langchain";'],llamar:r=>[`const state = await agent.invoke({ messages: [{ role: "user", content: ${r} }] });`,"const \
|
|
851
972
|
last = state.messages.at(-1);",'const text = last?.text ?? "";',"const basis = getSavingsReportFromMessage(last)?.cost.basis;"],daBasis:true,importsDeComprobacion:[],preguntar:r=>[`const state = await a\
|
|
852
973
|
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: \
|
|
853
974
|
"${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 \
|
|
854
|
-
Anthropic from "@anthropic-ai/sdk";','import { anthropicSavings } from "@bivelio/savings-layer/anthropic-sdk";'],adaptador:"claudeSavings",construir:(i,s)=>[`${
|
|
855
|
-
ings({`,...
|
|
975
|
+
Anthropic from "@anthropic-ai/sdk";','import { anthropicSavings } from "@bivelio/savings-layer/anthropic-sdk";'],adaptador:"claudeSavings",construir:(i,s)=>[`${Xe(s)}const claudeSavings = anthropicSav\
|
|
976
|
+
ings({`,...Be([...xn,...i],2),"});",...s?["","// Use `client` for messages.create(); `claudeSavings.middleware` goes LAST in the list."]:[],`${Xe(s)}const client = new Anthropic({ middleware: [claudeS\
|
|
856
977
|
avings.middleware] });`],exporta:["client","claudeSavings"],importsDeUso:[],llamar:i=>[r(i),o,"const basis = claudeSavings.reportFor(message)?.cost.basis;"],daBasis:true,importsDeComprobacion:[],preguntar:i=>[
|
|
857
978
|
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\
|
|
858
979
|
vider({ apiKey: process.env.ANTHROPIC_API_KEY }),",i=t==="openai"?"OpenAICompatibleProvider":"AnthropicProvider";return {imports:[t==="openai"?`import { createSavingsLayer, ${i} } from "@bivelio/saving\
|
|
859
980
|
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."]:
|
|
860
|
-
[],`${
|
|
981
|
+
[],`${Xe(c)}const layer = createSavingsLayer({`,...Be([o,...xn,...a],2),"});"],exporta:["layer"],importsDeUso:[],llamar:a=>[`const { text, report } = await layer.generate({ model: "${r}", messages: [{\
|
|
861
982
|
role: "user", content: ${a} }] });`,"const basis = report.cost.basis;"],daBasis:true,importsDeComprobacion:[],preguntar:a=>[`const { text, report } = await layer.generate({ model: "${r}", messages: [{ \
|
|
862
|
-
role: "user", content: ${a} }] });`]}}}}function
|
|
983
|
+
role: "user", content: ${a} }] });`]}}}}function di(e,t){let n=Wt(e,t);return ["// BiVelio Savings Layer: created once, when this module loads, and reused by every","// request. The exact cache lives i\
|
|
863
984
|
n this instance, so do not create one per request.",...n.imports,"",...n.construir([],true),""].join(`
|
|
864
|
-
`)}var
|
|
985
|
+
`)}var Jc=["// 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 \
|
|
865
986
|
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\
|
|
866
|
-
ile once it says ok."];function
|
|
987
|
+
ile once it says ok."];function Yc(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\
|
|
867
988
|
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" \
|
|
868
989
|
&& 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\
|
|
869
990
|
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\
|
|
870
|
-
.`;"]}function
|
|
871
|
-
imports:r,cuerpo:o}}function
|
|
872
|
-
new Set,t.set(s,a),n.push({modulo:s}));for(let c of i.split(", "))a.add(c);}return n.map(r=>typeof r=="string"?r:`import { ${[...t.get(r.modulo)??[]].sort().join(", ")} } from "${r.modulo}";`)}function
|
|
873
|
-
let n=
|
|
991
|
+
.`;"]}function Zc(e,t){let n=Wt(e,t),r=pi([...n.importsDeComprobacion,...n.imports]),o=e==="sdk"?n.construir([],false):['const seen = { calls: 0, avoidedLlm: 0, basis: "" };',...n.construir(Lm,false)];return {
|
|
992
|
+
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=
|
|
993
|
+
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 Xc(e,t){
|
|
994
|
+
let n=Wt(e,t),{imports:r,cuerpo:o}=Zc(e,t);return [...Jc,...r,"",...o,"","try {",...Be([...n.preguntar(JSON.stringify(Gc)),...Yc(e),"console.log(line);","if (!ok) process.exitCode = 1;"],2),"} catch (e\
|
|
874
995
|
rr) {"," console.log(`not ok: ${err instanceof Error ? err.message : String(err)}`);"," process.exitCode = 1;","} finally {",` ${n.adaptador}.close();`,"}",""].join(`
|
|
875
|
-
`)}function
|
|
876
|
-
rt const dynamic = "force-dynamic";',"","export async function GET() {",' if (process.env.NODE_ENV === "production") {',' return new Response("Not found", { status: 404 });'," }",...
|
|
877
|
-
y {",...
|
|
996
|
+
`)}function Qc(e,t){let n=Wt(e,t),{imports:r,cuerpo:o}=Zc(e,t);return [...Jc,"// It answers only in development: in production it is a 404.",...r,"","// Run on each request, never at build time.",'expo\
|
|
997
|
+
rt const dynamic = "force-dynamic";',"","export async function GET() {",' if (process.env.NODE_ENV === "production") {',' return new Response("Not found", { status: 404 });'," }",...Be(o,2)," tr\
|
|
998
|
+
y {",...Be([...n.preguntar(JSON.stringify(Gc)),...Yc(e),"return Response.json({ ok, message: line }, { status: ok ? 200 : 500 });"],4)," } catch (err) {"," return Response.json({ ok: false, messag\
|
|
878
999
|
e: `not ok: ${err instanceof Error ? err.message : String(err)}` }, { status: 500 });"," } finally {",` ${n.adaptador}.close();`," }","}",""].join(`
|
|
879
|
-
`)}function
|
|
880
|
-
async function POST(req${n.ts?": Request":""}) {`,` const { prompt } = ${n.ts?"(await req.json()) as { prompt: string }":"await req.json()"};`,...
|
|
1000
|
+
`)}function el(e,t,n){let r=Wt(e,t),o=r.daBasis?"{ text, basis }":"{ text }";return [...pi(r.importsDeUso),`import { ${r.exporta.slice().sort().join(", ")} } from "${n.importeDelCableado}";`,"",`export\
|
|
1001
|
+
async function POST(req${n.ts?": Request":""}) {`,` const { prompt } = ${n.ts?"(await req.json()) as { prompt: string }":"await req.json()"};`,...Be(r.llamar("prompt"),2),` return Response.json(${o}\
|
|
881
1002
|
);`,"}",""].join(`
|
|
882
|
-
`)}function
|
|
883
|
-
he handler: the exact cache lives in this instance.",...n.construir([],false),"","const app = express();","app.use(express.json());","",'app.post("/api/chat", async (req, res, next) => {'," try {",...
|
|
1003
|
+
`)}function tl(e,t){let n=Wt(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\
|
|
1004
|
+
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 {",...Be(
|
|
884
1005
|
n.llamar('String(req.body?.prompt ?? "")'),4),` res.json(${r});`," } catch (err) {"," next(err);"," }","});","","app.listen(Number(process.env.PORT ?? 3000));",""].join(`
|
|
885
|
-
`)}var
|
|
1006
|
+
`)}var Tr="usage: bvsala init [--write [--yes]] [--json] [--stack ai-sdk|mastra|langchain|anthropic-sdk|sdk] [--provider openai|anthropic] [--cwd <dir>]";function sl(e,t){let n={cwd:t,escribir:false,si:false,json:false};
|
|
886
1007
|
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.
|
|
887
|
-
json=true;else if(o==="--stack"){let s=i();if(!s||!
|
|
888
|
-
${
|
|
889
|
-
${
|
|
890
|
-
${
|
|
891
|
-
${
|
|
892
|
-
--yes."}:n.capa&&n.proveedor&&!
|
|
893
|
-
pm"],["yarn.lock","yarn"],["bun.lock","bun"],["bun.lockb","bun"],["package-lock.json","npm"]];function
|
|
894
|
-
r==="yarn"||r==="bun"||r==="npm")return r}for(let r=t,o=0;o<20;o++){for(let[s,a]of
|
|
895
|
-
e.dependencies])if(n&&typeof n=="object")for(let[r,o]of Object.entries(n))typeof o=="string"&&(t[r]=o);return t}function
|
|
1008
|
+
json=true;else if(o==="--stack"){let s=i();if(!s||!li.includes(s))return {ok:false,mensaje:`--stack needs one of: ${li.join(", ")}.
|
|
1009
|
+
${Tr}`};n.capa=s;}else if(o==="--provider"){let s=i();if(s!=="openai"&&s!=="anthropic")return {ok:false,mensaje:`--provider needs openai or anthropic.
|
|
1010
|
+
${Tr}`};n.proveedor=s;}else if(o==="--cwd"){let s=i();if(!s)return {ok:false,mensaje:`--cwd needs a directory.
|
|
1011
|
+
${Tr}`};n.cwd=s.startsWith("/")||/^[A-Za-z]:[\\/]/.test(s)?s:join(t,s);}else return {ok:false,mensaje:`unknown option: ${o}
|
|
1012
|
+
${Tr}`}}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 \
|
|
1013
|
+
--yes."}:n.capa&&n.proveedor&&!Sn[n.capa].includes(n.proveedor)?{ok:false,mensaje:`--stack ${n.capa} only works with --provider ${Sn[n.capa].join(" or ")}.`}:{ok:true,valor:n}}var $m=[["pnpm-lock.yaml","pn\
|
|
1014
|
+
pm"],["yarn.lock","yarn"],["bun.lock","bun"],["bun.lockb","bun"],["package-lock.json","npm"]];function Mm(e,t,n){if(typeof e.packageManager=="string"){let r=e.packageManager.split("@")[0];if(r==="pnpm"||
|
|
1015
|
+
r==="yarn"||r==="bun"||r==="npm")return r}for(let r=t,o=0;o<20;o++){for(let[s,a]of $m)if(n.existe(join(r,s)))return a;let i=dirname(r);if(i===r)break;r=i;}return "npm"}function Nm(e){let t={};for(let n of [e.devDependencies,
|
|
1016
|
+
e.dependencies])if(n&&typeof n=="object")for(let[r,o]of Object.entries(n))typeof o=="string"&&(t[r]=o);return t}function jm(e,t,n,r){let o=r.leer(join(n,"node_modules",...e.split("/"),"package.json"));if(o)
|
|
896
1017
|
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(
|
|
897
|
-
t)))return `${i[1]}.${i[2]??0}.${i[3]??0}`}function
|
|
898
|
-
r[o])return n[o]>r[o];return true}var
|
|
1018
|
+
t)))return `${i[1]}.${i[2]??0}.${i[3]??0}`}function hi(e){let[t=0,n=0,r=0]=e.split(/[.+-]/).map(o=>Number.parseInt(o,10)||0);return [t,n,r]}function gi(e,t){let n=hi(e),r=hi(t);for(let o=0;o<3;o++)if(n[o]!==
|
|
1019
|
+
r[o])return n[o]>r[o];return true}var al=[{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\
|
|
899
1020
|
\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\
|
|
900
|
-
angchain/core \u2265 1.1 < 2"},{paquete:"@anthropic-ai/sdk",capa:"anthropic-sdk",desde:"0.103.0",hasta:"1.0.0",texto:"@anthropic-ai/sdk \u2265 0.103 < 1"}],
|
|
901
|
-
langchain"],["ai","ai-sdk"],["@anthropic-ai/sdk","anthropic-sdk"],["openai","sdk"]];function
|
|
902
|
-
.py","Pipfile"].find(
|
|
1021
|
+
angchain/core \u2265 1.1 < 2"},{paquete:"@anthropic-ai/sdk",capa:"anthropic-sdk",desde:"0.103.0",hasta:"1.0.0",texto:"@anthropic-ai/sdk \u2265 0.103 < 1"}],cl=[["@mastra/core","mastra"],["langchain","\
|
|
1022
|
+
langchain"],["ai","ai-sdk"],["@anthropic-ai/sdk","anthropic-sdk"],["openai","sdk"]];function ll(e,t){let n=t.leer(join(e,"package.json"));if(n===void 0){let u=["pyproject.toml","requirements.txt","setup\
|
|
1023
|
+
.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\
|
|
903
1024
|
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\
|
|
904
1025
|
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\
|
|
905
1026
|
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\
|
|
906
|
-
t a JSON object. Fix it and run init again.`};let o=
|
|
907
|
-
xpress"in i?"express":"node",c=
|
|
1027
|
+
t a JSON object. Fix it and run init again.`};let o=Nm(r),i={};for(let[u,f]of Object.entries(o))i[u]=jm(u,f,e,t);let s=["app","src/app"].find(u=>t.existe(join(e,...u.split("/")))),a="next"in i?"next":"e\
|
|
1028
|
+
xpress"in i?"express":"node",c=cl.filter(([u])=>u in i).map(([,u])=>u),l={dir:e,gestor:Mm(r,e,t),ts:"typescript"in i||t.existe(join(e,"tsconfig.json")),esm:r.type==="module",anfitrion:a,src:t.existe(join(
|
|
908
1029
|
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"},
|
|
909
|
-
|
|
910
|
-
var
|
|
1030
|
+
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}}
|
|
1031
|
+
var rl=(e,t)=>t.some(n=>n in e.deps),Bm=["openai","@ai-sdk/openai","@langchain/openai"],Um=["@anthropic-ai/sdk","@ai-sdk/anthropic","@langchain/anthropic"];function zm(e,t){if(e==="anthropic-sdk")return "\
|
|
911
1032
|
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\
|
|
912
|
-
ain/anthropic"in t.deps)return "anthropic"}return
|
|
913
|
-
|
|
914
|
-
`node --env-file=${t} bivelio-check.mjs`:"node bivelio-check.mjs"}function
|
|
915
|
-
. Upgrade Node and run init again.`};let o=[],i=t.capa,s=[];if(i){let
|
|
916
|
-
i=
|
|
1033
|
+
ain/anthropic"in t.deps)return "anthropic"}return rl(t,Um)&&!rl(t,Bm)?"anthropic":"openai"}function ol(e,t){for(let n of al){if(n.capa!==e)continue;let r=t.deps[n.paquete];if(r!==void 0&&(!gi(r,n.desde)||
|
|
1034
|
+
gi(r,n.hasta)))return `${n.paquete} ${r} is outside what the adapter supports (${n.texto})`}}var fi={npm:"npm i",pnpm:"pnpm add",yarn:"yarn add",bun:"bun add"};function Fm(e){let t=e.ficherosEnv[0];return t?
|
|
1035
|
+
`node --env-file=${t} bivelio-check.mjs`:"node bivelio-check.mjs"}function ul(e,t,n){let[r=0]=hi(n.node);if(r<20)return {ok:false,mensaje:`Node ${n.node} is too old: @bivelio/savings-layer needs Node \u2265 20\
|
|
1036
|
+
. Upgrade Node and run init again.`};let o=[],i=t.capa,s=[];if(i){let m=ol(i,e);m&&o.push(`${m}: the snippets below will not work until you upgrade it.`);}else for(let m of e.capas){let b=ol(m,e);if(!b){
|
|
1037
|
+
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\
|
|
917
1038
|
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`."));
|
|
918
|
-
for(let
|
|
919
|
-
gestor]} ${
|
|
920
|
-
savings-layer");for(let
|
|
921
|
-
"0.4.25")&&o.push(`@bivelio/savings-layer ${l} has no framework adapters (they arrived in 0.4.25): ${
|
|
1039
|
+
for(let m of s){let b=al.find(v=>v.capa===m.capa&&m.motivo.startsWith(`${v.paquete} `))?.paquete??"";o.push(`${m.motivo}: showing ${En[i]} instead. To use the ${En[m.capa]} adapter, upgrade it: ${fi[e.
|
|
1040
|
+
gestor]} ${b}@latest`);}let a=t.proveedor??zm(i,e);if(!Sn[i].includes(a))return {ok:false,mensaje:`--stack ${i} only works with --provider ${Sn[i].join(" or ")}.`};let c=[];e.yaInstalado||c.push("@bivelio/\
|
|
1041
|
+
savings-layer");for(let m of Kc(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&&!gi(l,
|
|
1042
|
+
"0.4.25")&&o.push(`@bivelio/savings-layer ${l} has no framework adapters (they arrived in 0.4.25): ${fi[e.gestor]} @bivelio/savings-layer@latest`),r<22&&(i==="mastra"||i==="ai-sdk"&&(e.deps.ai??"7").startsWith(
|
|
922
1043
|
"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\
|
|
923
|
-
" and the package is ESM-only. The check is a .mjs file and runs as is; from your own CommonJS files, load it with `await import(\u2026)`, or with require() on Node \u2265 22.');let
|
|
1044
|
+
" 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\
|
|
924
1045
|
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\
|
|
925
|
-
ewal"}];if(i==="anthropic-sdk")
|
|
926
|
-
est without credentials"});else {let
|
|
927
|
-
"your provider key; the free check does not need it";
|
|
1046
|
+
ewal"}];if(i==="anthropic-sdk")p.push({nombre:"ANTHROPIC_API_KEY",puesta:n.env("ANTHROPIC_API_KEY")||n.env("ANTHROPIC_AUTH_TOKEN"),para:"needed even by the free check: the Anthropic SDK builds no requ\
|
|
1047
|
+
est without credentials"});else {let m=a==="openai"?"OPENAI_API_KEY":"ANTHROPIC_API_KEY",b=i==="mastra"?"your provider key; the free check works without it, but Mastra logs a warning with a stack trace":
|
|
1048
|
+
"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\
|
|
928
1049
|
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\
|
|
929
|
-
it to node with --env-file (Node \u2265 20.6).",
|
|
930
|
-
return c.length>0&&(
|
|
931
|
-
s=
|
|
932
|
-
a.push({ruta:
|
|
933
|
-
r (example: ${
|
|
934
|
-
o),existe:s(
|
|
1050
|
+
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};
|
|
1051
|
+
return c.length>0&&(f.comandoDeInstalacion=`${fi[e.gestor]} ${c.join(" ")}`),{ok:true,valor:f}}function dl(e,t){let n=e.deteccion,{capa:r,proveedor:o}=e,i=n.ts?"ts":n.esm||n.anfitrion==="next"?"js":"mjs",
|
|
1052
|
+
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){
|
|
1053
|
+
a.push({ruta:p,proposito:"wiring",contenido:di(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\
|
|
1054
|
+
r (example: ${f})`,ruta:f,contenido:el(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:Qc(r,
|
|
1055
|
+
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).`,
|
|
935
1056
|
'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\
|
|
936
|
-
ed once at startup, then used by the route",ruta:`server.${i}`,contenido:
|
|
937
|
-
contenido:
|
|
1057
|
+
ed once at startup, then used by the route",ruta:`server.${i}`,contenido:tl(r,o)}):a.push({ruta:p,proposito:"wiring",contenido:di(r,o),existe:s(p)}),a.push({ruta:"bivelio-check.mjs",proposito:"check",
|
|
1058
|
+
contenido:Xc(r,o),existe:s("bivelio-check.mjs")}),l.push(`Run it: ${Fm(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.
|
|
938
1059
|
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\
|
|
939
1060
|
(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\
|
|
940
|
-
ck once it says ok."),{...e,ficheros:a,usos:c,comoComprobar:l,avisos:u}}function
|
|
1061
|
+
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} -----
|
|
941
1062
|
${t.replace(/\n$/,"")}
|
|
942
|
-
${n}`}function
|
|
943
|
-
push(`Express${e.versionDelAnfitrion?` ${e.versionDelAnfitrion}`:""}`):t.push("Node.js"),t.push(e.ts?"TypeScript":e.esm?"JavaScript (ESM)":"JavaScript (CommonJS)"),t.push(e.gestor),t.join(", ")}function
|
|
944
|
-
let t=e.deteccion,n=
|
|
945
|
-
yet)"} with ${e.proveedor==="openai"?"OpenAI":"Anthropic"} models \u2192 ${
|
|
946
|
-
${
|
|
1063
|
+
${n}`}function Vm(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.
|
|
1064
|
+
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 qm(e){
|
|
1065
|
+
let t=e.deteccion,n=cl.find(([,s])=>s===e.capa)?.[0],r=n?t.deps[n]:void 0,o=t.capas.includes(e.capa);return `${`${En[e.capa]}${o&&r&&e.capa!=="sdk"?` ${r}`:""}`}${o||e.capa==="sdk"?"":" (not installed \
|
|
1066
|
+
yet)"} with ${e.proveedor==="openai"?"OpenAI":"Anthropic"} models \u2192 ${ui[e.capa]}`}function pl(e,t,n,r={}){let o=e.deteccion,i=[t,"",`Detected in ${o.dir}`,` app: ${Vm(o)}`,` LLM calls: \
|
|
1067
|
+
${qm(e)}`];if(e.alternativas.length>0&&i.push(` also found: ${e.alternativas.map(u=>`${En[u]} (${n} --stack ${u})`).join(", ")}`),o.yaInstalado){let u=o.deps["@bivelio/savings-layer"];i.push(` inst\
|
|
947
1068
|
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}`:
|
|
948
1069
|
" 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.
|
|
949
1070
|
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/\
|
|
950
1071
|
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");
|
|
951
|
-
i.push("",`${s++} \xB7 Wire it`),c&&i.push(
|
|
952
|
-
find(u=>u.proposito==="check");i.push("",`${s++} \xB7 Check it, for free`),l&&i.push(
|
|
953
|
-
i.push(` ${u}`);let
|
|
954
|
-
e (${
|
|
1072
|
+
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.
|
|
1073
|
+
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)
|
|
1074
|
+
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\
|
|
1075
|
+
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(`\
|
|
955
1076
|
|
|
956
|
-
`)}function
|
|
957
|
-
gestor,stacks:n.capas,installed:n.yaInstalado?n.deps["@bivelio/savings-layer"]??n.yaInstalado:null},stack:e.capa,provider:e.proveedor,adapter:
|
|
1077
|
+
`)}function fl(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.
|
|
1078
|
+
gestor,stacks:n.capas,installed:n.yaInstalado?n.deps["@bivelio/savings-layer"]??n.yaInstalado:null},stack:e.capa,provider:e.proveedor,adapter:ui[e.capa],install:e.comandoDeInstalacion??null,keys:e.claves.
|
|
958
1079
|
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.
|
|
959
|
-
contenido})),check:e.comoComprobar,notes:e.avisos},null,2)}async function
|
|
1080
|
+
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}\
|
|
960
1081
|
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\
|
|
961
1082
|
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(
|
|
962
1083
|
"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\
|
|
963
1084
|
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(
|
|
964
1085
|
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(`\
|
|
965
|
-
could not create ${a.ruta}: ${l instanceof Error?l.message:String(l)}`));}}return {salida:s,lineas:n,creados:r}}var
|
|
966
|
-
|
|
1086
|
+
could not create ${a.ruta}: ${l instanceof Error?l.message:String(l)}`));}}return {salida:s,lineas:n,creados:r}}var hl="savings-mode";function gl(e,t){for(let n of e){let r=join(n,"skills",hl,"SKILL.md");if(t.existe(r))return r}return null}var bl="<!-- bvsala:savings-mode:inicio -->",
|
|
1087
|
+
Ar="<!-- bvsala:savings-mode:fin -->";function Hm(e){let t=e.replace(/^---\n[\s\S]*?\n---\n*/,"").trim();return `${bl}
|
|
967
1088
|
${t}
|
|
968
1089
|
|
|
969
1090
|
_Always on (AGENTS.md has no activation step). Delete this block to turn it off; \`bvsala skill --codex --force\` restores it._
|
|
970
|
-
${
|
|
1091
|
+
${Ar}`}function vl(e){let t=gl(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=Hm(e.fs.leer(t)),
|
|
971
1092
|
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+`
|
|
972
|
-
`),{ok:true,destino:o,mensaje:
|
|
1093
|
+
`),{ok:true,destino:o,mensaje:bi(o,"installed")};let i=e.fs.leer(o),s=i.indexOf(bl),a=i.indexOf(Ar);return s===-1||a===-1||a<s?(e.fs.escribir(o,i.trimEnd()+`
|
|
973
1094
|
|
|
974
1095
|
`+n+`
|
|
975
|
-
`),{ok:true,destino:o,mensaje:
|
|
976
|
-
o,i.slice(0,s)+n+i.slice(a+
|
|
977
|
-
it; use --force to update it`}}function
|
|
1096
|
+
`),{ok:true,destino:o,mensaje:bi(o,"appended to the existing AGENTS.md")}):i.slice(s,a+Ar.length)===n?{ok:true,destino:o,mensaje:`[bvsala skill] already installed and up to date: ${o}`}:e.forzar?(e.fs.escribir(
|
|
1097
|
+
o,i.slice(0,s)+n+i.slice(a+Ar.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 \
|
|
1098
|
+
it; use --force to update it`}}function bi(e,t){return `[bvsala skill] ${t}: ${e}
|
|
978
1099
|
[bvsala skill] AGENTS.md is ALWAYS active in Codex (there is no activation step); delete the block to turn it off.
|
|
979
|
-
[bvsala skill] to measure its effect: work a few days with it and a few without, under \`bvsala codex\`, and compare in the dashboard.`}function
|
|
980
|
-
mensaje:`[bvsala skill] cannot find the bundled SKILL.md (roots tried: ${e.origenes.join(", ")})`};let n=e.proyecto?join(e.cwd,".claude","skills"):join(e.home,".claude","skills"),r=join(n,
|
|
1100
|
+
[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 yl(e){let t=gl(e.origenes,e.fs);if(!t)return {ok:false,destino:"",
|
|
1101
|
+
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,hl),o=join(r,"SKILL.\
|
|
981
1102
|
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\
|
|
982
1103
|
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}
|
|
983
1104
|
[bvsala skill] start (or restart) Claude Code and ask for "savings mode" \u2014 or let it activate on its own when you mention limits.
|
|
984
|
-
[bvsala skill] to measure its real effect: work a few days with it and a few without, under \`bvsala claude\`, and compare in the dashboard.`}}var
|
|
1105
|
+
[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 vi=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.
|
|
985
1106
|
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,
|
|
986
|
-
Math.ceil(t.length/4))}},
|
|
1107
|
+
Math.ceil(t.length/4))}},yi=new vi;var ki=class{estimators=new Map;modelToTokenizer=new Map;fallbackId;constructor(t=yi){this.fallbackId=t.id,this.estimators.set(t.id,t);}register(t){return this.estimators.set(t.id,t),this}mapModel(t,n){
|
|
987
1108
|
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.
|
|
988
|
-
get(r);if(o)return o}}return this.estimators.get(this.fallbackId)}count(t,n){return this.resolve(n).count(t)}};new
|
|
989
|
-
"text-embedding-3-large"]};var
|
|
990
|
-
"fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"];
|
|
991
|
-
decena",v:20+10*t}));C("hundred hundreds",{k:"cien"});C("thousand thousands",{k:"escala",v:1e3});C("million millions",{k:"escala",v:1e6});C("billion billions",{k:"escala",v:1e9});var
|
|
992
|
-
econd","third","fourth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelfth","thirteenth","fourteenth","fifteenth","sixteenth","seventeenth","eighteenth","nineteenth"];
|
|
1109
|
+
get(r);if(o)return o}}return this.estimators.get(this.fallbackId)}count(t,n){return this.resolve(n).count(t)}};new ki;var wl={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",
|
|
1110
|
+
"text-embedding-3-large"]};var Zm=new Map;function C(e,t){for(let n of e.split(/\s+/).filter(Boolean))Zm.set(n,t);}var Xm=["zero","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen",
|
|
1111
|
+
"fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"];Xm.forEach((e,t)=>C(e,{k:"unidad",v:t}));["twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"].forEach((e,t)=>C(e,{k:"\
|
|
1112
|
+
decena",v:20+10*t}));C("hundred hundreds",{k:"cien"});C("thousand thousands",{k:"escala",v:1e3});C("million millions",{k:"escala",v:1e6});C("billion billions",{k:"escala",v:1e9});var Qm=["","first","s\
|
|
1113
|
+
econd","third","fourth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelfth","thirteenth","fourteenth","fifteenth","sixteenth","seventeenth","eighteenth","nineteenth"];Qm.forEach((e,t)=>{
|
|
993
1114
|
e&&(C(e,{k:"ordinal",v:t}),t>=3&&C(`${e}s`,{k:"ordinal",v:t}));});["twentieth","thirtieth","fortieth","fiftieth","sixtieth","seventieth","eightieth","ninetieth"].forEach((e,t)=>{C(e,{k:"ordinal",v:20+10*
|
|
994
1115
|
t}),C(`${e}s`,{k:"ordinal",v:20+10*t});});C("hundredth hundredths",{k:"ordinal",v:100});C("thousandth thousandths",{k:"ordinal",v:1e3});C("millionth millionths",{k:"ordinal",v:1e6});C("half halves",{k:"\
|
|
995
1116
|
token",t:"f:1/2"});C("quarter quarters",{k:"token",t:"f:1/4"});C("once single",{k:"token",t:"m:1"});C("twice double doubled doubles doubling",{k:"token",t:"m:2"});C("thrice triple tripled triples trip\
|
|
996
1117
|
ling",{k:"token",t:"m:3"});C("quadruple quadrupled quadruples quadrupling",{k:"token",t:"m:4"});C("dozen dozens",{k:"token",t:"c:12"});C("pair pairs",{k:"token",t:"c:2"});C("times time",{k:"veces"});C(
|
|
997
|
-
"and",{k:"conector"});var
|
|
1118
|
+
"and",{k:"conector"});var eh=["cero","uno","dos","tres","cuatro","cinco","seis","siete","ocho","nueve","diez","","doce","trece","catorce","quince","dieciseis","diecisiete","dieciocho","diecinueve"];eh.
|
|
998
1119
|
forEach((e,t)=>e&&C(e,{k:"unidad",v:t}));C("veinte",{k:"decena",v:20});["veintiuno","veintidos","veintitres","veinticuatro","veinticinco","veintiseis","veintisiete","veintiocho","veintinueve"].forEach(
|
|
999
1120
|
(e,t)=>C(e,{k:"unidad",v:21+t}));["treinta","cuarenta","cincuenta","sesenta","setenta","ochenta","noventa"].forEach((e,t)=>C(e,{k:"decena",v:30+10*t}));C("cien ciento",{k:"centena",v:100});[["doscient\
|
|
1000
1121
|
os doscientas",200],["trescientos trescientas",300],["cuatrocientos cuatrocientas",400],["quinientos quinientas",500],["seiscientos seiscientas",600],["setecientos setecientas",700],["ochocientos ocho\
|
|
@@ -1007,9 +1128,9 @@ forEach(([e,t])=>C(e,{k:"ordinal",v:t}));C("mitad mitades medio media medios med
|
|
|
1007
1128
|
uanta","seixanta","setanta","vuitanta","noranta"].forEach((e,t)=>C(e,{k:"decena",v:20+10*t}));C("cent",{k:"centena",v:100});C("cents centes",{k:"cien"});C("milio milions",{k:"escala",v:1e6});[["segon \
|
|
1008
1129
|
segona segons segones",2],["terc tercos",3],["quart quarta quarts quartes",4],["cinque cinquena",5],["sise sisena",6],["sete setena",7],["vuite vuitena",8],["nove novena",9],["dese desena",10]].forEach(
|
|
1009
1130
|
([e,t])=>C(e,{k:"ordinal",v:t}));C("meitat meitats mig mitja",{k:"token",t:"f:1/2"});C("dotzena dotzenes",{k:"token",t:"c:12"});C("parell parells",{k:"token",t:"c:2"});C("vegades vegada",{k:"veces"});
|
|
1010
|
-
C("i",{k:"conector"});var
|
|
1011
|
-
|
|
1012
|
-
argv.slice(2));function
|
|
1131
|
+
C("i",{k:"conector"});var Eh={"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}};
|
|
1132
|
+
Kr(Eh);new Set(Object.values(wl).flatMap(e=>e.flatMap(t=>[t,`openai/${t}`])));function Vh(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 Dr=zc(process.
|
|
1133
|
+
argv.slice(2));function qh(){console.log(`bvsala ${be} \u2014 BiVelio Savings Layer
|
|
1013
1134
|
|
|
1014
1135
|
Commands:
|
|
1015
1136
|
gateway [--port N] [--upstream U]
|
|
@@ -1129,49 +1250,49 @@ forwards and warns. On a Claude or ChatGPT subscription there is no per-token in
|
|
|
1129
1250
|
traffic is metered at list-price equivalent and never carries commission.
|
|
1130
1251
|
Your prompts, completions and provider keys never reach BiVelio: what it receives is per-request
|
|
1131
1252
|
usage (token counts, cost, the model id and opaque ids); LICENSE \xA75 lists every field.
|
|
1132
|
-
More: savings.bivelio.com`);}
|
|
1133
|
-
cwd());e.ok||(console.error(`[bvsala init] ${e.mensaje}`),process.exit(1));let t=e.valor,n={leer:c=>{try{return readFileSync(c,"utf8")}catch{return}},existe:existsSync},r=
|
|
1134
|
-
${r.mensaje}`),process.exit(1));let o=
|
|
1135
|
-
t.json&&(console.log(
|
|
1136
|
-
0),console.log("");let{createInterface:s}=await import('readline/promises'),a=await
|
|
1253
|
+
More: savings.bivelio.com`);}Dr.tipo==="ayuda"&&(qh(),process.exit(Dr.salida));Dr.tipo==="version"&&(console.log(be),process.exit(0));var{comando:G,resto:pe}=Dr,Kt=wn(G);if(G==="init"){let e=sl(pe,process.
|
|
1254
|
+
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=ll(t.cwd,n);r.ok||(console.error(`[bvsala init]\
|
|
1255
|
+
${r.mensaje}`),process.exit(1));let o=ul(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=dl(o.valor,n);
|
|
1256
|
+
t.json&&(console.log(fl(i,be)),process.exit(0)),console.log(pl(i,`bvsala init \xB7 BiVelio Savings Layer ${be}`,"npx @bivelio/savings-layer@latest init",{escribira:t.escribir})),t.escribir||process.exit(
|
|
1257
|
+
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.stdout});
|
|
1137
1258
|
try{return await l.question(c)}finally{l.close();}},crearDir:c=>mkdirSync(c,{recursive:true}),crearExclusivo:(c,l)=>writeFileSync(c,l,{flag:"wx"})});for(let c of a.lineas)(a.salida===0?console.log:console.error)(c);process.
|
|
1138
|
-
exit(a.salida);}if(
|
|
1139
|
-
includes("--force")||
|
|
1140
|
-
exit(n.ok?0:1);}var
|
|
1141
|
-
`[bvsala ${
|
|
1142
|
-
by hand."),process.exit(1));let e=await
|
|
1259
|
+
exit(a.salida);}if(G==="skill"){let e=dirname(fileURLToPath(import.meta.url)),t={origenes:[join(e,"..",".."),join(e,"..")],home:homedir(),cwd:process.cwd(),proyecto:pe.includes("--project")||pe.includes("--proyecto"),forzar:pe.
|
|
1260
|
+
includes("--force")||pe.includes("--forzar"),fs:{existe:existsSync,leer:r=>readFileSync(r,"utf8"),escribir:(r,o)=>writeFileSync(r,o),crearDir:r=>mkdirSync(r,{recursive:true})}},n=pe.includes("--codex")?vl(t):yl(t);console.log(n.mensaje),process.
|
|
1261
|
+
exit(n.ok?0:1);}var Ci=pe.indexOf("--port")>=0?pe.indexOf("--port"):pe.indexOf("--puerto"),_t=Kt?0:Ci>=0?Number(pe[Ci+1]):8402;(!Number.isInteger(_t)||(G==="doctor"?_t<1:_t<0)||_t>65535)&&(console.error(
|
|
1262
|
+
`[bvsala ${G}] invalid port: ${pe[Ci+1]}`),process.exit(1));if(G==="doctor"){pe.includes("--write")&&(console.error("[bvsala doctor] --write does not exist yet: the doctor only prints; copy the block \
|
|
1263
|
+
by hand."),process.exit(1));let e=await Wc(_t);console.log(e.texto),process.exit(0);}function Hh(e,t){wn(e)||process.exit(1);let n=_r(e,0,[],{}).bin;if(process.platform==="win32"){let o=ci(n);o.tipo===
|
|
1143
1264
|
"exe"?n=o.ruta:o.tipo==="solo-shim"&&(console.error(`[bvsala ${e}] \`${n}\` is installed as an npm shim (${o.ruta}) and Windows cannot launch it safely with arguments (CVE-2024-27980). Install it with\
|
|
1144
1265
|
its native installer (which leaves a ${n}.exe on the PATH) or use the manual recipe in docs/terminales/.`),process.exit(127));}let r=spawn(n,t,{stdio:"inherit"});return r.on("error",o=>{console.error(`[b\
|
|
1145
|
-
vsala ${e}] could not launch \`${n}\`: ${String(o)}. Is it installed and on the PATH?`),process.exit(127);}),r.on("exit",(o,i)=>process.exit(o??(i?1:0))),new Promise(()=>{})}
|
|
1146
|
-
if(
|
|
1147
|
-
process.exit(1));var
|
|
1148
|
-
error(`[bvsala ${
|
|
1149
|
-
{}}):null,
|
|
1150
|
-
null&&await
|
|
1151
|
-
upstream??
|
|
1152
|
-
checkOnStart:
|
|
1153
|
-
{},...process.env.BVSALA_GATEWAY_COALESCE==="1"?{coalescer:!0}:{},...process.env.BVSALA_GATEWAY_USAGE_INJECT==="1"?{usageInject:!0}:{},...process.env.BVSALA_GATEWAY_SHADOW==="1"?{sombra:!0}:{},elision:
|
|
1266
|
+
vsala ${e}] could not launch \`${n}\`: ${String(o)}. Is it installed and on the PATH?`),process.exit(127);}),r.on("exit",(o,i)=>process.exit(o??(i?1:0))),new Promise(()=>{})}Kt&&Fc(pe)&&await Hh(G,pe);
|
|
1267
|
+
if(Kt){let e=jc(G);e&&(console.error(`[bvsala ${G}] ${e}`),process.exit(1));}var Wh=G==="gateway"?dc(pe):void 0,fe=pc({flag:Wh,env:process.env.BVSALA_GATEWAY_UPSTREAM});fe.ok||(console.error(fe.error),
|
|
1268
|
+
process.exit(1));var Ll=process.env.BIVELIO_SERVICE_KEY?.trim()||void 0,Tt=await nc({serviceAccountKey:Ll,licenseKey:process.env.BIVELIO_LICENSE_KEY,licenseServerUrl:Zo});Tt.ok||(console.
|
|
1269
|
+
error(`[bvsala ${G}] ${Tt.message}`),process.exit(1));var Ue=Kt?_r(G,0,pe,{modoCodex:G==="codex"?Lc({leerAuth:()=>readFileSync(join(homedir(),".codex","auth.json"),"utf8")}):void 0,...fe.upstream?{upstreamElegido:fe.upstream}:
|
|
1270
|
+
{}}):null,Gh=Kt&&process.env.BVSALA_GATEWAY_LOG!=="1",Ai=Ue?.upstream?null:qc(()=>readFileSync(process.env.BVSALA_ANILLO2_FICHERO??join(homedir(),".bvsala","anillo2.json"),"utf8")),Tn=Hc({enrolamiento:Ai,espiaVivo:Ai!==
|
|
1271
|
+
null&&await Vh(Ai.espia),upstreamEnv:fe.upstream,...fe.origen!=="none"?{upstreamOrigen:fe.origen}:{},elisionEnv:process.env.BVSALA_GATEWAY_ELISION,hoyUtcIso:new Date().toISOString().slice(0,10)}),Ri=fe.
|
|
1272
|
+
upstream??Tn.upstream,Ir=process.env.BVSALA_GATEWAY_ELISION??Tn.elision,Ae;try{Ae=await Ic({puerto:_t,...Gh?{log:()=>{},avisosDeNoMedido:!1}:{},license:{token:Tt.license.token,publicKey:vt,licenseServerUrl:Zo,
|
|
1273
|
+
checkOnStart:Tt.source==="offline"},warn:e=>console.error(e),serviceAccountKey:Ll,...process.env.BVSALA_SEAT_ID?{seatId:process.env.BVSALA_SEAT_ID}:{},...Ri?{upstream:Ri}:Ue?.upstream?{upstream:Ue.upstream}:
|
|
1274
|
+
{},...process.env.BVSALA_GATEWAY_COALESCE==="1"?{coalescer:!0}:{},...process.env.BVSALA_GATEWAY_USAGE_INJECT==="1"?{usageInject:!0}:{},...process.env.BVSALA_GATEWAY_SHADOW==="1"?{sombra:!0}:{},elision:Ir!==
|
|
1154
1275
|
"0",...process.env.BVSALA_GATEWAY_DIALES_ELISION==="1"?{dialesElision:!0}:{},...process.env.BVSALA_GATEWAY_MODELO_HERMANO==="1"?{modeloHermano:!0}:{},...process.env.BVSALA_GATEWAY_ESFUERZO?{esfuerzo:process.
|
|
1155
|
-
env.BVSALA_GATEWAY_ESFUERZO}:{},...process.env.BVSALA_METERING_URL?{meteringUrl:process.env.BVSALA_METERING_URL}:{}});}catch(e){console.error(`[bvsala ${
|
|
1156
|
-
upstream??"https://api.anthropic.com";console.log(`[bvsala gateway] v${
|
|
1157
|
-
line}`);for(let e of
|
|
1276
|
+
env.BVSALA_GATEWAY_ESFUERZO}:{},...process.env.BVSALA_METERING_URL?{meteringUrl:process.env.BVSALA_METERING_URL}:{}});}catch(e){console.error(`[bvsala ${G}] ${Vc(e,G,_t)}`),process.exit(1);}var $l=Ri??Ue?.
|
|
1277
|
+
upstream??"https://api.anthropic.com";console.log(`[bvsala gateway] v${be} listening on http://127.0.0.1:${Ae.puerto} \u2192 ${$l}`);(Tt.lineIsWarning?console.error:console.log)(`[bvsala gateway] ${Tt.
|
|
1278
|
+
line}`);for(let e of Tt.warnings)console.error(`[bvsala gateway] ${e}`);console.log("[bvsala gateway] metering: ON (service key present)");process.env.BVSALA_METERING_URL&&console.error(`[bvsala gatew\
|
|
1158
1279
|
ay] WARNING: BVSALA_METERING_URL=${process.env.BVSALA_METERING_URL} redirects usage reporting away from savings.bivelio.com (development only): your dashboard will not see this usage. The license and \
|
|
1159
|
-
the entitlements channel still use savings.bivelio.com.`);
|
|
1160
|
-
EWAY_USAGE_INJECT=1) \u2014 streamed chat completions without stream_options get include_usage; their last chunk has an empty choices list.");{let e=
|
|
1161
|
-
"1");(e.aviso?console.error:console.log)(`[bvsala gateway] ${e.linea}`);let t=
|
|
1162
|
-
let n=
|
|
1163
|
-
|
|
1164
|
-
hat you want, unset the variable.`);
|
|
1165
|
-
rough but is NOT metered. Use Node >= 22.15.`);var
|
|
1166
|
-
|
|
1167
|
-
platform==="win32"){let r=
|
|
1168
|
-
with arguments (CVE-2024-27980). Install it with its native installer (which leaves a ${e.bin}.exe on the PATH) or use the manual recipe in docs/terminales/.`),await
|
|
1169
|
-
t,e.args,{stdio:"inherit",env:{...process.env,...e.env}});n.on("error",r=>{console.error(`[bvsala ${
|
|
1170
|
-
()=>process.exit(127));}),n.on("exit",(r,o)=>{
|
|
1171
|
-
it: base_url=http://127.0.0.1:${
|
|
1172
|
-
ropic.com"||
|
|
1173
|
-
or for the others`):console.log(`[bvsala gateway] point your client at http://127.0.0.1:${
|
|
1174
|
-
|
|
1280
|
+
the entitlements channel 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_GAT\
|
|
1281
|
+
EWAY_USAGE_INJECT=1) \u2014 streamed chat completions without stream_options get include_usage; their last chunk has an empty choices list.");{let e=Ni(Ir,true,process.env.BVSALA_GATEWAY_DIALES_ELISION===
|
|
1282
|
+
"1");(e.aviso?console.error:console.log)(`[bvsala gateway] ${e.linea}`);let t=ts(process.env.BVSALA_GATEWAY_MODELO_HERMANO,true,Ir!=="0");(t.aviso?console.error:console.log)(`[bvsala gateway] ${t.linea}`);
|
|
1283
|
+
let n=Ji(process.env.BVSALA_GATEWAY_ESFUERZO,true,Ir!=="0");(n.aviso?console.error:console.log)(`[bvsala gateway] ${n.linea}`),Tn.linea&&(Tn.aviso?console.error:console.log)(`[bvsala gateway] ${Tn.linea}`);}
|
|
1284
|
+
fe.upstream&&Ue?.upstream&&fe.upstream!==Ue.upstream&&console.error(`[bvsala ${G}] WARNING: BVSALA_GATEWAY_UPSTREAM=${fe.upstream} overrides this terminal's upstream (${Ue.upstream}). If that is not w\
|
|
1285
|
+
hat you want, unset the variable.`);G==="codex"&&!Da()&&console.error(`[bvsala codex] WARNING: this Node (${process.version}) cannot decompress zstd and Codex sends its body in zstd: traffic passes th\
|
|
1286
|
+
rough but is NOT metered. Use Node >= 22.15.`);var Rl=false;function Ml(){if(Rl)return;Rl=true;let e=Tc(Ae.degradaciones());e&&console.error(e),console.error(fc(Ae.medicion(),G));}if(Ue&&Kt){let e=_r(G,Ae.puerto,
|
|
1287
|
+
pe,{...Ue.upstream?{modoCodex:Ue.upstream.includes("chatgpt.com")?"chatgpt":"api-key"}:{},...fe.upstream?{upstreamElegido:fe.upstream}:{}});e.nota&&console.log(`[bvsala ${G}] ${e.nota}`);let t=e.bin;if(process.
|
|
1288
|
+
platform==="win32"){let r=ci(e.bin);r.tipo==="exe"?t=r.ruta:r.tipo==="solo-shim"&&(console.error(`[bvsala ${G}] \`${e.bin}\` is installed as an npm shim (${r.ruta}) and Windows cannot launch it safely\
|
|
1289
|
+
with arguments (CVE-2024-27980). Install it with its native installer (which leaves a ${e.bin}.exe on the PATH) or use the manual recipe in docs/terminales/.`),await Ae.cerrar(),process.exit(127));}let n=spawn(
|
|
1290
|
+
t,e.args,{stdio:"inherit",env:{...process.env,...e.env}});n.on("error",r=>{console.error(`[bvsala ${G}] could not launch \`${e.bin}\`: ${String(r)}. Is it installed and on the PATH?`),Ae.cerrar().then(
|
|
1291
|
+
()=>process.exit(127));}),n.on("exit",(r,o)=>{Ml(),Ae.cerrar().then(()=>process.exit(r??(o?1:0)));});}else {let e=new URL($l).hostname;e==="api.openai.com"?console.log(`[bvsala gateway] point your SDK at \
|
|
1292
|
+
it: base_url=http://127.0.0.1:${Ae.puerto}/v1 (OpenAI SDKs) \xB7 streamed chat completions are metered when the request sets stream_options.include_usage \xB7 bvsala doctor for recipes`):e==="api.anth\
|
|
1293
|
+
ropic.com"||fe.upstream===void 0?console.log(`[bvsala gateway] point your terminal at it (or use \`bvsala ${ai.join("|")}\`): ANTHROPIC_BASE_URL=http://127.0.0.1:${Ae.puerto} claude \xB7 bvsala doct\
|
|
1294
|
+
or for the others`):console.log(`[bvsala gateway] point your client at http://127.0.0.1:${Ae.puerto} plus the path prefix it already uses (for example /v1) \xB7 bvsala doctor for recipes`);}var Nl=async()=>{
|
|
1295
|
+
Ml(),await Ae.cerrar(),process.exit(0);};process.on("SIGINT",()=>{Nl();});process.on("SIGTERM",()=>{Nl();});
|
|
1175
1296
|
/*! Bundled license information:
|
|
1176
1297
|
|
|
1177
1298
|
@noble/curves/utils.js:
|