@bivelio/savings-layer 0.5.1 → 1.0.0
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/CHANGELOG.md +115 -0
- package/LICENSE +183 -163
- package/LICENSE-CLOUD.md +174 -0
- package/NOTICE +11 -0
- package/README.md +228 -126
- package/dist/adapters/ai-sdk.js +78 -78
- package/dist/adapters/anthropic-sdk.js +88 -88
- package/dist/adapters/langchain.js +58 -58
- package/dist/adapters/mastra.js +70 -70
- package/dist/gateway/bin.js +1291 -1082
- package/dist/index.d.ts +367 -197
- package/dist/index.js +1717 -1641
- package/docs/terminales/README.md +39 -33
- package/docs/terminales/aider.md +1 -1
- package/docs/terminales/claude-code.md +2 -2
- package/docs/terminales/cline.md +1 -1
- package/docs/terminales/codex.md +3 -3
- package/docs/terminales/copilot.md +1 -1
- package/docs/terminales/crush.md +1 -1
- package/docs/terminales/cursor.md +32 -0
- package/docs/terminales/deepseek.md +28 -0
- package/docs/terminales/droid.md +1 -1
- package/docs/terminales/gemini.md +38 -0
- package/docs/terminales/goose.md +2 -2
- package/docs/terminales/kilo.md +2 -2
- package/docs/terminales/no-soportados.md +16 -27
- package/docs/terminales/ollama.md +19 -0
- package/docs/terminales/opencode.md +2 -2
- package/docs/terminales/qwen-code.md +2 -2
- package/package.json +48 -20
package/dist/gateway/bin.js
CHANGED
|
@@ -1,48 +1,134 @@
|
|
|
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
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
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 lt from'zlib';import {connect}from'net';var Ld=Object.defineProperty;var Zs=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var Md=(e,t)=>{for(var n in t)Ld(e,n,{get:t[n],enumerable:true});};function Ol(e){let t=(Array.isArray(e)?e[0]:e)?.trim().toLowerCase();return t==="1"||t==="true"}function Ll(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e;for(let n of [t.message?.
|
|
3
|
+
id,t.response?.id,t.id])if(typeof n=="string"&&er.test(n))return n;return null}function vs(e){try{return Ll(JSON.parse(e.toString("utf8")))}catch{return null}}function xg(e,t){let n=new Map,o={decisions:0,
|
|
4
|
+
applied:0,byReason:{},appliedTokensBefore:0,appliedTokensAfter:0,tokenBasis:"estimated"};for(let r of e){let i=r.report,s=jn(i?.attribution?.sessionId,200),a=n.get(s);if(a||(a={sessionId:s,requests:{total:0,
|
|
5
|
+
metered:0,notMetered:0,pending:0},costByBasis:{},notMeteredReasons:{},models:{}},n.set(s,a)),a.requests.total++,r.status==="pending"){a.requests.pending++;continue}if(r.status==="not_metered"||!i){a.requests.
|
|
6
|
+
notMetered++,gs(a.notMeteredReasons,jn(r.reason)??"unknown");continue}a.requests.metered++;let l=jn(i.model);l&&gs(a.models,l);let c=jn(i.cost?.basis,40)??"unknown",d=a.costByBasis[c]??=wg();d.requests++,
|
|
7
|
+
d.actualUsd+=Nn(i.cost?.actual),d.baselineUsd+=Nn(i.cost?.baselineEstimate),d.netSavingsUsd+=Nn(i.cost?.netSavingsUsd);for(let u of i.toolOutputCompaction?.decisions??[])o.decisions++,gs(o.byReason,jn(
|
|
8
|
+
u.reason,40)??"unknown"),u.status==="applied"&&(o.applied++,o.appliedTokensBefore+=Nn(u.tokensBefore),o.appliedTokensAfter+=Nn(u.tokensAfter));}return {schema:or,window:{reports:e.length,capacity:t,maxAgeMinutes:36e5/
|
|
9
|
+
6e4},sessions:[...n.values()],toolOutputCompaction:o}}function Ml(e){try{return new URL(e).origin}catch{return "unknown"}}function $l(e){let t;try{t=new URL(e??"/","http://127.0.0.1");}catch{return null}
|
|
10
|
+
return t.pathname.startsWith(yg)?t:null}function Eg(e){if(e===void 0||e==="")return true;let t;try{t=new URL(`http://${e}`).hostname.toLowerCase();}catch{return false}return Sg.has(t)}function Zo(e,t,n){e.writeHead(
|
|
11
|
+
t,{"content-type":"application/json","cache-control":"no-store"}),e.end(JSON.stringify(n));}function Ft(e,t,n,o){Zo(e,t,{type:"error",error:{type:n,message:o}});}async function Nl(e,t,n,o){if(e.resume(),
|
|
12
|
+
!Eg(e.headers.host)){Ft(t,403,"forbidden","bvsala gateway: local routes answer only to 127.0.0.1 or localhost");return}if(e.method!=="GET"){t.setHeader("allow","GET"),Ft(t,405,"method_not_allowed","bv\
|
|
13
|
+
sala gateway: local routes only answer GET");return}if(n.pathname==="/_bvsala/v1/status"){Zo(t,200,o.estado());return}if(n.pathname==="/_bvsala/v1/summary"){Zo(t,200,xg(o.buzon.vigentes(),o.buzon.limite));
|
|
14
|
+
return}let r=Number(n.searchParams.get("wait_ms")??"0");if(!Number.isFinite(r)||r<0){Ft(t,400,"invalid_request","bvsala gateway: wait_ms must be a non-negative number of milliseconds");return}let i=Math.
|
|
15
|
+
min(Math.floor(r),3e4),s=new AbortController;t.on("close",()=>s.abort());let a=null,l="",c=/^\/_bvsala\/v1\/reports\/([^/]+)$/.exec(n.pathname);if(c){let u="";try{u=decodeURIComponent(c[1]);}catch{u="";}
|
|
16
|
+
if(!er.test(u)){Ft(t,400,"invalid_request","bvsala gateway: malformed request id");return}a=()=>o.buzon.porPeticion(u),l=`request id ${u}`;}else if(n.pathname==="/_bvsala/v1/reports"){let u=n.searchParams.
|
|
17
|
+
get("response_id")??"";if(!er.test(u)){Ft(t,400,"invalid_request","bvsala gateway: pass ?response_id=<the id of the provider's response>");return}a=()=>o.buzon.porRespuesta(u),l=`response id ${u}`;}if(a===
|
|
18
|
+
null){Ft(t,404,"not_found",`bvsala gateway: no local route ${n.pathname}`);return}let d=await o.buzon.esperar(a,i,s.signal);if(!t.destroyed){if(d===void 0){Ft(t,404,"not_found",`bvsala gateway: no rep\
|
|
19
|
+
ort for ${l}. Reports exist only for requests sent with the header "${Bn}: 1", while this gateway process keeps them (the last ${o.buzon.limite}, one hour at most).`);return}Zo(t,200,d);}}var Bn,bs,yg,
|
|
20
|
+
kg,Pl,or,er,tr,nr,wg,Nn,jn,gs,Sg,ys=Zs(()=>{"use strict";Bn="x-bvsala-report",bs="x-bvsala-request-id",yg="/_bvsala/",kg="bvsala.gateway.report/1",Pl="bvsala.gateway.status/1",or="bvsala.gateway.summa\
|
|
21
|
+
ry/1",er=/^[A-Za-z0-9._:-]{1,200}$/;tr=class{entradas=new Map;porRespuestaId=new Map;oyentes=new Set;capacidad;now;constructor(t={}){this.capacidad=Math.max(1,Math.floor(t.capacidad??1e3)),this.now=t.
|
|
22
|
+
now??Date.now;}get tamano(){return this.entradas.size}get limite(){return this.capacidad}abrir(t,n){for(this.purgar();this.entradas.size>=this.capacidad;){let o=this.entradas.keys().next().value;if(o===
|
|
23
|
+
void 0)break;this.quitar(o);}this.entradas.set(t,{informe:{schema:kg,requestId:t,responseId:null,path:n,status:"pending",reason:null,report:null},abiertaMs:this.now()}),this.avisar();}anotarRespuesta(t,n){
|
|
24
|
+
let o=this.entradas.get(t);!o||o.informe.responseId!==null||!n||!er.test(n)||(o.informe.responseId=n,this.porRespuestaId.set(n,t),this.avisar());}medido(t,n){this.cerrar(t,"metered",null,n);}noMedido(t,n){
|
|
25
|
+
this.cerrar(t,"not_metered",n,null);}vigentes(){return this.purgar(),[...this.entradas.values()].map(t=>t.informe)}porPeticion(t){return this.purgar(),this.entradas.get(t)?.informe}porRespuesta(t){this.
|
|
26
|
+
purgar();let n=this.porRespuestaId.get(t);return n===void 0?void 0:this.entradas.get(n)?.informe}esperar(t,n,o){let r=s=>s!==void 0&&s.status!=="pending",i=t();return r(i)||n<=0||o?.aborted?Promise.resolve(
|
|
27
|
+
i):new Promise(s=>{let a=!1,l=()=>{a||(a=!0,clearTimeout(d),this.oyentes.delete(c),o?.removeEventListener("abort",l),s(t()));},c=()=>{r(t())&&l();},d=setTimeout(l,Math.min(n,3e4));this.oyentes.add(c),o?.
|
|
28
|
+
addEventListener("abort",l);})}cerrar(t,n,o,r){let i=this.entradas.get(t);!i||i.informe.status!=="pending"||(i.informe.status=n,i.informe.reason=o,i.informe.report=r===null?null:structuredClone(r),this.
|
|
29
|
+
avisar());}quitar(t){let n=this.entradas.get(t);this.entradas.delete(t);let o=n?.informe.responseId;o&&this.porRespuestaId.get(o)===t&&this.porRespuestaId.delete(o);}purgar(){let t=this.now()-36e5;for(let[
|
|
30
|
+
n,o]of this.entradas){if(o.abiertaMs>=t)break;this.quitar(n);}}avisar(){for(let t of [...this.oyentes])t();}};nr=class{resto="";leidos=0;id=null;observar(t){if(this.id!==null||this.leidos>262144)return;let n=typeof t==
|
|
31
|
+
"string"?t:t.toString("utf8");this.leidos+=n.length,this.resto+=n;let o;for(;(o=this.resto.indexOf(`
|
|
32
|
+
`))>=0;){let r=this.resto.slice(0,o).replace(/\r$/,"");if(this.resto=this.resto.slice(o+1),!r.startsWith("data:"))continue;let i=r.slice(5).trim();if(!(i===""||i==="[DONE]"))try{let s=Ll(JSON.parse(i));
|
|
33
|
+
if(s!==null){this.id=s,this.resto="";return}}catch{}}this.leidos>262144&&(this.resto="");}valor(){return this.id}},wg=()=>({requests:0,actualUsd:0,baselineUsd:0,netSavingsUsd:0}),Nn=e=>typeof e=="numbe\
|
|
34
|
+
r"&&Number.isFinite(e)?e:0,jn=(e,t=120)=>{if(typeof e!="string")return null;let n=e.replace(/[\u0000-\u001f]/g," ").trim();return n===""?null:n.slice(0,t)},gs=(e,t,n=1)=>{e[t]=(e[t]??0)+n;};Sg=new Set(
|
|
35
|
+
["127.0.0.1","localhost","[::1]"]);});var kd={};Md(kd,{ERROR_METODO:()=>vd,ERROR_PARAMETROS:()=>Jn,ERROR_PARSEO:()=>bd,ERROR_PETICION:()=>Wn,HERRAMIENTAS:()=>Kn,MAX_BYTES_POR_MENSAJE:()=>Yn,PUERTO_POR_DEFECTO:()=>gd,VERSIONES_MCP:()=>Vs,crearServidorMcp:()=>yd,
|
|
36
|
+
servirPorStdio:()=>xv,urlDelGateway:()=>wv});function hd(e){return typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}function wv(e){let t=`http://127.0.0.1:${gd}`;for(let o=0;o<e.length;o++){
|
|
37
|
+
let r=e[o],i=e[o+1];if(r==="--gateway"&&i!==void 0)t=i,o++;else if(r==="--port"&&i!==void 0){let s=Number(i);if(!Number.isInteger(s)||s<1||s>65535)return {ok:false,mensaje:`--port needs a port number, got\
|
|
38
|
+
${JSON.stringify(i)}`};t=`http://127.0.0.1:${s}`,o++;}else return {ok:false,mensaje:`unknown option: ${r}
|
|
39
|
+
usage: bvsala mcp [--gateway http://127.0.0.1:<port> | --port <port>]`}}let n;try{n=new URL(t);}catch{return {ok:false,mensaje:`--gateway is not a URL: ${JSON.stringify(t)}`}}return n.protocol!=="http:"||![
|
|
40
|
+
"127.0.0.1","localhost","[::1]"].includes(n.hostname)||n.username||n.password?{ok:false,mensaje:"bvsala mcp reads only the local gateway: --gateway must be http://127.0.0.1:<port> (or localhost), without\
|
|
41
|
+
credentials."}:{ok:true,url:n.origin}}function yd(e){let t=e.fetch??fetch;async function n(c){let d;try{d=await t(`${e.gateway}${c}`,{method:"GET",signal:AbortSignal.timeout(yv),headers:{accept:"applic\
|
|
42
|
+
ation/json"}});}catch{return {ok:false,mensaje:`the local gateway at ${e.gateway} is not answering. Start it (bvsala gateway --upstream anthropic) or pass --gateway/--port.`}}let u;try{u=await d.json();}catch{
|
|
43
|
+
return {ok:false,mensaje:`the local gateway answered ${d.status} without JSON on ${c}`}}if(!d.ok){let f=u?.error?.message;return {ok:false,mensaje:`the local gateway answered ${d.status} on ${c}${typeof f=="s\
|
|
44
|
+
tring"?`: ${f}`:""}`}}return {ok:true,json:u}}let o=c=>({content:[{type:"text",text:JSON.stringify(c)}],structuredContent:c,isError:false}),r=c=>({content:[{type:"text",text:c}],isError:true}),i={gateway:e.gateway,
|
|
45
|
+
readOnly:true,note:"metadata of this local gateway only: no request ids, no content"};async function s(){let c=await n("/_bvsala/v1/summary");if(!c.ok)return c;let d=c.json;return d?.schema!==or?{ok:false,
|
|
46
|
+
mensaje:`the local gateway does not serve ${or} (an older bvsala?): update it to use this tool.`}:{ok:true,r:d}}async function a(c){if(c==="gateway_status"){let m=await n("/_bvsala/v1/status");return m.
|
|
47
|
+
ok?o({scope:i,status:m.json}):r(m.mensaje)}if(c==="session_costs"){let m=await s();return m.ok?o({scope:i,window:m.r.window,sessions:m.r.sessions,note:"Only requests sent with the header x-bvsala-repo\
|
|
48
|
+
rt: 1 are in the mailbox (the last N, one hour at most), so this is not your whole bill. Money is grouped by cost basis and never added across bases: measured and estimated are different things."}):r(
|
|
49
|
+
m.mensaje)}let d=await s();if(!d.ok)return r(d.mensaje);let u=d.r.toolOutputCompaction,f=Object.entries(u.byReason).sort((m,h)=>h[1]-m[1]).map(([m,h])=>({reason:m,toolOutputs:h,meaning:kv[m]??"unknown\
|
|
50
|
+
reason code."}));return o({scope:i,window:d.r.window,toolOutputs:u.decisions,applied:u.applied,coverage:u.decisions===0?null:Math.round(u.applied/u.decisions*1e3)/1e3,estimatedTokens:{before:u.appliedTokensBefore,
|
|
51
|
+
after:u.appliedTokensAfter,basis:u.tokenBasis},opportunities:f,note:u.decisions===0?"No tool-output decisions in this window. lossless-data runs where the request is built by the SDK (createSavingsLay\
|
|
52
|
+
er with toolOutputCompaction: { profile: 'lossless-data' }); the gateway forwards bytes and does not compact tool outputs. Nothing here is a saving.":"Token counts are local estimates, never a verifie\
|
|
53
|
+
d saving. Experiments (turning a lever on, A/B) are not available here: they wait for the canonical API."})}async function l(c){let d="id"in c,u=d&&hd(c.id)?c.id:null;if(c.jsonrpc!=="2.0"||typeof c.method!=
|
|
54
|
+
"string"||d&&!hd(c.id))return c.jsonrpc==="2.0"&&typeof c.method!="string"&&("result"in c||"error"in c)?null:Ye(u,Wn,"invalid JSON-RPC 2.0 request");let f=c.params??{};if(c.params!==void 0&&(c.params===
|
|
55
|
+
null||typeof c.params!="object"||Array.isArray(c.params)))return d?Ye(u,Jn,"params must be an object"):null;if(!d)return null;switch(c.method){case "initialize":{let m=f.protocolVersion,h=Vs.includes(m)?
|
|
56
|
+
m:Vs[0];return fr(u,{protocolVersion:h,capabilities:{tools:{listChanged:false}},serverInfo:{name:"bvsala",title:"BiVelio Savings Layer (local, read-only)",version:e.version},instructions:"Read-only metad\
|
|
57
|
+
ata of the local bvsala gateway: status, cost per session, and tool-output compaction decisions. No content is ever returned and nothing can be changed from here."})}case "ping":return fr(u,{});case "to\
|
|
58
|
+
ols/list":{let m=0;if(f.cursor!==void 0){let g=typeof f.cursor=="string"?/^p(\d{1,4})$/.exec(f.cursor):null;if(m=g?Number(g[1]):-1,m<=0||m>=Kn.length)return Ye(u,Jn,"invalid cursor")}let h=Kn.slice(m,
|
|
59
|
+
m+md),v=m+md;return fr(u,{tools:h,...v<Kn.length?{nextCursor:`p${v}`}:{}})}case "tools/call":{let m=f.name;if(typeof m!="string"||!Kn.some(v=>v.name===m))return Ye(u,Jn,`unknown tool: ${typeof m=="stri\
|
|
60
|
+
ng"?m.slice(0,80):String(m)}`);let h=f.arguments;return h!==void 0&&(h===null||typeof h!="object"||Array.isArray(h)||Object.keys(h).length>0)?Ye(u,Jn,`${m} takes no arguments`):fr(u,await a(m))}default:
|
|
61
|
+
return Ye(u,vd,`method not found: ${c.method.slice(0,80)}`)}}return {async manejar(c){let d=c.replace(/\r$/,"");if(d.trim()==="")return null;if(Buffer.byteLength(d,"utf8")>Yn)return JSON.stringify(Ye(null,
|
|
62
|
+
Wn,`message larger than ${Yn} bytes`));let u;try{u=JSON.parse(d);}catch{return JSON.stringify(Ye(null,bd,"parse error"))}if(Array.isArray(u))return JSON.stringify(Ye(null,Wn,"batches are not supported"));
|
|
63
|
+
if(u===null||typeof u!="object")return JSON.stringify(Ye(null,Wn,"invalid JSON-RPC 2.0 request"));let f=await l(u);return f===null?null:JSON.stringify(f)}}}function xv(e,t,n){let o=yd(n),r="",i=false,s=Promise.
|
|
64
|
+
resolve(),a=l=>{s=s.then(async()=>{let c=await o.manejar(l);c!==null&&t.write(`${c}
|
|
65
|
+
`);});};return new Promise(l=>{e.setEncoding?.("utf8"),e.on("data",c=>{r+=typeof c=="string"?c:c.toString("utf8");let d;for(;(d=r.indexOf(`
|
|
66
|
+
`))>=0;){let u=r.slice(0,d);if(r=r.slice(d+1),i){i=false;continue}a(u);}r.length>Yn&&(r="",i||(i=true,a("x".repeat(Yn+1))));}),e.on("end",()=>{r!==""&&!i&&a(r),s.then(()=>l());});})}var Vs,gd,Yn,md,yv,bd,Wn,vd,
|
|
67
|
+
Jn,Fs,zs,Kn,kv,fr,Ye,wd=Zs(()=>{"use strict";ys();Vs=["2025-06-18","2025-03-26","2024-11-05"],gd=8402,Yn=1024*1024,md=2,yv=5e3,bd=-32700,Wn=-32600,vd=-32601,Jn=-32602,Fs={type:"object",properties:{},additionalProperties:!1},
|
|
68
|
+
zs=e=>({title:e,readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}),Kn=[{name:"gateway_status",title:"Local gateway status",description:"Status of the local bvsala gateway: version\
|
|
69
|
+
, upstream origin, license state and plan, whether metering is on, and the report mailbox headers. No keys, no content.",inputSchema:Fs,annotations:zs("Local gateway status")},{name:"session_costs",title:"\
|
|
70
|
+
Cost per session",description:"Cost per Claude Code session of the requests this gateway's report mailbox holds (the last N, one hour at most): requests, metered or not and why, and money per cost bas\
|
|
71
|
+
is (measured, reference, estimated\u2026) kept apart, never added together. Counts and USD only: no request ids, no content.",inputSchema:Fs,annotations:zs("Cost per session")},{name:"compaction_oppor\
|
|
72
|
+
tunities",title:"Tool-output compaction opportunities",description:"What the lossless-data tool-output compaction decided on the requests in this gateway's mailbox: how many tool outputs were compacte\
|
|
73
|
+
d, how many were bypassed and why (reason codes), and the ESTIMATED tokens before and after. Estimates, never a verified saving. Read-only: it proposes nothing and changes nothing.",inputSchema:Fs,annotations:zs(
|
|
74
|
+
"Compaction opportunities")}],kv={applied:"already compacted: whitespace removed from strict JSON.",not_smaller:"already compact: removing whitespace would not save a token. Nothing to gain.",below_threshold:"\
|
|
75
|
+
would save fewer characters than the minimum. Nothing worth changing.",not_json:"not a JSON object or array. Out of scope for lossless-data.",invalid_json:"looks like JSON but is not strict JSON. Left\
|
|
76
|
+
as is; fixing the tool's output is the only lossless way.",duplicate_keys:"JSON with a repeated key: parsers keep only one value, so it cannot be compacted without changing what it says. Fix the tool\
|
|
77
|
+
.",invalid_unicode:"contains an unpaired surrogate. Left as is.",protected:"a file view or an excepted tool: kept verbatim on purpose (agents edit files by exact match)."},fr=(e,t)=>({jsonrpc:"2.0",id:e,
|
|
78
|
+
result:t}),Ye=(e,t,n)=>({jsonrpc:"2.0",id:e,error:{code:t,message:n}});});var ro="context-management-2025-06-27";function xr(){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 $d=e=>e===32||e===10||e===13||e===9,na=e=>e>=48&&e<=57,Nd=e=>na(e)||e>=65&&e<=70||e>=97&&e<=102,jd=new Set([34,92,47,98,102,110,114,116,117]),ea=/-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/y;function ta(e,t){
|
|
79
|
+
let n=e.length,o=false,r=t+1;for(;r<n;){let i=e.charCodeAt(r);if(i===34)return {fin:r+1,escapes:o};if(i===92){let s=e.charCodeAt(r+1);if(!jd.has(s))return {fallo:"invalid_json",posicion:r};if(o=true,s===117){
|
|
80
|
+
for(let a=r+2;a<r+6;a++)if(!Nd(e.charCodeAt(a)))return {fallo:"invalid_json",posicion:r};r+=6;}else r+=2;continue}if(i<32)return {fallo:"invalid_json",posicion:r};if(i>=55296&&i<=56319){let s=e.charCodeAt(
|
|
81
|
+
r+1);if(!(s>=56320&&s<=57343))return {fallo:"invalid_unicode",posicion:r};r+=2;continue}if(i>=56320&&i<=57343)return {fallo:"invalid_unicode",posicion:r};r++;}return {fallo:"invalid_json",posicion:n}}function oa(e,t={}){
|
|
82
|
+
let n=e.length,o=[],r="valor",i=0,s=(c,d=i)=>({ok:false,fallo:c,posicion:d}),a=(c,d)=>t.lexema?.(c,d)!==false,l=()=>o.length===0?"fin":"comaOFin";for(;;){for(;i<n&&$d(e.charCodeAt(i));)i++;if(r==="fin")return i===
|
|
83
|
+
n?{ok:true}:s("invalid_json");if(i>=n)return s("invalid_json");let c=e.charCodeAt(i);if(r==="valorOFin"){if(c===93){if(o.pop(),!a(i,i+1))return s("stopped");i++,r=l();continue}r="valor";}if(r==="claveOFi\
|
|
84
|
+
n"){if(c===125){if(o.pop(),!a(i,i+1))return s("stopped");i++,r=l();continue}r="clave";}switch(r){case "valor":{if(c===123||c===91){if(o.push(c===123?new Set:null),!a(i,i+1))return s("stopped");i++,r=c===
|
|
85
|
+
123?"claveOFin":"valorOFin";continue}if(c===34){let u=ta(e,i);if("fallo"in u)return s(u.fallo,u.posicion);if(!a(i,u.fin))return s("stopped");i=u.fin,r=l();continue}if(c===45||na(c)){ea.lastIndex=i;let u=ea.
|
|
86
|
+
exec(e);if(!u)return s("invalid_json");let f=i+u[0].length;if(t.numero?.(u[0])===false||!a(i,f))return s("stopped");i=f,r=l();continue}let d=c===116?"true":c===102?"false":c===110?"null":null;if(d&&e.startsWith(
|
|
87
|
+
d,i)){if(!a(i,i+d.length))return s("stopped");i+=d.length,r=l();continue}return s("invalid_json")}case "clave":{if(c!==34)return s("invalid_json");let d=ta(e,i);if("fallo"in d)return s(d.fallo,d.posicion);
|
|
88
|
+
let u=d.escapes?JSON.parse(e.slice(i,d.fin)):e.slice(i+1,d.fin-1),f=o[o.length-1];if(f.has(u))return s("duplicate_keys");if(f.add(u),t.clave?.(u)===false||!a(i,d.fin))return s("stopped");i=d.fin,r="dosPu\
|
|
89
|
+
ntos";continue}case "dosPuntos":{if(c!==58)return s("invalid_json");if(!a(i,i+1))return s("stopped");i++,r="valor";continue}case "comaOFin":{let d=o[o.length-1];if(c===44){if(!a(i,i+1))return s("stopped");
|
|
90
|
+
i++,r=d?"clave":"valor";continue}if(c===125&&d||c===93&&d===null){if(o.pop(),!a(i,i+1))return s("stopped");i++,r=l();continue}return s("invalid_json")}}}}var Bd=new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});function Ud(e){try{return Bd.decode(e)}catch{return null}}function Fd(e){return /^(?:0|[1-9]\d{0,9})$/.test(e)&&Number(e)<4294967295}function zd(e){
|
|
91
|
+
return oa(e,{clave:t=>!Fd(t),numero:t=>String(Number(t))===t}).ok}function io(e,t){if(t!==void 0&&t!==""&&t!=="identity")return null;let n=Ud(e);if(n===null)return null;let o;try{o=JSON.parse(n);}catch{
|
|
92
|
+
return null}return zd(n)?o:null}function sa(e,t){try{let n=io(e,t);if(n===null||typeof n!="object"||Array.isArray(n)||typeof n.model!="string"||!Array.isArray(n.messages))return null;let o=qd(n.context_management),r=Hd(n.context_management);
|
|
93
|
+
return n.context_management=Gd(n.context_management),{cuerpo:Buffer.from(JSON.stringify(n),"utf8"),nuestros:o,triggerDelCliente:r}}catch{return null}}function qd(e){let t=e!==null&&typeof e=="object"&&
|
|
94
|
+
!Array.isArray(e)?e.edits:void 0,n=(Array.isArray(t)?t:[]).filter(o=>o!==null&&typeof o=="object"&&!Array.isArray(o)&&o.type===Sr);return ra(n)!==ra([xr().edits[0]])}function Hd(e){let t=e!==null&&typeof e==
|
|
95
|
+
"object"&&!Array.isArray(e)?e.edits:void 0,n=(Array.isArray(t)?t:[]).filter(r=>r!==null&&typeof r=="object"&&!Array.isArray(r)&&r.type===Sr);if(n.length===0)return null;let o=Number.POSITIVE_INFINITY;
|
|
96
|
+
for(let r of n){let i=r.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<o&&(o=s);}return o}function ra(e){return JSON.
|
|
97
|
+
stringify(e,(t,n)=>n!==null&&typeof n=="object"&&!Array.isArray(n)?Object.fromEntries(Object.keys(n).sort().map(o=>[o,n[o]])):n)}var Sr="clear_tool_uses_20250919",ia="clear_thinking_20251015";function Gd(e){
|
|
98
|
+
let t=xr().edits[0],n=e!==null&&typeof e=="object"&&!Array.isArray(e)?{...e}:{},o=(Array.isArray(n.edits)?n.edits:[]).filter(s=>s!==null&&typeof s=="object"&&!Array.isArray(s)&&s.type!==Sr),r=o.filter(
|
|
99
|
+
s=>s.type===ia),i=o.filter(s=>s.type!==ia);return {...n,edits:[...r,...i,t]}}function aa(e,t,n=false){let o=" (TTL tuning ON if your licence includes cache_ttl_tuning; fail-closed)",r=n?" \xB7 context elisio\
|
|
15
100
|
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
101
|
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
|
|
18
|
-
n=>n.length>0).includes(
|
|
19
|
-
Number(t[2]);return n>5||n===5&&
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
high","claude-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
102
|
+
ce channel: OPEN by default (=0 turns the levers off)")+o+r,aviso:n}}function ca(e){return e===void 0||e.trim()===""?ro:e.split(",").map(n=>n.trim()).filter(
|
|
103
|
+
n=>n.length>0).includes(ro)?e:`${e},${ro}`}function la(e){let t=e.toLowerCase(),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Wd(e){let t=/^gpt-(\d+)(?:\.(\d+))?(?![\d.])/.exec(e);if(!t)return false;let n=Number(t[1]),o=t[2]===void 0?0:
|
|
104
|
+
Number(t[2]);return n>5||n===5&&o>=6}function Se(e){let t=la(e);return t.startsWith("gpt-")||t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4")?Wd(t)?1.25:1:t.startsWith("gemini")||t.startsWith(
|
|
105
|
+
"deepseek-")||t.startsWith("qwen")||t.startsWith("glm-")?1:1.25}function Yt(e){let t=e.toLowerCase();return t.startsWith("claude")||t.startsWith("anthropic/")||la(t).startsWith("claude")?2:Se(e)}var Tr=1.25,Rr=2,Kd=.3,Yd=/^(custom|bash_|text_editor_|computer_|browser_|memory_)/;function Ar(e){return Array.isArray(e.mcp_servers)&&e.mcp_servers.length>0?true:Array.isArray(e.tools)?e.tools.some(t=>{
|
|
106
|
+
let n=t!==null&&typeof t=="object"?t.type:void 0;return typeof n=="string"&&!Yd.test(n)}):false}var Qd=4096,Xd=(e,t)=>e==="cache_control"?void 0:t;function Er(e){return e===void 0?"":JSON.stringify(e,Xd)??
|
|
107
|
+
""}function Zd(e){return Array.isArray(e)?e.filter(t=>!(t!==null&&typeof t=="object"&&t.defer_loading===true)):e}function _r(e){return createHash("sha1").update(e).digest("base64url").slice(0,16)}function gt(e,t){
|
|
108
|
+
let n=io(e,t);if(n===null||typeof n!="object"||Array.isArray(n))return null;let o=n;return typeof o.model!="string"||!Array.isArray(o.messages)?null:o}function Ir(e){let t=Er(e.system),n=Er(Zd(e.tools)),
|
|
109
|
+
o=Array.isArray(e.messages)?e.messages.slice(0,Qd):[],r=[],i=[];for(let s of o){let a=Er(s);r.push(_r(a)),i.push(Buffer.byteLength(a,"utf8"));}return {system:_r(t),tools:_r(n),mensajes:r,bytes:i,bytesFijos:Buffer.
|
|
110
|
+
byteLength(t,"utf8")+Buffer.byteLength(n,"utf8")}}function Dr(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 o=0;
|
|
111
|
+
for(;o<e.mensajes.length&&o<t.mensajes.length&&e.mensajes[o]===t.mensajes[o];)o++;let r=0;for(let i=o;i<t.bytes.length;i++)r+=t.bytes[i]??0;return r/n}function Pr(e){let{fraccionNueva:t,umbral:n=Kd}=e;
|
|
112
|
+
return t>=n}function ep(e,t){e.ttl==="1h"?(e.ttl="5m",t.rebajadas++):(e.ttl==="5m"||e.ttl===void 0)&&t.yaEran5m++;}var bn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Cr=e=>bn(e)&&bn(e.cache_control)?
|
|
113
|
+
e.cache_control:null,tp=8;function so(e,t,n,o){if(!(!Array.isArray(e)||o>tp))for(let r of e){let i=Cr(r);if(i&&n(i,t),!bn(r))continue;Array.isArray(r.content)&&so(r.content,t,n,o+1);let s=r.source;bn(
|
|
114
|
+
s)&&s.type==="content"&&Array.isArray(s.content)&&so(s.content,t,n,o+1);}}function Or(e,t){let n=Cr(e);if(n&&t(n,"raiz"),so(e.system,"system",t,0),Array.isArray(e.tools))for(let o of e.tools){let r=Cr(
|
|
115
|
+
o);r&&t(r,"tools");}if(Array.isArray(e.messages)){let o=e.messages.length-1;e.messages.forEach((r,i)=>{bn(r)&&so(r.content,i===o?"ultimoMensaje":"mensaje",t,0);});}}function Lr(e,t){let n=Buffer.isBuffer(
|
|
116
|
+
e)?gt(e,t):e;if(n===null)return null;try{let o={rebajadas:0,yaEran5m:0};return Or(n,r=>ep(r,o)),o.rebajadas===0?null:{cuerpo:Buffer.from(JSON.stringify(n),"utf8"),rebajadas:o.rebajadas,yaEran5m:o.yaEran5m,
|
|
117
|
+
herramientaDeServidor:Ar(n)}}catch{return null}}function np(e){let{cacheEscrita5m:t,inputPer1k:n,yaEran5m:o,herramientaDeServidor:r}=e;return o>0||r||t<=0||n<=0?0:t/1e3*n*(Rr-Tr)}function ua(e,t,n){return e.
|
|
118
|
+
rebajadas<=0?0:np({cacheEscrita5m:t,inputPer1k:n,yaEran5m:e.yaEran5m,herramientaDeServidor:e.herramientaDeServidor})}var ao=class{constructor(t=512,n=3600*1e3){this.maxEntradas=t;this.maxEdadMs=n;}maxEntradas;maxEdadMs;visto=new Map;ultima(t,n){
|
|
119
|
+
let o=this.visto.get(t);if(o!==void 0){if(n-o.vistoMs>this.maxEdadMs){this.visto.delete(t);return}return o.huella}}anotar(t,n,o){for(this.visto.delete(t),this.visto.set(t,{huella:n,vistoMs:o});this.visto.
|
|
120
|
+
size>this.maxEntradas;){let r=this.visto.keys().next();if(r.done===true)break;this.visto.delete(r.value);}}get tamano(){return this.visto.size}};var Mr="mid-conversation-output-config-2026-07-01",lo=["low","medium","high","xhigh","max"],op=new Set(["claude-fable-5-1","claude-mythos-5-1","claude-opus-5-5","claude-opus-5"]),da={"claude-fable-5-1":"\
|
|
121
|
+
high","claude-mythos-5-1":"high","claude-opus-5-5":"medium","claude-opus-5":"high"};function rp(e){return fa(e)?da[e]:void 0}function pa(e,t){let n=rp(e);return n!==void 0&&lo.indexOf(t)<lo.indexOf(n)}
|
|
122
|
+
var co=lo.filter(e=>Object.keys(da).some(t=>pa(t,e)));function fa(e){return op.has(e)}function $r(e){return e!==void 0&&lo.includes(e)}function ip(e){return {role:"system",content:[],output_config:{effort:e}}}
|
|
123
|
+
function sp(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 ma(e,t,n){
|
|
124
|
+
let o=gt(e,n);if(o===null||typeof o.model!="string"||!fa(o.model)||!pa(o.model,t)||sp(o))return null;let r=o.messages;return Array.isArray(r)?(o.messages=[...r,ip(t)],{cuerpo:Buffer.from(JSON.stringify(
|
|
125
|
+
o),"utf8"),nivel:t}):null}function ha(e){return e===void 0||e.trim()===""?Mr:e.split(",").map(n=>n.trim()).includes(Mr)?e:`${e},${Mr}`}function ga(e,t,n){return e===void 0||e===""?{linea:`per-turn eff\
|
|
126
|
+
ort: OFF (BVSALA_GATEWAY_EFFORT=${co.join("|")} turns it on)`,aviso:false}:$r(e)?co.includes(e)?n?{linea:`per-turn effort: ARMED at "${e}" (ON if your licence includes per_turn_effort; fail-closed). On\
|
|
41
127
|
ly fable-5-1, mythos-5-1, opus-5-5 and opus-5, and only below the model's default effort (high; medium on opus-5-5${e==="medium"?", so opus-5-5 passes through unchanged at this level":""}); every othe\
|
|
42
128
|
r request passes through unchanged. Does NOT reset the prefix cache: the dial is appended at the end and nothing earlier is rewritten. Not yet verified against the quality gate`,aviso:false}:{linea:"per-\
|
|
43
129
|
turn effort: NOT ARMED - BVSALA_GATEWAY_ELISION=0 turns off the levers",aviso:true}:{linea:`per-turn effort: NOT ARMED \u2014 "${e}" is not below any supported model's default effort (high; medium on claude-opus-5-5), s\
|
|
44
|
-
o it could only leave the bill as it is or raise it. This lever only lowers effort: use ${
|
|
45
|
-
join(", ")}`,aviso:true}}var
|
|
130
|
+
o it could only leave the bill as it is or raise it. This lever only lowers effort: use ${co.join(" or ")}`,aviso:true}:{linea:`per-turn effort: NOT ARMED \u2014 "${e}" is not a level. Use one of: ${co.
|
|
131
|
+
join(", ")}`,aviso:true}}var yn={"gpt-4.1":{inputPer1k:.002,outputPer1k:.008,cachedInputPer1k:5e-4},"gpt-4.1-mini":{inputPer1k:4e-4,outputPer1k:.0016,cachedInputPer1k:1e-4},"gpt-4.1-nano":{inputPer1k:1e-4,outputPer1k:4e-4,cachedInputPer1k:25e-6},
|
|
46
132
|
"gpt-4o":{inputPer1k:.0025,outputPer1k:.01,cachedInputPer1k:.00125},"gpt-4o-mini":{inputPer1k:15e-5,outputPer1k:6e-4,cachedInputPer1k:75e-6},"gpt-4-turbo":{inputPer1k:.01,outputPer1k:.03},"gpt-4":{inputPer1k:.03,
|
|
47
133
|
outputPer1k:.06},"gpt-3.5-turbo":{inputPer1k:5e-4,outputPer1k:.0015},"gpt-5":{inputPer1k:.00125,outputPer1k:.01,cachedInputPer1k:125e-6},"gpt-5-codex":{inputPer1k:.00125,outputPer1k:.01,cachedInputPer1k:125e-6},
|
|
48
134
|
"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},
|
|
@@ -63,74 +149,82 @@ thos-5":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:.001},"claude-sonnet-4"
|
|
|
63
149
|
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\
|
|
64
150
|
h":{inputPer1k:75e-5,outputPer1k:.00375,cachedInputPer1k:75e-6},"gemini-3.1-flash-lite":{inputPer1k:25e-5,outputPer1k:.0015,cachedInputPer1k:25e-6},"gemini-3-flash-preview":{inputPer1k:5e-4,outputPer1k:.003,
|
|
65
151
|
cachedInputPer1k:5e-5},"gemini-3.5-flash":{inputPer1k:.0015,outputPer1k:.009,cachedInputPer1k:15e-5},"gemini-3.5-flash-lite":{inputPer1k:3e-4,outputPer1k:.0025,cachedInputPer1k:3e-5},"gemini-3.1-pro-p\
|
|
66
|
-
review":{inputPer1k:.002,outputPer1k:.012,cachedInputPer1k:2e-4},"gemini-2.5-pro":{inputPer1k:.00125,outputPer1k:.01,cachedInputPer1k:125e-6},"gemini-2.5-flash":{inputPer1k:3e-4,outputPer1k:.0025,cachedInputPer1k:3e-5}
|
|
67
|
-
|
|
68
|
-
inputPer1k
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
""
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
152
|
+
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},
|
|
153
|
+
"deepseek-flash":{inputPer1k:3e-4,outputPer1k:.0012,cachedInputPer1k:3e-6},"deepseek-v4-pro":{inputPer1k:.00132,outputPer1k:.00396,cachedInputPer1k:3e-6},"qwen3.8-max":{inputPer1k:.002,outputPer1k:.006,
|
|
154
|
+
cachedInputPer1k:2e-4},"qwen3.8-flash":{inputPer1k:15e-5,outputPer1k:47e-5,cachedInputPer1k:15e-6},"qwen3.7-flash":{inputPer1k:3e-5,outputPer1k:13e-5,cachedInputPer1k:3e-6},"qwen-flash":{inputPer1k:5e-5,
|
|
155
|
+
outputPer1k:4e-4,cachedInputPer1k:5e-6},"qwen-plus":{inputPer1k:115e-6,outputPer1k:287e-6,cachedInputPer1k:115e-7},"glm-5.3":{inputPer1k:.001111,outputPer1k:.003889},"glm-5.3-flash":{inputPer1k:111e-6,
|
|
156
|
+
outputPer1k:389e-6}},ap={"gemini-3.8-flash":{vigenteHasta:"2027-01-01"},"gemini-3.7-flash":{vigenteHasta:"2027-01-01"},"gemini-3.6-flash":{vigenteHasta:"2027-01-01"}},cp={"gemini-3.8-flash":[{vigenteDesde:"\
|
|
157
|
+
2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}],"gemini-3.7-flash":[{vigenteDesde:"2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}],"ge\
|
|
158
|
+
mini-3.6-flash":[{vigenteDesde:"2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}]},lp=Object.fromEntries(Object.keys(yn).map(e=>[e,[{...ap[e],precio:yn[e]},...cp[e]??[]]]));var up=864e13;function ba(e){let t=e instanceof Date?e.getTime():e,n=typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<=up?t:Date.now();return new Date(n).toISOString().slice(0,10)}function va(e,t){
|
|
159
|
+
for(let n of lp[e]??[])if(!(n.vigenteDesde!==void 0&&t<n.vigenteDesde)&&!(n.vigenteHasta!==void 0&&t>=n.vigenteHasta))return n.precio}function ya(e,t,n){if(!n)return;let o=e[n];if(o)return o;let r=n.lastIndexOf("/"),i=r>=0?n.slice(r+1):n,s=e[i];if(s)return s;for(let a of t){if(!i.startsWith(a))continue;let l=i.charAt(a.length);if(l!==
|
|
160
|
+
""&&l!=="-"&&l!=="."&&l!=="_")continue;let c=i.slice(a.length+1);if(!(/^\d/.test(c)&&!/^\d{4}/.test(c)))return e[a]}}function jr(e){return Object.keys(e).sort((t,n)=>n.length-t.length)}var dp=["o3-dee\
|
|
161
|
+
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"],Nr={...yn,...Object.
|
|
162
|
+
fromEntries(dp.map(e=>[e,null]))},pp=jr(Nr);function je(e,t){let n=At(e);return n===void 0?void 0:va(n,ba(t))}var fp=Object.fromEntries(Object.keys(Nr).map(e=>[e,Nr[e]===null?null:e]));function At(e){
|
|
163
|
+
return ya(fp,pp,e)??void 0}var mp=/^\d{4}-?\d{2}-?\d{2}$/;function Qt(e,t){let n=At(e);if(n===void 0)return;let o=e.lastIndexOf("/"),r=o>=0?e.slice(o+1):e;if(!(n!==e&&n!==r&&!mp.test(r.slice(n.length+
|
|
164
|
+
1))))return va(n,ba(t))}var ka={"claude-fable-5":"claude-fable-5-1"};function hp(e,t){let n=je(e),o=je(t);if(n===void 0||o===void 0||n.inputPer1k!==o.inputPer1k||n.outputPer1k!==o.outputPer1k||Se(e)!==Se(t))return false;let r=n.
|
|
165
|
+
cachedInputPer1k??n.inputPer1k;return (o.cachedInputPer1k??o.inputPer1k)<r}function gp(e){let t=At(e);if(t===void 0||t!==e)return null;let n=ka[t];return n===void 0||n===t||!hp(t,n)?null:{solicitado:e,
|
|
166
|
+
servido:n}}var bp=/(^|,)\s*context-1m/i;function vp(e){let t=e.tool_choice;if(t===null||typeof t!="object")return false;let n=t.type;return n==="any"||n==="tool"}function Br(e,t,n={}){if(n.betas!==void 0&&
|
|
167
|
+
bp.test(n.betas))return null;let o=gt(e,t);if(o===null||vp(o))return null;let r=gp(o.model);return r===null?null:(o.model=r.servido,{cuerpo:Buffer.from(JSON.stringify(o),"utf8"),cambio:r})}function wa(e,t,n){
|
|
168
|
+
let o=Object.entries(ka).map(([r,i])=>`${r}\u2192${i}`).join(", ");return e!=="1"?{linea:"sibling model routing: OFF (BVSALA_GATEWAY_SIBLING_MODEL=1 turns it on)",aviso:false}:n?{linea:`sibling model r\
|
|
169
|
+
outing: ARMED (${o}; ON if your licence includes sibling_model_routing; fail-closed). Changes the model you see in the response; cache reads cost 0.025\xD7 instead of 0.1\xD7 (list price). Turning it on mid\
|
|
81
170
|
-conversation pays one cold prefix write, once. If the provider rejects the rewritten request (400), it is re-sent unchanged once`,aviso:false}:{linea:"sibling model routing: NOT ARMED - BVSALA_GATEWAY_E\
|
|
82
|
-
LISION=0 turns off the levers",aviso:true}}var
|
|
83
|
-
t.flushIntervalMs??15e3,this.maxBatch=t.maxBatch??50,this.maxBuffer=t.maxBuffer??1e3,this.ci=t.ci??false;}setSeat(t,n){t&&(this.seatId=t),this.ci=n;}
|
|
84
|
-
let
|
|
85
|
-
|
|
86
|
-
(clearInterval(this.timer),this.timer=void 0);
|
|
87
|
-
length>=i?
|
|
88
|
-
let t=this.options.fetchImpl??globalThis.fetch;if(!t)return;let n=this.
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
: the
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
at
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
e.
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
return
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
let
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
let
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
171
|
+
LISION=0 turns off the levers",aviso:true}}var xa=new Set;function Z(e,t){xa.has(e)||(xa.add(e),console.warn(t));}var ye="1.0.0",Ur="x-bvsala-version";var Xt=class{options;now;flushIntervalMs;maxBatch;maxBuffer;buffer=[];seatId;ci;timer;inflight=null;fallosSeguidos=0;contadores={sent:0,requeued:0,discarded:0,dropped:0};constructor(t){this.options=t,
|
|
172
|
+
this.now=t.now??(()=>Date.now()),this.flushIntervalMs=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;}stats(){
|
|
173
|
+
return {...this.contadores}}record(t){let n=this.now();this.buffer.push({report:t,at:n});let o=yp(t);if(o&&this.buffer.push({report:o,at:n}),this.buffer.length>this.maxBuffer){let r=this.buffer.length-
|
|
174
|
+
this.maxBuffer;this.contadores.dropped+=r,this.buffer.splice(0,r);}this.buffer.length>=this.maxBatch&&this.flush();}start(){this.timer||(this.timer=setInterval(()=>{this.flush();},this.flushIntervalMs),this.
|
|
175
|
+
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??Math.ceil(this.maxBuffer/
|
|
176
|
+
this.maxBatch)+4,o=0;for(let r=0;r<n&&this.buffer.length>0;r++){let i=this.buffer.length;if(await this.flush(),o=this.buffer.length>=i?o+1:0,o>=2)break}}async flush(){if(this.inflight)return this.inflight;
|
|
177
|
+
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.fetch;if(!t)return;let n=this.
|
|
178
|
+
buffer.splice(0,this.maxBatch),o=new AbortController,r=setTimeout(()=>o.abort(),Math.max(1,this.options.requestTimeoutMs??1e4));try{let i=n.map(a=>this.toWire(a)),s=await t(this.options.url,{method:"P\
|
|
179
|
+
OST",headers:{"content-type":"application/json",authorization:`Bearer ${this.options.serviceAccountKey}`,[Ur]:`${this.options.surface??"sdk"}/${ye}`},body:JSON.stringify(i),signal:o.signal});s.ok?(this.
|
|
180
|
+
fallosSeguidos=0,this.contadores.sent+=n.length):s.status===429?(this.fallosSeguidos++,this.requeue(n),this.avisarDeFallo("the server rate-limited the batch with HTTP 429"),await this.esperarReintento(
|
|
181
|
+
s)):s.status>=500?(this.fallosSeguidos++,this.requeue(n),this.avisarDeFallo(`the server responded ${s.status}`)):s.status===401||s.status===403?(this.contadores.discarded+=n.length,Z(`metering-auth-${s.
|
|
182
|
+
status}`,`[bv-sala] usage reporting is being rejected with HTTP ${s.status} at ${this.options.url}. Check 'serviceAccountKey' (rotated? revoked? from another organization?). Until it works, no usage i\
|
|
183
|
+
s reported: the dashboard will say it sees no traffic and billable seats will show zero.`),this.options.onAuthError?.(s.status)):(this.contadores.discarded+=n.length,this.fallosSeguidos++,this.avisarDeFallo(
|
|
184
|
+
s.status===404||s.status===405?`HTTP ${s.status}: the reporting URL looks wrong`:`the server rejected the batch with HTTP ${s.status}`));}catch(i){this.fallosSeguidos++,this.requeue(n),this.avisarDeFallo(
|
|
185
|
+
i instanceof Error?i.message:"network error");}finally{clearTimeout(r);}}async esperarReintento(t){let n=t.headers?.get("retry-after"),o=n!=null?Number(n):Number.NaN,r=n?Date.parse(n):Number.NaN,i=Number.
|
|
186
|
+
isFinite(o)?o*1e3:Number.isFinite(r)?r-this.now():Number.NaN,a=Math.max(0,this.options.retryDelayMs??250)*2**Math.min(8,this.fallosSeguidos-1),l=Math.min(3e4,Math.max(0,Number.isFinite(i)?i:a));l>0&&await new Promise(
|
|
187
|
+
c=>setTimeout(c,l));}avisarDeFallo(t){if(this.options.silenceWarnings)return;let n=this.fallosSeguidos;n<3||(n-3)%12!==0||console.warn(`[bv-sala] usage reporting has failed ${n} times in a row against ${this.
|
|
188
|
+
options.url} (${t}). Requests keep working, but usage is not arriving: the dashboard will say it sees no traffic and billable seats will show zero. Check 'meteringUrl' \u2014 by default it is \`\${licenseSer\
|
|
189
|
+
verUrl}/api/metering/usage\`.`);}requeue(t){this.contadores.requeued+=t.length,this.buffer=[...t,...this.buffer],this.buffer.length>this.maxBuffer&&(this.contadores.dropped+=this.buffer.length-this.maxBuffer,
|
|
190
|
+
this.buffer.length=this.maxBuffer);}toWire(t){let n=t.report;return {orgId:this.options.orgId??"self",...this.seatId?{seatId:this.seatId}:{},...this.ci?{ci:true}:{},requestId:n.requestId,model:n.model,at:t.
|
|
191
|
+
at,avoidedLlm:n.calls.avoidedLlm,actualLlm:n.calls.actualLlm,baselineInputTokens:n.tokens.baselineInput,actualInputTokens:n.tokens.actualInput,eliminatedInputTokens:n.tokens.eliminatedInput,compressedInputTokens:n.
|
|
192
|
+
tokens.compressedInput,baselineOutputTokens:n.tokens.baselineOutput,actualOutputTokens:n.tokens.actualOutput,providerCachedInputTokens:n.tokens.providerCachedInput??0,cacheResult:n.cache.result,...n.cost.
|
|
193
|
+
eliminatedInputFloorCost!==void 0&&Number.isFinite(n.cost.eliminatedInputFloorCost)&&n.cost.eliminatedInputFloorCost>0&&n.tokens.eliminatedInput>0?{eliminatedInputFloorCost:n.cost.eliminatedInputFloorCost}:
|
|
194
|
+
{},...kp(n),baselineCost:n.cost.baselineEstimate,actualCost:n.cost.actual,netSavings:n.cost.netSavingsRatio,...n.cost.basis?{basis:n.cost.basis}:{},...n.cost.basis==="reference"&&n.cache.reference&&/^[A-Za-z0-9._:/-]{1,128}$/.
|
|
195
|
+
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.
|
|
196
|
+
attribution.sessionId}:{},...n.attribution?.agentId?{agentId:n.attribution.agentId}:{}}}};function yp(e){let t=e.measure;if(!t)return null;let n=t.wouldHaveSaved.usd;if(!(Number.isFinite(n)&&n>0))return null;
|
|
197
|
+
let o=`${e.requestId}:shadow`;if(!/^[A-Za-z0-9._:/-]{1,128}$/.test(o))return null;let r=Math.max(0,e.cost.actual),i=Math.max(0,r-n),s=r>0?Math.min(1,(r-i)/r):0,{measure:a,nativeSavings:l,...c}=e;return {
|
|
198
|
+
...c,requestId:o,cache:{...e.cache,result:"miss"},cost:{baselineEstimate:r,actual:i,netSavingsRatio:s,netSavingsUsd:r-i,basis:"shadow"}}}function kp(e){let t=e.nativeSavings;if(!t||t.basis!=="measured")
|
|
199
|
+
return {};let n=o=>Number.isFinite(o)&&o>=0;return !n(t.readDiscountUsd)||!n(t.writePremiumUsd)?{}:!(t.readDiscountUsd>0)&&!(t.writePremiumUsd>0)?{}:{...t.readDiscountUsd>0?{nativeCacheReadSavings:t.readDiscountUsd}:
|
|
200
|
+
{},...t.writePremiumUsd>0?{nativeCacheWritePremium:t.writePremiumUsd}:{}}}function uo(){return globalThis.process}function wp(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\
|
|
201
|
+
]";return new RegExp(`-${t}{8,10}-${t}{5}$`).test(e)}function xp(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??
|
|
202
|
+
e.NETLIFY)}async function Sp(){if(uo()?.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 Ep(e,t=Sp){
|
|
203
|
+
if(e.KUBERNETES_SERVICE_HOST||xp(e))return;let n=e.HOSTNAME??e.COMPUTERNAME??await t();if(!(!n||wp(n)))return n}async function _p(){let e=uo();if(!e||!e.env)return;let t=e.env,n=await Ep(t),o=[e.platform,
|
|
204
|
+
e.arch,e.execPath,n,t.USER??t.USERNAME??t.LOGNAME,t.HOME??t.USERPROFILE].filter(r=>typeof r=="string"&&r.length>0);return o.length?o.join("|"):void 0}var Cp=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTI\
|
|
205
|
+
ONS","GITLAB_CI","CIRCLECI","TRAVIS","JENKINS_URL","BUILDKITE","TF_BUILD","TEAMCITY_VERSION","BITBUCKET_BUILD_NUMBER","CODEBUILD_BUILD_ID","HEROKU_TEST_RUN_ID","DRONE"];function po(){let e=uo()?.env;if(!e)
|
|
206
|
+
return false;for(let t of Cp){let n=e[t];if(n&&n!=="false"&&n!=="0")return true}return false}async function Tp(e,t){let n=globalThis.crypto,o=new TextEncoder;if(n?.subtle)try{let s=await n.subtle.importKey("raw",
|
|
207
|
+
o.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await n.subtle.sign("HMAC",s,o.encode(t));return [...new Uint8Array(a)].map(l=>l.toString(16).padStart(2,"0")).join("")}catch{}let r=2166136261,i=`${e}\
|
|
208
|
+
|${t}`;for(let s=0;s<i.length;s++)r^=i.charCodeAt(s),r=Math.imul(r,16777619);return (r>>>0).toString(16).padStart(8,"0")}async function fo(e){let n=uo()?.env?.BVSALA_SEAT_ID;if(n&&Rp.test(n))return n;let o=await _p();
|
|
209
|
+
if(!o)return;let r=await Tp(e,o);if(r)return `m-${r.slice(0,32)}`}var Rp=/^[A-Za-z0-9._:/-]{1,128}$/;function Fr(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function mo(e,t=""){if(typeof e!="number"){let n=t&&
|
|
210
|
+
`"${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 Be(e,t,n=""){
|
|
211
|
+
let o=Fr(e),r=e?.length,i=t!==void 0;if(!o||i&&r!==t){let s=n&&`"${n}" `,a=i?` of length ${t}`:"",l=o?`length=${r}`:`type=${typeof e}`,c=s+"expected Uint8Array"+a+", got "+l;throw o?new RangeError(c):
|
|
212
|
+
new TypeError(c)}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 Ea(e,t){Be(e,void 0,"digestInt\
|
|
213
|
+
o() output");let n=t.outputLen;if(e.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function kn(...e){for(let t=0;t<e.length;t++)e[t].fill(0);}function ho(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var _a=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Ap=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function go(e){if(Be(e),_a)return e.toHex();
|
|
214
|
+
let t="";for(let n=0;n<e.length;n++)t+=Ap[e[n]];return t}var rt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Sa(e){if(e>=rt._0&&e<=rt._9)return e-rt._0;if(e>=rt.A&&e<=rt.F)return e-(rt.A-10);if(e>=rt.a&&
|
|
215
|
+
e<=rt.f)return e-(rt.a-10)}function wn(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);if(_a)try{return Uint8Array.fromHex(e)}catch(r){throw r instanceof SyntaxError?
|
|
216
|
+
new RangeError(r.message):r}let t=e.length,n=t/2;if(t%2)throw new RangeError("hex string expected, got unpadded hex of length "+t);let o=new Uint8Array(n);for(let r=0,i=0;r<n;r++,i+=2){let s=Sa(e.charCodeAt(
|
|
217
|
+
i)),a=Sa(e.charCodeAt(i+1));if(s===void 0||a===void 0){let l=e[i]+e[i+1];throw new RangeError('hex string expected, got non-hex character "'+l+'" at index '+i)}o[r]=s*16+a;}return o}function Vr(...e){let t=0;for(let o=0;o<e.length;o++){let r=e[o];Be(r),t+=r.length;}let n=new Uint8Array(t);for(let o=0,r=0;o<e.length;o++){let i=e[o];n.set(i,r),r+=i.length;}return n}function Ca(e,t={}){let n=(r,i)=>e(i).update(r).digest(),o=e(void 0);return n.outputLen=o.outputLen,n.blockLen=o.blockLen,n.canXOF=o.canXOF,n.create=r=>e(r),Object.assign(n,t),Object.freeze(n)}function Ta(e=32){
|
|
218
|
+
mo(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(
|
|
219
|
+
`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}var Ra=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});var bo=class{blockLen;outputLen;canXOF=false;padOffset;isLE;buffer;view;finished=false;length=0;pos=0;destroyed=false;constructor(t,n,o,r){this.blockLen=t,this.outputLen=n,this.padOffset=o,this.isLE=r,this.buffer=
|
|
220
|
+
new Uint8Array(t),this.view=ho(this.buffer);}update(t){zr(this),Be(t);let{view:n,buffer:o,blockLen:r}=this,i=t.length;for(let s=0;s<i;){let a=Math.min(r-this.pos,i-s);if(a===r){let l=ho(t);for(;r<=i-s;s+=
|
|
221
|
+
r)this.process(l,s);continue}o.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===r&&(this.process(n,0),this.pos=0);}return this.length+=t.length,this.roundClean(),this}digestInto(t){zr(this),
|
|
222
|
+
Ea(t,this),this.finished=true;let{buffer:n,view:o,blockLen:r,isLE:i}=this,{pos:s}=this;n[s++]=128,kn(this.buffer.subarray(s)),this.padOffset>r-s&&(this.process(o,0),s=0);for(let u=s;u<r;u++)n[u]=0;o.setBigUint64(
|
|
223
|
+
r-8,BigInt(this.length*8),i),this.process(o,0);let a=ho(t),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let c=l/4,d=this.get();if(c>d.length)throw new Error("_s\
|
|
224
|
+
ha2: outputLen bigger than state");for(let u=0;u<c;u++)a.setUint32(4*u,d[u],i);}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let o=t.slice(0,n);return this.destroy(),o}_cloneInto(t){t||=new this.
|
|
225
|
+
constructor,t.set(...this.get());let{blockLen:n,buffer:o,length:r,finished:i,destroyed:s,pos:a}=this;return t.destroyed=s,t.finished=i,t.length=r,t.pos=a,r%n&&t.buffer.set(o),t}clone(){return this._cloneInto()}};var de=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var vo=BigInt(4294967295),Aa=BigInt(32);function Ip(e,t=false){return t?{h:Number(e&vo),l:Number(e>>Aa&vo)}:{h:Number(e>>Aa&vo)|0,l:Number(e&vo)|0}}function Ia(e,t=false){let n=e.length,o=new Uint32Array(n),
|
|
226
|
+
r=new Uint32Array(n);for(let i=0;i<n;i++){let{h:s,l:a}=Ip(e[i],t);[o[i],r[i]]=[s,a];}return [o,r]}var qr=(e,t,n)=>e>>>n,Hr=(e,t,n)=>e<<32-n|t>>>n,It=(e,t,n)=>e>>>n|t<<32-n,Dt=(e,t,n)=>e<<32-n|t>>>n,xn=(e,t,n)=>e<<64-n|t>>>n-32,Sn=(e,t,n)=>e>>>n-32|t<<64-n;function He(e,t,n,o){let r=(t>>>0)+(o>>>0);return {h:e+n+(r/2**32|0)|0,l:r|0}}var Da=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Pa=(e,t,n,o)=>t+n+o+(e/2**32|0)|0,Oa=(e,t,n,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),La=(e,t,n,o,r)=>t+
|
|
227
|
+
n+o+r+(e/2**32|0)|0,Ma=(e,t,n,o,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0)+(r>>>0),$a=(e,t,n,o,r,i)=>t+n+o+r+i+(e/2**32|0)|0;var Na=Ia(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242",
|
|
134
228
|
"0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc6\
|
|
135
229
|
8b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","\
|
|
136
230
|
0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3\
|
|
@@ -138,812 +232,810 @@ c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a6
|
|
|
138
232
|
x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5d\
|
|
139
233
|
efb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0x\
|
|
140
234
|
eada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c1\
|
|
141
|
-
00d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),
|
|
142
|
-
super(128,t,16,false);}get(){let{Ah:t,Al:n,Bh:
|
|
143
|
-
t|0,this.Al=n|0,this.Bh=
|
|
144
|
-
16;
|
|
145
|
-
|
|
146
|
-
Fl:
|
|
147
|
-
0,ee=
|
|
148
|
-
0;let
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
0;Cl=
|
|
152
|
-
expected boolean, got type="+typeof e)}return e}function
|
|
153
|
-
"number"){let n=t&&`"${t}" `;throw new TypeError(n+"expected number, got type="+typeof e)}if(!Number.isSafeInteger(e)){let n=t&&`"${t}" `;throw new RangeError(n+"expected safe integer, got "+e)}}function
|
|
154
|
-
function
|
|
155
|
-
return
|
|
156
|
-
"expected valid "+e+": "+n+" <= n < "+
|
|
157
|
-
`param "${i}" is invalid: expected own property`);let
|
|
158
|
-
entries(i).forEach(([a,
|
|
159
|
-
modulus, got "+t);let n=e%t;return n>=
|
|
160
|
-
o number");if(t<=
|
|
161
|
-
throw new Error("invert: does not exist");return
|
|
162
|
-
t,
|
|
163
|
-
n=
|
|
164
|
-
cmov(m,f,
|
|
165
|
-
|
|
166
|
-
if(
|
|
167
|
-
g=d.sqr(g),
|
|
168
|
-
|
|
169
|
-
t",BYTES:"number",BITS:"number"},n=
|
|
170
|
-
if(e.ORDER<=
|
|
171
|
-
ONE;if(n===
|
|
172
|
-
a:(
|
|
173
|
-
let n=
|
|
174
|
-
|
|
175
|
-
BITS=="number"&&(
|
|
176
|
-
freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:
|
|
177
|
-
048 bytes");this.ORDER=t,this.BITS=
|
|
178
|
-
t "+typeof t);return
|
|
179
|
-
return
|
|
180
|
-
ORDER)}sqrN(t){return t*t}addN(t,n){return t+n}subN(t,n){return t-n}mulN(t,n){return t*n}inv(t){return
|
|
181
|
-
return this.isLE?
|
|
182
|
-
eld.fromBytes: expected "+
|
|
183
|
-
let
|
|
184
|
-
ion"),
|
|
185
|
-
throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function
|
|
186
|
-
shiftBy:s}}function
|
|
187
|
-
isNeg:f,isNegF:m,offsetF:
|
|
188
|
-
t.ZERO,this.Fn=t.Fn,this.bits=n;}_unsafeLadder(t,n,
|
|
189
|
-
s=t,a=s;for(let
|
|
190
|
-
s=
|
|
191
|
-
ZERO){let i=
|
|
192
|
-
get(n);return
|
|
193
|
-
t);return i===1?this._unsafeLadder(t,n,
|
|
194
|
-
ds"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(let
|
|
195
|
-
let
|
|
196
|
-
freeze(Object.assign({},t)),{CURVE:t,Fp:
|
|
197
|
-
let n=t,
|
|
198
|
-
sqrt(
|
|
199
|
-
g,
|
|
200
|
-
this.X=u("x",g),this.Y=u("y",
|
|
201
|
-
x:
|
|
202
|
-
|
|
203
|
-
throw new Error("bad point: x=0 and x_0=1");return
|
|
204
|
-
y}precompute(g=8,
|
|
205
|
-
|
|
206
|
-
left != right (2)")}equals(g){f(g);let{X:
|
|
207
|
-
Y,this.Z,
|
|
208
|
-
|
|
209
|
-
ie*
|
|
210
|
-
this,g,
|
|
211
|
-
g,
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
8),Object.freeze(m.prototype),Object.freeze(m),m}var
|
|
215
|
-
toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity();}toAffine(t){return this.ep.toAffine(t)}toHex(){return
|
|
235
|
+
00d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),Pp=Na[0],Op=Na[1],bt=new Uint32Array(80),vt=new Uint32Array(80),Gr=class extends bo{constructor(t){
|
|
236
|
+
super(128,t,16,false);}get(){let{Ah:t,Al:n,Bh:o,Bl:r,Ch:i,Cl:s,Dh:a,Dl:l,Eh:c,El:d,Fh:u,Fl:f,Gh:m,Gl:h,Hh:v,Hl:g}=this;return [t,n,o,r,i,s,a,l,c,d,u,f,m,h,v,g]}set(t,n,o,r,i,s,a,l,c,d,u,f,m,h,v,g){this.Ah=
|
|
237
|
+
t|0,this.Al=n|0,this.Bh=o|0,this.Bl=r|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=l|0,this.Eh=c|0,this.El=d|0,this.Fh=u|0,this.Fl=f|0,this.Gh=m|0,this.Gl=h|0,this.Hh=v|0,this.Hl=g|0;}process(t,n){for(let S=0;S<
|
|
238
|
+
16;S++,n+=4)bt[S]=t.getUint32(n),vt[S]=t.getUint32(n+=4);for(let S=16;S<80;S++){let w=bt[S-15]|0,I=vt[S-15]|0,D=It(w,I,1)^It(w,I,8)^qr(w,I,7),P=Dt(w,I,1)^Dt(w,I,8)^Hr(w,I,7),O=bt[S-2]|0,j=vt[S-2]|0,J=It(
|
|
239
|
+
O,j,19)^xn(O,j,61)^qr(O,j,6),ee=Dt(O,j,19)^Sn(O,j,61)^Hr(O,j,6),C=Oa(P,ee,vt[S-7],vt[S-16]),R=La(C,D,J,bt[S-7],bt[S-16]);bt[S]=R|0,vt[S]=C|0;}let{Ah:o,Al:r,Bh:i,Bl:s,Ch:a,Cl:l,Dh:c,Dl:d,Eh:u,El:f,Fh:m,
|
|
240
|
+
Fl:h,Gh:v,Gl:g,Hh:y,Hl:k}=this;for(let S=0;S<80;S++){let w=It(u,f,14)^It(u,f,18)^xn(u,f,41),I=Dt(u,f,14)^Dt(u,f,18)^Sn(u,f,41),D=u&m^~u&v,P=f&h^~f&g,O=Ma(k,I,P,Op[S],vt[S]),j=$a(O,y,w,D,Pp[S],bt[S]),J=O|
|
|
241
|
+
0,ee=It(o,r,28)^xn(o,r,34)^xn(o,r,39),C=Dt(o,r,28)^Sn(o,r,34)^Sn(o,r,39),R=o&i^o&a^i&a,$=r&s^r&l^s&l;y=v|0,k=g|0,v=m|0,g=h|0,m=u|0,h=f|0,{h:u,l:f}=He(c|0,d|0,j|0,J|0),c=a|0,d=l|0,a=i|0,l=s|0,i=o|0,s=r|
|
|
242
|
+
0;let F=Da(J,C,$);o=Pa(F,j,ee,R),r=F|0;}(({h:o,l:r}=He(this.Ah|0,this.Al|0,o|0,r|0))),{h:i,l:s}=He(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l}=He(this.Ch|0,this.Cl|0,a|0,l|0),{h:c,l:d}=He(this.Dh|0,this.Dl|0,c|
|
|
243
|
+
0,d|0),{h:u,l:f}=He(this.Eh|0,this.El|0,u|0,f|0),{h:m,l:h}=He(this.Fh|0,this.Fl|0,m|0,h|0),{h:v,l:g}=He(this.Gh|0,this.Gl|0,v|0,g|0),{h:y,l:k}=He(this.Hh|0,this.Hl|0,y|0,k|0),this.set(o,r,i,s,a,l,c,d,
|
|
244
|
+
u,f,m,h,v,g,y,k);}roundClean(){kn(bt,vt);}destroy(){this.destroyed=true,kn(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}},Wr=class extends Gr{Ah=de[0]|0;Al=de[1]|0;Bh=de[2]|0;Bl=de[3]|0;Ch=de[4]|
|
|
245
|
+
0;Cl=de[5]|0;Dh=de[6]|0;Dl=de[7]|0;Eh=de[8]|0;El=de[9]|0;Fh=de[10]|0;Fl=de[11]|0;Gh=de[12]|0;Gl=de[13]|0;Hh=de[14]|0;Hl=de[15]|0;constructor(){super(64);}};var yo=Ca(()=>new Wr,Ra(3));var re=(e,t,n)=>Be(e,t,n),Kr=mo,Yr=go,Ge=(...e)=>Vr(...e),ja=e=>wn(e),xo=Fr,Ba=e=>Ta(e),wo=BigInt(0),Jr=BigInt(1);function Zt(e,t=""){if(typeof e!="boolean"){let n=t&&`"${t}" `;throw new TypeError(n+"\
|
|
246
|
+
expected boolean, got type="+typeof e)}return e}function Lp(e){if(typeof e=="bigint"){if(!ko(e))throw new RangeError("positive bigint expected, got "+e)}else Kr(e);return e}function it(e,t=""){if(typeof e!=
|
|
247
|
+
"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 Ua(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);return e===""?wo:BigInt("0x"+e)}function Qr(e){return Ua(go(e))}function st(e){return Ua(go(En(Be(e)).reverse()))}
|
|
248
|
+
function Xr(e,t){if(mo(t),t===0)throw new RangeError("zero length");e=Lp(e);let n=e.toString(16);if(n.length>t*2)throw new RangeError("number too large");return wn(n.padStart(t*2,"0"))}function Fa(e,t){
|
|
249
|
+
return Xr(e,t).reverse()}function za(e,t){if(e=re(e),t=re(t),e.length!==t.length)return false;let n=0;for(let o=0;o<e.length;o++)n|=e[o]^t[o];return n===0}function En(e){return Uint8Array.from(re(e))}var ko=e=>typeof e=="bigint"&&wo<=e;function Mp(e,t,n){return ko(e)&&ko(t)&&ko(n)&&t<=e&&e<n}function Zr(e,t,n,o){if(!Mp(t,n,o))throw new RangeError(
|
|
250
|
+
"expected valid "+e+": "+n+" <= n < "+o+", got "+t)}function ei(e){if(e<wo)throw new Error("expected non-negative bigint, got "+e);let t;for(t=0;e>wo;e>>=Jr,t+=1);return t}var Va=e=>(Jr<<BigInt(e))-Jr;function Pt(e,t={},n={}){if(Object.prototype.toString.call(e)!=="[object Object]")throw new TypeError("expected valid options object");function o(i,s,a){if(!a&&s!=="function"&&!Object.hasOwn(e,i))throw new TypeError(
|
|
251
|
+
`param "${i}" is invalid: expected own property`);let l=e[i];if(a&&l===void 0)return;let c=typeof l;if(c!==s||l===null)throw new TypeError(`param "${i}" is invalid: expected ${s}, got ${c}`)}let r=(i,s)=>Object.
|
|
252
|
+
entries(i).forEach(([a,l])=>o(a,l,s));r(t,false),r(n,true);}var ti=()=>{throw new Error("not implemented")};var pe=BigInt(0),ae=BigInt(1),Ot=BigInt(2),Wa=BigInt(3),Ja=BigInt(4),Ka=BigInt(5),$p=BigInt(7),Ya=BigInt(8),Np=BigInt(9),Qa=BigInt(16);function ne(e,t){if(t<=pe)throw new Error("mod: expected positive\
|
|
253
|
+
modulus, got "+t);let n=e%t;return n>=pe?n:t+n}function Ue(e,t,n){if(t<pe)throw new Error("pow2: expected non-negative exponent, got "+t);let o=e;for(;t-- >pe;)o*=o,o%=n;return o}function qa(e,t){if(e===pe)throw new Error("invert: expected non-zer\
|
|
254
|
+
o number");if(t<=pe)throw new Error("invert: expected positive modulus, got "+t);let n=ne(e,t),o=t,r=pe,s=ae;for(;n!==pe;){let c=o/n,d=o-n*c,u=r-s*c;o=n,n=d,r=s,s=u;}if(o!==ae)
|
|
255
|
+
throw new Error("invert: does not exist");return ne(r,t)}function ni(e,t,n){let o=e;if(!o.eql(o.sqr(t),n))throw new Error("Cannot find square root")}function Xa(e,t){let n=e,o=(n.ORDER+ae)/Ja,r=n.pow(
|
|
256
|
+
t,o);return ni(n,r,t),r}function jp(e,t){let n=e,o=(n.ORDER-Ka)/Ya,r=n.mul(t,Ot),i=n.pow(r,o),s=n.mul(t,i),a=n.mul(n.mul(s,Ot),i),l=n.mul(s,n.sub(a,n.ONE));return ni(n,l,t),l}function Bp(e){let t=Co(e),
|
|
257
|
+
n=Za(e),o=n(t,t.neg(t.ONE)),r=n(t,o),i=n(t,t.neg(o)),s=(e+$p)/Qa;return((a,l)=>{let c=a,d=c.pow(l,s),u=c.mul(d,o),f=c.mul(d,r),m=c.mul(d,i),h=c.eql(c.sqr(u),l),v=c.eql(c.sqr(f),l);d=c.cmov(d,u,h),u=c.
|
|
258
|
+
cmov(m,f,v);let g=c.eql(c.sqr(u),l),y=c.cmov(d,u,g);return ni(c,y,l),y})}function Za(e){if(e<Wa)throw new Error("sqrt is not defined for small field");let t=e-ae,n=0;for(;t%Ot===pe;)t/=Ot,n++;let o=Ot,
|
|
259
|
+
r=Co(e);for(;Ha(r,o)===1;)if(o++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Xa;let i=r.pow(o,t),s=(t+ae)/Ot;return function(l,c){let d=l;if(d.is0(c))return c;
|
|
260
|
+
if(Ha(d,c)!==1)throw new Error("Cannot find square root");let u=n,f=d.mul(d.ONE,i),m=d.pow(c,t),h=d.pow(c,s);for(;!d.eql(m,d.ONE);){if(d.is0(m))return d.ZERO;let v=1,g=d.sqr(m);for(;!d.eql(g,d.ONE);)if(v++,
|
|
261
|
+
g=d.sqr(g),v===u)throw new Error("Cannot find square root");let y=ae<<BigInt(u-v-1),k=d.pow(f,y);u=v,f=d.sqr(k),m=d.mul(m,f),h=d.mul(h,k);}return h}}function Up(e){return e%Ja===Wa?Xa:e%Ya===Ka?jp:e%Qa===
|
|
262
|
+
Np?Bp(e):Za(e)}var at=(e,t)=>(ne(e,t)&ae)===ae,Fp=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ec(e){let t={ORDER:"bigin\
|
|
263
|
+
t",BYTES:"number",BITS:"number"},n=Fp.reduce((o,r)=>(o[r]="function",o),t);if(Pt(e,n),it(e.BYTES,"BYTES"),it(e.BITS,"BITS"),e.BYTES<1||e.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");
|
|
264
|
+
if(e.ORDER<=ae)throw new Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function zp(e,t,n){let o=e;if(n<pe)throw new Error("invalid exponent, negatives unsupported");if(n===pe)return o.
|
|
265
|
+
ONE;if(n===ae)return t;let r=o.ONE,i=t;for(;n>pe;)n&ae&&(r=o.mul(r,i)),i=o.sqr(i),n>>=ae;return r}function _o(e,t,n=false){let o=e,r=new Array(t.length).fill(n?o.ZERO:void 0),i=t.reduce((a,l,c)=>o.is0(l)?
|
|
266
|
+
a:(r[c]=a,o.mul(a,l)),o.ONE),s=o.inv(i);return t.reduceRight((a,l,c)=>o.is0(l)?a:(r[c]=o.mul(a,r[c]),o.mul(a,l)),s),r}function Ha(e,t){let n=e,o=(n.ORDER-ae)/Ot,r=n.pow(t,o),i=n.eql(r,n.ONE),s=n.eql(r,n.ZERO),a=n.eql(r,n.neg(n.ONE));if(!i&&!s&&!a)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function Vp(e,t){if(t!==void 0&&Kr(t),e<=pe)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);
|
|
267
|
+
let n=ei(e);if(t!==void 0&&t<n)throw new Error(`invalid n length: expected bit length (${n}) >= n.length (${t})`);let o=t!==void 0?t:n,r=Math.ceil(o/8);return {nBitLength:o,nByteLength:r}}var Ga=new WeakMap,
|
|
268
|
+
Eo=class{ORDER;BITS;BYTES;isLE;ZERO=pe;ONE=ae;_lengths;_mod;constructor(t,n={}){if(t<=ae)throw new Error("invalid field: expected ORDER > 1, got "+t);let o;this.isLE=false,n!=null&&typeof n=="object"&&(typeof n.
|
|
269
|
+
BITS=="number"&&(o=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.
|
|
270
|
+
freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:r,nByteLength:i}=Vp(t,o);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2\
|
|
271
|
+
048 bytes");this.ORDER=t,this.BITS=r,this.BYTES=i,Object.freeze(this);}create(t){return ne(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new TypeError("invalid field element: expected bigint, go\
|
|
272
|
+
t "+typeof t);return pe<=t&&t<this.ORDER}is0(t){return t===pe}isValidNot0(t){return !this.is0(t)&&this.isValid(t)}isOdd(t){return (t&ae)===ae}neg(t){return ne(-t,this.ORDER)}eql(t,n){return t===n}sqr(t){
|
|
273
|
+
return ne(t*t,this.ORDER)}add(t,n){return ne(t+n,this.ORDER)}sub(t,n){return ne(t-n,this.ORDER)}mul(t,n){return ne(t*n,this.ORDER)}pow(t,n){return zp(this,t,n)}div(t,n){return ne(t*qa(n,this.ORDER),this.
|
|
274
|
+
ORDER)}sqrN(t){return t*t}addN(t,n){return t+n}subN(t,n){return t-n}mulN(t,n){return t*n}inv(t){return qa(t,this.ORDER)}sqrt(t){let n=Ga.get(this);return n||Ga.set(this,n=Up(this.ORDER)),n(this,t)}toBytes(t){
|
|
275
|
+
return this.isLE?Fa(t,this.BYTES):Xr(t,this.BYTES)}fromBytes(t,n=false){re(t);let{_lengths:o,BYTES:r,isLE:i,ORDER:s,_mod:a}=this;if(o){if(t.length<1||!o.includes(t.length)||t.length>r)throw new Error("Fi\
|
|
276
|
+
eld.fromBytes: expected "+o+" bytes, got "+t.length);let c=new Uint8Array(r);c.set(t,i?0:c.length-t.length),t=c;}if(t.length!==r)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+t.length);
|
|
277
|
+
let l=i?st(t):Qr(t);if(a&&(l=ne(l,s)),!n&&!this.isValid(l))throw new Error("invalid field element: outside of range 0..ORDER");return l}invertBatch(t){return _o(this,t)}cmov(t,n,o){return Zt(o,"condit\
|
|
278
|
+
ion"),o?n:t}};Object.freeze(Eo.prototype);function Co(e,t={}){return new Eo(e,t)}var To=BigInt(0),si=BigInt(1);function tc(e,t){let n=t.negate();return e?n:t}function Ao(e,t){let n=_o(e.Fp,t.map(o=>o.Z));return t.map((o,r)=>e.fromAffine(o.toAffine(n[r])))}function ic(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)
|
|
279
|
+
throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function oi(e,t){ic(e,t);let n=Math.ceil(t/e)+1,o=2**(e-1),r=2**e,i=Va(e),s=BigInt(e);return {windows:n,windowSize:o,mask:i,maxNumber:r,
|
|
280
|
+
shiftBy:s}}function nc(e,t,n){let{windowSize:o,mask:r,maxNumber:i,shiftBy:s}=n,a=Number(e&r),l=e>>s;a>o&&(a-=i,l+=si);let c=t*o,d=c+Math.abs(a)-1,u=a===0,f=a<0,m=t%2!==0;return {nextN:l,offset:d,isZero:u,
|
|
281
|
+
isNeg:f,isNegF:m,offsetF:c}}var ri=new WeakMap,sc=new WeakMap;function ii(e){return sc.get(e)||1}function oc(e){if(e!==To)throw new Error("invalid wNAF")}var Ro=class{BASE;ZERO;Fn;bits;constructor(t,n){this.BASE=t.BASE,this.ZERO=
|
|
282
|
+
t.ZERO,this.Fn=t.Fn,this.bits=n;}_unsafeLadder(t,n,o=this.ZERO){let r=t;for(;n>To;)n&si&&(o=o.add(r)),r=r.double(),n>>=si;return o}precomputeWindow(t,n){let{windows:o,windowSize:r}=oi(n,this.bits),i=[],
|
|
283
|
+
s=t,a=s;for(let l=0;l<o;l++){a=s,i.push(a);for(let c=1;c<r;c++)a=a.add(s),i.push(a);s=a.double();}return i}wNAF(t,n,o){if(!this.Fn.isValid(o))throw new Error("invalid scalar");let r=this.ZERO,i=this.BASE,
|
|
284
|
+
s=oi(t,this.bits);for(let a=0;a<s.windows;a++){let{nextN:l,offset:c,isZero:d,isNeg:u,isNegF:f,offsetF:m}=nc(o,a,s);o=l,d?i=i.add(tc(f,n[m])):r=r.add(tc(u,n[c]));}return oc(o),{p:r,f:i}}wNAFUnsafe(t,n,o,r=this.
|
|
285
|
+
ZERO){let i=oi(t,this.bits);for(let s=0;s<i.windows&&o!==To;s++){let{nextN:a,offset:l,isZero:c,isNeg:d}=nc(o,s,i);if(o=a,!c){let u=n[l];r=r.add(d?u.negate():u);}}return oc(o),r}getPrecomputes(t,n,o){let r=ri.
|
|
286
|
+
get(n);return r||(r=this.precomputeWindow(n,t),t!==1&&(typeof o=="function"&&(r=o(r)),ri.set(n,r))),r}cached(t,n,o){let r=ii(t);return this.wNAF(r,this.getPrecomputes(r,t,o),n)}unsafe(t,n,o,r){let i=ii(
|
|
287
|
+
t);return i===1?this._unsafeLadder(t,n,r):this.wNAFUnsafe(i,this.getPrecomputes(i,t,o),n,r)}createCache(t,n){ic(n,this.bits),sc.set(t,n),ri.delete(t);}hasCache(t){return ii(t)!==1}};function rc(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return ec(t),t}else return Co(e,{isLE:n})}function ac(e,t,n={},o){if(o===void 0&&(o=e==="edwar\
|
|
288
|
+
ds"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(let l of ["p","n","h"]){let c=t[l];if(!(typeof c=="bigint"&&c>To))throw new Error(`CURVE.${l} must be positive bigint`)}
|
|
289
|
+
let r=rc(t.p,n.Fp,o),i=rc(t.n,n.Fn,o),a=["Gx","Gy","a","d"];for(let l of a)if(!r.isValid(t[l]))throw new Error(`CURVE.${l} must be valid field element of CURVE.Fp`);return t=Object.
|
|
290
|
+
freeze(Object.assign({},t)),{CURVE:t,Fp:r,Fn:i}}function cc(e,t){return function(o){let r=e(o);return {secretKey:r,publicKey:t(r)}}}var yt=BigInt(0),ce=BigInt(1),ai=BigInt(2),qp=BigInt(8);function Hp(e,t,n,o){let r=e.sqr(n),i=e.sqr(o),s=e.add(e.mul(t.a,r),i),a=e.add(e.ONE,e.mul(t.d,e.mul(r,i)));return e.eql(s,a)}function lc(e,t={}){
|
|
291
|
+
let n=t,o=ac("edwards",e,n,n.FpFnLE),{Fp:r,Fn:i}=o,s=o.CURVE,{h:a}=s;Pt(n,{},{uvRatio:"function"});let l=ai<<BigInt(i.BYTES*8)-ce,c=v=>r.create(v),d=n.uvRatio===void 0?(v,g)=>{try{return {isValid:!0,value:r.
|
|
292
|
+
sqrt(r.div(v,g))}}catch{return {isValid:false,value:yt}}}:n.uvRatio;if(!Hp(r,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function u(v,g,y=false){let k=y?ce:yt;return Zr("coordinate "+v,
|
|
293
|
+
g,k,l),g}function f(v){if(!(v instanceof m))throw new Error("EdwardsPoint expected")}class m{static BASE=new m(s.Gx,s.Gy,ce,c(s.Gx*s.Gy));static ZERO=new m(yt,ce,ce,yt);static Fp=r;static Fn=i;X;Y;Z;T;constructor(g,y,k,S){
|
|
294
|
+
this.X=u("x",g),this.Y=u("y",y),this.Z=u("z",k,true),this.T=u("t",S),Object.freeze(this);}static CURVE(){return s}static fromAffine(g){if(g instanceof m)throw new Error("extended point not allowed");let{
|
|
295
|
+
x:y,y:k}=g||{};return u("x",y),u("y",k),new m(y,k,ce,c(y*k))}static fromBytes(g,y=false){let k=r.BYTES,{a:S,d:w}=s;g=En(re(g,k,"point")),Zt(y,"zip215");let I=En(g),D=g[k-1];I[k-1]=D&-129;let P=st(I),O=y?
|
|
296
|
+
l:r.ORDER;Zr("point.y",P,yt,O);let j=c(P*P),J=c(j-ce),ee=c(w*j-S),{isValid:C,value:R}=d(J,ee);if(!C)throw new Error("bad point: invalid y coordinate");let $=(R&ce)===ce,F=(D&128)!==0;if(!y&&R===yt&&F)
|
|
297
|
+
throw new Error("bad point: x=0 and x_0=1");return F!==$&&(R=c(-R)),m.fromAffine({x:R,y:P})}static fromHex(g,y=false){return m.fromBytes(ja(g),y)}get x(){return this.toAffine().x}get y(){return this.toAffine().
|
|
298
|
+
y}precompute(g=8,y=true){return h.createCache(this,g),y||this.multiply(ai),this}assertValidity(){let g=this,{a:y,d:k}=s;if(g.is0())throw new Error("bad point: ZERO");let{X:S,Y:w,Z:I,T:D}=g,P=c(S*S),O=c(
|
|
299
|
+
w*w),j=c(I*I),J=c(j*j),ee=c(P*y),C=c(j*c(ee+O)),R=c(J+c(k*c(P*O)));if(C!==R)throw new Error("bad point: equation left != right (1)");let $=c(S*w),F=c(I*D);if($!==F)throw new Error("bad point: equation\
|
|
300
|
+
left != right (2)")}equals(g){f(g);let{X:y,Y:k,Z:S}=this,{X:w,Y:I,Z:D}=g,P=c(y*D),O=c(w*S),j=c(k*D),J=c(I*S);return P===O&&j===J}is0(){return this.equals(m.ZERO)}negate(){return new m(c(-this.X),this.
|
|
301
|
+
Y,this.Z,c(-this.T))}double(){let{a:g}=s,{X:y,Y:k,Z:S}=this,w=c(y*y),I=c(k*k),D=c(ai*c(S*S)),P=c(g*w),O=y+k,j=c(c(O*O)-w-I),J=P+I,ee=J-D,C=P-I,R=c(j*ee),$=c(J*C),F=c(j*C),ie=c(ee*J);return new m(R,$,ie,
|
|
302
|
+
F)}add(g){f(g);let{a:y,d:k}=s,{X:S,Y:w,Z:I,T:D}=this,{X:P,Y:O,Z:j,T:J}=g,ee=c(S*P),C=c(w*O),R=c(D*k*J),$=c(I*j),F=c((S+w)*(P+O)-ee-C),ie=$-R,fe=$+R,Re=c(C-y*ee),Pe=c(F*ie),Ce=c(fe*Re),Xe=c(F*Re),Ae=c(
|
|
303
|
+
ie*fe);return new m(Pe,Ce,Ae,Xe)}subtract(g){return f(g),this.add(g.negate())}multiply(g){if(!i.isValidNot0(g))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:y,f:k}=h.cached(
|
|
304
|
+
this,g,S=>Ao(m,S));return Ao(m,[y,k])[0]}multiplyUnsafe(g){if(!i.isValid(g))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return g===yt?m.ZERO:this.is0()||g===ce?this:h.unsafe(this,
|
|
305
|
+
g,y=>Ao(m,y))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return h.unsafe(this,s.n).is0()}toAffine(g){let y=this,k=g,{X:S,Y:w,Z:I}=y,D=y.is0();k==null&&(k=D?qp:r.inv(I));let P=c(S*
|
|
306
|
+
k),O=c(w*k),j=r.mul(I,k);if(D)return {x:yt,y:ce};if(j!==ce)throw new Error("invZ was invalid");return {x:P,y:O}}clearCofactor(){return a===ce?this:this.multiplyUnsafe(a)}toBytes(){let{x:g,y}=this.toAffine(),
|
|
307
|
+
k=r.toBytes(y);return k[k.length-1]|=g&ce?128:0,k}toHex(){return Yr(this.toBytes())}toString(){return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let h=new Ro(m,i.BITS);return i.BITS>=8&&m.BASE.precompute(
|
|
308
|
+
8),Object.freeze(m.prototype),Object.freeze(m),m}var Io=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(t){this.ep=t;}static fromBytes(t){ti();}static fromHex(t){ti();}get x(){return this.
|
|
309
|
+
toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity();}toAffine(t){return this.ep.toAffine(t)}toHex(){return Yr(this.toBytes())}toString(){
|
|
216
310
|
return this.toHex()}isTorsionFree(){return true}isSmallOrder(){return false}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){return this.assertSame(t),this.init(this.ep.subtract(t.ep))}multiply(t){
|
|
217
311
|
return this.init(this.ep.multiply(t))}multiplyUnsafe(t){return this.init(this.ep.multiplyUnsafe(t))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,n){
|
|
218
|
-
return this.ep.precompute(t,n),this}};function
|
|
219
|
-
function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:i}=
|
|
220
|
-
`hash.outputLen must be ${d}, got ${
|
|
221
|
-
|
|
222
|
-
SecretKey"),
|
|
223
|
-
point:ie,pointBytes:
|
|
224
|
-
i&&(
|
|
225
|
-
alid s");let
|
|
226
|
-
"signature"),
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
57)throw new Error("only defined for 25519 and 448");let ie=
|
|
231
|
-
|
|
312
|
+
return this.ep.precompute(t,n),this}};function uc(e,t,n={}){if(typeof t!="function")throw new Error('"hash" function param is required');let o=t,r=n;Pt(r,{},{adjustScalarBytes:"function",randomBytes:"\
|
|
313
|
+
function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:i}=r,{BASE:s,Fp:a,Fn:l}=e,c=o.outputLen,d=2*a.BYTES;if(c!==void 0&&(it(c,"hash.outputLen"),c!==d))throw new Error(
|
|
314
|
+
`hash.outputLen must be ${d}, got ${c}`);let u=r.randomBytes===void 0?Ba:r.randomBytes,f=r.adjustScalarBytes===void 0?C=>C:r.adjustScalarBytes,m=r.domain===void 0?(C,R,$)=>{if(Zt($,"phflag"),R.length||
|
|
315
|
+
$)throw new Error("Contexts/pre-hash are not supported");return C}:r.domain;function h(C){return l.create(st(C))}function v(C){let R=P.secretKey;re(C,P.secretKey,"secretKey");let $=re(o(C),2*R,"hashed\
|
|
316
|
+
SecretKey"),F=f($.slice(0,R)),ie=$.slice(R,2*R),fe=h(F);return {head:F,prefix:ie,scalar:fe}}function g(C){let{head:R,prefix:$,scalar:F}=v(C),ie=s.multiply(F),fe=ie.toBytes();return {head:R,prefix:$,scalar:F,
|
|
317
|
+
point:ie,pointBytes:fe}}function y(C){return g(C).pointBytes}function k(C=Uint8Array.of(),...R){let $=Ge(...R);return h(o(m($,re(C,void 0,"context"),!!i)))}function S(C,R,$={}){C=re(C,void 0,"message"),
|
|
318
|
+
i&&(C=i(C));let{prefix:F,scalar:ie,pointBytes:fe}=g(R),Re=k($.context,F,C),Pe=s.multiply(Re).toBytes(),Ce=k($.context,Pe,fe,C),Xe=l.create(Re+Ce*ie);if(!l.isValid(Xe))throw new Error("sign failed: inv\
|
|
319
|
+
alid s");let Ae=Ge(Pe,l.toBytes(Xe));return re(Ae,P.signature,"result")}let w={zip215:r.zip215};function I(C,R,$,F=w){let{context:ie}=F,fe=F.zip215===void 0?!!w.zip215:F.zip215,Re=P.signature;C=re(C,Re,
|
|
320
|
+
"signature"),R=re(R,void 0,"message"),$=re($,P.publicKey,"publicKey"),fe!==void 0&&Zt(fe,"zip215"),i&&(R=i(R));let Pe=Re/2,Ce=C.subarray(0,Pe),Xe=st(C.subarray(Pe,Re)),Ae,qt,dt;try{Ae=e.fromBytes($,fe),
|
|
321
|
+
qt=e.fromBytes(Ce,fe),dt=s.multiplyUnsafe(Xe);}catch{return false}if(!fe&&Ae.isSmallOrder())return false;let Zn=k(ie,Ce,$,R);return qt.add(Ae.multiplyUnsafe(Zn)).subtract(dt).clearCofactor().is0()}let D=a.BYTES,
|
|
322
|
+
P={secretKey:D,publicKey:D,signature:2*D,seed:D};function O(C){return C=C===void 0?u(P.seed):C,re(C,P.seed,"seed")}function j(C){return xo(C)&&C.length===P.secretKey}function J(C,R){try{return !!e.fromBytes(
|
|
323
|
+
C,R===void 0?w.zip215:R)}catch{return false}}let ee={getExtendedPublicKey:g,randomSecretKey:O,isValidSecretKey:j,isValidPublicKey:J,toMontgomery(C){let{y:R}=e.fromBytes(C),$=P.publicKey,F=$===32;if(!F&&$!==
|
|
324
|
+
57)throw new Error("only defined for 25519 and 448");let ie=F?a.div(ce+R,ce-R):a.div(R-ce,R+ce);return a.toBytes(ie)},toMontgomerySecret(C){let R=P.secretKey;re(C,R);let $=o(C.subarray(0,R));return f(
|
|
325
|
+
$).subarray(0,R)}};return Object.freeze(P),Object.freeze(ee),Object.freeze({keygen:cc(O,y),getPublicKey:y,sign:S,verify:I,utils:ee,Point:e,lengths:P})}var Jp=BigInt(0),ct=BigInt(1),pc=BigInt(2);var Kp=BigInt(5),Yp=BigInt(8),en=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),pi={p:en,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Yp,
|
|
232
326
|
a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6d\
|
|
233
|
-
c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function
|
|
234
|
-
i*e%i,
|
|
235
|
-
return e[0]&=248,e[31]&=127,e[31]|=64,e}var
|
|
236
|
-
s=
|
|
237
|
-
Fn;function
|
|
238
|
-
"1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var
|
|
239
|
-
fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),
|
|
240
|
-
|
|
241
|
-
oint expected")}init(t){return new e(t)}static fromBytes(t){
|
|
242
|
-
let a=i(s*s),
|
|
243
|
-
"invalid ristretto255 encoding 2");return new e(new
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
e.measure_grace_days:0;return {...e,expires_at:e.measure_expires_at,grace_days:Math.max(0,t)}}var
|
|
327
|
+
c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Qp(e){let t=BigInt(10),n=BigInt(20),o=BigInt(40),r=BigInt(80),i=en,a=e*e%
|
|
328
|
+
i*e%i,l=Ue(a,pc,i)*a%i,c=Ue(l,ct,i)*e%i,d=Ue(c,Kp,i)*c%i,u=Ue(d,t,i)*d%i,f=Ue(u,n,i)*u%i,m=Ue(f,o,i)*f%i,h=Ue(m,r,i)*m%i,v=Ue(h,r,i)*m%i,g=Ue(v,t,i)*d%i;return {pow_p_5_8:Ue(g,pc,i)*e%i,b2:a}}function Xp(e){
|
|
329
|
+
return e[0]&=248,e[31]&=127,e[31]|=64,e}var li=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function fi(e,t){let n=en,o=ne(t*t*t,n),r=ne(o*o*t,n),i=Qp(e*r).pow_p_5_8,
|
|
330
|
+
s=ne(e*o*i,n),a=ne(t*s*s,n),l=s,c=ne(s*li,n),d=a===e,u=a===ne(-e,n),f=a===ne(-e*li,n);return d&&(s=l),(u||f)&&(s=c),at(s,n)&&(s=ne(-s,n)),{isValid:d||u,value:s}}var wt=lc(pi,{uvRatio:fi}),kt=wt.Fp,hc=wt.
|
|
331
|
+
Fn;function Zp(e){return uc(wt,yo,Object.assign({adjustScalarBytes:Xp,zip215:true},e))}var gc=Zp({});var ui=li;BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");var tf=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt(
|
|
332
|
+
"1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var fc=e=>fi(ct,e),rf=BigInt("0x7\
|
|
333
|
+
fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),di=e=>kt.create(st(e)&rf);var xt=class e extends Io{static BASE=new e(
|
|
334
|
+
wt.BASE);static ZERO=new e(wt.ZERO);static Fp=kt;static Fn=hc;constructor(t){super(t);}static fromAffine(t){return new e(wt.fromAffine(t))}assertSame(t){if(!(t instanceof e))throw new Error("RistrettoP\
|
|
335
|
+
oint expected")}init(t){return new e(t)}static fromBytes(t){Be(t,32);let{a:n,d:o}=pi,r=en,i=w=>kt.create(w),s=di(t);if(!za(kt.toBytes(s),t)||at(s,r))throw new Error("invalid ristretto255 encoding 1");
|
|
336
|
+
let a=i(s*s),l=i(ct+n*a),c=i(ct-n*a),d=i(l*l),u=i(c*c),f=i(n*o*d-u),{isValid:m,value:h}=fc(i(f*u)),v=i(h*c),g=i(h*v*f),y=i((s+s)*v);at(y,r)&&(y=i(-y));let k=i(l*g),S=i(y*k);if(!m||at(S,r)||k===Jp)throw new Error(
|
|
337
|
+
"invalid ristretto255 encoding 2");return new e(new wt(y,k,ct,S))}static fromHex(t){return e.fromBytes(wn(t))}toBytes(){let{X:t,Y:n,Z:o,T:r}=this.ep,i=en,s=g=>kt.create(g),a=s(s(o+n)*s(o-n)),l=s(t*n),
|
|
338
|
+
c=s(l*l),{value:d}=fc(s(a*c)),u=s(d*a),f=s(d*l),m=s(u*f*r),h;if(at(r*m,i)){let g=s(n*ui),y=s(t*ui);t=g,n=y,h=s(u*tf);}else h=f;at(t*m,i)&&(n=s(-n));let v=s((o-n)*h);return at(v,i)&&(v=s(-v)),kt.toBytes(
|
|
339
|
+
v)}equals(t){this.assertSame(t);let{X:n,Y:o}=this.ep,{X:r,Y:i}=t.ep,s=c=>kt.create(c),a=s(n*i)===s(o*r),l=s(o*i)===s(n*r);return a||l}is0(){return this.equals(e.ZERO)}};Object.freeze(xt.BASE);Object.freeze(
|
|
340
|
+
xt.ZERO);Object.freeze(xt.prototype);Object.freeze(xt);function Do(e){if(e.plan!=="measure"||typeof e.measure_expires_at!="number"||!Number.isFinite(e.measure_expires_at))return e;let t=typeof e.measure_grace_days=="number"&&Number.isFinite(e.measure_grace_days)?
|
|
341
|
+
e.measure_grace_days:0;return {...e,expires_at:e.measure_expires_at,grace_days:Math.max(0,t)}}var Lt=`-----BEGIN PUBLIC KEY-----
|
|
248
342
|
MCowBQYDK2VwAyEAWBiklf0kmDIVmM7nMiCxwiEAkwQIiqWGuRiRDJonsFY=
|
|
249
|
-
-----END PUBLIC KEY-----`;function
|
|
250
|
-
length%4?"=".repeat(4-t.length%4):"";return
|
|
251
|
-
function
|
|
252
|
-
function
|
|
253
|
-
oken"};let n=e.split("."),
|
|
254
|
-
u=t.keys[d];if(!u)return {ok:false,reason:`unknown key id "${d}"`};a=u;}else {if(!t)return {ok:false,reason:"no verification key"};a=t;}let
|
|
255
|
-
return {ok:false,reason:"invalid public key"}}let
|
|
256
|
-
{ok:false,reason:"bad signature"}}function
|
|
257
|
-
signatureValid:!0,payload:
|
|
258
|
-
e.expires_at?"active":t<=
|
|
259
|
-
if(
|
|
260
|
-
seq!="number"||typeof i.asOf!="number"||!Array.isArray(i.revoked))return
|
|
261
|
-
nowSeconds??Math.floor(Date.now()/1e3),
|
|
343
|
+
-----END PUBLIC KEY-----`;function bc(e){let t=atob(e),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n}function mi(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.
|
|
344
|
+
length%4?"=".repeat(4-t.length%4):"";return bc(t+n)}function af(e){let t=e.replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=bc(t);return n.subarray(n.length-32)}var cf=new TextEncoder,vc=new TextDecoder;
|
|
345
|
+
function hi(e){return typeof e=="object"&&e!==null&&"keys"in e}function tn(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 lf=/^[A-Za-z0-9_-]+$/;
|
|
346
|
+
function yc(e){let t=e.split(".");return t.length===3&&t.every(n=>lf.test(n))}function Cn(e){return e===""?"empty":yc(e)?"token":"malformed"}function Tn(e,t){if(!yc(e))return {ok:false,reason:"malformed t\
|
|
347
|
+
oken"};let n=e.split("."),o=n[0],r=n[1],i=n[2],s;try{s=JSON.parse(vc.decode(mi(o)));}catch{return {ok:false,reason:"header is not valid JSON"}}let a;if(hi(t)){let d=typeof s.kid=="string"?s.kid:t.defaultKid,
|
|
348
|
+
u=t.keys[d];if(!u)return {ok:false,reason:`unknown key id "${d}"`};a=u;}else {if(!t)return {ok:false,reason:"no verification key"};a=t;}let l;try{if(l=af(a),l.length!==32)return {ok:!1,reason:"invalid public key"}}catch{
|
|
349
|
+
return {ok:false,reason:"invalid public key"}}let c=false;try{c=gc.verify(mi(i),cf.encode(`${o}.${r}`),l);}catch{return {ok:false,reason:"signature verification error"}}return c?{ok:true,header:s,payloadBytes:mi(r)}:
|
|
350
|
+
{ok:false,reason:"bad signature"}}function gi(e,t){let n=Tn(e,t);if(!n.ok||!n.payloadBytes)return {signatureValid:false,...n.reason?{reason:n.reason}:{}};try{let o=JSON.parse(vc.decode(n.payloadBytes));return {
|
|
351
|
+
signatureValid:!0,payload:Do(o)}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function Po(e,t,n){if(n?.has(e.jti))return "revoked";let o=e.expires_at+e.grace_days*86400;return t<=
|
|
352
|
+
e.expires_at?"active":t<=o?"grace":"expired"}var kc="BVSALA-REVOC",uf=300,df=new TextDecoder;function wc(e,t,n={}){let o=c=>({ok:false,seq:-1,asOf:0,revoked:new Set,reason:c}),r=Tn(e,t);if(!r.ok||!r.payloadBytes)return o(r.reason??"bad signature");
|
|
353
|
+
if(r.header?.typ!==kc)return o(`unexpected token type "${String(r.header?.typ??"")}" (want ${kc})`);let i;try{i=JSON.parse(df.decode(r.payloadBytes));}catch{return o("payload is not valid JSON")}if(typeof i.
|
|
354
|
+
seq!="number"||typeof i.asOf!="number"||!Array.isArray(i.revoked))return o("malformed revocation payload");let s=n.minSeq??0;if(i.seq<s)return o(`stale/rolled-back list (seq ${i.seq} < ${s})`);let a=n.
|
|
355
|
+
nowSeconds??Math.floor(Date.now()/1e3),l=n.maxSkewSeconds??uf;return i.asOf>a+l?o(`asOf too far in the future (${i.asOf} > ${a+l})`):{ok:true,seq:i.seq,asOf:i.asOf,revoked:new Set(i.revoked)}}var nn=class{_seq=-1;_asOf=0;_lastContactAt=0;set=new Set;get seq(){
|
|
262
356
|
return this._seq}get asOf(){return this._asOf}get lastContactAt(){return this._lastContactAt}markContact(t){t>this._lastContactAt&&(this._lastContactAt=t);}has(t){return this.set.has(t)}snapshot(){return this.
|
|
263
|
-
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
|
|
264
|
-
(this._asOf=t.asOf),r
|
|
265
|
-
|
|
266
|
-
expires_at+
|
|
267
|
-
isEntitled:f=>u()&&
|
|
268
|
-
0){let
|
|
269
|
-
|
|
357
|
+
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 o=this.set.size>n,r=t.seq>this._seq;return t.seq>this._seq&&(this._seq=t.seq),t.asOf>this._asOf&&
|
|
358
|
+
(this._asOf=t.asOf),o||r}};function Oo(e,t,n){let o=()=>Math.floor((n.now?n.now():Date.now())/1e3),r=n.startedAt??o(),i=tn(e),s=Cn(i),a=s==="token"?gi(i,t):{signatureValid:false,reason:s},l=a.signatureValid?a.payload:void 0,c=new Set(
|
|
359
|
+
l?.plan==="measure"?[]:l?.features??[]),d=()=>{if(s==="empty")return "none";if(!l)return "invalid";let f=Po(l,o(),n.revocation.snapshot());if(n.maxStalenessSeconds!=null&&(f==="active"||f==="grace")){let m=l.
|
|
360
|
+
expires_at+l.grace_days*86400,h=Math.min(r,m),v=Math.max(n.revocation.lastContactAt,h);if(o()-v>n.maxStalenessSeconds)return "stale"}return f},u=()=>{let f=d();return f==="active"||f==="grace"};return {
|
|
361
|
+
isEntitled:f=>u()&&c.has(f),isActive:()=>u(),status:d,reason:()=>l?void 0:a.reason,plan:()=>l&&u()?l.plan:void 0,refreshAfter:()=>{if(l)return Math.min(l.expires_at,o()+86400)}}}var on={pollIntervalSeconds:900,floorSeconds:300,maxIntervalSeconds:3600,jitterRatio:.1,maxSkewSeconds:300,requestTimeoutMs:3e4},xc=3,pf=12;function ff(e){let t=e.random??Math.random,n;if(e.consecutiveFailures>
|
|
362
|
+
0){let r=Math.pow(2,Math.min(e.consecutiveFailures,4));n=Math.min(e.maxIntervalSeconds,e.floorSeconds*r);}else {let r=e.refreshAfter!=null?e.refreshAfter-e.nowSeconds:e.pollIntervalSeconds,i=r<0?e.pollIntervalSeconds:
|
|
363
|
+
r;n=Math.min(e.pollIntervalSeconds,Math.max(e.floorSeconds,i));}let o=1+(t()*2-1)*e.jitterRatio;return Math.max(e.floorSeconds,n*o)}var mf=10,Rn=class{constructor(t){this.opts=t;}opts;timer=null;controller=null;consecutiveFailures=0;stopped=false;started=false;lastEtag=null;consecutive304=0;now(){
|
|
270
364
|
return this.opts.nowSeconds?this.opts.nowSeconds():Math.floor(Date.now()/1e3)}resolveFetch(){return this.opts.fetchImpl?this.opts.fetchImpl:typeof fetch<"u"?fetch:void 0}async pollOnce(){let t=this.resolveFetch();
|
|
271
365
|
if(!t){this.avisar("sin-fetch","[bv-sala] no global fetch available; revocation call-home disabled (offline). License expiry is still enforced from the token."),this.opts.onEvent?.({type:"no-fetch"});
|
|
272
|
-
return}let n=new AbortController;this.controller=n;let
|
|
366
|
+
return}let n=new AbortController;this.controller=n;let o=this.opts.requestTimeoutMs??on.requestTimeoutMs,r=setTimeout(()=>n.abort(),o);r.unref?.();let i={accept:"application/json"};this.lastEtag&&(i["\
|
|
273
367
|
if-none-match"]=this.lastEtag);try{let s=await t(this.opts.url,{signal:n.signal,headers:i});if(s.status===304){this.consecutiveFailures=0,this.opts.snapshot.markContact(this.now()),this.opts.onEvent?.(
|
|
274
|
-
{type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=
|
|
275
|
-
ions HTTP ${s.status}`);let a=s.headers.get("etag"),
|
|
276
|
-
opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??
|
|
368
|
+
{type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=mf&&(this.consecutive304=0,this.lastEtag=null);return}if(this.consecutive304=0,!s.ok)throw new Error(`revocat\
|
|
369
|
+
ions HTTP ${s.status}`);let a=s.headers.get("etag"),l=await s.json();if(!l.list)throw new Error("response missing `list`");this.consecutiveFailures=0;let c=wc(l.list,this.opts.publicKeyPem,{minSeq:this.
|
|
370
|
+
opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??on.maxSkewSeconds});if(!c.ok){let u=c.reason??"rejected";this.opts.onEvent?.({type:"rejected",reason:u}),this.avisar(`r\
|
|
277
371
|
echazada:${u}`,`[bv-sala] the revocation list does NOT verify (${u}). The last known-good list is kept, so revocations ALREADY known still apply, but new ones are not arriving. Check ${this.opts.url}.`);
|
|
278
|
-
return}a&&(this.lastEtag=a),this.opts.snapshot.markContact(this.now());let d=this.opts.snapshot.apply(
|
|
279
|
-
unchanged",seq:
|
|
280
|
-
silenceWarnings}avisar(t,n){this.callado()||
|
|
281
|
-
Error?t.message:String(t);console.warn(`[bv-sala] could not reach the revocation server ${n} times in a row (${
|
|
282
|
-
riving. Check egress to ${this.opts.url}.`);}start(){this.started||this.stopped||(this.started=true,this.pollOnce().finally(()=>this.schedule()));}schedule(){if(this.stopped)return;let t=
|
|
283
|
-
opts.getRefreshAfter?.(),nowSeconds:this.now(),consecutiveFailures:this.consecutiveFailures,floorSeconds:this.opts.floorSeconds??
|
|
284
|
-
maxIntervalSeconds:this.opts.maxIntervalSeconds??
|
|
285
|
-
pollOnce().finally(()=>this.schedule());},t*1e3),this.timer.unref?.();}stop(){this.stopped=true,this.timer&&(clearTimeout(this.timer),this.timer=null),this.controller?.abort();}};var
|
|
286
|
-
|
|
287
|
-
ni":
|
|
288
|
-
"gpt-5.4":
|
|
289
|
-
"gpt-5.4-mini":
|
|
290
|
-
outputPer1k:.015,largo:{estandar:{inputPer1k:.01,cachedInputPer1k:.001,outputPer1k:.045},tier:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225}}}),"gpt-5.6-luna":
|
|
372
|
+
return}a&&(this.lastEtag=a),this.opts.snapshot.markContact(this.now());let d=this.opts.snapshot.apply(c);this.opts.onEvent?.(d?{type:"applied",seq:c.seq,size:this.opts.snapshot.snapshot().size}:{type:"\
|
|
373
|
+
unchanged",seq:c.seq});}catch(s){this.consecutiveFailures++,this.opts.onEvent?.({type:"error",error:s}),this.avisarFalloDeRed(s);}finally{clearTimeout(r),this.controller=null;}}callado(){return !!this.opts.
|
|
374
|
+
silenceWarnings}avisar(t,n){this.callado()||Z(`poller:${this.opts.url}:${t}`,n);}avisarFalloDeRed(t){if(this.callado())return;let n=this.consecutiveFailures;if(n<xc||(n-xc)%pf!==0)return;let o=t instanceof
|
|
375
|
+
Error?t.message:String(t);console.warn(`[bv-sala] could not reach the revocation server ${n} times in a row (${o}). The license KEEPS working and known revocations still apply, but NEW ones are not ar\
|
|
376
|
+
riving. Check egress to ${this.opts.url}.`);}start(){this.started||this.stopped||(this.started=true,this.pollOnce().finally(()=>this.schedule()));}schedule(){if(this.stopped)return;let t=ff({refreshAfter:this.
|
|
377
|
+
opts.getRefreshAfter?.(),nowSeconds:this.now(),consecutiveFailures:this.consecutiveFailures,floorSeconds:this.opts.floorSeconds??on.floorSeconds,pollIntervalSeconds:this.opts.pollIntervalSeconds??on.pollIntervalSeconds,
|
|
378
|
+
maxIntervalSeconds:this.opts.maxIntervalSeconds??on.maxIntervalSeconds,jitterRatio:this.opts.jitterRatio??on.jitterRatio,...this.opts.random?{random:this.opts.random}:{}});this.timer=setTimeout(()=>{this.
|
|
379
|
+
pollOnce().finally(()=>this.schedule());},t*1e3),this.timer.unref?.();}stop(){this.stopped=true,this.timer&&(clearTimeout(this.timer),this.timer=null),this.controller?.abort();}};var hf="https://developers.openai.com/api/docs/pricing",gf="https://ai.google.dev/gemini-api/docs/pricing",bi="2026-09-27",N=e=>({...e,fuente:hf,consultado:bi}),We=e=>({...e,fuente:gf,consultado:bi}),
|
|
380
|
+
bf="https://platform.claude.com/docs/en/about-claude/pricing",le=e=>({...e,fuente:bf,consultado:bi});({openai:{flex:{"gpt-5":N({inputPer1k:625e-6,cachedInputPer1k:625e-7,outputPer1k:.005}),"gpt-5-mi\
|
|
381
|
+
ni":N({inputPer1k:125e-6,cachedInputPer1k:125e-7,outputPer1k:.001}),"gpt-5-nano":N({inputPer1k:25e-6,cachedInputPer1k:25e-7,outputPer1k:2e-4}),"gpt-5.2":N({inputPer1k:875e-6,cachedInputPer1k:875e-7,outputPer1k:.007}),
|
|
382
|
+
"gpt-5.4":N({inputPer1k:.00125,cachedInputPer1k:13e-5,outputPer1k:.0075,largo:{estandar:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225},tier:{inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.01125}}}),
|
|
383
|
+
"gpt-5.4-mini":N({inputPer1k:375e-6,cachedInputPer1k:375e-7,outputPer1k:.00225}),"gpt-5.4-nano":N({inputPer1k:1e-4,cachedInputPer1k:1e-5,outputPer1k:625e-6}),"gpt-5.5":N({inputPer1k:.0025,cachedInputPer1k:25e-5,
|
|
384
|
+
outputPer1k:.015,largo:{estandar:{inputPer1k:.01,cachedInputPer1k:.001,outputPer1k:.045},tier:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225}}}),"gpt-5.6-luna":N({inputPer1k:1e-4,cachedInputPer1k:1e-5,
|
|
291
385
|
cacheWritePer1k:125e-6,outputPer1k:6e-4,largo:{estandar:{inputPer1k:4e-4,cachedInputPer1k:4e-5,cacheWritePer1k:5e-4,outputPer1k:.0018},tier:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,
|
|
292
|
-
outputPer1k:9e-4}}}),"gpt-5.6-sol":
|
|
293
|
-
tier:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.015}},vigenteHasta:"2026-11-21"}),"gpt-5.6-terra":
|
|
294
|
-
largo:{estandar:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.018},tier:{inputPer1k:.002,cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.009}}}),o3:
|
|
295
|
-
cachedInputPer1k:25e-5,outputPer1k:.004}),"o4-mini":
|
|
296
|
-
largo:{estandar:{inputPer1k:.02,cachedInputPer1k:.002,cacheWritePer1k:.025,outputPer1k:.075},tier:{inputPer1k:.01,cachedInputPer1k:.001,cacheWritePer1k:.0125,outputPer1k:.0375}}}),"gpt-6-sol":
|
|
386
|
+
outputPer1k:9e-4}}}),"gpt-5.6-sol":N({inputPer1k:.002,cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.01,largo:{estandar:{inputPer1k:.008,cachedInputPer1k:8e-4,cacheWritePer1k:.01,outputPer1k:.03},
|
|
387
|
+
tier:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.015}},vigenteHasta:"2026-11-21"}),"gpt-5.6-terra":N({inputPer1k:.001,cachedInputPer1k:1e-4,cacheWritePer1k:.00125,outputPer1k:.006,
|
|
388
|
+
largo:{estandar:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.018},tier:{inputPer1k:.002,cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.009}}}),o3:N({inputPer1k:.001,
|
|
389
|
+
cachedInputPer1k:25e-5,outputPer1k:.004}),"o4-mini":N({inputPer1k:55e-5,cachedInputPer1k:138e-6,outputPer1k:.0022}),"gpt-6-astra":N({inputPer1k:.005,cachedInputPer1k:5e-4,cacheWritePer1k:.00625,outputPer1k:.025,
|
|
390
|
+
largo:{estandar:{inputPer1k:.02,cachedInputPer1k:.002,cacheWritePer1k:.025,outputPer1k:.075},tier:{inputPer1k:.01,cachedInputPer1k:.001,cacheWritePer1k:.0125,outputPer1k:.0375}}}),"gpt-6-sol":N({inputPer1k:.001,
|
|
297
391
|
cachedInputPer1k:1e-4,cacheWritePer1k:.00125,outputPer1k:.005,largo:{estandar:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.015},tier:{inputPer1k:.002,cachedInputPer1k:2e-4,
|
|
298
|
-
cacheWritePer1k:.0025,outputPer1k:.0075}}}),"gpt-6-luna":
|
|
299
|
-
outputPer1k:75e-5},tier:{inputPer1k:1e-4,cachedInputPer1k:1e-5,cacheWritePer1k:125e-6,outputPer1k:375e-6}}})},batch:{"gpt-6-astra":
|
|
300
|
-
largo:{estandar:{inputPer1k:.02,cachedInputPer1k:.002,cacheWritePer1k:.025,outputPer1k:.075},tier:{inputPer1k:.01,cachedInputPer1k:.001,cacheWritePer1k:.0125,outputPer1k:.0375}}}),"gpt-6-sol":
|
|
392
|
+
cacheWritePer1k:.0025,outputPer1k:.0075}}}),"gpt-6-luna":N({inputPer1k:5e-5,cachedInputPer1k:5e-6,cacheWritePer1k:625e-7,outputPer1k:25e-5,largo:{estandar:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,
|
|
393
|
+
outputPer1k:75e-5},tier:{inputPer1k:1e-4,cachedInputPer1k:1e-5,cacheWritePer1k:125e-6,outputPer1k:375e-6}}})},batch:{"gpt-6-astra":N({inputPer1k:.005,cachedInputPer1k:5e-4,cacheWritePer1k:.00625,outputPer1k:.025,
|
|
394
|
+
largo:{estandar:{inputPer1k:.02,cachedInputPer1k:.002,cacheWritePer1k:.025,outputPer1k:.075},tier:{inputPer1k:.01,cachedInputPer1k:.001,cacheWritePer1k:.0125,outputPer1k:.0375}}}),"gpt-6-sol":N({inputPer1k:.001,
|
|
301
395
|
cachedInputPer1k:1e-4,cacheWritePer1k:.00125,outputPer1k:.005,largo:{estandar:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.015},tier:{inputPer1k:.002,cachedInputPer1k:2e-4,
|
|
302
|
-
cacheWritePer1k:.0025,outputPer1k:.0075}}}),"gpt-6-luna":
|
|
303
|
-
outputPer1k:75e-5},tier:{inputPer1k:1e-4,cachedInputPer1k:1e-5,cacheWritePer1k:125e-6,outputPer1k:375e-6}}}),"gpt-5.6-sol":
|
|
396
|
+
cacheWritePer1k:.0025,outputPer1k:.0075}}}),"gpt-6-luna":N({inputPer1k:5e-5,cachedInputPer1k:5e-6,cacheWritePer1k:625e-7,outputPer1k:25e-5,largo:{estandar:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,
|
|
397
|
+
outputPer1k:75e-5},tier:{inputPer1k:1e-4,cachedInputPer1k:1e-5,cacheWritePer1k:125e-6,outputPer1k:375e-6}}}),"gpt-5.6-sol":N({inputPer1k:.002,cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.01,
|
|
304
398
|
largo:{estandar:{inputPer1k:.008,cachedInputPer1k:8e-4,cacheWritePer1k:.01,outputPer1k:.03},tier:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.015}},vigenteHasta:"2026-11-21"}),
|
|
305
|
-
"gpt-5.6-terra":
|
|
306
|
-
cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.009}}}),"gpt-5.6-luna":
|
|
307
|
-
cacheWritePer1k:5e-4,outputPer1k:.0018},tier:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,outputPer1k:9e-4}}}),"gpt-5.5":
|
|
308
|
-
estandar:{inputPer1k:.01,cachedInputPer1k:.001,outputPer1k:.045},tier:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225}}}),"gpt-5.4":
|
|
309
|
-
largo:{estandar:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225},tier:{inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.01125}}}),"gpt-5.4-mini":
|
|
310
|
-
outputPer1k:.00225}),"gpt-5.4-nano":
|
|
311
|
-
cachedInputPer1k:625e-7,outputPer1k:.005}),"gpt-5-mini":
|
|
312
|
-
4.1":
|
|
313
|
-
pt-4o-mini":
|
|
314
|
-
{inputPer1k:.01,outputPer1k:.04})}},anthropic:{batch:{"claude-fable-5-1":
|
|
315
|
-
cacheWritePer1k:.00625,outputPer1k:.025}),"claude-fable-5":
|
|
316
|
-
cacheWritePer1k:.00625,outputPer1k:.025}),"claude-opus-5-5":
|
|
317
|
-
cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-8":
|
|
318
|
-
cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-6":
|
|
319
|
-
cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4":
|
|
320
|
-
cacheWritePer1k:.00125,outputPer1k:.005}),"claude-sonnet-5-5":{...
|
|
321
|
-
cachedInputPer1k:15e-5,cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-sonnet-4-5":
|
|
322
|
-
cachedInputPer1k:15e-5,cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-haiku-4-5":
|
|
323
|
-
cachedInputPer1k:4e-5,cacheWritePer1k:5e-4,outputPer1k:.002})}},google:{flex:{"gemini-3.7-flash":
|
|
324
|
-
.5-flash":
|
|
325
|
-
outputPer1k:.006,cachedInputPer1k:2e-4,largo:{estandar:{inputPer1k:.004,outputPer1k:.018,cachedInputPer1k:4e-4},tier:{inputPer1k:.002,outputPer1k:.009,cachedInputPer1k:4e-4}}}),"gemini-2.5-pro":
|
|
399
|
+
"gpt-5.6-terra":N({inputPer1k:.001,cachedInputPer1k:1e-4,cacheWritePer1k:.00125,outputPer1k:.006,largo:{estandar:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.018},tier:{inputPer1k:.002,
|
|
400
|
+
cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.009}}}),"gpt-5.6-luna":N({inputPer1k:1e-4,cachedInputPer1k:1e-5,cacheWritePer1k:125e-6,outputPer1k:6e-4,largo:{estandar:{inputPer1k:4e-4,cachedInputPer1k:4e-5,
|
|
401
|
+
cacheWritePer1k:5e-4,outputPer1k:.0018},tier:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,outputPer1k:9e-4}}}),"gpt-5.5":N({inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.015,largo:{
|
|
402
|
+
estandar:{inputPer1k:.01,cachedInputPer1k:.001,outputPer1k:.045},tier:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225}}}),"gpt-5.4":N({inputPer1k:.00125,cachedInputPer1k:13e-5,outputPer1k:.0075,
|
|
403
|
+
largo:{estandar:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225},tier:{inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.01125}}}),"gpt-5.4-mini":N({inputPer1k:375e-6,cachedInputPer1k:375e-7,
|
|
404
|
+
outputPer1k:.00225}),"gpt-5.4-nano":N({inputPer1k:1e-4,cachedInputPer1k:1e-5,outputPer1k:625e-6}),"gpt-5.2":N({inputPer1k:875e-6,cachedInputPer1k:875e-7,outputPer1k:.007}),"gpt-5":N({inputPer1k:625e-6,
|
|
405
|
+
cachedInputPer1k:625e-7,outputPer1k:.005}),"gpt-5-mini":N({inputPer1k:125e-6,cachedInputPer1k:125e-7,outputPer1k:.001}),"gpt-5-nano":N({inputPer1k:25e-6,cachedInputPer1k:25e-7,outputPer1k:2e-4}),"gpt-\
|
|
406
|
+
4.1":N({inputPer1k:.001,outputPer1k:.004}),"gpt-4.1-mini":N({inputPer1k:2e-4,outputPer1k:8e-4}),"gpt-4.1-nano":N({inputPer1k:5e-5,outputPer1k:2e-4}),"gpt-4o":N({inputPer1k:.00125,outputPer1k:.005}),"g\
|
|
407
|
+
pt-4o-mini":N({inputPer1k:75e-6,outputPer1k:3e-4}),o3:N({inputPer1k:.001,outputPer1k:.004}),"o4-mini":N({inputPer1k:55e-5,outputPer1k:.0022}),"o3-mini":N({inputPer1k:55e-5,outputPer1k:.0022}),"o3-pro":N(
|
|
408
|
+
{inputPer1k:.01,outputPer1k:.04})}},anthropic:{batch:{"claude-fable-5-1":le({inputPer1k:.005,cachedInputPer1k:125e-6,cacheWritePer1k:.00625,outputPer1k:.025}),"claude-mythos-5-1":le({inputPer1k:.005,cachedInputPer1k:125e-6,
|
|
409
|
+
cacheWritePer1k:.00625,outputPer1k:.025}),"claude-fable-5":le({inputPer1k:.005,cachedInputPer1k:5e-4,cacheWritePer1k:.00625,outputPer1k:.025}),"claude-mythos-5":le({inputPer1k:.005,cachedInputPer1k:5e-4,
|
|
410
|
+
cacheWritePer1k:.00625,outputPer1k:.025}),"claude-opus-5-5":le({inputPer1k:.002,cachedInputPer1k:1e-4,cacheWritePer1k:.0025,outputPer1k:.01}),"claude-opus-5":le({inputPer1k:.0025,cachedInputPer1k:25e-5,
|
|
411
|
+
cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-8":le({inputPer1k:.0025,cachedInputPer1k:25e-5,cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-7":le({inputPer1k:.0025,cachedInputPer1k:25e-5,
|
|
412
|
+
cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-6":le({inputPer1k:.0025,cachedInputPer1k:25e-5,cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-5":le({inputPer1k:.0025,cachedInputPer1k:25e-5,
|
|
413
|
+
cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4":le({inputPer1k:.0075,cachedInputPer1k:75e-5,cacheWritePer1k:.009375,outputPer1k:.0375}),"claude-sonnet-5":le({inputPer1k:.001,cachedInputPer1k:1e-4,
|
|
414
|
+
cacheWritePer1k:.00125,outputPer1k:.005}),"claude-sonnet-5-5":{...le({inputPer1k:.001,cachedInputPer1k:1e-4,cacheWritePer1k:.00125,outputPer1k:.005})},"claude-sonnet-4-6":le({inputPer1k:.0015,
|
|
415
|
+
cachedInputPer1k:15e-5,cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-sonnet-4-5":le({inputPer1k:.0015,cachedInputPer1k:15e-5,cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-sonnet-4":le({inputPer1k:.0015,
|
|
416
|
+
cachedInputPer1k:15e-5,cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-haiku-4-5":le({inputPer1k:5e-4,cachedInputPer1k:5e-5,cacheWritePer1k:625e-6,outputPer1k:.0025}),"claude-3-5-haiku":le({inputPer1k:4e-4,
|
|
417
|
+
cachedInputPer1k:4e-5,cacheWritePer1k:5e-4,outputPer1k:.002})}},google:{flex:{"gemini-3.7-flash":We({inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3\
|
|
418
|
+
.5-flash":We({inputPer1k:75e-5,outputPer1k:.0045,cachedInputPer1k:8e-5}),"gemini-3.5-flash-lite":We({inputPer1k:15e-5,outputPer1k:.00125,cachedInputPer1k:2e-5}),"gemini-3.1-pro-preview":We({inputPer1k:.001,
|
|
419
|
+
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":We({inputPer1k:625e-6,
|
|
326
420
|
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\
|
|
327
|
-
sh":
|
|
328
|
-
{inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.1-flash-lite":
|
|
329
|
-
view":
|
|
330
|
-
slice(0,n):"",
|
|
331
|
-
|
|
421
|
+
sh":We({inputPer1k:15e-5,outputPer1k:.00125,cachedInputPer1k:3e-5}),"gemini-3.8-flash":We({inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.6-flash":We(
|
|
422
|
+
{inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.1-flash-lite":We({inputPer1k:125e-6,outputPer1k:75e-5,cachedInputPer1k:125e-7}),"gemini-3-flash-pre\
|
|
423
|
+
view":We({inputPer1k:25e-5,outputPer1k:.0015,cachedInputPer1k:5e-5})}}});function vi(e){let t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}function Lo(e){let t=e.toLowerCase(),
|
|
424
|
+
n=t.indexOf("/"),o=n>0?t.slice(0,n):"",r=vi(t);return o==="openai"||o==="azure-openai"?"openai":o==="google"||o==="google-vertex"?"google":o==="anthropic"?"anthropic":o==="deepseek"?"deepseek":o==="qw\
|
|
425
|
+
en"||o==="dashscope"?"qwen":o==="glm"||o==="zhipu"?"glm":/^(gpt-|o[1-9](-|$))/.test(r)?"openai":r.startsWith("gemini")?"google":r.startsWith("claude-")?"anthropic":r.startsWith("deepseek-")?"deepseek":
|
|
426
|
+
r.startsWith("qwen")?"qwen":r.startsWith("glm-")?"glm":null}var Sc={flex:.5,default:1,auto:1,priority:1,fast:1,scale:1,standard:1,batch:.5};Math.min(...Object.values(Sc).filter(e=>e<1));function Mo(e){if(e==null||e==="")return null;let t=Sc[e];return t==null?{servido:e,factor:null,conDescuento:false}:{servido:e,factor:t,conDescuento:t<1}}var wf={"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.\
|
|
332
427
|
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\
|
|
333
428
|
.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,
|
|
334
429
|
"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\
|
|
335
430
|
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\
|
|
336
|
-
sh":true,"gemini-3.6-flash":true,"gemini-3.1-flash-lite":true,"gemini-3-flash-preview":true,"gemini-3.5-flash":true,"gemini-3.5-flash-lite":true,"gemini-3.1-pro-preview":true,"gemini-2.5-pro":true,"gemini-2.5-flash":true
|
|
337
|
-
|
|
338
|
-
/^
|
|
339
|
-
|
|
340
|
-
if(
|
|
341
|
-
let o=
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
Math.max(0,
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
431
|
+
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,
|
|
432
|
+
"deepseek-flash":false,"deepseek-v4-pro":true,"qwen3.8-max":true,"qwen3.8-flash":true,"qwen3.7-flash":true,"qwen-flash":false,"qwen-plus":false,"glm-5.3":true,"glm-5.3-flash":true},xf=new Set(["claude-opus-4-7","claude-op\
|
|
433
|
+
us-4-8"]),Sf=[/^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($|[-_.])/,/^qwq/,/^qwen3/,/^glm-(4\.[5-9]|[5-9])/,
|
|
434
|
+
/magistral/];function yi(e){let t=e.lastIndexOf("/"),n=(t>=0?e.slice(t+1):e).toLowerCase();if(Sf.some(i=>i.test(n)))return "reasoning-model";let o=At(e);if(o===void 0)return "unclassified-model";let r=wf[o];
|
|
435
|
+
if(r===true)return "reasoning-model";if(r!==false)return "unclassified-model";if(xf.has(o))return "temperature-ignored"}var rn=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0;function ki(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){
|
|
436
|
+
if(n===null||typeof n!="object")continue;let o=n;if(o.type!=="compaction")continue;t.iteraciones++,t.input+=rn(o.input_tokens),t.output+=rn(o.output_tokens),t.cacheRead+=rn(o.cache_read_input_tokens);
|
|
437
|
+
let r=o.cache_creation,i=rn(r?.ephemeral_5m_input_tokens),s=rn(r?.ephemeral_1h_input_tokens),a=typeof o.cache_creation_input_tokens=="number"?rn(o.cache_creation_input_tokens):i+s;t.cacheWrite+=a,t.cacheWrite1h+=
|
|
438
|
+
Math.min(s,a);}return t.iteraciones>0?t:null}var Ef={anthropic:"explicit",openai:"automatic",google:"implicit",unknown:"unknown"};function wi(e){return Math.round(e*1e10)/1e10}function xi(e,t,n){let o=Math.max(0,n.leidos),r=Math.max(0,n.escritos),
|
|
439
|
+
i=Math.min(r,Math.max(0,n.escritos1h));if(o===0&&r===0)return;let s=Lo(e),a=s==="anthropic"||s==="openai"||s==="google"?s:"unknown",l=Se(e),c=Yt(e),d=t.cachedInputPer1k,u=d!==void 0&&
|
|
440
|
+
Number.isFinite(d),f=d??t.inputPer1k,m=u?o/1e3*Math.max(0,t.inputPer1k-f):0,h=u?(r-i)/1e3*t.inputPer1k*Math.max(0,l-1)+i/1e3*t.inputPer1k*Math.max(0,c-1):0;return {provider:a,mechanism:Ef[a],...n.marcadoPorLaCapa!==
|
|
441
|
+
void 0?{layerMarked:n.marcadoPorLaCapa}:{},cacheReadTokens:o,cacheWriteTokens:r,cacheWrite1hTokens:i,inputPer1k:t.inputPer1k,cachedInputPer1k:f,writeMultiplier:l,write1hMultiplier:c,readDiscountUsd:wi(
|
|
442
|
+
m),writePremiumUsd:wi(h),netUsd:wi(m-h),basis:u?"measured":"unmeasured"}}var _f=new Set([null,"cyber","general_harms"]);function No(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\
|
|
443
|
+
efusal"||!("category"in n))return false;let o=n.category;return !(o!==null&&typeof o!="string"||!_f.has(o)||e.bloques!==0||e.outputTokens!==0||Array.isArray(e.iterations)&&e.iterations.length>1)}var jo="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\
|
|
444
|
+
able","do not feel comfortable","'d rather not","would rather not","don't think i can","do not think i can"].join("|")+")",Ei="(?:much|many times|happy|glad|grateful|excited|thankful|proud|sorry|impor\
|
|
445
|
+
tant|good|great|amazing|nice|relieved|pleased|delighted|impressed|helpful|useful|valuable|lucky|blessed|thrilled|fun|cool|beautiful|wonderful)",Cf=`(?:help(?! but| feeling| thinking| noticing| wonderi\
|
|
350
446
|
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\
|
|
351
|
-
itate|contribute|go along|go into|walk you through|explain how|describe how(?! ${
|
|
447
|
+
itate|contribute|go along|go into|walk you through|explain how|describe how(?! ${Ei})|tell you how(?! ${Ei})|teach|instruct|encourage|condone|endorse|promote|role-?play|pretend|do that|do this|do so|w\
|
|
352
448
|
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\
|
|
353
449
|
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\
|
|
354
|
-
s|evaluate|comment on|speak to|give out|dox|tell (?:you )?(?:whether|if))`,
|
|
450
|
+
s|evaluate|comment on|speak to|give out|dox|tell (?:you )?(?:whether|if))`,Tc="i(?:'ll| will| must| need to|'d| would)?(?: have to)? ?(?:respectfully |politely )?decline",Rc="(?:(?:that|this|it)(?:'s|\
|
|
355
451
|
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\
|
|
356
452
|
sure (?:that )?it(?:'s| is| would be) appropriate|(?:this|that|the|your) request (?:cannot|can't|can not|will not|won't) be (?:fulfilled|completed|processed|honou?red|accommodated|carried out|answere\
|
|
357
|
-
d)|(?:this|that|your) request (?:is|would be) (?:considered )?(?:inappropriate|illegal|unlawful|unethical|harmful|dangerous|against|not appropriate|a violation))",
|
|
453
|
+
d)|(?:this|that|your) request (?:is|would be) (?:considered )?(?:inappropriate|illegal|unlawful|unethical|harmful|dangerous|against|not appropriate|a violation))",Tf="(?:(?:i'm |i am |i'm really |i am\
|
|
358
454
|
really |i'm so |really |so )?sorry|i apologi[sz]e|my apologies|apologies|unfortunately|regrettably|i'm afraid|i am afraid|as an ai|as a language model|as an assistant|i understand|i appreciate|thank \
|
|
359
|
-
you for|thanks for|while i understand|while i appreciate)",p="\\p{L}*",
|
|
455
|
+
you for|thanks for|while i understand|while i appreciate)",p="\\p{L}*",Ci="no (?:puedo|voy a|me es posible|estoy en condiciones de|me siento c\xF3mod[oa])",Rf=`(?:ayudar${p}|asistir${p}|proporcionar${p}\
|
|
360
456
|
|facilitar${p}|dar${p}|ofrecer${p}|crear${p}|escribir${p}|generar${p}|compartir${p}|cumplir|responder${p}|colaborar|participar|atender${p}|hacer eso|hacerlo|con eso|con esto|con esa|con esta|con tu|de\
|
|
361
457
|
terminar${p}|identificar${p}|saber${p}|acceder|revelar${p}|divulgar${p}|verificar${p}|confirmar${p}|localizar${p}|rastrear${p}|adivinar${p}|predecir${p}|diagnosticar${p}|recomendar${p}(?![^.!?]{0,60}s\
|
|
362
|
-
uficiente)|recetar${p}|aconsejar${p})`,
|
|
363
|
-
icial|modelo de lenguaje|asistente)|entiendo)"
|
|
458
|
+
uficiente)|recetar${p}|aconsejar${p})`,Af="(?:lo siento|lo lamento|siento|lamento|disculpa|disculpe|perd\xF3n|perdona|lamentablemente|desafortunadamente|me temo que|como (?:una )?(?:ia|inteligencia artif\
|
|
459
|
+
icial|modelo de lenguaje|asistente)|entiendo)",Ti="no (?:puc|et puc|us puc|em sento c\xF2mod[ea]|estic en condicions de)",If=`(?:ajudar${p}|assistir${p}|proporcionar${p}|facilitar${p}|donar${p}|oferir${p}\
|
|
364
460
|
|crear${p}|escriure${p}|generar${p}|compartir${p}|complir|respondre${p}|col\xB7laborar|participar|fer aix\xF2|fer-ho|amb aix\xF2|amb aquesta|amb la teva|determinar${p}|identificar${p}|saber${p}|accedi\
|
|
365
|
-
r|revelar${p}|divulgar${p}|verificar${p}|confirmar${p}|localitzar${p}|rastrejar${p}|endevinar${p}|predir${p}|diagnosticar${p}|recomanar${p}(?![^.!?]{0,60}prou)|receptar${p}|aconsellar${p})`,
|
|
366
|
-
sento|ho lamento|em sap greu|disculpa|disculpeu|perdona|malauradament|lamentablement|dissortadament|com a (?:ia|intel\xB7lig\xE8ncia artificial|model de llenguatge|assistent)|entenc)",
|
|
367
|
-
peux|pourrai|pourrais|vais|souhaite)(?: malheureusement)? pas|je ne suis pas en mesure d[e']|je refuse d[e'])",
|
|
461
|
+
r|revelar${p}|divulgar${p}|verificar${p}|confirmar${p}|localitzar${p}|rastrejar${p}|endevinar${p}|predir${p}|diagnosticar${p}|recomanar${p}(?![^.!?]{0,60}prou)|receptar${p}|aconsellar${p})`,Df="(?:ho \
|
|
462
|
+
sento|ho lamento|em sap greu|disculpa|disculpeu|perdona|malauradament|lamentablement|dissortadament|com a (?:ia|intel\xB7lig\xE8ncia artificial|model de llenguatge|assistent)|entenc)",Ri="(?:je ne (?:\
|
|
463
|
+
peux|pourrai|pourrais|vais|souhaite)(?: malheureusement)? pas|je ne suis pas en mesure d[e']|je refuse d[e'])",Pf="(?:aider|assister|fournir|r\xE9pondre|cr\xE9er|\xE9crire|g\xE9n\xE9rer|partager|donner|proposer|part\
|
|
368
464
|
iciper|expliquer comment|acc\xE9der \xE0|satisfaire|faire cela|faire \xE7a|le faire|d\xE9terminer|identifier|savoir|divulguer|r\xE9v\xE9ler|v\xE9rifier|confirmer|localiser|retrouver|deviner|pr\xE9dire|diagnostiquer|prescrire\
|
|
369
|
-
|conseiller|recommander(?![^.!?]{0,60}assez))",
|
|
370
|
-
|
|
465
|
+
|conseiller|recommander(?![^.!?]{0,60}assez))",Of="(?:d\xE9sol\xE9e?|je suis d\xE9sol\xE9e?|je regrette|malheureusement|h\xE9las|je comprends|en tant qu'(?:ia|intelligence artificielle|mod\xE8le de langage|assistant))",
|
|
466
|
+
Ai="(?:ich (?:kann|werde|darf|m\xF6chte)|(?:kann|werde|darf|m\xF6chte) ich)(?: \\p{L}+){0,4}? (?:nicht|keine\\p{L}*)(?: \\p{L}+){0,3}?",Lf="(?:helfen|unterst\xFCtzen|bereitstellen|geben|erstellen|schreib\
|
|
371
467
|
en|generieren|beantworten|liefern|nachkommen|teilen|anbieten|erkl\xE4ren|behilflich sein|bestimmen|feststellen|identifizieren|wissen|zugreifen|preisgeben|offenlegen|verraten|\xFCberpr\xFCfen|best\xE4tigen|ausfind\
|
|
372
|
-
ig machen|orten|verfolgen|erraten|vorhersagen|diagnostizieren|verschreiben|raten|sagen, ob)",
|
|
373
|
-
(?:eine )?(?:ki|k\xFCnstliche intelligenz|sprachmodell|assistent))",
|
|
468
|
+
ig machen|orten|verfolgen|erraten|vorhersagen|diagnostizieren|verschreiben|raten|sagen, ob)",Mf="(?:es tut mir leid|tut mir leid|entschuldigung|entschuldige|leider|bedauerlicherweise|ich verstehe|als \
|
|
469
|
+
(?:eine )?(?:ki|k\xFCnstliche intelligenz|sprachmodell|assistent))",Ii="non (?:posso|sono in grado di|riesco a|mi sento a mio agio (?:a|nel))",$f=`(?:aiutar${p}|assister${p}|fornir${p}|crear${p}|scriv\
|
|
374
470
|
er${p}|generar${p}|condivider${p}|risponder${p}|dar${p}|offrir${p}|soddisfare|partecipare|farlo|fare questo|con questo|con questa|determinar${p}|identificar${p}|saper${p}|accedere|rivelar${p}|divulgar${p}\
|
|
375
|
-
|verificar${p}|confermar${p}|localizzar${p}|rintracciar${p}|indovinar${p}|prevedere|diagnosticar${p}|prescriver${p}|consigliar${p}(?![^.!?]{0,60}abbastanza))`,
|
|
376
|
-
ortunatamente|capisco|come (?:un'?\\s?)?(?:ia|intelligenza artificiale|modello linguistico|assistente))",
|
|
377
|
-
|
|
471
|
+
|verificar${p}|confermar${p}|localizzar${p}|rintracciar${p}|indovinar${p}|prevedere|diagnosticar${p}|prescriver${p}|consigliar${p}(?![^.!?]{0,60}abbastanza))`,Nf="(?:mi dispiace|spiacente|purtroppo|sf\
|
|
472
|
+
ortunatamente|capisco|come (?:un'?\\s?)?(?:ia|intelligenza artificiale|modello linguistico|assistente))",Di="n\xE3o (?:posso|consigo|vou|sou capaz de|estou em condi\xE7\xF5es de|me sinto confort\xE1vel (?:em|a))",
|
|
473
|
+
jf=`(?:ajudar${p}|auxiliar${p}|assistir${p}|fornecer${p}|criar${p}|escrever${p}|gerar${p}|compartilhar${p}|partilhar${p}|dar${p}|oferecer${p}|responder${p}|atender${p}|cumprir|participar|fazer isso|co\
|
|
378
474
|
m isso|com esse|com essa|determinar${p}|identificar${p}|saber${p}|acessar|aceder|revelar${p}|divulgar${p}|verificar${p}|confirmar${p}|localizar${p}|rastrear${p}|adivinhar${p}|prever${p}|diagnosticar${p}\
|
|
379
|
-
|receitar${p}|aconselhar${p}|recomendar${p}(?![^.!?]{0,60}o suficiente))`,
|
|
380
|
-
lo de linguagem|assistente))",
|
|
381
|
-
e (?:ser )?(?:atender|atendida|cumplir|cumplida|completar|completada|procesar|procesada)",`${
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
475
|
+
|receitar${p}|aconselhar${p}|recomendar${p}(?![^.!?]{0,60}o suficiente))`,Bf="(?:desculpe|desculpa|sinto muito|lamento|infelizmente|entendo|compreendo|como (?:uma? )?(?:ia|intelig\xEAncia artificial|mode\
|
|
476
|
+
lo de linguagem|assistente))",Nt="(?:[\\s,]+[\\p{L}'\u2019-]+){0,4}?[\\s,]+",Pi=[`${jo}${Nt}${Cf}`,Tc,Rc,`${Ci}${Nt}${Rf}`,"lamento no poder","(?:esta|esa|la|tu) (?:solicitud|petici\xF3n) no (?:se )?pued\
|
|
477
|
+
e (?:ser )?(?:atender|atendida|cumplir|cumplida|completar|completada|procesar|procesada)",`${Ti}${Nt}${If}`,`${Ri}${Nt}${Pf}`,`${Ai} ${Lf}`,`${Ii}${Nt}${$f}`,`${Di}${Nt}${jf}`].join("|"),Uf=[Tf,Af,Df,
|
|
478
|
+
Of,Mf,Nf,Bf].join("|"),Ff=new RegExp(`^(?:${Pi})(?![\\p{L}])`,"u"),zf=new RegExp(`^(?:${Uf})(?![\\p{L}])`,"u"),Ac=new RegExp(`(?:^|[^\\p{L}'])(?:${Pi})(?![\\p{L}])`,"u"),Ic=[jo,Tc,Rc,Ci,"lamento no po\
|
|
479
|
+
der","(?:esta|esa|la|tu) (?:solicitud|petici\xF3n) no (?:se )?puede",Ti,Ri,Ai,Ii,Di].join("|"),Vf=new RegExp(`^(?:${Ic})`,"u"),Si=new RegExp(`(?:${Ic})`,"u"),qf="(?:really|even|honestly|quite|possibly\
|
|
480
|
+
|truly|personally|actually|simply|just|ever|always)",Bo="i(?:'m| am)? ?(?:can't|cannot|can not|won't|will not|not going to|not able to|unable to)",Hf=["wait","believe","imagine (?:how|what|why|anythin\
|
|
481
|
+
g|anyone|anybody|life|living|being|a (?:better|world|life|time|single))","thank","stress","(?:over|under)?emphasi[sz]e","overstate","understate","exaggerate","(?:recommend|praise|rave about|speak high\
|
|
482
|
+
ly of|say enough good)[^.!?]{0,60}enough","say enough","get enough","help (?:but|feeling|thinking|noticing|wondering|laughing|smiling|myself|it)",`(?:tell you|say|express|describe|explain|put into wor\
|
|
483
|
+
ds) (?:how|what a) ${Ei}`,"express (?:my|our) (?:gratitude|thanks|appreciation)","begin to (?:describe|imagine|tell|express|thank|understand|fathom|comprehend|count)","agree (?:more|with you more)","c\
|
|
484
|
+
omplain","disagree","deny (?:that|it|this|the)","fault (?:you|it|that|this|the)","argue with (?:that|this|you|those|these|the (?:logic|results|data|numbers|math|facts))","find (?:any|anything|a single\
|
|
485
|
+
|no|nothing)","identify (?:any|anything|a single)","spot (?:any|anything|a single)","see (?:any|anything|a single|why not|a (?:reason|problem|downside|issue|bug))","think of (?:any|anything|a (?:reaso\
|
|
486
|
+
n|better|single|downside))","lie","sugar-?coat(?: it| this| that)?","bore you","belabou?r","rehash","judge you","keep you","get over","resist","top (?:that|this)","go wrong","say (?:that )?i","pretend\
|
|
487
|
+
(?:otherwise|(?:that )?(?:i'm|i am|it's|it is|this is|everything|there's|there is|we|you))","remember (?:a time|the last time|when i)","stop (?:thinking|smiling|laughing|listening|reading|talking abo\
|
|
488
|
+
ut)"],Gf="(?:be (?:100% |completely |entirely |absolutely |totally |fully |one hundred percent )?(?:sure|certain)|say (?:for (?:sure|certain)|with (?:certainty|confidence)|definitively|exactly|precise\
|
|
489
|
+
ly|for a fact)|know (?:for (?:sure|certain)|exactly|precisely)|guarantee|promise|speak for|vouch for|recall|remember|run|test|execute|see (?:your|the) (?:screen|code|file|image|output|logs?))[^.!?]{0,\
|
|
490
|
+
160}?(?:,|\\s)(?:but|however)(?![\\p{L}])",Uo=`(?:${qf} ){0,2}(?:(?:${Hf.join("|")})(?![\\p{L}])|${Gf})`,Oi="no (?:(?:te|le|les|os|lo|la|me|se) )?(?:puedo|voy a)",Wf=["esperar",`creer${p}`,`imaginar${p}`,
|
|
491
|
+
"dejar de",`evitar${p}`,`agradecer${p}`,`negar${p}`,`mentir${p}`,`quejar${p}`,"estar m\xE1s",`(?:encontrar|ver|detectar|identificar|notar)${p} (?:ning\xFAn|ninguna|ningun|nada|ni un|motivo para no|raz\xF3n \
|
|
492
|
+
para no)`,`recomendar${p}[^.!?]{0,60}(?:suficiente|bastante)`,`(?:enfatizar|recalcar|subrayar|insistir|exagerar|ponderar)${p}`,`(?:decir|expresar)${p} (?:lo|cu\xE1nto|cuanto|c\xF3mo de|como de)`,`resi\
|
|
493
|
+
stir${p}`,"m\xE1s que","sino","pedir m\xE1s"],Jf=`(?:estar (?:100 ?% |completamente |totalmente |del todo )?segur[oa]|asegurar${p}|garantizar${p}|prometer${p}|(?:decir|saber|afirmar)${p} con (?:certez\
|
|
494
|
+
a|seguridad|exactitud)|ejecutar${p}|probar${p}|recordar${p}|ver (?:tu|la|el) (?:pantalla|c\xF3digo|archivo))[^.!?]{0,160}?(?:,|\\s)(?:pero|aunque|sin embargo)(?![\\p{L}])`,Li=`(?:(?:${Wf.join("|")})(?\
|
|
495
|
+
![\\p{L}])|${Jf})`,Mi="no (?:(?:et|us|el|la|ho|em|li|els|les) )?(?:puc|penso|podr\xE9)",Kf=[`esperar${p}`,`creure${p}`,`imaginar${p}`,"deixar de",`evitar${p}`,`agrair${p}`,`negar${p}`,`mentir${p}`,`qu\
|
|
496
|
+
eixar${p}`,"estar m\xE9s",`(?:trobar|veure|detectar|identificar)${p} (?:cap|res|ni un|ni una)`,`recomanar${p}[^.!?]{0,60}prou`,`(?:emfatitzar|remarcar|subratllar|insistir|exagerar)${p}`,`dir${p} (?:co\
|
|
497
|
+
m de|quant|prou)`,`resistir${p}`,"m\xE9s que","sin\xF3","fer altra cosa que"],Yf=`(?:estar (?:100 ?% |completament |del tot )?segura?|assegurar${p}|garantir${p}|prometre${p}|(?:dir|saber|afirmar)${p} \
|
|
498
|
+
amb (?:certesa|seguretat)|executar${p}|provar${p}|recordar${p})[^.!?]{0,160}?(?:,|\\s)(?:per\xF2|pero|tot i que)(?![\\p{L}])`,$i=`(?:(?:${Kf.join("|")})(?![\\p{L}])|${Yf})`,Ni="je ne (?:peux|pourrai|p\
|
|
499
|
+
ourrais|vais)(?: malheureusement)? pas",Qf="(?:vous |te |t'|me |m'|le |la |les |l'|lui |leur |y |en |se |s')",Xf=["attendre","croire","imaginer","emp\xEAcher","remercier","(?:trop |assez )?(?:insister\
|
|
500
|
+
|souligner|exag\xE9rer)","mentir","nier","plaindre","\xEAtre plus","(?:trouver|voir|d\xE9tecter|identifier|rep\xE9rer) (?:aucun|aucune|rien|de (?:probl\xE8me|raison|souci))","dire (?:\xE0 quel point|comb\
|
|
501
|
+
ien|assez)","recommander[^.!?]{0,60}assez","r\xE9sister","faire autrement que"],Zf="(?:\xEAtre (?:(?:tout \xE0 fait|absolument|enti\xE8rement|100 ?%) )?(?:s\xFBre?|certaine?)|garantir|promettre|affirmer|dire avec\
|
|
502
|
+
certitude|ex\xE9cuter|tester|souvenir|rappeler|voir (?:votre|ton|ta|le|la) (?:\xE9cran|code|fichier))[^.!?]{0,160}?(?:,|\\s)(?:mais|cependant|toutefois)(?![\\p{L}])",ji=`${Qf}*(?:(?:${Xf.join("|")})(\
|
|
503
|
+
?![\\p{L}])|${Zf})`,Bi="non (?:(?:ti|vi|la|lo|le|gli|ne|mi|ci) )?(?:posso|riesco a|sono in grado di|ho intenzione di)",em=[`aspettar${p}`,`creder${p}`,`immaginar${p}`,"fare a meno",`ringraziar${p}`,"c\
|
|
504
|
+
he","non",`negar${p}`,`mentir${p}`,`lamentar${p}`,"(?:essere|esser) pi\xF9",`(?:trovare|vedere|notare|individuare|rilevare) (?:nessun${p}|niente|alcun${p}|un solo)`,`consigliar${p}[^.!?]{0,60}abbastan\
|
|
505
|
+
za`,`(?:sottolinear|enfatizzar|insister|esagerar)${p}`,`dir${p} (?:quanto|abbastanza)`,`resister${p}`],tm=`(?:(?:esserne|essere) (?:del tutto |completamente |al 100 ?% )?(?:sicur[oa]|cert[oa])|garanti\
|
|
506
|
+
r${p}|prometter${p}|(?:dir|affermar)${p} con certezza|eseguir${p}|testar${p}|ricordar${p})[^.!?]{0,160}?(?:,|\\s)(?:ma|per\xF2|tuttavia)(?![\\p{L}])`,Ui=`(?:(?:${em.join("|")})(?![\\p{L}])|${tm})`,Fi="\
|
|
507
|
+
n\xE3o (?:(?:te|lhe|lhes|vos|o|a|me) )?(?:posso|consigo|vou|sou capaz de)",nm=["esperar","acreditar",`imaginar${p}`,"deixar de",`evitar${p}`,`agradecer${p}`,`negar${p}`,`mentir${p}`,`(?:me )?(?:queixa\
|
|
411
508
|
r|reclamar)${p}`,"concordar mais","estar mais","sen\xE3o","(?:fazer )?mais (?:do )?que",`(?:encontrar|ver|identificar|detetar|detectar|notar) (?:nenhum${p}|nada|um \xFAnico|uma \xFAnica)`,`recomendar${p}\
|
|
412
|
-
[^.!?]{0,60}(?:o )?suficiente`,`(?:enfatizar|sublinhar|ressaltar|insistir|exagerar)${p}`,`dizer${p} (?:o quanto|quanto|como|o suficiente)`,`resistir${p}`],
|
|
509
|
+
[^.!?]{0,60}(?:o )?suficiente`,`(?:enfatizar|sublinhar|ressaltar|insistir|exagerar)${p}`,`dizer${p} (?:o quanto|quanto|como|o suficiente)`,`resistir${p}`],om=`(?:ter (?:a )?certeza|estar (?:100 ?% |co\
|
|
413
510
|
mpletamente |totalmente )?(?:segur[oa]|cert[oa])|garantir${p}|prometer${p}|(?:dizer|afirmar|saber)${p} com (?:certeza|seguran\xE7a)|executar${p}|testar${p}|lembrar${p})[^.!?]{0,160}?(?:,|\\s)(?:mas|por\
|
|
414
|
-
\xE9m|contudo)(?![\\p{L}])`,
|
|
511
|
+
\xE9m|contudo)(?![\\p{L}])`,zi=`(?:(?:${nm.join("|")})(?![\\p{L}])|${om})`,Vi="(?:ich (?:kann|werde|darf)|kann ich|werde ich)",rm=["(?:kaum|nicht) erwarten","glauben","vorstellen","genug (?:danken|bet\
|
|
415
512
|
onen|empfehlen|loben|sagen|hervorheben)","oft genug","\\p{L}*l\xFCgen","leugnen","bestreiten","beschweren","beklagen","(?:mehr|besser) zustimmen","widerstehen","keine?n? (?:fehler|probleme?|grund|hake\
|
|
416
|
-
n|m\xE4ngel|bugs?|nachteile?|einw\xE4nde?)","sagen, wie (?:sehr|froh|dankbar|gl\xFCcklich)"],
|
|
417
|
-
,|\\s)(?:aber|jedoch|allerdings)(?![\\p{L}])",
|
|
418
|
-
\\s
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
)
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
?:
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
|
437
|
-
|
|
438
|
-
)
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
)?
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
matchAll(
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
let
|
|
470
|
-
length
|
|
471
|
-
|
|
472
|
-
|
|
513
|
+
n|m\xE4ngel|bugs?|nachteile?|einw\xE4nde?)","sagen, wie (?:sehr|froh|dankbar|gl\xFCcklich)"],im="(?:(?:mit )?sicherheit|genau|garantieren|versprechen|100 ?%|ausf\xFChren|testen|erinnern)[^.!?]{0,160}?(?:\
|
|
514
|
+
,|\\s)(?:aber|jedoch|allerdings)(?![\\p{L}])",Dc=`[^.!?]*?(?<![\\p{L}])(?:(?:${rm.join("|")})(?![\\p{L}])|${im})`,qi="(?:no[,.!]? |non[,.!]? |n\xE3o[,.!]? |nein[,.!]? )?",sm=[`${Bo}\\s`,`${Oi}\\s`,`${Mi}\
|
|
515
|
+
\\s`,`${Ni}\\s?`,`${Bi}\\s`,`${Fi}\\s`,`${Vi}(?:\\s[\\p{L}\\p{N}'-]+){0,6}?\\s(?:nicht|keine?\\p{L}*)`].join("|"),am=new RegExp("^"+qi+"(?:"+sm+")","u"),cm=new RegExp("^"+qi+"(?:"+[`${Bo}\\s(?!${Uo})\\\
|
|
516
|
+
p{L}`,`${Oi}\\s(?!${Li})\\p{L}`,`${Mi}\\s(?!${$i})\\p{L}`,`${Ni}\\s?(?!${ji})\\p{L}`,`${Bi}\\s(?!${Ui})\\p{L}`,`${Fi}\\s(?!${zi})\\p{L}`,`${Vi}(?!${Dc})(?:\\s[\\p{L}\\p{N}'-]+){0,6}?\\s(?:nicht|keine?\\p{L\
|
|
517
|
+
}*)(?![\\p{L}])(?!\\s(?:nur|mehr als|anders|umhin))`].join("|")+")","u"),lm=new RegExp("^"+qi+"(?:"+[`${Bo}\\s(?=${Uo})`,`${Oi}\\s(?=${Li})`,`${Mi}\\s(?=${$i})`,`${Ni}\\s?(?=${ji})`,`${Bi}\\s(?=${Ui})`,
|
|
518
|
+
`${Fi}\\s(?=${zi})`,`${Vi}(?=${Dc})`].join("|")+")","u"),Pc="(?:(?:i'm |i am )?(?:really |so |very |truly |terribly )?sorry|i apologi[sz]e|my apologies|apologies|unfortunately|regrettably|i'm afraid|i\
|
|
519
|
+
am afraid)",Oc="(?:lo siento(?: mucho)?|lo lamento|disculpa|disculpe|perd\xF3n|perdona|lamentablemente|desafortunadamente|me temo que)",Lc="(?:ho sento(?: molt)?|em sap greu|disculpa|disculpeu|perdon\
|
|
520
|
+
a|malauradament|lamentablement|dissortadament)",Mc="(?:(?:je suis )?(?:vraiment )?d\xE9sol\xE9e?|je regrette|pardon|malheureusement|h\xE9las)",$c="(?:es tut mir (?:sehr |wirklich )?leid|tut mir leid|e\
|
|
521
|
+
ntschuldigung|leider|bedauerlicherweise)",Nc="(?:mi dispiace(?: molto)?|spiacente|scusa|scusami|mi scuso|purtroppo|sfortunatamente)",jc="(?:desculpe|desculpa|sinto muito|lamento|pe\xE7o desculpa|infelizm\
|
|
522
|
+
ente)",um=new RegExp(`^(?:${[Pc,Oc,Lc,Mc,$c,Nc,jc].join("|")})`,"u"),dm=Uo,pm=Li,fm=$i,mm=ji,hm=Ui,gm=zi,Mt=e=>`[,.!:;]?\\s(?:(?:${e})\\s)?`,bm="\\s\\p{L}",vm=[`${Pc}${Mt("but|however,?")}(?:as an ai(\
|
|
523
|
+
?: language model| assistant)?,?\\s)?${jo}\\s(?!${dm})\\p{L}`,`${Oc}${Mt("pero")}${Ci}(?:\\s(?:te|le|les|os))?\\s(?!${pm})\\p{L}`,`${Lc}${Mt("per\xF2|pero")}${Ti}\\s(?!${fm})\\p{L}`,`${Mc}${Mt("mais")}${Ri}\
|
|
524
|
+
(?:\\s(?:vous|te))?\\s?(?!${mm})\\p{L}`,`${$c}${Mt("aber")}${Ai}${bm}`,`${Nc}${Mt("ma")}${Ii}\\s(?!${hm})\\p{L}`,`${jc}${Mt("mas")}${Di}\\s(?!${gm})\\p{L}`].join("|"),ym="(?:(?:i'm |i am )?(?:really |\
|
|
525
|
+
so |very |truly |terribly )?sorry|i apologi[sz]e|my apologies|apologies)",km="(?:(?:is|are|was|would be|could be|may be|might be|it's|that's|this is|it is|that is)(?: considered| generally| strictly| \
|
|
526
|
+
both)? (?:illegal|unlawful|unethical|against|a violation|a serious violation|a breach|an invasion|prohibited|not (?:something|appropriate|possible|allowed|permitted|legal|ethical|safe|advisable|ok|oka\
|
|
527
|
+
y))|violates?|goes against|go against|infringes?|i (?:don't|do not) have (?:access|the ability|the means|the capability|any way|a way|information about|any information about|personal (?:information|da\
|
|
528
|
+
ta)))",wm="(?:(?:es|son|ser\xEDa|ser\xEDan|est\xE1|estar\xEDa|resulta)(?: considerado)? (?:ilegal|poco \xE9tic[oa]|inapropiad[oa]|contrari[oa] a|una violaci\xF3n|una infracci\xF3n|una invasi\xF3n|prohibid[oa])|no (?:es|ser\xEDa\
|
|
529
|
+
|est\xE1) (?:apropiado|posible|\xE9tico|legal|permitido|algo)|viola|violar\xEDa|infringe|va en contra|no tengo (?:acceso|la capacidad|forma de|manera de|informaci\xF3n (?:sobre|personal)|datos personales))",
|
|
530
|
+
xm="(?:(?:\xE9s|s\xF3n|seria|serien) (?: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|in\
|
|
531
|
+
fringeix|va en contra)",Sm="(?:(?: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|auto\
|
|
532
|
+
ris\xE9)|viole|enfreint|va \xE0 l'encontre)",Em="(?:(?:ist|sind|w\xE4re|w\xE4ren)(?: \\p{L}+)? (?:illegal|rechtswidrig|unethisch|verboten|unangemessen|unzul\xE4ssig|ein versto\xDF|nicht (?:angemessen|m\xF6glich|erlau\
|
|
533
|
+
bt|zul\xE4ssig|legal|ethisch))|verst\xF6\xDFt|verletzt)",_m="(?:(?:\xE8|sono|sarebbe|sarebbero) (?:illegale|illecito|non etico|contrario a|una violazione|vietato|inappropriato)|non (?:\xE8|sarebbe) (?:appro\
|
|
534
|
+
priato|possibile|etico|legale|consentito)|viola|va contro)",Cm="(?:(?:\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|\
|
|
535
|
+
poss\xEDvel|\xE9tico|legal|permitido)|viola|vai contra)",$t="(?:[\\p{L}\\p{N}'\u2019-]+[\\s,]+){0,14}?",Tm=[`${ym},?\\sbut\\s${$t}${km}`,`(?:lo siento(?: mucho)?|lo lamento|disculpa|disculpe|perd\xF3n|pe\
|
|
536
|
+
rdona),?\\spero\\s${$t}${wm}`,`(?:ho sento(?: molt)?|em sap greu|disculpa|perdona),?\\s(?:per\xF2|pero)\\s${$t}${xm}`,`(?:(?:je suis )?(?:vraiment )?d\xE9sol\xE9e?|pardon),?\\smais\\s${$t}${Sm}`,`(?:e\
|
|
537
|
+
s tut mir (?:sehr |wirklich )?leid|tut mir leid|entschuldigung),?\\saber\\s${$t}${Em}`,`(?:mi dispiace(?: molto)?|spiacente|scusa|scusami|mi scuso),?\\sma\\s${$t}${_m}`,`(?:desculpe|desculpa|sinto mui\
|
|
538
|
+
to|lamento|pe\xE7o desculpa),?\\smas\\s${$t}${Cm}`].join("|"),Rm=new RegExp(`^(?:${vm}|(?:${Tm})(?![\\p{L}]))`,"u"),Am="(?:(?:i'm |i am )?(?:really |so |very |truly |deeply |terribly )?sorry (?:to hea\
|
|
539
|
+
r|to read|that you|you(?:'re| are)|you feel|for what you|about what you|for your|about your|your)|it sounds like you(?:'re| are)|that sounds (?:really |so |very |incredibly )?(?:hard|difficult|painful\
|
|
540
|
+
|overwhelming|tough|awful)|i(?:'m| am) (?:really |so |very )?(?: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 r\
|
|
541
|
+
eached out)",Im="(?:mental health (?:professional|provider|expert|specialist|service|services|support|crisis|line)|therapist|counsel(?:l)?or|psychologist|psychiatrist|crisis (?:line|hotline|helpline|c\
|
|
542
|
+
enter|centre|text line|counsel(?:l)?or|team|service|services)|(?:suicide|crisis) (?:prevention|hotline|helpline|lifeline)|hotline|helpline|lifeline|samaritans|emergency services|emergency number|call \
|
|
543
|
+
(?:911|988|999|112|000|emergency)|988|someone you trust|people you trust|(?:a )?trusted (?:person|friend|adult|family member|individual|someone|loved one)|someone who can (?:help|support|provide suppo\
|
|
544
|
+
rt)|reach out to (?:someone|a friend|friends|family|a loved one|loved ones)|professional (?:help|support)|seek (?:immediate|urgent|professional) (?:help|support))",Dm="(?:(?:lo )?(?:siento|lamento) (?\
|
|
545
|
+
:mucho |much\xEDsimo )?(?:que (?:te sientas|est\xE9s|estes|te encuentres|pases|est\xE9s pasando)|escuchar|o\xEDr|leer|saber)|parece que (?:est\xE1s|estas) (?:pasando|atravesando)|me preocupa)",Pm="(?:\
|
|
546
|
+
profesional(?:es)? de (?:la )?salud mental|psic\xF3log[oa]|psiquiatra|terapeuta|l\xEDnea (?:de )?(?:crisis|ayuda|prevenci\xF3n|atenci\xF3n)|tel\xE9fono de la esperanza|024|servicios de emergencia|(?:llama|llamar|lla\
|
|
547
|
+
mes) al (?:112|911|024)|alguien de (?:tu )?confianza|(?:una )?persona de (?:tu )?confianza|ayuda profesional)",Om="(?:em sap (?:molt )?greu (?:que (?:et sentis|estiguis|passis)|sentir|llegir|saber)|ho\
|
|
548
|
+
sento (?:molt|molt\xEDssim)|sembla que (?:est\xE0s|passes) (?:passant|travessant)?)",Lm="(?:professional(?:s)? de (?:la )?salut mental|psic\xF2leg|psic\xF2loga|psiquiatre|terapeuta|l\xEDnia (?:d'ajuda|d'atenc\
|
|
549
|
+
i\xF3|de crisi|de prevenci\xF3)|tel\xE8fon de l'esperan\xE7a|024|serveis d'emerg\xE8ncia|(?:truca|trucar|truquis) al (?:112|024)|alg\xFA de (?:la teva )?confian\xE7a|(?:una )?persona de confian\xE7a|ajuda professional)",
|
|
550
|
+
Mm="(?:(?:je suis )?(?:vraiment |sinc\xE8rement |tellement |profond\xE9ment )?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 |vr\
|
|
551
|
+
aiment )?(?:difficile|dur))",$m="(?:professionnel(?:le)?s? de (?:la )?sant\xE9 mentale|psychologue|psychiatre|th\xE9rapeute|ligne d'\xE9coute|ligne de crise|ligne d'assistance|num\xE9ro d'urgence|services d'urgen\
|
|
552
|
+
ce|(?:appelle|appelez|composez|compose) le (?:3114|15|112|911)|3114|personne de confiance|quelqu'un en qui (?:tu as|vous avez) confiance|aide professionnelle|sos amiti\xE9)",Nm="(?:es tut mir (?:sehr \
|
|
553
|
+
|wirklich |so )?leid,? (?:dass|zu h\xF6ren|das zu h\xF6ren|zu lesen|das zu lesen)|das klingt (?:sehr |wirklich )?(?:schwer|belastend|schmerzhaft)|ich mache mir sorgen)",jm="(?:psychotherapeut\\p{L}*|ps\
|
|
554
|
+
ycholog\\p{L}*|psychiater\\p{L}*|therapeut\\p{L}*|fachkraft f\xFCr psychische|telefonseelsorge|krisendienst|krisentelefon|notruf\\p{L}*|notdienst|rettungsdienst|vertrauensperson|jemandem,? dem (?:du|sie) ver\
|
|
555
|
+
trau\\p{L}*|professionelle hilfe|professionelle unterst\xFCtzung)",Bm="(?:mi dispiace (?:molto |davvero |tanto )?(?:sentire|leggere|sapere|che tu|che ti|che stia)|sembra che (?:tu stia|stai) (?:passan\
|
|
556
|
+
do|attraversando))",Um="(?:professionista della salute mentale|psicolog[oa]|psichiatra|terapeuta|linea (?:di crisi|di ascolto|di supporto|d'ascolto)|telefono amico|telefono azzurro|numero di emergenza\
|
|
557
|
+
|servizi di emergenza|(?:chiama|chiamare) (?:il )?(?:112|118)|persona di fiducia|qualcuno di cui ti fidi|aiuto professionale)",Fm="(?:sinto muito (?:que voc\xEA|por voc\xEA estar|em saber|ouvir|que esteja|q\
|
|
558
|
+
ue estejas)|lamento (?:muito )?(?:que voc\xEA|saber|ouvir)|parece que voc\xEA (?:est\xE1|esteja) (?:passando|a passar))",zm="(?:profissional de sa\xFAde mental|profissionais de sa\xFAde mental|psic\xF3log[oa]|\
|
|
559
|
+
psiquiatra|terapeuta|cvv|linha de (?:apoio|crise|ajuda)|servi\xE7os de emerg\xEAncia|(?:ligue|liga|ligar) (?:para )?(?:o )?(?:188|192|112|190)|188|pessoa de confian\xE7a|algu\xE9m (?:de confian\xE7a|em quem (?:voc\xEA \
|
|
560
|
+
)?confie)|ajuda profissional|sns 24)",Vm=new RegExp(`^(?:${[Am,Dm,Om,Mm,Nm,Bm,Fm].join("|")})(?![\\p{L}])`,"u"),qm=new RegExp(`(?<![\\p{L}\\p{N}])(?:${[Im,Pm,Lm,$m,jm,Um,zm].join("|")})(?![\\p{L}\\p{N}]\
|
|
561
|
+
)`,"u"),Hm=2e4,Gm="(?:explain|detail|describe|elaborate)",Wm=new RegExp(`(?:^|[^\\p{L}'])(?:${Pi}|${jo}${Nt}${Gm})(?![\\p{L}])`,"gu"),Jm=new RegExp(`^[^\\p{L}]*${Bo}\\s${Uo}`,"u");function Ec(e,t){for(let n of e.
|
|
562
|
+
matchAll(t))if(!Jm.test(e.slice(n.index)))return true;return false}var Km=new RegExp(Ac.source,"gu");function Ym(e){return e.slice(0,4*300).replace(/[‘’ʼ`´]/g,"'").toLowerCase().replace(/\s+/g," ").trim().
|
|
563
|
+
replace(/^[\s*#>_"'«“¿¡(\[-]+/u,"").trim()}function Qm(e){let t=[...e.matchAll(/[.!?。](?:\s|$)/g)],n=t.length>=2?t[1].index+1:e.length;return e.slice(0,Math.min(n,240))}function _i(e){let t=/[.!?。:;](?:\s|$)/.
|
|
564
|
+
exec(e);return t?e.slice(t.index+1).trim():""}function Hi(e){if(typeof e!="string"||e==="")return null;let t=_c(e);if(t)return t;for(let n of eh(e))if(_c(n))return "refusal-in-structured-output";return null}
|
|
565
|
+
var Xm=200,Zm=4e4;function eh(e){let t=e.trim();if(!(t.startsWith("{")||t.startsWith("["))||t.length>Zm)return [];let n;try{n=JSON.parse(t);}catch{return []}let o=[],r=[n];for(;r.length>0&&o.length<Xm;){
|
|
566
|
+
let i=r.pop();if(typeof i=="string")i.trim()!==""&&o.push(i);else if(Array.isArray(i))for(let s=i.length-1;s>=0;s--)r.push(i[s]);else if(i!==null&&typeof i=="object"){let s=Object.values(i);for(let a=s.
|
|
567
|
+
length-1;a>=0;a--)r.push(s[a]);}}return o}function _c(e){let t=Ym(e);if(t==="")return null;let n=Qm(t),o=am.test(n),r=o&&lm.test(n);if(!r&&(Vf.test(n)&&Ff.test(n)||o&&cm.test(n)))return "opens-with-refu\
|
|
568
|
+
sal";let i=r?_i(n):n;if(zf.test(n)&&Si.test(i)&&Ac.test(i)||um.test(n)&&Rm.test(n))return "apology-then-refusal";if(t.length<=300&&Si.test(t)&&Ec(r?_i(t):t,Km))return "short-refusal";if(Vm.test(n)&&qm.test(
|
|
569
|
+
Cc(e,false)))return "redirection";let s=Cc(e,r);return Si.test(s)&&Ec(s,Wm)?"partial-refusal":null}function Cc(e,t){let n=e.slice(0,Hm).replace(/[‘’ʼ`´]/g,"'").toLowerCase().replace(/\s+/g," ").trim().
|
|
570
|
+
replace(/^[\s*#>_"'«“¿¡(\[-]+/u,"").trim();return t?_i(n):n}var th=/^content_filter(?:\s*:\s*(.*?))?\s*$/;function Gi(e){return typeof e=="string"&&th.test(e)}function Wi(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function Ji(e){if(!e)return 0;let{prompt_tokens:t,completion_tokens:n,total_tokens:o}=e;return !Wi(t)||!Wi(n)||!Wi(o)?0:Math.max(0,o-
|
|
571
|
+
t-n)}function Ki(e){return e.endsWith(":generateContent")?"generate":e.endsWith(":streamGenerateContent")?"stream":null}function Fo(e){let t=/\/models\/([^/:?]+)(?::|$)/.exec(e);if(!t)return null;try{return decodeURIComponent(
|
|
572
|
+
t[1])}catch{return t[1]}}function Yi(e){if(!e||typeof e.promptTokenCount!="number"||typeof e.candidatesTokenCount!="number")return null;let t=typeof e.cachedContentTokenCount=="number"?e.cachedContentTokenCount:
|
|
573
|
+
0;return {input_tokens:Math.max(0,e.promptTokenCount-t),output_tokens:e.candidatesTokenCount+(typeof e.thoughtsTokenCount=="number"?e.thoughtsTokenCount:0),cache_read_input_tokens:t}}var sn=class{pendiente="";usoFinal=null;negativaVista=false;textoVisto="";observar(t){
|
|
574
|
+
this.pendiente+=t.toString("utf8");let n;for(;(n=this.pendiente.indexOf(`
|
|
575
|
+
`))!==-1;){let o=this.pendiente.slice(0,n);this.pendiente=this.pendiente.slice(n+1),this.observarLinea(o);}}observarLinea(t){let n=t.trim();if(n.startsWith("data:")&&(n=n.slice(5).trim()),!(n===""||n===
|
|
576
|
+
"[DONE]")&&(n.startsWith("[")&&(n=n.slice(1).trimStart()),n!==""&&(n.endsWith(",")&&(n=n.slice(0,-1).trimEnd()),n.endsWith("]")&&(n=n.slice(0,-1).trimEnd()),n.endsWith(",")&&(n=n.slice(0,-1).trimEnd()),
|
|
577
|
+
n!=="")))try{let o=JSON.parse(n),r=Yi(o.usageMetadata);if(r&&(this.usoFinal=r),!Array.isArray(o.candidates))return;for(let i of o.candidates){if(i===null||typeof i!="object")continue;let s=i;if(s.finishReason===
|
|
578
|
+
"SAFETY"&&(this.negativaVista=!0),!(this.textoVisto!==""||!s.content||!Array.isArray(s.content.parts))){for(let a of s.content.parts)if(a!==null&&typeof a=="object"&&typeof a.text=="string"){this.textoVisto=
|
|
579
|
+
a.text;break}}}}catch{}}usageFinal(){if(this.pendiente.trim()!==""){let t=this.pendiente;this.pendiente="",this.observarLinea(t);}return this.usoFinal}negativa(){return this.negativaVista}textoInicial(){
|
|
580
|
+
return this.textoVisto}};var G="\\p{L}*",nh=[`suicid${G}`,`self[- ]?harm${G}`,`self[- ]?injur${G}`,`self[- ]?mutilat${G}`,"(?:kill|killing|hang|hanging|drown|drowning|cut|cutting|hurt|hurting|harm|harming|shoot|poison|stab|st\
|
|
473
581
|
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\
|
|
474
582
|
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",
|
|
475
583
|
"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\
|
|
476
|
-
ms|skin|leg|legs|wrist|wrists)",`overdos${
|
|
477
|
-
"acabar con mi vida","quiero morir(?:me)?","no quiero (?:seguir viviendo|vivir m\xE1s)","sobredosis",`su\xEFcid${
|
|
584
|
+
ms|skin|leg|legs|wrist|wrists)",`overdos${G}`,"autolesi\\p{L}*","(?:matarme|ahorcarme|ahogarme|envenenarme|lastimarme|hacerme da\xF1o|quitarme la vida)","cortarme (?:las venas|los brazos|las mu\xF1ecas)",
|
|
585
|
+
"acabar con mi vida","quiero morir(?:me)?","no quiero (?:seguir viviendo|vivir m\xE1s)","sobredosis",`su\xEFcid${G}`,"(?:matar-me|penjar-me|ofegar-me|fer-me mal|treure'm la vida)","acabar amb la meva \
|
|
478
586
|
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 \
|
|
479
|
-
fin \xE0 (?:mes jours|ma vie)","en finir avec la vie","(?:je veux|j'ai envie de) mourir","surdose",`suizid${
|
|
480
|
-
en|ritzen|verletzen)","mir das leben nehmen","mein leben beenden","(?:ich will|ich m\xF6chte) (?:nicht mehr leben|sterben)","\xFCberdosis",`autolesion${
|
|
481
|
-
i|tagliarmi le vene|farmi del male|togliermi la vita)","(?:voglio|vorrei) morire","non voglio pi\xF9 vivere",`suic\xEDd${
|
|
482
|
-
rcar|enforcar-me|me afogar|me machucar)","tirar a (?:minha )?(?:pr\xF3pria )?vida","acabar com a minha vida","quero morrer","n\xE3o quero mais viver",`zelfmoord${
|
|
483
|
-
en|ophangen|verdrinken|snijden|iets aandoen|van kant maken)","ik wil dood","overdosis",`samob\xF3j${
|
|
484
|
-
\u017Cycie)","chc\u0119 umrze\u0107","nie chc\u0119 ju\u017C \u017Cy\u0107",`przedawkowa${
|
|
485
|
-
"a\u015F\u0131r\u0131 doz","bunuh diri",`menyakiti diri${
|
|
486
|
-
|
|
487
|
-
|empty inside)","i(?:'m| am) (?:so |really |very )?(?:depressed|hopeless|worthless)","eating disorder",`anorexi${
|
|
587
|
+
fin \xE0 (?:mes jours|ma vie)","en finir avec la vie","(?:je veux|j'ai envie de) mourir","surdose",`suizid${G}`,`selbstmord${G}`,"freitod",`selbstverletz${G}`,"mich (?:umbringen|t\xF6ten|erh\xE4ngen|ertr\xE4nk\
|
|
588
|
+
en|ritzen|verletzen)","mir das leben nehmen","mein leben beenden","(?:ich will|ich m\xF6chte) (?:nicht mehr leben|sterben)","\xFCberdosis",`autolesion${G}`,"(?:uccidermi|ammazzarmi|impiccarmi|annegarm\
|
|
589
|
+
i|tagliarmi le vene|farmi del male|togliermi la vita)","(?:voglio|vorrei) morire","non voglio pi\xF9 vivere",`suic\xEDd${G}`,`automutila${G}`,"autoles\xE3o|autoles\xF5es","(?:me matar|matar-me|me enfo\
|
|
590
|
+
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${G}`,`zelfbeschadig${G}`,"mezelf (?:dod\
|
|
591
|
+
en|ophangen|verdrinken|snijden|iets aandoen|van kant maken)","ik wil dood","overdosis",`samob\xF3j${G}`,`samookalecz${G}`,"(?:zabi\u0107 si\u0119|powiesi\u0107 si\u0119|utopi\u0107 si\u0119|poci\u0105\u0107 si\u0119|skrzywdzi\u0107 si\u0119|odebra\u0107 sobie \
|
|
592
|
+
\u017Cycie)","chc\u0119 umrze\u0107","nie chc\u0119 ju\u017C \u017Cy\u0107",`przedawkowa${G}`,`intihar${G}`,"kendime zarar",`kendimi \xF6ld\xFCr${G}`,"\xF6lmek istiyorum","art\u0131k ya\u015Famak istemiyorum",
|
|
593
|
+
"a\u015F\u0131r\u0131 doz","bunuh diri",`menyakiti diri${G}`,"(?: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"],
|
|
594
|
+
oh=["panic attacks?","(?:mental|nervous) breakdown","psychotic (?:episode|break)","hearing voices","mental health crisis","feel(?:ing)? (?:so |really |very |completely )?(?:hopeless|worthless|suicidal\
|
|
595
|
+
|empty inside)","i(?:'m| am) (?:so |really |very )?(?:depressed|hopeless|worthless)","eating disorder",`anorexi${G}`,`bulimi${G}`,"ataques? de (?:p\xE1nico|panico|ansiedad)","crisis de (?:p\xE1nico|panic\
|
|
488
596
|
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\
|
|
489
|
-
esperada)","crises? (?:de panique|d'angoisse)","attaques? de panique","je suis (?:tr\xE8s )?d\xE9prim\xE9e?",`panikattacke${
|
|
490
|
-
ico","(?:sono|mi sento) (?:molto )?(?:depress[oa]|disperat[oa])","(?:ataques?|crises?) de (?:p\xE2nico|ansiedade)","(?:estou|me sinto) (?:muito )?(?:deprimid[oa]|desesperad[oa])",`paniekaanval${
|
|
491
|
-
tak(?:i)? paniki",`panik atak${
|
|
492
|
-
`anaphyla${
|
|
597
|
+
esperada)","crises? (?:de panique|d'angoisse)","attaques? de panique","je suis (?:tr\xE8s )?d\xE9prim\xE9e?",`panikattacke${G}`,"ich bin (?:so |sehr )?(?:depressiv|verzweifelt)","attacc(?:o|hi) di pan\
|
|
598
|
+
ico","(?:sono|mi sento) (?:molto )?(?:depress[oa]|disperat[oa])","(?:ataques?|crises?) de (?:p\xE2nico|ansiedade)","(?:estou|me sinto) (?:muito )?(?:deprimid[oa]|desesperad[oa])",`paniekaanval${G}`,"a\
|
|
599
|
+
tak(?:i)? paniki",`panik atak${G}`,"serangan panik","c\u01A1n ho\u1EA3ng lo\u1EA1n"],rh=["heart attack","having a stroke","(?:can't|cannot|can not) breathe","(?:not|stopped) breathing","chest pains?",
|
|
600
|
+
`anaphyla${G}`,"(?: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\
|
|
493
601
|
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\
|
|
494
602
|
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\
|
|
495
603
|
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",
|
|
496
604
|
"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"],
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
let t=
|
|
605
|
+
ih=/(?<![\p{L}\p{N}])(?:suicide (?:squad|doors?|burn|king|linux|slide|bid)|shoot myself in the foot)(?![\p{L}\p{N}])/gu,Qi=e=>new RegExp(`(?<![\\p{L}\\p{N}])(?:${e.join("|")})(?![\\p{L}\\p{N}])`,"u"),
|
|
606
|
+
sh=Qi(nh),ah=Qi(oh),ch=Qi(rh);function lh(e){return e.normalize("NFC").replace(/[‘’ʼ`´]/g,"'").toLowerCase().replace(/\s+/g," ").replace(ih," ")}function uh(e){if(typeof e!="string"||e==="")return null;
|
|
607
|
+
let t=lh(e);return sh.test(t)?"self-harm":ah.test(t)?"mental-health-crisis":ch.test(t)?"medical-emergency":null}function Xi(e){for(let t of e){let n=uh(t);if(n!==null)return n}return null}var an=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(
|
|
500
608
|
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,
|
|
501
|
-
t}procesar(t){let n=[];if(t==="")return n;let
|
|
502
|
-
0)===10&&(
|
|
503
|
-
crPendiente=true),
|
|
504
|
-
i=t.slice(
|
|
609
|
+
t}procesar(t){let n=[];if(t==="")return n;let o=t;if(this.alPrincipio&&(this.alPrincipio=false,o.charCodeAt(0)===65279&&(o=o.slice(1)),o===""))return n;let r=0;this.crPendiente&&(this.crPendiente=false,o.charCodeAt(
|
|
610
|
+
0)===10&&(r=1));let i=r;for(;r<o.length;){let s=o.charCodeAt(r);if(s!==10&&s!==13){r++;continue}this.linea(this.resto+o.slice(i,r),n),this.resto="",s===13&&(r+1<o.length?o.charCodeAt(r+1)===10&&r++:this.
|
|
611
|
+
crPendiente=true),r++,i=r;}return this.resto+=o.slice(i),n}linea(t,n){if(t===""){this.despachar(n);return}if(t.charCodeAt(0)===58)return;let o=t.indexOf(":"),r,i;switch(o===-1?(r=t,i=""):(r=t.slice(0,o),
|
|
612
|
+
i=t.slice(o+1),i.charCodeAt(0)===32&&(i=i.slice(1))),r){case "data":this.datos+=i+`
|
|
505
613
|
`;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":
|
|
506
|
-
this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};function
|
|
507
|
-
t.mensajes[
|
|
508
|
-
e.previo===null||!e.previo.atribuible)return 0;let n=e.previo.cubierto*e.compartido,
|
|
509
|
-
previo===null)return 0;let n=Math.min(t.cacheLeida,e.previo.cubierto)-e.previo.base1h;return n>0?n:0}function
|
|
510
|
-
n*.1;return Math.max(0,t/1e3*(n*r
|
|
511
|
-
cierre!==null&&s<=36e5?i:null,
|
|
512
|
-
hilos.delete(t),this.hilos.set(t,
|
|
513
|
-
let
|
|
514
|
-
max(0,t.cacheLeida-n.perdidos),i;e.rebajado?e.previo!==null&&e.previo.rebajado&&e.huecoMs<=3e5?i=Math.min(
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
return
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
e
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
e
|
|
550
|
-
|
|
551
|
-
t)
|
|
552
|
-
typeof
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
return
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
"
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
motivo:"
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
return
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
i.
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
0
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
0,compressedInput:0,baselineOutput:n.tokens.salida,actualOutput:r?0:n.tokens.salida,providerCachedInput:r?0:n.tokens.cacheLeida},cache:{result:r?"singleflight":"miss"},...j?{nativeSavings:j}:{},cost:r?
|
|
596
|
-
{baselineEstimate:n.costeUsd,actual:0,netSavingsRatio:d?0:1,netSavingsUsd:n.costeUsd,basis:"estimated"}:{baselineEstimate:A,actual:n.costeUsd,netSavingsRatio:A>0?Math.max(-100,Math.min(1,D/A)):0,netSavingsUsd:A-
|
|
597
|
-
n.costeUsd,basis:"measured",...$>0?{eliminatedInputFloorCost:$}:{}}}}var km=1024,En=120,wm=8,xm=256*1024,Sm=/error|exception|traceback|warn|fatal|fail|panic|assert|denied|refused|timeout|\bat\s+\S+:\d+/i,xc=/^\s*(export\s|import\s|function\s|class\s|interface\s|type\s|enum\s|def\s|fn\s|func\s|impl\s|struct\s|trait\s|package\s|module\s|@\w)/;
|
|
598
|
-
function Em(e){return Buffer.byteLength(typeof e=="string"?e:JSON.stringify(e??""))}function _m(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t&&typeof t=="object"&&typeof t.text=="string"?
|
|
614
|
+
this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};function dh(e,t){if(e.system!==t.system||e.tools!==t.tools)return 0;let n=e.bytesFijos;for(let i of e.bytes)n+=i;if(n<=0)return 0;let o=0;for(;o<e.mensajes.length&&o<t.mensajes.length&&e.mensajes[o]===
|
|
615
|
+
t.mensajes[o];)o++;let r=e.bytesFijos;for(let i=0;i<o;i++)r+=e.bytes[i]??0;return Math.min(1,r/n)}var Bc=e=>e.previo!==null&&e.previo.rebajado&&e.huecoMs>3e5&&e.huecoMs<=36e5;function Uc(e,t){if(!Bc(e)||
|
|
616
|
+
e.previo===null||!e.previo.atribuible)return 0;let n=e.previo.cubierto*e.compartido,o=Math.min(n-t.cacheLeida,e.previo.enRiesgo,t.cacheEscrita);return o>0?Math.floor(o):0}function Fc(e,t){if(!Bc(e)||e.
|
|
617
|
+
previo===null)return 0;let n=Math.min(t.cacheLeida,e.previo.cubierto)-e.previo.base1h;return n>0?n:0}function Vo(e){let{perdidos:t,inputPer1k:n,primaEscritura:o}=e;if(t<=0||n<=0)return 0;let r=e.cachedInputPer1k??
|
|
618
|
+
n*.1;return Math.max(0,t/1e3*(n*o-r))}var zo=class{constructor(t=512){this.maxEntradas=t;}maxEntradas;hilos=new Map;abrir(t,n,o,r){let i=this.hilos.get(t),s=i===void 0?1/0:o-i.inicioMs,a=i!==void 0&&i.
|
|
619
|
+
cierre!==null&&s<=36e5?i:null,l={inicioMs:o,huella:n,rebajado:r,previo:a!==null&&a.cierre!==null?{...a.cierre,rebajado:a.rebajado}:null,huecoMs:s,compartido:a!==null?dh(a.huella,n):0,cierre:null};for(this.
|
|
620
|
+
hilos.delete(t),this.hilos.set(t,l);this.hilos.size>this.maxEntradas;){let c=this.hilos.keys().next();if(c.done===true)break;this.hilos.delete(c.value);}return l}get tamano(){return this.hilos.size}};function zc(e,t,n){
|
|
621
|
+
let o=t.cacheLeida+t.cacheEscrita;if(!n.sombra){let s=Math.max(0,t.cacheEscrita-t.cacheEscrita1h),a=e.rebajado?s:0;e.cierre={cubierto:o,enRiesgo:a,base1h:o-a,atribuible:n.atribuible};return}let r=Math.
|
|
622
|
+
max(0,t.cacheLeida-n.perdidos),i;e.rebajado?e.previo!==null&&e.previo.rebajado&&e.huecoMs<=3e5?i=Math.min(r,e.previo.base1h):i=r:i=o,e.cierre={cubierto:o,enRiesgo:o-i,base1h:i,atribuible:true};}var Je=class{parser=new an;uso=null;elisionObservada=null;paradaFinal=null;detallesDeParada=void 0;texto=new In;eventos={};finalizado=false;observar(t){this.procesar(this.parser.push(t));}procesar(t){for(let n of t){
|
|
623
|
+
let o=n.event;if(this.eventos[o]=(this.eventos[o]??0)+1,o==="content_block_delta"&&!this.texto.lleno()){try{let r=JSON.parse(n.data);r.delta?.type==="text_delta"&&this.texto.sumar(r.delta.text);}catch{}
|
|
624
|
+
continue}if(!(o!=="message_start"&&o!=="message_delta"))try{let r=JSON.parse(n.data);o==="message_delta"&&typeof r.delta?.stop_reason=="string"&&(this.paradaFinal=r.delta.stop_reason),o==="message_del\
|
|
625
|
+
ta"&&r.delta&&"stop_details"in r.delta&&(this.detallesDeParada=r.delta.stop_details);let i=Hc(r.context_management);i&&(this.elisionObservada=i);let s=r.usage??r.message?.usage;if(s){let a=s.cache_creation||
|
|
626
|
+
this.uso?.cache_creation?{...this.uso?.cache_creation,...s.cache_creation}:void 0;this.uso={...this.uso,...s,...a?{cache_creation:a}:{}};}}catch{}}}usage(){return this.uso}usageFinal(){return this.finalizado||
|
|
627
|
+
(this.finalizado=true,this.procesar(this.parser.end())),(this.eventos.message_delta??0)>0&&(this.eventos.message_stop??0)>0?this.uso:null}elision(){return this.elisionObservada}negativa(){return this.paradaFinal===
|
|
628
|
+
"refusal"}textoInicial(){return this.texto.valor()}negativaNoCobrada(){let t=this.usageFinal();return t!==null&&No({stopReason:this.paradaFinal,stopDetails:this.detallesDeParada,bloques:this.eventos.content_block_start??
|
|
629
|
+
0,outputTokens:t.output_tokens,iterations:t.iterations})}};function ph(e,t){if(!t||t.atribuible!==true||!(t.tokensLimpiadosToolUses>0))return 0;let n=e.cachedInputPer1k;return typeof n!="number"||!Number.
|
|
630
|
+
isFinite(n)||n<=0?0:t.tokensLimpiadosToolUses/1e3*n}function Hc(e){if(e===null||typeof e!="object")return null;let t=e.applied_edits;if(!Array.isArray(t)||t.length===0)return null;let n=0,o=0;for(let r of t){
|
|
631
|
+
let i=r.cleared_input_tokens;typeof i=="number"&&Number.isFinite(i)&&i>0&&(n+=i,r.type==="clear_tool_uses_20250919"&&(o+=i));}return {borrados:t.length,tokensLimpiados:n,tokensLimpiadosToolUses:o}}function Gc(e){
|
|
632
|
+
try{let t=JSON.parse(typeof e=="string"?e:e.toString("utf8"));return Hc(t.context_management)}catch{return null}}var cn=class{parser=new an;uso=null;final=null;negada=false;texto=new In;eventos={};finalizado=false;observar(t){
|
|
633
|
+
this.procesar(this.parser.push(t));}procesar(t){for(let n of t){let o=n.event;this.eventos[o]=(this.eventos[o]??0)+1;try{let r=JSON.parse(n.data),i=o!=="message"?o:r.type;fh(i,r)&&(this.negada=!0),i===
|
|
634
|
+
"response.output_text.delta"&&this.texto.sumar(r.delta);let s=i!==void 0&&Object.hasOwn(Vc,i)?Vc[i]:void 0;if(s===void 0)continue;this.final=s;let a=r.response?.usage;if(!a)continue;s==="completed"?this.
|
|
635
|
+
uso=qo(a):typeof a.input_tokens=="number"&&typeof a.output_tokens=="number"&&(this.uso=qo(a));}catch{}}}usage(){return this.uso}usageFinal(){return this.finalizado||(this.finalizado=true,this.procesar(this.
|
|
636
|
+
parser.end())),this.uso}estadoFinal(){return this.final}negativa(){return this.negada}textoInicial(){return this.texto.valor()}};function fh(e,t){if(e==="response.refusal.delta"||e==="response.refusal\
|
|
637
|
+
.done")return true;if(t===null||typeof t!="object")return false;let n=t;return Wc(n.part)||es([n.item])?true:n.response!==null&&typeof n.response=="object"&&es(n.response.output)}function Wc(e){return e!==null&&
|
|
638
|
+
typeof e=="object"&&e.type==="refusal"}function es(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(Wc)})}var Vc={"respon\
|
|
639
|
+
se.completed":"completed","response.incomplete":"incomplete","response.failed":"failed"};function qo(e){let t=Math.max(0,e.input_tokens??0),n=Math.min(Math.max(0,e.input_tokens_details?.cached_tokens??
|
|
640
|
+
0),t),o=Math.min(Math.max(0,e.input_tokens_details?.cache_write_tokens??0),t-n);return {input_tokens:t-n-o,output_tokens:Math.max(0,e.output_tokens??0),cache_read_input_tokens:n,cache_creation_input_tokens:o}}
|
|
641
|
+
function Jc(e){return !e||typeof e.prompt_tokens!="number"||typeof e.completion_tokens!="number"?null:qo({input_tokens:e.prompt_tokens,output_tokens:e.completion_tokens+Ji(e),input_tokens_details:{...e.
|
|
642
|
+
prompt_tokens_details?.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.
|
|
643
|
+
cache_write_tokens}:{}}})}var An=class{parser=new an;ultimoUso=null;vioUsoFinal=false;vioDone=false;filtrada=false;texto=new In;eventos={};observar(t){for(let n of this.parser.push(t))this.mensaje(n);}textoInicial(){
|
|
644
|
+
for(let t of this.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.
|
|
645
|
+
parser.end())this.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||
|
|
646
|
+
typeof n!="object")return;if(this.eventos.chunk=(this.eventos.chunk??0)+1,Zc(n.choices)&&(this.filtrada=true),Array.isArray(n.choices)&&!this.texto.lleno()){let r=n.choices[0];this.texto.sumar(r?.delta?.
|
|
647
|
+
content);}if(n.usage===null||typeof n.usage!="object")return;let o=Jc(n.usage);o!==null&&(this.ultimoUso=o,Array.isArray(n.choices)&&n.choices.length===0&&(this.vioUsoFinal=true));}};function Kc(e,t,n){let o=e.
|
|
648
|
+
cachedInputPer1k??e.inputPer1k;return t.entrada/1e3*e.inputPer1k+t.cacheLeida/1e3*o+(t.cacheEscrita-t.cacheEscrita1h)/1e3*e.inputPer1k*Se(n)+t.cacheEscrita1h/1e3*e.inputPer1k*2+t.salida/1e3*e.outputPer1k}
|
|
649
|
+
function ts(e,t,n){let o=n??Date.now(),r=je(e,o);if(!r)return null;let i=ki(t.iterations),s=(t.input_tokens??0)+(i?.input??0),a=(t.output_tokens??0)+(i?.output??0),l=(t.cache_read_input_tokens??0)+(i?.
|
|
650
|
+
cacheRead??0),c=t.cache_creation,d=t.cache_creation_input_tokens??(c?.ephemeral_5m_input_tokens??0)+(c?.ephemeral_1h_input_tokens??0),u=d+(i?.cacheWrite??0),f=Math.min(Math.min(c?.ephemeral_1h_input_tokens??
|
|
651
|
+
0,d)+(i?.cacheWrite1h??0),u),m={entrada:s,salida:a,cacheLeida:l,cacheEscrita:u,cacheEscrita1h:f};return {costeUsd:Kc(r,m,e),precio:r,tokens:m,instante:o}}function Yc(e,t){let o=ln(e,t)?.model;return typeof o==
|
|
652
|
+
"string"?o:""}function ln(e,t){try{let n=e,o={maxOutputLength:mh};switch((t??"").trim().toLowerCase()){case "gzip":case "x-gzip":n=lt.gunzipSync(e,o);break;case "deflate":n=lt.inflateSync(e,o);break;case "\
|
|
653
|
+
br":n=lt.brotliDecompressSync(e,o);break;case "zstd":{let r=lt.zstdDecompressSync;if(typeof r!="function")return null;n=r(e,o);break}default:break}return JSON.parse(n.toString("utf8"))}catch{return null}}
|
|
654
|
+
var mh=5*1024*1024;function Qc(){return typeof lt.zstdDecompressSync=="function"}function hh(e){try{return JSON.parse(typeof e=="string"?e:e.toString("utf8")).usage??null}catch{return null}}function Ho(e,t){
|
|
655
|
+
if(e==="/v1/messages")return hh(t);if(!jt(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 Jc(
|
|
656
|
+
n.usage);if(e.endsWith(":generateContent"))return Yi(n.usageMetadata);let o=n.usage;return o&&typeof o.input_tokens=="number"&&typeof o.output_tokens=="number"?qo(o):null}catch{return null}}function Xc(e,t){
|
|
657
|
+
if(!e.endsWith("/responses"))return false;try{let n=JSON.parse(typeof t=="string"?t:t.toString("utf8"));return n!==null&&typeof n=="object"&&n.status==="failed"}catch{return false}}function Zc(e){let t=n=>{let o=n!==
|
|
658
|
+
null&&typeof n=="object"?n.refusal:void 0;return typeof o=="string"&&o!==""};return Array.isArray(e)&&e.some(n=>{if(n===null||typeof n!="object")return false;let o=n;return Gi(o.finish_reason)||t(o.message)||
|
|
659
|
+
t(o.delta)})}function el(e,t){if(e!=="/v1/messages"&&!e.endsWith("/chat/completions")&&!e.endsWith("/responses"))return false;try{let n=JSON.parse(typeof t=="string"?t:t.toString("utf8"));return n===null||
|
|
660
|
+
typeof n!="object"?!1:e==="/v1/messages"?n.stop_reason==="refusal":e.endsWith("/chat/completions")?Zc(n.choices):es(n.output)}catch{return false}}var Zi=1200,In=class{t="";sumar(t){typeof t=="string"&&this.
|
|
661
|
+
t.length<Zi&&(this.t=(this.t+t).slice(0,Zi));}lleno(){return this.t.length>=Zi}valor(){return this.t}};function tl(e,t){try{let n=JSON.parse(typeof t=="string"?t:t.toString("utf8"));if(n===null||typeof n!=
|
|
662
|
+
"object")return "";let o=(r,i,s)=>Array.isArray(r)?r.filter(a=>a!==null&&typeof a=="object"&&a.type===i).map(a=>a[s]).filter(a=>typeof a=="string").join(""):"";if(e==="/v1/messages")return o(n.content,
|
|
663
|
+
"text","text");if(e.endsWith("/chat/completions")){let i=(Array.isArray(n.choices)?n.choices[0]:void 0)?.message?.content;return typeof i=="string"?i:o(i,"text","text")}return e.endsWith("/responses")&&
|
|
664
|
+
Array.isArray(n.output)?n.output.map(r=>r!==null&&typeof r=="object"?o(r.content,"output_text","text"):"").join(""):""}catch{return ""}}function nl(e){return Hi(e)!==null}function ns(e,t){if(e!=="/v1/m\
|
|
665
|
+
essages")return false;try{let n=JSON.parse(typeof t=="string"?t:t.toString("utf8"));return n===null||typeof n!="object"?!1:No({stopReason:n.stop_reason,stopDetails:n.stop_details,bloques:Array.isArray(n.content)?
|
|
666
|
+
n.content.length:-1,outputTokens:n.usage?.output_tokens,iterations:n.usage?.iterations})}catch{return false}}function ol(e,t){let n=typeof t=="string"?t:t.toString("utf8"),o=i=>{if(i===null||typeof i!="ob\
|
|
667
|
+
ject")return;let s=i,a=c=>c!==null&&typeof c=="object"?c.service_tier:void 0,l;return e==="/v1/messages"?(l=a(s.usage),l===void 0&&s.message!==null&&typeof s.message=="object"&&(l=a(s.message.usage))):
|
|
668
|
+
e.endsWith("/chat/completions")?l=s.service_tier:e.endsWith("/responses")&&(l=s.service_tier,l===void 0&&s.response!==null&&typeof s.response=="object"&&(l=s.response.service_tier)),typeof l=="string"&&
|
|
669
|
+
l!==""?l:void 0};try{return o(JSON.parse(n))}catch{}let r;for(let i of n.split(`
|
|
670
|
+
`)){if(!i.startsWith("data:"))continue;let s=i.slice(5).trim();if(!(s===""||s==="[DONE]"))try{r=o(JSON.parse(s))??r;}catch{}}return r}function jt(e){return e==="/v1/messages"||e.endsWith("/chat/complet\
|
|
671
|
+
ions")||e.endsWith("/responses")||e.endsWith(":generateContent")||e.endsWith(":streamGenerateContent")}var gh=Buffer.from('"stream_options":{"include_usage":true},',"utf8");function rl(e,t){let n=(t??
|
|
672
|
+
"").trim().toLowerCase();if(n!==""&&n!=="identity")return {cuerpo:null,motivo:"comprimido"};let o;try{o=JSON.parse(e.toString("utf8").replace(/^\uFEFF/,""));}catch{return {cuerpo:null,motivo:"ilegible"}}
|
|
673
|
+
if(o===null||typeof o!="object"||Array.isArray(o))return {cuerpo:null,motivo:"ilegible"};let r=o;if(r.stream!==true)return {cuerpo:null,motivo:"no-stream"};if(r.stream_options?.include_usage===true)return {cuerpo:null,
|
|
674
|
+
motivo:"ya-lo-pide"};if(r.stream_options!==void 0)return {cuerpo:null,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&&
|
|
675
|
+
e[i+2]===191){i+=3;continue}break}return e[i]!==123?{cuerpo:null,motivo:"ilegible"}:{cuerpo:Buffer.concat([e.subarray(0,i+1),gh,e.subarray(i+1)]),motivo:"inyectado"}}function il(e,t){let n=ln(e,t);if(n===
|
|
676
|
+
null||typeof n!="object")return null;let o=n;return o.stream!==true?null:o.stream_options?.include_usage===true}function os(e,t,n){if((t??"").split(",").some(o=>o.trim().startsWith("oauth-"))||e.startsWith(
|
|
677
|
+
"/backend-api/"))return true;try{let o=new URL(n).hostname.toLowerCase();return o==="chatgpt.com"||o.endsWith(".chatgpt.com")}catch{return false}}function sl(e,t,n,o,r,i,s,a,l,c,d){return ll(e,t,n,false,o,r,i,s,
|
|
678
|
+
a,l,c===true,d??null)}function bh(e){if(e===null||typeof e!="object"||Array.isArray(e))return [];let t=e,n=r=>typeof r=="string"?[r]:Array.isArray(r)?r.filter(i=>i!==null&&typeof i=="object").filter(i=>i.
|
|
679
|
+
type==="text"||i.type==="input_text").map(i=>i.text).filter(i=>typeof i=="string"):[],o=r=>Array.isArray(r)?r.filter(i=>i!==null&&typeof i=="object").filter(i=>i.role==="user").flatMap(i=>n(i.content)):
|
|
680
|
+
[];return [...o(t.messages),...typeof t.input=="string"?[t.input]:o(t.input)]}function vh(e){return Xi(bh(e))}var yh=new Set(["auto","default","priority","standard_only"]);function kh(e){if(e==null)return 1;
|
|
681
|
+
if(typeof e!="string")return null;if(yh.has(e))return 1;let t=Mo(e);return t!==null&&t.conDescuento&&t.factor!==null?t.factor:null}function wh(e){if(e===void 0)return 1;if(e==="scale")return null;let t=Mo(
|
|
682
|
+
e);return t!==null&&t.factor!==null?t.factor:null}function al(e,t,n,o,r){if(!n||!n.conContador)return {ok:false,reason:"no-primary-record"};if(n.suscripcion||r.suscripcion)return {ok:false,reason:"subscriptio\
|
|
683
|
+
n"};if(!n.proveedorOficial)return {ok:false,reason:"unofficial-upstream"};if(!n.intacta)return {ok:false,reason:"layer-changed-request"};if(n.fallida)return {ok:false,reason:"primary-failed"};if(n.negativa===true)return {
|
|
684
|
+
ok:false,reason:"primary-refused"};if(n.negativaEnTexto===true)return {ok:false,reason:"primary-text-refusal"};if(vh(o)!==null)return {ok:false,reason:"sensitive-topic"};if(!r.entregada)return {ok:false,reason:"client\
|
|
685
|
+
-disconnected"};let i=o!==null&&typeof o=="object"&&!Array.isArray(o)?o:{},s=kh(i.service_tier),a=wh(r.tierServido);if(s===null||a===null)return {ok:false,reason:"service-tier"};let l=Math.min(s,a),c=Qt(e,
|
|
686
|
+
t.instante),d=c?.cachedInputPer1k;if(!c||typeof d!="number"||!Number.isFinite(d)||!(d>0)||!Number.isFinite(c.inputPer1k)||d>c.inputPer1k||!Number.isFinite(c.outputPer1k)||c.outputPer1k<0)return {ok:false,
|
|
687
|
+
reason:"no-cached-price"};let u=t.tokens,f=u.entrada+u.cacheLeida+u.cacheEscrita,m=v=>Number.isInteger(v)&&v>=0;if(!m(u.entrada)||!m(u.cacheLeida)||!m(u.cacheEscrita)||!m(u.salida)||!(f>0))return {ok:false,
|
|
688
|
+
reason:"no-credit"};let h=i.temperature===0&&yi(e)===void 0;return {ok:true,credit:{requestId:n.requestId,at:n.at,inputTokens:f,outputTokens:u.salida,creditedInputTokens:f,creditedOutputTokens:h?Math.floor(
|
|
689
|
+
.95*u.salida):0,cachedInputPer1k:d,outputPer1k:c.outputPer1k,tierFactor:l}}}function rs(e){return e.tierFactor*(e.creditedInputTokens/1e3*e.cachedInputPer1k+e.creditedOutputTokens/1e3*e.outputPer1k)}function cl(e,t,n,o,r,i){
|
|
690
|
+
let s=r?rs(r):0;return i===true||!r||!(s>0)||!Number.isFinite(s)?ll(e,t,n,true,o,void 0,void 0,void 0,false,false,i===true):{requestId:e,model:t,...o&&(o.sessionId||o.agentId)?{attribution:o}:{},calls:{avoidedLlm:1,
|
|
691
|
+
actualLlm:0},tokens:{baselineInput:r.creditedInputTokens,actualInput:0,eliminatedInput:0,compressedInput:0,baselineOutput:r.creditedOutputTokens,actualOutput:0,providerCachedInput:0},cache:{result:"si\
|
|
692
|
+
ngleflight",reference:r},cost:{baselineEstimate:s,actual:0,netSavingsRatio:1,netSavingsUsd:s,basis:"reference"}}}function is(e,t,n,o,r){return {requestId:e,model:t,...r&&(r.sessionId||r.agentId)?{attribution:r}:
|
|
693
|
+
{},calls:{avoidedLlm:0,actualLlm:0},tokens:{baselineInput:0,actualInput:0,eliminatedInput:0,compressedInput:0,baselineOutput:0,actualOutput:0,providerCachedInput:0},cache:{result:"miss"},cost:{baselineEstimate:n,
|
|
694
|
+
actual:o,netSavingsRatio:n>0?Math.max(-100,Math.min(1,(n-o)/n)):0,netSavingsUsd:n-o,basis:"shadow"}}}function xh(e,t){let n=je(e.solicitado,t.instante);return n===void 0?0:Math.max(0,Kc(n,t.tokens,e.solicitado)-
|
|
695
|
+
t.costeUsd)}function ll(e,t,n,o,r,i,s,a,l=false,c=false,d=false,u=null){d&&(n={...n,costeUsd:0});let f=n.tokens.entrada+n.tokens.cacheLeida+n.tokens.cacheEscrita,h=!o&&!l&&!c&&!d,v=n.tokens.cacheEscrita-n.tokens.
|
|
696
|
+
cacheEscrita1h,g=h&&u?Math.max(0,Math.min(u.perdidos,n.tokens.cacheEscrita)):0,k=h&&s&&s.rebajadas>0&&s.yaEran5m===0&&!s.herramientaDeServidor&&v-g>0?(v-g)/1e3*n.precio.inputPer1k*(2-1.25):0,S=n.tokens.
|
|
697
|
+
cacheEscrita>0?(Math.max(0,v)*1.25+n.tokens.cacheEscrita1h*2)/n.tokens.cacheEscrita:2,w=Math.min(n.costeUsd,Vo({perdidos:g,inputPer1k:n.precio.inputPer1k,cachedInputPer1k:n.precio.cachedInputPer1k,primaEscritura:S})),
|
|
698
|
+
I=h&&a?xh(a,n):0,D=Math.max(0,n.costeUsd+k+I-w),P=D-n.costeUsd,O=o||c||d?0:ph(n.precio,i),j=h?xi(t,n.precio,{leidos:n.tokens.cacheLeida,escritos:n.tokens.cacheEscrita,escritos1h:n.tokens.cacheEscrita1h}):void 0;return {requestId:e,model:t,...r&&(r.sessionId||r.agentId)?{attribution:r}:{},calls:o?{avoidedLlm:1,actualLlm:0}:{avoidedLlm:0,actualLlm:1},tokens:{baselineInput:f,actualInput:o?
|
|
699
|
+
0:f,eliminatedInput:o?0:i?.tokensLimpiados??0,compressedInput:0,baselineOutput:n.tokens.salida,actualOutput:o?0:n.tokens.salida,providerCachedInput:o?0:n.tokens.cacheLeida},cache:{result:o?"singleflig\
|
|
700
|
+
ht":"miss"},...j?{nativeSavings:j}:{},cost:o?{baselineEstimate:n.costeUsd,actual:0,netSavingsRatio:d?0:1,netSavingsUsd:n.costeUsd,basis:"estimated"}:{baselineEstimate:D,actual:n.costeUsd,netSavingsRatio:D>
|
|
701
|
+
0?Math.max(-100,Math.min(1,P/D)):0,netSavingsUsd:D-n.costeUsd,basis:"measured",...O>0?{eliminatedInputFloorCost:O}:{}}}}var Sh=1024,Dn=120,Eh=8,_h=256*1024,Ch=/error|exception|traceback|warn|fatal|fail|panic|assert|denied|refused|timeout|\bat\s+\S+:\d+/i,pl=/^\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)/;
|
|
702
|
+
function Th(e){return Buffer.byteLength(typeof e=="string"?e:JSON.stringify(e??""))}function Rh(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t&&typeof t=="object"&&typeof t.text=="string"?
|
|
599
703
|
t.text:"").join(`
|
|
600
|
-
`):""}var
|
|
601
|
-
`),n=Math.max(1,t.length),
|
|
602
|
-
test(a)||/\b(INFO|DEBUG|TRACE|WARN|ERROR)\b/.test(a))&&(i+=1);}return
|
|
704
|
+
`):""}var Ah=/^\s*\d+[\t→]/;function fl(e){return e.replace(Ah,"")}function Ih(e){if(!e)return "otro";let t=e.split(`
|
|
705
|
+
`),n=Math.max(1,t.length),o=0,r=0,i=0;for(let s of t){let a=fl(s);(/^[+-](?![+-])/.test(a)||a.startsWith("@@")||a.startsWith("diff --git"))&&(o+=1),pl.test(a)&&(r+=1),(/^\s*(\d{4}-\d{2}-\d{2}|\[\d|\d{2}:\d{2}:\d{2})/.
|
|
706
|
+
test(a)||/\b(INFO|DEBUG|TRACE|WARN|ERROR)\b/.test(a))&&(i+=1);}return o/n>.25?"diff":i/n>.3?"log":r/n>.08?"codigo":"otro"}function Dh(e,t){if(t==="diff"||t==="otro")return Buffer.byteLength(e);let n=e.
|
|
603
707
|
split(`
|
|
604
|
-
`),
|
|
605
|
-
n[i])+1;return Math.min(
|
|
606
|
-
n:${JSON.stringify(e??"")}`;let t=e;return t.type==="text"&&typeof t.text=="string"&&Object.keys(t).every(n=>n==="type"||n==="text"||n==="cache_control")?`text:${t.text}`:`json:${JSON.stringify(t,
|
|
607
|
-
function
|
|
608
|
-
t.ttl==="1h"?"1h":"5m"}function
|
|
609
|
-
let a=
|
|
610
|
-
n("tools",
|
|
611
|
-
"object"){n("?:invalido",
|
|
612
|
-
:${s?.type??"?"}`,s);}return t}function
|
|
613
|
-
return n}function
|
|
614
|
-
f))return {clave:u.clave,bytes:u.bytes};let m=
|
|
615
|
-
|
|
616
|
-
var
|
|
617
|
-
|
|
618
|
-
t),this.entradas.set(t,{expira:n+
|
|
619
|
-
value;if(n===void 0)break;this.entradas.delete(n);}}};function
|
|
620
|
-
"|").update(t[
|
|
621
|
-
t");s&&i===
|
|
622
|
-
5m";hayPrevio=false;atPrevio=0;acumulado=
|
|
623
|
-
previo=i,this.previoUltimoBp=-1,this.previoTtl="5m",this.hayPrevio=true,this.atPrevio=t.at,n;let s=i.map((
|
|
624
|
-
|
|
625
|
-
n.tokensEntrada+=d[
|
|
626
|
-
n.tokensEntrada,this.acumulado.entradaUsd+=n.entradaUsd,this.acumulado.totalUsd+=n.totalUsd,n}let
|
|
627
|
-
|
|
628
|
-
[]:this.previo.slice(
|
|
629
|
-
|
|
630
|
-
|
|
708
|
+
`),o=new Set;for(let i=0;i<n.length;i++){let s=fl(n[i]);(t==="log"?Ch.test(s):pl.test(s))&&(o.add(i),t==="log"&&(i>0&&o.add(i-1),i<n.length-1&&o.add(i+1)));}let r=Dn;for(let i of o)r+=Buffer.byteLength(
|
|
709
|
+
n[i])+1;return Math.min(r,Buffer.byteLength(e))}var Ph=(e,t)=>e==="cache_control"?void 0:t;function Oh(e){if(typeof e=="string")return `text:${e}`;if(!e||typeof e!="object"||Array.isArray(e))return `jso\
|
|
710
|
+
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,Ph)}`}
|
|
711
|
+
function Lh(e){return createHash("sha256").update(Oh(e)).digest("hex").slice(0,16)}function Mh(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.cache_control;return !t||typeof t!="object"?null:
|
|
712
|
+
t.ttl==="1h"?"1h":"5m"}function ml(e){let t=[],n=(o,r)=>{let i=Th(r),s={clave:Lh(r),tipo:o,marca:Mh(r),bytes:i,bytesV1:i,clase:"otro",esError:false};if(o.endsWith(":tool_result")&&r&&typeof r=="object"){
|
|
713
|
+
let a=r;s.esError=a.is_error===true;let l=Rh(a.content);s.clase=Ih(l);let c=i-Buffer.byteLength(l);s.bytesV1=Math.min(i,Math.max(0,c)+Dh(l,s.clase));}t.push(s);};if(Array.isArray(e.tools))for(let o of e.tools)
|
|
714
|
+
n("tools",o);if(Array.isArray(e.system))for(let o of e.system)n("system",o);else (e.system??void 0)!==void 0&&n("system",e.system);for(let o of Array.isArray(e.messages)?e.messages:[]){if(!o||typeof o!=
|
|
715
|
+
"object"){n("?:invalido",o);continue}let r=o,i=typeof r.role=="string"?r.role:"?";if(typeof r.content=="string")n(`${i}:text`,r.content);else if(Array.isArray(r.content))for(let s of r.content)n(`${i}\
|
|
716
|
+
:${s?.type??"?"}`,s);}return t}function $h(){return {nacimiento:new Map,turno:0,elididosV2m:new Set}}function Nh(e,t){let n=e.turno++;for(let o of t)e.nacimiento.has(o.clave)||e.nacimiento.set(o.clave,n);
|
|
717
|
+
return n}function hl(e,t,n,o,r=_h){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>=Sh&&f!==i;return t.map((u,f)=>{if(!s(u,
|
|
718
|
+
f))return {clave:u.clave,bytes:u.bytes};let m=o-(n.nacimiento.get(u.clave)??o);return m>=2&&m*u.bytes/1024>=Eh?{clave:`${u.clave}:e`,bytes:Dn}:{clave:u.clave,bytes:u.bytes}});}function jh(e,t){let n=je(e,t);return n?{inputPer1k:n.inputPer1k,lecturaPer1k:n.cachedInputPer1k??n.inputPer1k,escrituraPer1k:n.inputPer1k*
|
|
719
|
+
Se(e),escritura1hPer1k:n.inputPer1k*Yt(e)}:null}function ul(){return {lecturaUsd:0,escrituraUsd:0,entradaUsd:0,totalUsd:0,tokensLeidos:0,tokensEscritos:0,tokensEntrada:0,tokensInvalidados:0,invalidacionUsd:0}}
|
|
720
|
+
var as={"1h":36e5,"5m":3e5},Bh=20,Uh=6e3,Fh=2e4,un=class{constructor(t=Fh){this.tope=t;}tope;entradas=new Map;get size(){return this.entradas.size}viva(t,n){let o=this.entradas.get(t);return o&&n<=o.expira?
|
|
721
|
+
o:null}escribir(t,n,o){this.entradas.delete(t),this.entradas.set(t,{expira:n+as[o],ttl:o}),this.entradas.size>this.tope&&this.podar(n);}refrescar(t,n){let o=this.entradas.get(t);o&&(this.entradas.delete(
|
|
722
|
+
t),this.entradas.set(t,{expira:n+as[o.ttl],ttl:o.ttl}));}podar(t){for(let[n,o]of this.entradas)t>o.expira&&this.entradas.delete(n);for(;this.entradas.size>this.tope;){let n=this.entradas.keys().next().
|
|
723
|
+
value;if(n===void 0)break;this.entradas.delete(n);}}};function zh(e,t){let n=new Array(t.length),o=createHash("sha256").update(`model:${e}`).digest("hex");for(let r=0;r<t.length;r++)o=createHash("sha256").update(o).update(
|
|
724
|
+
"|").update(t[r]).digest("hex").slice(0,32),n[r]=o;return n}function Vh(e){let t=new Array(e.length),n=-1,o="";for(let r=0;r<e.length;r++){let i=e[r],s=i.endsWith(":tool_use")||i.endsWith(":tool_resul\
|
|
725
|
+
t");s&&i===o||(n+=1),o=s?i:"",t[r]=n;}return t}function dl(e,t){return e.endsWith(":image")?Math.min(t,Uh):t}var Pn=class{constructor(t,n){this.transformar=t;this.cache=n??new un;}transformar;estado=$h();cache;previo=[];previoUltimoBp=-1;previoTtl="\
|
|
726
|
+
5m";hayPrevio=false;atPrevio=0;acumulado=ul();paso(t){let n=ul(),o=Nh(this.estado,t.bloques),r=jh(t.model,t.at),i=this.transformar(t.bloques,this.estado,o);if(!r||t.entradaReal<=0||i.length===0)return this.
|
|
727
|
+
previo=i,this.previoUltimoBp=-1,this.previoTtl="5m",this.hayPrevio=true,this.atPrevio=t.at,n;let s=i.map((w,I)=>t.bloques[I]?.tipo??""),a=i.map((w,I)=>t.bloques[I]?.marca??null),l=t.bloques.reduce((w,I)=>w+
|
|
728
|
+
dl(I.tipo,I.bytes),0),c=l>0?t.entradaReal/l:0,d=i.map((w,I)=>dl(s[I],w.bytes)*c),u=zh(t.model,i.map(w=>w.clave)),f=Vh(s),m=a.map((w,I)=>w?I:-1).filter(w=>w>=0);if(m.length===0){for(let w=0;w<i.length;w++)
|
|
729
|
+
n.tokensEntrada+=d[w],n.entradaUsd+=d[w]/1e3*r.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+=
|
|
730
|
+
n.tokensEntrada,this.acumulado.entradaUsd+=n.entradaUsd,this.acumulado.totalUsd+=n.totalUsd,n}let h=-1;for(let w of m){let I=f[w]-(Bh-1);for(let D=w;D>=0&&f[D]>=I;D--)if(this.cache.viva(u[D],t.at)){D>
|
|
731
|
+
h&&(h=D);break}}for(let w=0;w<=h;w++)this.cache.refrescar(u[w],t.at);let v=m[m.length-1];for(let w of m)w>h&&this.cache.escribir(u[w],t.at,a[w]);let g=0,k=this.hayPrevio&&t.at-this.atPrevio>as[this.previoTtl]?
|
|
732
|
+
[]:this.previo.slice(h+1,this.previoUltimoBp+1),S=0;for(let w=0;w<i.length;w++){let I=i[w],D=d[w];if(w<=h){n.tokensLeidos+=D,n.lecturaUsd+=D/1e3*r.lecturaPer1k;continue}if(w>v){n.tokensEntrada+=D,n.entradaUsd+=
|
|
733
|
+
D/1e3*r.inputPer1k;continue}for(;m[g]<w;)g+=1;let P=a[m[g]]==="1h"?r.escritura1hPer1k:r.escrituraPer1k;n.tokensEscritos+=D,n.escrituraUsd+=D/1e3*P;let O=S;for(;O<k.length&&k[O].clave!==I.clave;)O+=1;O<
|
|
734
|
+
k.length&&(k[O].bytes===I.bytes&&(n.tokensInvalidados+=D,n.invalidacionUsd+=D/1e3*(P-r.lecturaPer1k)),S=O+1);}return this.previo=i,this.previoUltimoBp=v,this.previoTtl=a[v]??"5m",this.hayPrevio=true,this.
|
|
631
735
|
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.
|
|
632
736
|
totalUsd+=n.totalUsd,this.acumulado.tokensLeidos+=n.tokensLeidos,this.acumulado.tokensEscritos+=n.tokensEscritos,this.acumulado.tokensEntrada+=n.tokensEntrada,this.acumulado.tokensInvalidados+=n.tokensInvalidados,
|
|
633
|
-
this.acumulado.invalidacionUsd+=n.invalidacionUsd,n}};function
|
|
634
|
-
0),
|
|
635
|
-
0)>0};if(
|
|
737
|
+
this.acumulado.invalidacionUsd+=n.invalidacionUsd,n}};function gl(e){return e.map(t=>({clave:t.clave,bytes:t.bytes}))}var Hh=64,Go=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??
|
|
738
|
+
0),o=(t.uso.input_tokens??0)+(t.uso.cache_read_input_tokens??0)+n;if(o<=0)return null;let r={bloques:ml(t.cuerpo),at:t.at,model:t.model,entradaReal:o,escritura1h:(t.uso.cache_creation?.ephemeral_1h_input_tokens??
|
|
739
|
+
0)>0};if(r.bloques.length===0)return null;let i=this.cadenaPara(this.clave(t),t.model),s=i.base.paso(r),a=i.v0.paso(r);return s.totalUsd<=0&&a.totalUsd<=0?null:{baselineUsd:s.totalUsd,politicaUsd:a.totalUsd}}clave(t){
|
|
636
740
|
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(
|
|
637
|
-
"hex").slice(0,16)}\xB7${t.model}`}cachesDe(t){let n=this.cachesPorModelo.get(t);return n||(n={base:new
|
|
638
|
-
let
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
this.ttlMs=t.ttlMs??3e5,this.fetchImpl=t.fetchImpl??fetch,this.log=t.log??(()=>{}),this.refrescar();}tiene(t){return this.refrescarSiVencio(),this.features.
|
|
642
|
-
this.razonDeBloqueo}refrescar(){return this.enVuelo?this.enVuelo:(this.enVuelo=this.pedir().finally(()=>{this.enVuelo=null;}),this.enVuelo)}refrescarSiVencio(){
|
|
643
|
-
null&&this.refrescar();}async pedir(){try{let t=await this.fetchImpl(this.url,{method:"GET",headers:{authorization:`Bearer ${this.clave}`},signal:AbortSignal.
|
|
644
|
-
"entitlements HTTP 401",
|
|
645
|
-
"entitlements response has an unexpected shape");return}this.features=new Set(n.features),this.razonDeBloqueo=typeof n.reason=="string"&&n.reason.trim()!==""?
|
|
646
|
-
"number"&&n.refreshAfterSeconds>0?Math.min(n.refreshAfterSeconds*1e3,this.ttlMs):this.ttlMs;this.validoHasta=Date.now()+
|
|
647
|
-
this.validoHasta=Date.now()+Math.min(6e4,this.ttlMs),this.avisado||(this.avisado=true,this.log(n??`[gateway] entitlements unavailable (${t}) \u2014
|
|
648
|
-
|
|
649
|
-
VL";function
|
|
650
|
-
isFinite(e);function
|
|
651
|
-
t.grace_days>=0&&Array.isArray(t.features)&&t.features.every(n=>typeof n=="string")}function
|
|
652
|
-
ty"};if(
|
|
653
|
-
if(i!==
|
|
654
|
-
payload is not valid JSON"}}return
|
|
655
|
-
rification error: ${
|
|
656
|
-
t?`${n.slice(0,t)}...`:n}function
|
|
657
|
-
"string"?
|
|
658
|
-
|
|
659
|
-
addEventListener("abort",s,{once:true}));let a=
|
|
660
|
-
fetch,
|
|
661
|
-
n"};if(
|
|
662
|
-
unexpected response (no license token)"}}let u=d?.token;if(typeof u!="string"||u.trim()==="")return {kind:"unreachable",cause:"unexpected response (no license token)"};let f=
|
|
663
|
-
ok?{kind:"token",license:f.license}:{kind:"not-verifying",reason:
|
|
664
|
-
e*1e3).toISOString().slice(0,10)}catch{return "an unknown date"}}var
|
|
665
|
-
icense of the service key's organization is used. Unset BIVELIO_LICENSE_KEY or replace it with this organization's license key.",
|
|
666
|
-
fy against this build's BiVelio key (${e}); starting with BIVELIO_LICENSE_KEY. Update @bivelio/savings-layer (npm i -g @bivelio/savings-layer).`;function
|
|
741
|
+
"hex").slice(0,16)}\xB7${t.model}`}cachesDe(t){let n=this.cachesPorModelo.get(t);return n||(n={base:new un,v0:new un},this.cachesPorModelo.set(t,n)),n}cadenaPara(t,n){let o=this.cadenas.get(t);if(!o){
|
|
742
|
+
let r=this.cachesDe(n);if(o={base:new Pn(i=>gl(i),r.base),v0:new Pn((i,s,a)=>hl("v0",i,s,a),r.v0),ultimoUso:0},this.cadenas.set(t,o),this.cadenas.size>Hh){let i=null,s=1/0;for(let[a,l]of this.cadenas)
|
|
743
|
+
l.ultimoUso<s&&(s=l.ultimoUso,i=a);i!==null&&this.cadenas.delete(i);}}return o.ultimoUso=Date.now(),o}};var Wo=class{tiene(){return true}blockReason(){return null}},Gh="[gateway] entitlements: BIVELIO_SERVICE_KEY is no longer recognised (HTTP 401): savings features disabled and usage is not being reported;\
|
|
744
|
+
create a new key at https://savings.bivelio.com/dashboard/install and relaunch",Jo=class{url;clave;ttlMs;fetchImpl;log;features=new Set;razonDeBloqueo=null;validoHasta=0;enVuelo=null;avisado=false;constructor(t){
|
|
745
|
+
this.url=t.url,this.clave=t.serviceAccountKey,this.ttlMs=t.ttlMs??3e5,this.fetchImpl=t.fetchImpl??fetch,this.log=t.log??(()=>{}),this.refrescar();}tiene(t){return this.refrescarSiVencio(),this.features.
|
|
746
|
+
has(t)}blockReason(){return this.refrescarSiVencio(),this.razonDeBloqueo}refrescar(){return this.enVuelo?this.enVuelo:(this.enVuelo=this.pedir().finally(()=>{this.enVuelo=null;}),this.enVuelo)}refrescarSiVencio(){
|
|
747
|
+
Date.now()>this.validoHasta&&this.enVuelo===null&&this.refrescar();}async pedir(){try{let t=await this.fetchImpl(this.url,{method:"GET",headers:{authorization:`Bearer ${this.clave}`},signal:AbortSignal.
|
|
748
|
+
timeout(1e4)});if(t.status===401){this.cerrar("entitlements HTTP 401",Gh);return}if(!t.ok){this.cerrar(`entitlements HTTP ${t.status}`);return}let n=await t.json();if(!Array.isArray(n.features)||!n.features.
|
|
749
|
+
every(r=>typeof r=="string")){this.cerrar("entitlements response has an unexpected shape");return}this.features=new Set(n.features),this.razonDeBloqueo=typeof n.reason=="string"&&n.reason.trim()!==""?
|
|
750
|
+
n.reason.trim():null;let o=typeof n.refreshAfterSeconds=="number"&&n.refreshAfterSeconds>0?Math.min(n.refreshAfterSeconds*1e3,this.ttlMs):this.ttlMs;this.validoHasta=Date.now()+o,this.avisado=!1;}catch(t){
|
|
751
|
+
this.cerrar(String(t));}}cerrar(t,n){this.features=new Set,this.validoHasta=Date.now()+Math.min(6e4,this.ttlMs),this.avisado||(this.avisado=true,this.log(n??`[gateway] entitlements unavailable (${t}) \u2014 s\
|
|
752
|
+
avings features disabled (fail-closed); traffic keeps flowing`));}};var us="https://savings.bivelio.com",ke="https://savings.bivelio.com/dashboard/account",St="https://savings.bivelio.com/dashboard/install",Wh=1e4,Jh=3e3,bl=6e4,Kh=36e5,Yh=7*86400,Qh=3e4,Xh=86400,Zh="B\
|
|
753
|
+
VL";function ds(e){return Lt}function eg(e){return hi(e)?Object.keys(e.keys??{}).length===0:e.trim()===""}var cs=e=>typeof e=="string"&&e.trim()!=="",Ko=e=>typeof e=="number"&&Number.
|
|
754
|
+
isFinite(e);function tg(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let t=e;return cs(t.jti)&&cs(t.org_id)&&cs(t.plan)&&Ko(t.seats)&&Ko(t.issued_at)&&Ko(t.expires_at)&&Ko(t.grace_days)&&
|
|
755
|
+
t.grace_days>=0&&Array.isArray(t.features)&&t.features.every(n=>typeof n=="string")}function Mn(e,t){try{let n=tn(typeof e=="string"?e:""),o=Cn(n);if(o==="empty")return {ok:!1,shape:"empty",reason:"emp\
|
|
756
|
+
ty"};if(o==="malformed")return {ok:!1,shape:"malformed",reason:"malformed"};let r=Tn(n,t);if(!r.ok||!r.payloadBytes)return {ok:!1,shape:"token",reason:Ln(r.reason??"bad signature")};let i=r.header?.typ;
|
|
757
|
+
if(i!==Zh)return {ok:!1,shape:"token",reason:`not a license token (typ ${Ln(String(i??"none"))})`};let s;try{s=JSON.parse(new TextDecoder().decode(r.payloadBytes));}catch{return {ok:!1,shape:"token",reason:"\
|
|
758
|
+
payload is not valid JSON"}}return tg(s)?{ok:!0,license:{token:n,payload:Do(s)}}:{ok:!1,shape:"token",reason:"license payload has the wrong field types"}}catch(n){return {ok:false,shape:"token",reason:`ve\
|
|
759
|
+
rification error: ${Ln(String(n))}`}}}function Bt(e,t,n){return Po(e,Math.floor(t/1e3),n)}var Ut=e=>e==="active"||e==="grace";function Ln(e,t=200){let n=e.replace(/[^\x20-\x7E]/g,"?");return n.length>
|
|
760
|
+
t?`${n.slice(0,t)}...`:n}function ng(e){return `${Number((e/1e3).toFixed(3))} s`}function og(e){let t=e,n=typeof t?.message=="string"&&t.message!==""?t.message:String(e),o=t?.cause,r=o&&typeof o.code==
|
|
761
|
+
"string"?o.code:o&&typeof o.message=="string"?o.message:void 0;return r?`${n} (${r})`:n}async function vl(e){let t=`${e.licenseServerUrl.replace(/\/+$/,"")}/api/license/current`,n=l=>e.serviceAccountKey?
|
|
762
|
+
l.split(e.serviceAccountKey).join("[service key]"):l,o=new AbortController,r=false,i=setTimeout(()=>{r=true,o.abort();},e.timeoutMs);i.unref?.();let s=()=>o.abort();e.signal&&(e.signal.aborted?o.abort():e.signal.
|
|
763
|
+
addEventListener("abort",s,{once:true}));let a=l=>r?{kind:"unreachable",cause:`timed out after ${ng(e.timeoutMs)}`}:{kind:"unreachable",cause:Ln(n(`network error: ${og(l)}`))};try{let l=e.fetchImpl??globalThis.
|
|
764
|
+
fetch,c;try{c=await l(t,{method:"GET",headers:{authorization:`Bearer ${e.serviceAccountKey}`,accept:"application/json"},signal:o.signal});}catch(m){return a(m)}if(c.status===401)return {kind:"key-unknow\
|
|
765
|
+
n"};if(c.status===404)return {kind:"no-license"};if(!c.ok)return {kind:"unreachable",cause:`HTTP ${c.status}`};let d;try{d=await c.json();}catch(m){return r||o.signal.aborted?a(m):{kind:"unreachable",cause:"\
|
|
766
|
+
unexpected response (no license token)"}}let u=d?.token;if(typeof u!="string"||u.trim()==="")return {kind:"unreachable",cause:"unexpected response (no license token)"};let f=Mn(u,e.publicKey);return f.
|
|
767
|
+
ok?{kind:"token",license:f.license}:{kind:"not-verifying",reason:Ln(f.reason)}}catch(l){return a(l)}finally{clearTimeout(i),e.signal?.removeEventListener("abort",s);}}function ze(e){try{return new Date(
|
|
768
|
+
e*1e3).toISOString().slice(0,10)}catch{return "an unknown date"}}var $n=(e,t)=>e+t*Xh,rg="WARNING: BIVELIO_LICENSE_KEY belongs to a different organization than BIVELIO_SERVICE_KEY and is ignored; the l\
|
|
769
|
+
icense of the service key's organization is used. Unset BIVELIO_LICENSE_KEY or replace it with this organization's license key.",ig=e=>`WARNING: the license served by savings.bivelio.com does not veri\
|
|
770
|
+
fy against this build's BiVelio key (${e}); starting with BIVELIO_LICENSE_KEY. Update @bivelio/savings-layer (npm i -g @bivelio/savings-layer).`;function sg(e,t={}){switch(e){case "no-public-key":return "\
|
|
667
771
|
this build has no embedded BiVelio verification key (it is running from source): install the published package (npm i -g @bivelio/savings-layer) or run pnpm build first.";case "service-key-missing":return `\
|
|
668
|
-
BIVELIO_SERVICE_KEY is not set. The gateway needs two things and does not start without them: an active BiVelio subscription (${ke}) and its service key (bvk_..., created at ${
|
|
772
|
+
BIVELIO_SERVICE_KEY is not set. The gateway needs two things and does not start without them: an active BiVelio subscription (${ke}) and its service key (bvk_..., created at ${St}, step 2). Export the\
|
|
669
773
|
key and relaunch: the license is collected with it automatically.`;case "service-key-malformed":return "BIVELIO_SERVICE_KEY does not look like a service key (service keys start with bvk_)."+(t.keyLooksLikeLicense?
|
|
670
|
-
" It looks like a license key: that one goes in BIVELIO_LICENSE_KEY.":"")+` Create a service key at ${
|
|
671
|
-
is not recognised by savings.bivelio.com (HTTP 401): it was deleted or rotated, or it was copied incompletely. Create a new one at ${
|
|
672
|
-
r organization has no active BiVelio license, and the gateway does not start without one. Get the free Measure license (no card; shadow mode: it measures and applies no lever) at ${
|
|
673
|
-
t ${ke}, and relaunch; the license is collected automatically with your service key.`;case "license-expired":{let n=t.expiresAt??0;return `your BiVelio license expired on ${
|
|
674
|
-
nded on ${
|
|
774
|
+
" It looks like a license key: that one goes in BIVELIO_LICENSE_KEY.":"")+` Create a service key at ${St} (step 2), export it and relaunch.`;case "service-key-not-recognised":return `BIVELIO_SERVICE_KEY\
|
|
775
|
+
is not recognised by savings.bivelio.com (HTTP 401): it was deleted or rotated, or it was copied incompletely. Create a new one at ${St} (step 2), export it and relaunch.`;case "no-license":return `you\
|
|
776
|
+
r organization has no active BiVelio license, and the gateway does not start without one. Get the free Measure license (no card; shadow mode: it measures and applies no lever) at ${St}, or subscribe a\
|
|
777
|
+
t ${ke}, and relaunch; the license is collected automatically with your service key.`;case "license-expired":{let n=t.expiresAt??0;return `your BiVelio license expired on ${ze(n)} and its grace period e\
|
|
778
|
+
nded on ${ze($n(n,t.graceDays??0))}. Renew at ${ke} and relaunch.`+(t.cause?` (savings.bivelio.com could not be reached to look for a renewed license: ${t.cause})`:"")}case "license-invalid":{let n=t.reason??
|
|
675
779
|
"bad signature";return t.tokenSource==="savings.bivelio.com"?`the license served by savings.bivelio.com does not verify against this build's BiVelio key (${n}). Update @bivelio/savings-layer (npm i -g\
|
|
676
780
|
@bivelio/savings-layer); if it persists, write to support@bivelio.com.`:t.shape==="malformed"?`BIVELIO_LICENSE_KEY is not a license key: a license key has three dot-separated parts and several hundre\
|
|
677
|
-
d characters. Did you paste the bvk_ service key by mistake? That one goes in BIVELIO_SERVICE_KEY; the license key is the other value on ${
|
|
678
|
-
icense online by itself.`:`BIVELIO_LICENSE_KEY does not verify against this build's BiVelio key (${n}). Copy the WHOLE key again from ${
|
|
781
|
+
d characters. Did you paste the bvk_ service key by mistake? That one goes in BIVELIO_SERVICE_KEY; the license key is the other value on ${St}. Or unset BIVELIO_LICENSE_KEY: the gateway collects the l\
|
|
782
|
+
icense online by itself.`:`BIVELIO_LICENSE_KEY does not verify against this build's BiVelio key (${n}). Copy the WHOLE key again from ${St}, or unset BIVELIO_LICENSE_KEY to collect it online; if it pe\
|
|
679
783
|
rsists, update @bivelio/savings-layer or write to support@bivelio.com.`}case "unreachable":return `could not collect your license from savings.bivelio.com (${t.cause??"unknown cause"}). The gateway does\
|
|
680
|
-
not start without a verified license. Check your connection and relaunch. If savings.bivelio.com is down, export BIVELIO_LICENSE_KEY=<your license key> (from ${
|
|
681
|
-
his machine and used only when savings.bivelio.com cannot be reached, and it must be replaced by hand every billing period.`}}function
|
|
682
|
-
a=t==="online"?"collected with your service key and verified on this machine":
|
|
683
|
-
verified on this machine";if(n==="grace"){let
|
|
684
|
-
til ${s} (+${i} ${i===1?"day":"days"} grace), ${a}`}var
|
|
685
|
-
serviceAccountKey?.trim();if(!
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
784
|
+
not start without a verified license. Check your connection and relaunch. If savings.bivelio.com is down, export BIVELIO_LICENSE_KEY=<your license key> (from ${St}) as a fallback: it is verified on t\
|
|
785
|
+
his machine and used only when savings.bivelio.com cannot be reached, and it must be replaced by hand every billing period.`}}function ls(e,t,n,o){let r=e.plan.toUpperCase(),i=e.grace_days,s=ze(e.expires_at),
|
|
786
|
+
a=t==="online"?"collected with your service key and verified on this machine":o?`from BIVELIO_LICENSE_KEY, verified on this machine (savings.bivelio.com unreachable: ${o})`:"from BIVELIO_LICENSE_KEY, \
|
|
787
|
+
verified on this machine";if(n==="grace"){let l=ze($n(e.expires_at,i));return `license: ${r}, IN GRACE: expired on ${s}, keeps working until ${l}. Renew at ${ke} (${a})`}return `license: ${r}, active un\
|
|
788
|
+
til ${s} (+${i} ${i===1?"day":"days"} grace), ${a}`}var Fe=(e,t)=>({ok:false,code:e,message:sg(e,t)});async function yl(e){let t=e.now??Date.now,n=ds();if(eg(n))return Fe("no-public-key");let o=e.
|
|
789
|
+
serviceAccountKey?.trim();if(!o){if(e.licenseKey!==void 0){let l=Mn(e.licenseKey,n);if(l.ok){let c=Bt(l.license.payload,t());return Ut(c)?{ok:true,license:l.license,source:"offline",status:c,line:ls(l.license.
|
|
790
|
+
payload,"offline",c),lineIsWarning:true,warnings:[]}:Fe("license-expired",{expiresAt:l.license.payload.expires_at,graceDays:l.license.payload.grace_days})}if(l.shape!=="empty")return Fe("license-invalid",
|
|
791
|
+
{tokenSource:"BIVELIO_LICENSE_KEY",shape:l.shape,reason:l.reason})}return {ok:true,license:null,source:"community",status:"active",line:"COMMUNITY MODE (open core): every local saving lever on, zero tele\
|
|
792
|
+
metry - no BiVelio keys set",lineIsWarning:false,warnings:[]}}if(!o.startsWith("bvk_"))return Fe("service-key-malformed",{keyLooksLikeLicense:Cn(tn(o))==="token"});let r=null;if(e.licenseKey!==void 0){let l=Mn(
|
|
793
|
+
e.licenseKey,n);if(l.ok)r=l.license;else if(l.shape!=="empty")return Fe("license-invalid",{tokenSource:"BIVELIO_LICENSE_KEY",shape:l.shape,reason:l.reason})}let i=r!==null&&Ut(Bt(r.payload,t())),s=await vl(
|
|
794
|
+
{licenseServerUrl:e.licenseServerUrl,serviceAccountKey:o,publicKey:n,timeoutMs:e.timeoutMs??(i?Jh:Wh),...e.fetchImpl?{fetchImpl:e.fetchImpl}:{}}),a=(l,c)=>{let d=Bt(r.payload,t());return Ut(d)?{ok:true,
|
|
795
|
+
license:r,source:"offline",status:d,line:ls(r.payload,"offline",d,l),lineIsWarning:true,warnings:c}:Fe("license-expired",{expiresAt:r.payload.expires_at,graceDays:r.payload.grace_days,...l?{cause:l}:{}})};
|
|
796
|
+
switch(s.kind){case "key-unknown":return Fe("service-key-not-recognised");case "no-license":return Fe("no-license");case "token":{let l=s.license,c=Bt(l.payload,t()),d=r&&r.payload.org_id!==l.payload.org_id?
|
|
797
|
+
[rg]:[];return Ut(c)?{ok:true,license:l,source:"online",status:c,line:ls(l.payload,"online",c),lineIsWarning:c==="grace",warnings:d}:Fe("license-expired",{expiresAt:l.payload.expires_at,graceDays:l.payload.
|
|
798
|
+
grace_days})}case "not-verifying":return i?a(void 0,[ig(s.reason)]):Fe("license-invalid",{tokenSource:"savings.bivelio.com",reason:s.reason});case "unreachable":return r?a(s.cause,[]):Fe("unreachable",{
|
|
799
|
+
cause:s.cause})}}var ag=new Set(["expired","revoked","no-license","blocked","invalid"]);function ps(e,t,n){let o=typeof t=="string"?t.trim():"";if(o!==""){let i="reported by savings.bivelio.com";return o===
|
|
800
|
+
"license-revoked"?{serve:false,state:"revoked",detail:i}:o==="license-expired"?{serve:false,state:"expired",detail:i}:o==="no-license"?{serve:false,state:"no-license",detail:i}:{serve:false,state:"blocked",detail:i}}
|
|
801
|
+
let r=e.status();return r==="active"||r==="grace"?{serve:true,state:r}:r==="expired"?{serve:false,state:"expired",detail:n?`grace period ended ${ze($n(n.expires_at,n.grace_days))}`:"grace period ended"}:r===
|
|
802
|
+
"revoked"?{serve:false,state:"revoked",detail:"license id revoked"}:{serve:false,state:"invalid",detail:"license no longer verifies"}}var On="requests already in flight were not interrupted";function cg(e){
|
|
803
|
+
switch(e){case "expired":return `bvsala gateway: the BiVelio license for this organization has expired. New requests are refused until it is renewed at ${ke}; ${On}.`;case "revoked":return `bvsala gateway\
|
|
804
|
+
: the BiVelio license for this organization is no longer active (revoked or cancelled). New requests are refused; ${On}. Check ${ke} or write to support@bivelio.com.`;case "no-license":return `bvsala ga\
|
|
805
|
+
teway: this organization has no active BiVelio license. New requests are refused until you subscribe at ${ke}; ${On}.`;case "blocked":return `bvsala gateway: savings.bivelio.com reports the BiVelio lice\
|
|
806
|
+
nse for this organization as not active. New requests are refused; ${On}. Check ${ke}.`;case "invalid":return `bvsala gateway: the license loaded by this gateway no longer verifies. New requests are ref\
|
|
807
|
+
used; ${On}. Relaunch the terminal; if it persists, write to support@bivelio.com.`}}function kl(e){return JSON.stringify({type:"error",error:{type:"license_error",status:e,message:cg(e)}})}var lg={expired:`\
|
|
808
|
+
Renew at ${ke}`,revoked:`Check ${ke} or write to support@bivelio.com`,"no-license":`Subscribe at ${ke}`,blocked:`Check ${ke}`,invalid:"Relaunch the terminal; if it persists, write to support@bivelio.c\
|
|
809
|
+
om"};function wl(e,t,n){if(!t.serve)return e===t.state?null:`[bvsala gateway] license ${t.state} (${t.detail}): new requests are refused with HTTP 402; requests in flight are not touched. ${lg[t.state]}`;
|
|
810
|
+
let o=ze(n.expires_at),r=ze($n(n.expires_at,n.grace_days));return e!==null&&ag.has(e)?t.state==="grace"?`[bvsala gateway] license in grace again (it expired on ${o} and keeps working until ${r}): serv\
|
|
811
|
+
ing new requests. Renew at ${ke}`:`[bvsala gateway] license ${t.state} again (expires ${o}): serving new requests`:t.state==="grace"&&e!=="grace"?`[bvsala gateway] license in grace: it expired on ${o}\
|
|
812
|
+
and keeps working until ${r}. Renew at ${ke}`:null}function fs(e,t,n,o){return {license:e,gate:Oo(e.token,t,{revocation:n,...o?{now:o}:{}})}}var Yo=class{constructor(t){this.o=t;}o;timer=null;enVuelo=false;parado=false;ctrl=null;avisados=new Set;ahora(){
|
|
813
|
+
return this.o.now?this.o.now():Date.now()}start(t={}){this.parado||this.timer!==null||(this.timer=setInterval(()=>{this.check();},this.o.intervalMs??Kh),this.timer.unref?.(),t.checkNow&&this.check({force:true}));}stop(){
|
|
707
814
|
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.
|
|
708
|
-
enVuelo||this.parado)return false;let n=this.o.current(),
|
|
709
|
-
force&&!i&&r
|
|
710
|
-
publicKey:this.o.publicKey,timeoutMs:this.o.timeoutMs??
|
|
711
|
-
switch(a.kind){case "token":{let
|
|
712
|
-
ahora(),d)),f=
|
|
713
|
-
`[bvsala gateway] license renewal: BIVELIO_SERVICE_KEY is no longer recognised (HTTP 401). This session keeps its current license until ${
|
|
714
|
-
se":return this.avisar("no-license",`[bvsala gateway] license renewal: savings.bivelio.com reports no active license for this organization (HTTP 404). This session keeps its current license until ${
|
|
815
|
+
enVuelo||this.parado)return false;let n=this.o.current(),o=Ut(Bt(n.payload,this.ahora(),this.o.revocation.snapshot())),r=n.payload.expires_at-Math.floor(this.ahora()/1e3),i=n.payload.plan==="measure";if(!t.
|
|
816
|
+
force&&!i&&o&&r>(this.o.leadSeconds??Yh))return false;this.enVuelo=true;let s=new AbortController;this.ctrl=s;try{let a=await vl({licenseServerUrl:this.o.licenseServerUrl,serviceAccountKey:this.o.serviceAccountKey,
|
|
817
|
+
publicKey:this.o.publicKey,timeoutMs:this.o.timeoutMs??Qh,signal:s.signal,...this.o.fetchImpl?{fetchImpl:this.o.fetchImpl}:{}});if(this.parado)return !1;let l=ze($n(n.payload.expires_at,n.payload.grace_days));
|
|
818
|
+
switch(a.kind){case "token":{let c=a.license.payload,d=this.o.revocation.snapshot();if(c.jti===n.payload.jti||this.o.revocation.has(c.jti)||!Ut(Bt(c,this.ahora(),d)))return !1;let u=Ut(Bt(n.payload,this.
|
|
819
|
+
ahora(),d)),f=c.org_id!==n.payload.org_id,m=c.expires_at>n.payload.expires_at||i&&c.plan!=="measure";return !f&&!m&&u?!1:(this.o.onAdopt(a.license),!0)}case "key-unknown":return this.avisar("key-unknown",
|
|
820
|
+
`[bvsala gateway] license renewal: BIVELIO_SERVICE_KEY is no longer recognised (HTTP 401). This session keeps its current license until ${l}; create a new key at ${St} and relaunch.`),!1;case "no-licen\
|
|
821
|
+
se":return this.avisar("no-license",`[bvsala gateway] license renewal: savings.bivelio.com reports no active license for this organization (HTTP 404). This session keeps its current license until ${l}\
|
|
715
822
|
; subscribe or renew at ${ke}.`),!1;case "not-verifying":return this.avisar(`not-verifying:${a.reason}`,`[bvsala gateway] license renewal: the license served by savings.bivelio.com does not verify agai\
|
|
716
|
-
nst this build's BiVelio key (${a.reason}); update @bivelio/savings-layer.`),!1;case "unreachable":return !1}return !1}catch{return false}finally{this.ctrl===s&&(this.ctrl=null),this.enVuelo=false;}}};function
|
|
717
|
-
length??0;return {definiciones:t,referencias:
|
|
823
|
+
nst this build's BiVelio key (${a.reason}); update @bivelio/savings-layer.`),!1;case "unreachable":return !1}return !1}catch{return false}finally{this.ctrl===s&&(this.ctrl=null),this.enVuelo=false;}}};function xl(e){let t=0,n=0;for(;;){let i=e.indexOf('"input_schema"',n);if(i<0)break;t+=1,n=i+14;}let o=0;for(n=0;;){let i=e.indexOf('"tool_reference"',n);if(i<0)break;o+=1,n=i+16;}let r=e.match(/"defer_loading"\s*:\s*true/g)?.
|
|
824
|
+
length??0;return {definiciones:t,referencias:o,diferidas:r}}var ug=40;function Sl(e){return e.referencias>0||(e.diferidas??0)>0||e.definiciones<ug?null:`[bvsala gateway] your client sends ${e.definiciones}\
|
|
718
825
|
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\
|
|
719
|
-
f you launched the terminal by hand, export ENABLE_TOOL_SEARCH=true. In our own corpus that block was 24.5% of input spend.`}var
|
|
720
|
-
"
|
|
826
|
+
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 ms=5*1024*1024,pg=/^\/v1\/(?:messages|chat\/completions|responses|embeddings)\/?$/,fg=/^\/openai\/deployments\/[^/]+\/(?:chat\/completions|responses|embeddings)\/?$/;
|
|
827
|
+
function El(e,t){return e==="POST"&&(pg.test(t)||fg.test(t))}var mg=["authorization","x-api-key","x-goog-api-key","cookie","anthropic-version","anthropic-beta","api-key","openai-organization","openai-\
|
|
828
|
+
project","openai-beta","accept","content-type","content-encoding"];function _l(e,t,n,o=""){return createHash("sha256").update(e).update(`
|
|
721
829
|
`).update(t).update(`
|
|
722
|
-
`).update(
|
|
723
|
-
`).update(n).digest("hex")}function
|
|
724
|
-
`)}var
|
|
725
|
-
i=0,s=false;return {capturar:a=>{if(!s){if(i+=a.length,i>
|
|
726
|
-
{primaria:
|
|
727
|
-
return
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
e
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
830
|
+
`).update(o).update(`
|
|
831
|
+
`).update(n).digest("hex")}function Cl(e){return mg.map(t=>`${t}=${e(t)??""}`).join(`
|
|
832
|
+
`)}var Qo=class{enVuelo=new Map;primarias=0;gemelas=0;registrar(t){if(this.enVuelo.has(t))return null;this.primarias+=1;let n,o=new Promise(a=>n=a);this.enVuelo.set(t,{promesa:o,resolver:n});let r=[],
|
|
833
|
+
i=0,s=false;return {capturar:a=>{if(!s){if(i+=a.length,i>ms){s=true,r.length=0;return}r.push(a);}},terminar:(a,l,c)=>{let d=!s&&a>=200&&a<300;this.enVuelo.get(t)?.resolver(d?{status:a,headers:l,chunks:r,...c?
|
|
834
|
+
{primaria:c}:{}}:null),this.enVuelo.delete(t);},abortar:()=>{this.enVuelo.get(t)?.resolver(null),this.enVuelo.delete(t);}}}async esperar(t){let n=this.enVuelo.get(t);if(!n)return null;let o=await n.promesa;
|
|
835
|
+
return o&&(this.gemelas+=1),o}tieneEnVuelo(t){return this.enVuelo.has(t)}};var Tl={openai:"https://api.openai.com",anthropic:"https://api.anthropic.com",gemini:"https://generativelanguage.googleapis.com",deepseek:"https://api.deepseek.com",qwen:"https://dashscope.aliyuncs.co\
|
|
836
|
+
m",glm:"https://open.bigmodel.cn",moonshot:"https://api.moonshot.cn",minimax:"https://api.minimaxi.com",openrouter:"https://openrouter.ai",ollama:"http://localhost:11434",vllm:"http://localhost:8000",
|
|
837
|
+
lmstudio:"http://localhost:1234"},hg=new Set(["https://api.openai.com","https://api.anthropic.com","https://generativelanguage.googleapis.com","https://api.deepseek.com","https://dashscope.aliyuncs.co\
|
|
838
|
+
m","https://open.bigmodel.cn","https://api.moonshot.cn","https://api.minimaxi.com"]);function Rl(e){let t;try{t=new URL(e).origin;}catch{return false}return hg.has(t)}function gg(e){let t=(()=>{try{return new URL(
|
|
839
|
+
e).origin}catch{return e}})();for(let[n,o]of Object.entries(Tl))if(o===t)return n}function hs(e,t){return gg(e)==="deepseek"&&t.startsWith("/v1/messages")?`/anthropic${t}`:t}function Al(e){for(let t=0;t<
|
|
840
|
+
e.length;t++){let n=e[t];if(n==="--upstream"){let o=e[t+1];return o!==void 0&&!o.startsWith("--")?o:null}if(n.startsWith("--upstream=")){let o=n.slice(11);return o.trim()!==""?o:null}}}function bg(e){
|
|
841
|
+
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 Il(e){if(e.flag===
|
|
842
|
+
null)return {ok:false,error:"[bvsala gateway] --upstream needs a value: an alias (openai, anthropic, gemini, deepseek, qwen, glm\u2026) or an origin URL such as https://api.openai.com"};let t,n;if(e.flag!==
|
|
843
|
+
void 0)t=e.flag,n="flag";else if(e.env!==void 0&&e.env.trim()!=="")t=e.env,n="env";else return {ok:true,upstream:void 0,origen:"none"};let o=Tl[t.trim().toLowerCase()];if(o!==void 0)return {ok:true,upstream:o,
|
|
844
|
+
origen:n};let r={ok:false,error:`[bvsala gateway] invalid upstream ${bg(t)}: use an alias (openai, anthropic, gemini, deepseek\u2026) or an http(s) origin URL`},i;try{i=new URL(t.trim());}catch{return r}return i.
|
|
845
|
+
protocol!=="http:"&&i.protocol!=="https:"?r:i.pathname!=="/"||i.search!==""||i.hash!==""?{ok:true,upstream:i.origin,origen:n,aviso:`[bvsala gateway] WARNING: the upstream path "${i.pathname}" is ignored\
|
|
846
|
+
: requests keep the path the client sends (for example /v1/chat/completions), so put that prefix in the client's base URL instead.`}:{ok:true,upstream:i.origin,origen:n}}var vg="other reasons",Xo=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:vg;this.noMedidas.
|
|
847
|
+
set(n,(this.noMedidas.get(n)??0)+1);}estado(){return {medidas:this.medidas,replicas:this.replicas,noMedidas:Object.fromEntries(this.noMedidas)}}};function Dl(e,t){let n=`[bvsala ${t}] metering in this r\
|
|
848
|
+
un:`,o=Object.entries(e.noMedidas).sort((a,l)=>l[1]-a[1]||a[0].localeCompare(l[0])),r=o.reduce((a,[,l])=>a+l,0);if(e.medidas===0&&e.replicas===0&&r===0)return `${n} no inference request went through th\
|
|
737
849
|
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\
|
|
738
|
-
der's usage`+(e.replicas>0?` \xB7 ${e.replicas} duplicate(s) answered with a replica, valued from the request that travelled`:"");if(
|
|
739
|
-
"; ");return `${n} ${i} \xB7 ${
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
let i=this.entradas.get(t);!i||i.informe.status!=="pending"||(i.informe.status=n,i.informe.reason=r,i.informe.report=o===null?null:structuredClone(o),this.avisar());}quitar(t){let n=this.entradas.get(t);
|
|
747
|
-
this.entradas.delete(t);let r=n?.informe.responseId;r&&this.porRespuestaId.get(r)===t&&this.porRespuestaId.delete(r);}purgar(){let t=this.now()-36e5;for(let[n,r]of this.entradas){if(r.abiertaMs>=t)break;
|
|
748
|
-
this.quitar(n);}}avisar(){for(let t of [...this.oyentes])t();}};function qc(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e;for(let n of [t.message?.id,t.response?.id,t.id])if(typeof n==
|
|
749
|
-
"string"&&$r.test(n))return n;return null}function Mi(e){try{return qc(JSON.parse(e.toString("utf8")))}catch{return null}}var Nr=class{resto="";leidos=0;id=null;observar(t){if(this.id!==null||this.leidos>
|
|
750
|
-
262144)return;let n=typeof t=="string"?t:t.toString("utf8");this.leidos+=n.length,this.resto+=n;let r;for(;(r=this.resto.indexOf(`
|
|
751
|
-
`))>=0;){let o=this.resto.slice(0,r).replace(/\r$/,"");if(this.resto=this.resto.slice(r+1),!o.startsWith("data:"))continue;let i=o.slice(5).trim();if(!(i===""||i==="[DONE]"))try{let s=qc(JSON.parse(i));
|
|
752
|
-
if(s!==null){this.id=s,this.resto="";return}}catch{}}this.leidos>262144&&(this.resto="");}valor(){return this.id}};function Hc(e){try{return new URL(e).origin}catch{return "unknown"}}function Gc(e){let t;
|
|
753
|
-
try{t=new URL(e??"/","http://127.0.0.1");}catch{return null}return t.pathname.startsWith(ph)?t:null}var mh=new Set(["127.0.0.1","localhost","[::1]"]);function hh(e){if(e===void 0||e==="")return true;let t;
|
|
754
|
-
try{t=new URL(`http://${e}`).hostname.toLowerCase();}catch{return false}return mh.has(t)}function Li(e,t,n){e.writeHead(t,{"content-type":"application/json","cache-control":"no-store"}),e.end(JSON.stringify(
|
|
755
|
-
n));}function Mt(e,t,n,r){Li(e,t,{type:"error",error:{type:n,message:r}});}async function Wc(e,t,n,r){if(e.resume(),!hh(e.headers.host)){Mt(t,403,"forbidden","bvsala gateway: local routes answer only to\
|
|
756
|
-
127.0.0.1 or localhost");return}if(e.method!=="GET"){t.setHeader("allow","GET"),Mt(t,405,"method_not_allowed","bvsala gateway: local routes only answer GET");return}if(n.pathname==="/_bvsala/v1/statu\
|
|
757
|
-
s"){Li(t,200,r.estado());return}let o=Number(n.searchParams.get("wait_ms")??"0");if(!Number.isFinite(o)||o<0){Mt(t,400,"invalid_request","bvsala gateway: wait_ms must be a non-negative number of milli\
|
|
758
|
-
seconds");return}let i=Math.min(Math.floor(o),3e4),s=new AbortController;t.on("close",()=>s.abort());let a=null,c="",l=/^\/_bvsala\/v1\/reports\/([^/]+)$/.exec(n.pathname);if(l){let u="";try{u=decodeURIComponent(
|
|
759
|
-
l[1]);}catch{u="";}if(!$r.test(u)){Mt(t,400,"invalid_request","bvsala gateway: malformed request id");return}a=()=>r.buzon.porPeticion(u),c=`request id ${u}`;}else if(n.pathname==="/_bvsala/v1/reports"){
|
|
760
|
-
let u=n.searchParams.get("response_id")??"";if(!$r.test(u)){Mt(t,400,"invalid_request","bvsala gateway: pass ?response_id=<the id of the provider's response>");return}a=()=>r.buzon.porRespuesta(u),c=`\
|
|
761
|
-
response id ${u}`;}if(a===null){Mt(t,404,"not_found",`bvsala gateway: no local route ${n.pathname}`);return}let d=await r.buzon.esperar(a,i,s.signal);if(!t.destroyed){if(d===void 0){Mt(t,404,"not_found",
|
|
762
|
-
`bvsala gateway: no report for ${c}. Reports exist only for requests sent with the header "${An}: 1", while this gateway process keeps them (the last ${r.buzon.limite}, one hour at most).`);return}Li(
|
|
763
|
-
t,200,d);}}var Kc=4096;function Jc(e){let t={marcas:0,de1h:0,deOtroTtl:0,enLaCola:false,herramientaDeServidor:false};return fo(e,(n,r)=>{t.marcas++,n.ttl==="1h"?t.de1h++:t.deOtroTtl++,(r==="raiz"||r==="ultimoMensaje")&&
|
|
764
|
-
(t.enLaCola=true);}),t.herramientaDeServidor=co(e),t}function Yc(e){let t=e["x-claude-code-session-id"];if(typeof t=="string"?t!=="":Array.isArray(t)&&t.length>0)return true;let n=e["user-agent"];return typeof n==
|
|
765
|
-
"string"&&n.startsWith("claude-cli/")}var Zc=e=>e.cache_creation_input_tokens??(e.cache_creation?.ephemeral_5m_input_tokens??0)+(e.cache_creation?.ephemeral_1h_input_tokens??0);function Xc(e){if((e.cache_read_input_tokens??
|
|
766
|
-
0)===0&&Zc(e)===0&&(e.input_tokens??0)>=Kc)return true;let n=e.cache_creation;return n!==void 0&&(n.ephemeral_5m_input_tokens??0)>0&&(n.ephemeral_1h_input_tokens??0)===0}function Qc(e){let{vista:t,uso:n,
|
|
767
|
-
ttlReescritoPorLaCapa:r}=e;if(t.marcas===0)return null;if((n.cache_read_input_tokens??0)===0&&Zc(n)===0&&t.enLaCola&&(n.input_tokens??0)>=Kc)return "cacheIgnorada";let i=n.cache_creation;return !r&&t.de1h>
|
|
768
|
-
0&&t.deOtroTtl===0&&!t.herramientaDeServidor&&i!==void 0&&(i.ephemeral_1h_input_tokens??0)===0&&(i.ephemeral_5m_input_tokens??0)>0?"ttlAcortado":null}function Ni(e,t){let n=`[gateway] degraded traffic${t.
|
|
769
|
-
sesion?` (session ${t.sesion})`:""} \xB7 `,r=" Logged once per session; further cases are counted, not logged.";return e==="cacheIgnorada"?n+`prompt caching: the request carried cache_control and the \
|
|
850
|
+
der's usage`+(e.replicas>0?` \xB7 ${e.replicas} duplicate(s) answered with a replica, valued from the request that travelled`:"");if(r===0)return `${n} ${i}.`;let s=o.map(([a,l])=>`${l} \xD7 ${a}`).join(
|
|
851
|
+
"; ");return `${n} ${i} \xB7 ${r} forwarded but NOT metered (nothing is estimated in their place): ${s}. What each reason means and what to do: docs/terminales/README.md.`}ys();var jl=4096;function Bl(e){let t={marcas:0,de1h:0,deOtroTtl:0,enLaCola:false,herramientaDeServidor:false};return Or(e,(n,o)=>{t.marcas++,n.ttl==="1h"?t.de1h++:t.deOtroTtl++,(o==="raiz"||o==="ultimoMensaje")&&
|
|
852
|
+
(t.enLaCola=true);}),t.herramientaDeServidor=Ar(e),t}function Ul(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==
|
|
853
|
+
"string"&&n.startsWith("claude-cli/")}var Fl=e=>e.cache_creation_input_tokens??(e.cache_creation?.ephemeral_5m_input_tokens??0)+(e.cache_creation?.ephemeral_1h_input_tokens??0);function zl(e){if((e.cache_read_input_tokens??
|
|
854
|
+
0)===0&&Fl(e)===0&&(e.input_tokens??0)>=jl)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 Vl(e){let{vista:t,uso:n,
|
|
855
|
+
ttlReescritoPorLaCapa:o}=e;if(t.marcas===0)return null;if((n.cache_read_input_tokens??0)===0&&Fl(n)===0&&t.enLaCola&&(n.input_tokens??0)>=jl)return "cacheIgnorada";let i=n.cache_creation;return !o&&t.de1h>
|
|
856
|
+
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 ks(e,t){let n=`[gateway] degraded traffic${t.
|
|
857
|
+
sesion?` (session ${t.sesion})`:""} \xB7 `,o=" Logged once per session; further cases are counted, not logged.";return e==="cacheIgnorada"?n+`prompt caching: the request carried cache_control and the \
|
|
770
858
|
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\
|
|
771
|
-
m: another proxy in the chain, or an endpoint that ignores prompt caching.`+
|
|
859
|
+
m: another proxy in the chain, or an endpoint that ignores prompt caching.`+o:e==="ttlAcortado"?n+`cache TTL: every cache_control in the request asked for ttl "1h" and the provider wrote the cache at \
|
|
772
860
|
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\
|
|
773
|
-
ntry expires between turns more than 5 minutes apart.`+
|
|
861
|
+
ntry expires between turns more than 5 minutes apart.`+o: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 \
|
|
774
862
|
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\
|
|
775
|
-
y hand.`+
|
|
776
|
-
if(this.dichas.has(
|
|
777
|
-
cuentas}}};function
|
|
863
|
+
y hand.`+o}var rr=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 o=`${t}|${n??""}`;
|
|
864
|
+
if(this.dichas.has(o))return false;if(this.dichas.add(o),this.dichas.size>this.maxSesiones){let r=this.dichas.values().next();r.done!==true&&this.dichas.delete(r.value);}return true}contadores(){return {...this.
|
|
865
|
+
cuentas}}};function ql(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) \
|
|
778
866
|
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\
|
|
779
|
-
his run: ${t.join(" \xB7 ")}. What each one means and what to do: "What the gateway guarantees" in docs/terminales/README.md of the package.`}var
|
|
780
|
-
d have saved shows on your dashboard as an estimate, never billed. To turn the levers on, upgrade at https://savings.bivelio.com/dashboard/account - the gateway picks up the new license by itself.",
|
|
867
|
+
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 Tg="[bvsala gateway] Measure license: SHADOW mode. Requests are forwarded to the provider byte for byte (no levers, no coalescing, no usage injection) and your usage is measured; what a lever woul\
|
|
868
|
+
d have saved shows on your dashboard as an estimate, never billed. To turn the levers on, upgrade at https://savings.bivelio.com/dashboard/account - the gateway picks up the new license by itself.",Wl='\
|
|
781
869
|
[bvsala gateway] streamed /v1/chat/completions requests without stream_options.include_usage carry no usage, so they are forwarded but NOT metered. Add stream_options={"include_usage": True} to the ca\
|
|
782
|
-
ll (Node: stream_options: { include_usage: true }); its last chunk then has an empty choices list.',
|
|
783
|
-
nge.",
|
|
784
|
-
out the provider's final usage, so it was forwarded but NOT metered. Nothing is estimated in its place.`,
|
|
785
|
-
1/messages, \u2026/chat/completions and \u2026/responses only.`,
|
|
786
|
-
proxy-connection","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"]);function
|
|
787
|
-
|
|
788
|
-
"proxy-authorization","te","trailer","transfer-encoding","upgrade","expect"]);function
|
|
789
|
-
|
|
790
|
-
d not start`:t==="EACCES"?`port ${n} cannot be opened: permission denied`:`could not listen on 127.0.0.1:${n} (${t})`,{cause:
|
|
791
|
-
if(e===t)return true;let n=Object.keys(e);return n.length!==Object.keys(t).length?false:n.every(
|
|
792
|
-
resolve(false):new Promise(t=>{let n=()=>
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
"
|
|
812
|
-
request body (content-encoding: ${
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
"
|
|
834
|
-
0
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
let
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
"
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
system}
|
|
862
|
-
herramientaDeServidor:
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
T)
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
"
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
870
|
+
ll (Node: stream_options: { include_usage: true }); its last chunk then has an empty choices list.',Rg=Wl+" Or start the gateway with BVSALA_GATEWAY_USAGE_INJECT=1 to add it for clients you cannot cha\
|
|
871
|
+
nge.",Ag=Wl+" 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.",Ig=e=>`[bvsala gateway] POST ${e} answered with\
|
|
872
|
+
out the provider's final usage, so it was forwarded but NOT metered. Nothing is estimated in its place.`,Dg=e=>`[bvsala gateway] POST ${e} is forwarded but NOT metered: the gateway reads usage from /v\
|
|
873
|
+
1/messages, \u2026/chat/completions and \u2026/responses only.`,Hl=/\/(count_tokens|input_tokens)$/,Pg=["content-encoding","content-length","transfer-encoding"],Og=new Set(["connection","keep-alive","\
|
|
874
|
+
proxy-connection","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"]);function Lg(e){let t=new Set((e.connection??"").split(",").map(o=>o.trim().toLowerCase()).filter(
|
|
875
|
+
o=>o!=="")),n={};for(let[o,r]of Object.entries(e)){let i=o.toLowerCase();Og.has(i)||t.has(i)||(n[o]=r);}return n}var Mg=5e3,$g=new Set(["connection","keep-alive","proxy-connection","proxy-authenticate",
|
|
876
|
+
"proxy-authorization","te","trailer","transfer-encoding","upgrade","expect"]);function dn(e){let t=e?.cause;if(t==null)return String(e);let n=t instanceof AggregateError&&t.errors.length>0?t.errors.map(
|
|
877
|
+
o=>String(o)).join("; "):String(t);return `${String(e)} \xB7 cause: ${n}`}var ws=class extends Error{code;puerto;constructor(t,n,o){super(t==="EADDRINUSE"?`port ${n} is already in use: the gateway coul\
|
|
878
|
+
d not start`:t==="EACCES"?`port ${n} cannot be opened: permission denied`:`could not listen on 127.0.0.1:${n} (${t})`,{cause:o}),this.name="ErrorDeEscucha",this.code=t,this.puerto=n;}};function Gl(e,t){
|
|
879
|
+
if(e===t)return true;let n=Object.keys(e);return n.length!==Object.keys(t).length?false:n.every(o=>Object.hasOwn(t,o)&&e[o]===t[o])}function Ng(e){return e.writableFinished?Promise.resolve(true):e.destroyed?Promise.
|
|
880
|
+
resolve(false):new Promise(t=>{let n=()=>r(true),o=()=>r(e.writableFinished),r=i=>{e.off("finish",n),e.off("close",o),t(i);};e.once("finish",n),e.once("close",o);})}async function Jl(e){let t=!e?.license,n="",
|
|
881
|
+
o=null;if(e?.license){n=ds(e.license.publicKey);let b=Mn(e.license.token,n);if(!b.ok)throw new Error(`arrancarGateway: the license token does not verify (${b.reason})`);o=b.license;}let r=(e.upstream??
|
|
882
|
+
"https://api.anthropic.com").replace(/\/+$/,""),i=Rl(r),s=e.fetchImpl??fetch,a=e.log??(b=>console.log(b)),l=e.warn??(b=>console.error(b)),c=e.license?.now??Date.now,d=e.license?.licenseServerUrl?.replace(
|
|
883
|
+
/\/+$/,""),u=new nn,f=o?fs(o,n,u,c):null,m=()=>f?.license.payload.plan,h;if(e.serviceAccountKey){h=new Xt({url:e.meteringUrl??"https://savings.bivelio.com/api/metering/usage",serviceAccountKey:e.serviceAccountKey,
|
|
884
|
+
surface:"gateway",...e.fetchImpl?{fetchImpl:e.fetchImpl}:{},onAuthError:_=>Z("gateway-ingest-auth",`[bvsala gateway] the usage ingest is rejecting the credential (${_}). Traffic keeps flowing (warn, n\
|
|
885
|
+
ever break), but this usage is not reaching your dashboard. Check BIVELIO_SERVICE_KEY and your subscription status at savings.bivelio.com.`)});let b=po();e.seatId?h.setSeat(e.seatId,b):fo(e.serviceAccountKey).
|
|
886
|
+
then(_=>h?.setSeat(_,b)).catch(()=>{}),h.start();}else t?Z("gateway-modo-comunitario","[bvsala gateway] COMMUNITY MODE (open core): no BIVELIO_SERVICE_KEY - every local saving lever is on and traffic i\
|
|
887
|
+
s metered only in the local report routes (x-bvsala-report). Nothing is sent to BiVelio. Add a service key to get the cloud dashboard, org entitlements and team metering."):Z("gateway-sin-clave","[bvs\
|
|
888
|
+
ala gateway] no BIVELIO_SERVICE_KEY: this in-process gateway forwards traffic but does not meter it (a service key is what authorizes metering).");let v=e.coalescer?new Qo:null,g=new Set,y=()=>{let b,
|
|
889
|
+
_=new Promise(L=>b=L);return g.add(_),()=>{g.delete(_),b();}},k=e.sombra&&h?new Go:null,S=new tr,w=new ao,I=new zo,D=new rr,P=new Xo,O=e.serviceAccountKey?new Jo({url:d?`${d}/api/org/entitlements`:new URL(
|
|
890
|
+
"/api/org/entitlements",e.meteringUrl??"https://savings.bivelio.com/api/metering/usage").toString(),serviceAccountKey:e.serviceAccountKey,...e.fetchImpl?{fetchImpl:e.fetchImpl}:{},...e.entitlementsTtlMs!==
|
|
891
|
+
void 0?{ttlMs:e.entitlementsTtlMs}:{},log:a}):t?new Wo:null,j=O!==null&&e.elision!==false,J=()=>t?{serve:true,state:"active"}:ps(f.gate,O?.blockReason()??null,f.license.payload),ee=null;if(!t){let b=ps(f.gate,
|
|
892
|
+
null,f.license.payload);b.serve&&(ee=b.state);}let C=b=>{if(t)return;let _=wl(ee,b,f.license.payload);ee=b.state,_&&l(_);},R,$,F=Number.NEGATIVE_INFINITY,ie=new Set,fe=(b,_)=>{ie.has(b)||(ie.add(b),a(_));},
|
|
893
|
+
Re=false,Pe=b=>b==="/v1/messages"?new Je:b.endsWith("/responses")?new cn:b.endsWith("/chat/completions")?new An:Ki(b)==="stream"?new sn:null,Ce=(b,_,L,U,K,q,Q)=>{S.noMedido(b,q),a(`[gateway] ${_} ${L} \u2192 ${U}${K?
|
|
894
|
+
" (stream)":""} \xB7 not metered: ${q}`),(jt(L)||L.startsWith("/v1/"))&&P.noMedida(q),e.avisosDeNoMedido!==false&&(Q==="chat"&&Z("gateway-chat-sin-include-usage",Rg),Q==="chat-con-inyeccion"&&Z("gateway-\
|
|
895
|
+
chat-sin-include-usage-con-inyeccion",Ag),Q==="uso"&&Z(`gateway-sin-usage:${L}`,Ig(L)),Q==="dialecto"&&Z(`gateway-sin-dialecto:${L}`,Dg(L)));},Xe=(b,_,L,U)=>{let K=b instanceof cn?b.estadoFinal():null;
|
|
896
|
+
if(K!==null&&K!=="completed")return {motivo:`the response ended as response.${K} without usage`,aviso:"uso"};if(!(b instanceof An&&U!=="inyectado"&&il(_,L)!==true))return {motivo:"the stream ended without\
|
|
897
|
+
the provider's final usage event",aviso:"uso"};let Q="the request did not ask for usage (stream_options.include_usage)";return U==="rechazada-por-el-upstream"?{motivo:`${Q}, and the upstream rejects \
|
|
898
|
+
that option`,aviso:null}:U==="comprimido"?{motivo:`${Q}; usage injection skips compressed request bodies`,aviso:"chat-con-inyeccion"}:U!==null?{motivo:Q,aviso:"chat-con-inyeccion"}:{motivo:Q,aviso:"ch\
|
|
899
|
+
at"}},Ae=(b,_,L,U,K,q,Q,te,se,Ht,Ve,xe,Ze,x,B,Ct,pt,eo)=>{if(!h||!L){S.noMedido(b,h?"the provider reported no usage":"metering is off: the gateway has no BIVELIO_SERVICE_KEY");return}let Oe=h,Le=L,oe=eo??
|
|
900
|
+
Yc(_,q),et=`[gateway] POST ${K}${U?" \xB7 COALESCED (call avoided)":""}`;if(!oe){let V=`could not read the model from the request body${q?` (content-encoding: ${q})`:""}`;a(`${et} \xB7 not metered: ${V}`),
|
|
901
|
+
P.noMedida(V),S.noMedido(b,"could not read the model from the request body"),Z(`gateway-sin-modelo:${K}`,`[bvsala gateway] could not read the model from the ${K} request body (content-encoding: ${q??"\
|
|
902
|
+
none"}); its usage is forwarded but not metered.`);return}let Te=!U&&Ve?Ve.servido:oe,Y=ts(Te,L,Ht);if(Y){let V=U?al(oe,Y,Ze,ln(_,q),{suscripcion:xe===true,entregada:x?.entregada===true,tierServido:x?.tierServido}):
|
|
903
|
+
null,Gt=m()==="measure",he=0;pt&&!U&&(he=Gt?Fc(pt,Y.tokens):Uc(pt,Y.tokens),zc(pt,Y.tokens,{sombra:Gt,atribuible:!!se&&se.rebajadas>0&&se.yaEran5m===0&&!se.herramientaDeServidor&&xe!==true&&i&&B!==true,perdidos:he}));
|
|
904
|
+
let Tt=!Gt&&he>0?{perdidos:he}:null,Me=U?cl(b,oe,Y,Q,V?.ok?V.credit:null,B===true):sl(b,Te,Y,Q,te,se,Ve,xe===true,!i,B===true,Tt);h.record(Me),U?P.replica():P.medida(),S.medido(b,Me);let H=Me.cost.eliminatedInputFloorCost;
|
|
905
|
+
a(`[gateway] POST ${K} ${U?"\xB7 COALESCED (call avoided)":""} \xB7 ${Te!==oe?`${oe}\u2192${Te} (sibling model)`:oe} \xB7 $${(B?0:Y.costeUsd).toFixed(6)} (in ${Y.tokens.entrada}, cache\u2191${Y.tokens.
|
|
906
|
+
cacheEscrita}${Y.tokens.cacheEscrita1h?` (1h ${Y.tokens.cacheEscrita1h})`:""} cache\u2193${Y.tokens.cacheLeida}, out ${Y.tokens.salida})`+(te?` \xB7 elision: ${te.borrados} clear(s), ${te.tokensLimpiados}\
|
|
907
|
+
tok cleared by the provider`+(H!==void 0?` \xB7 floor $${H.toFixed(6)} (cache read price)`:te.tokensLimpiadosToolUses>0?te.atribuible?" \xB7 no cache read price in the catalog: no floor":" \xB7 your own\
|
|
908
|
+
context_management settings: counted, not credited":te.tokensLimpiados>0?" \xB7 thinking only (your config): counted, not credited":""):"")+(Tt?` \xB7 cache TTL miss: ${Tt.perdidos} tok rewritten bec\
|
|
909
|
+
ause the 5m entry expired (net $${Me.cost.netSavingsUsd.toFixed(6)} on this call)`:"")+(B?" \xB7 refusal the provider does not bill: measured at $0, no saving credited":"")+(xe&&!U&&(se||Ve)?" \xB7 subsc\
|
|
910
|
+
ription traffic: lever applied, saving not credited (no per-token invoice)":"")+(!i&&!xe&&!U&&(se||Ve||te?.atribuible)?" \xB7 unofficial upstream: lever applied, saving not credited (list prices only hol\
|
|
911
|
+
d at the provider's own API)":"")+(V?V.ok?` \xB7 by reference: floor $${rs(V.credit).toFixed(6)} (cache read price${V.credit.creditedOutputTokens>0?`, ${V.credit.creditedOutputTokens} output tok at te\
|
|
912
|
+
mperature 0`:", no output credited"})`:` \xB7 estimated, not by reference: ${V.reason}`:""));let M=te?.atribuible===true&&te.tokensLimpiadosToolUses>0,qe=m()==="measure";if(qe&&!U&&K==="/v1/messages"&&!xe&&
|
|
913
|
+
i&&B!==true)try{let ge=Br(_,q),be=ge?ts(ge.cambio.servido,Le,Ht):null,ft=ge&&be&&be.costeUsd<Y.costeUsd?be:null,mt=ft??Y,Ie=Ct?ua(Ct,mt.tokens.cacheEscrita1h,mt.precio.inputPer1k):0,tt=Vo({perdidos:he,inputPer1k:mt.
|
|
914
|
+
precio.inputPer1k,cachedInputPer1k:mt.precio.cachedInputPer1k,primaEscritura:Ct?Tr:Rr}),ue=mt.costeUsd-Ie+tt;ue!==Y.costeUsd&&(Oe.record(is(`${b}:shadow`,oe,Y.costeUsd,ue,Q)),a(`[gateway] measure (sha\
|
|
915
|
+
dow) \xB7 ${oe} \xB7 `+[ft&&ge?`sibling model ${ge.cambio.servido}`:null,Ie>0?`cache TTL 1h\u21925m on ${mt.tokens.cacheEscrita1h} written tok`:null,tt>0?`cache miss the 5m TTL would have caused on ${he}\
|
|
916
|
+
tok (+$${tt.toFixed(6)})`:null].filter(Boolean).join(" + ")+` \xB7 this call would have cost $${ue.toFixed(6)} instead of $${Y.costeUsd.toFixed(6)} (not applied)`));}catch{}k&&!qe&&!U&&K==="/v1/messag\
|
|
917
|
+
es"&&setImmediate(()=>{try{let ge=ln(_,q);if(!ge||typeof ge!="object")return;let be=k.observar({cuerpo:ge,uso:Le,model:oe,at:Ht??Date.now(),...Q?.sessionId!==void 0?{sessionId:Q.sessionId}:{},...Q?.agentId!==
|
|
918
|
+
void 0?{agentId:Q.agentId}:{}});if(!be)return;if(M){a(`[gateway] shadow estimate \xB7 ${oe} \xB7 the provider already cleared context via our settings: chain advances, nothing emitted`);return}Oe.record(
|
|
919
|
+
is(`${b}:shadow`,oe,be.baselineUsd,be.politicaUsd,Q)),a(`[gateway] shadow estimate \xB7 ${oe} \xB7 baseline $${be.baselineUsd.toFixed(6)} \u2192 with elision $${be.politicaUsd.toFixed(6)}`);}catch{}});}else
|
|
920
|
+
S.noMedido(b,`model "${Te}" has no list price in the catalog`),a(`${et} \xB7 not metered: model "${Te}" has no list price in the catalog`),P.noMedida(`model "${Te}" has no list price in the catalog`),
|
|
921
|
+
Z(`gateway-sin-precio:${Te}`,`[bvsala gateway] model "${Te}" is not in the price catalog; its usage is forwarded but not metered.`);},qt=(b,_,L,U,K,q)=>{if(!(b!=="/v1/messages"||U===null||!zl(U)||(L===
|
|
922
|
+
void 0||L===""||L==="identity")&&!_.includes('"cache_control"')))try{let te=ln(_,L);if(te===null||typeof te!="object"||Array.isArray(te))return;let se=Vl({vista:Bl(te),uso:U,ttlReescritoPorLaCapa:K});
|
|
923
|
+
se!==null&&D.anotar(se,q)&&a(ks(se,{sesion:q,entrada:U.input_tokens??0,escrita5m:U.cache_creation?.ephemeral_5m_input_tokens??0}));}catch{}},dt=createServer(async(b,_)=>{let L=randomUUID(),U=Date.now(),K=J();if(C(K),!K.
|
|
924
|
+
serve){let H=c();$&&H-F>=bl&&(F=H,$.check({force:true})),b.resume(),_.writeHead(402,{"content-type":"application/json","cache-control":"no-store","x-bvsala-license-status":K.state}),_.end(b.method==="HE\
|
|
925
|
+
AD"?void 0:kl(K.state));let M="/";try{M=new URL(b.url??"/","http://x").pathname;}catch{}a(`[gateway] ${b.method} ${M} \u2192 402 (license ${K.state})`);return}let q=m()==="measure";q&&Z("gateway-licenc\
|
|
926
|
+
ia-medir",Tg);let Q=$l(b.url);if(Q!==null){await Nl(b,_,Q,{buzon:S,estado:()=>({schema:Pl,gateway:"bvsala",version:ye,upstream:Ml(r),license:t?{state:"active",plan:"community",expiresAt:null}:{state:K.
|
|
927
|
+
state,plan:m()??null,expiresAt:f?ze(f.license.payload.expires_at):null},metering:h!==void 0,reports:{requestHeader:Bn,responseHeader:bs,capacity:S.limite}})});return}let te=Ol(b.headers[Bn]),se=te?new nr:
|
|
928
|
+
null;if(te){let H="/";try{H=new URL(b.url??"/","http://x").pathname;}catch{}S.abrir(L,H);}let Ht=H=>te?{...H,[bs]:L}:H,Ve=null,xe=new AbortController;_.on("close",()=>{_.writableEnded||xe.abort();});let Ze=null,
|
|
929
|
+
x=new URL(b.url??"/",r);x.pathname=hs(r,x.pathname);let B=null,Ct=Buffer.alloc(0),pt=false,eo=false,Oe=null,Le=null,oe=false,et=false,Te=(H,M)=>{if(H===null||Oe===null||!Oe.nuestros)return H;let qe=M?.cache_creation,
|
|
930
|
+
ge=M?.cache_creation_input_tokens??(qe?.ephemeral_5m_input_tokens??0)+(qe?.ephemeral_1h_input_tokens??0),be=(M?.input_tokens??0)+(M?.cache_read_input_tokens??0)+ge+H.tokensLimpiados,ft=Oe.triggerDelCliente!==
|
|
931
|
+
null&&be>=Oe.triggerDelCliente;return {...H,atribuible:!ft}},Y=b.headers["content-encoding"],V=Array.isArray(Y)?Y[0]:Y,Gt=H=>{let M=Array.isArray(H)?H[0]:H;return M!==void 0&&/^[A-Za-z0-9._:/-]{1,128}$/.
|
|
932
|
+
test(M)?M:void 0},he=Gt(b.headers["x-claude-code-session-id"]),Tt=Gt(b.headers["x-claude-code-agent-id"]),Me=he!==void 0||Tt!==void 0?{...he!==void 0?{sessionId:he}:{},...Tt!==void 0?{agentId:Tt}:{}}:
|
|
933
|
+
void 0;try{let H=[];for await(let E of b)H.push(E);let M=Buffer.concat(H);Ct=M,x=new URL(b.url??"/",r),x.pathname=hs(r,x.pathname);let qe=v!==null&&!q&&M.length>0&&El(b.method??"",x.pathname),ge=Cl(E=>{
|
|
934
|
+
let T=b.headers[E];return Array.isArray(T)?T.join(", "):T}),be=qe?_l("POST",x.pathname+x.search,M,ge):"";if(qe)if(v.tieneEnVuelo(be)){let E=await v.esperar(be);if(E){let T=y();try{let X=xe.signal.aborted||
|
|
935
|
+
_.destroyed;X||_.writeHead(E.status,Ht(E.headers)),Ve=E.status;let ve=Pe(x.pathname)??new Je;for(let Kt of E.chunks)X||_.write(Kt),ve.observar(Kt),se?.observar(Kt);se&&S.anotarRespuesta(L,se.valor()??
|
|
936
|
+
vs(Buffer.concat(E.chunks))),X||_.end();let $e=X?!1:await Ng(_),Ne=ve.usageFinal()??Ho(x.pathname,Buffer.concat(E.chunks));if(Ne===null){if(h&&!Hl.test(x.pathname)){let Kt=String(E.headers["content-ty\
|
|
937
|
+
pe"]??"").includes("text/event-stream");Ce(L,b.method??"POST",x.pathname,E.status,Kt,jt(x.pathname)?Kt?Xe(ve,M,V,null).motivo:"the response carried no usage":"no usage dialect for this route",null);}return}
|
|
938
|
+
let ot=b.headers["anthropic-beta"],Od=os(x.pathname,Array.isArray(ot)?ot.join(", "):ot,r);Ae(L,M,Ne,!0,x.pathname,V,Me,null,null,U,null,Od,E.primaria??null,{entregada:$e,tierServido:ol(x.pathname,Buffer.
|
|
939
|
+
concat(E.chunks))},x.pathname==="/v1/messages"&&(ve instanceof Je&&ve.negativaNoCobrada()||ns(x.pathname,Buffer.concat(E.chunks))));return}finally{T();}}}else Ze=v.registrar(be);let ft=b.headers.connection,
|
|
940
|
+
mt=new Set((Array.isArray(ft)?ft.join(","):ft??"").split(",").map(E=>E.trim().toLowerCase()).filter(E=>E!=="")),Ie={};for(let[E,T]of Object.entries(b.headers))E==="host"||E==="content-length"||T===void 0||
|
|
941
|
+
$g.has(E)||mt.has(E)||E!==Bn&&(Ie[E]=Array.isArray(T)?T.join(", "):T);let tt={...Ie};oe=os(x.pathname,tt["anthropic-beta"],r);let ue=M;if(j&&!q&&e.dialesElision===!0&&b.method==="POST"&&x.pathname==="\
|
|
942
|
+
/v1/messages"&&O.tiene("context_elision"))try{let E=sa(M,V);E!==null&&(ue=E.cuerpo,Oe={nuestros:E.nuestros,triggerDelCliente:E.triggerDelCliente},Ie["anthropic-beta"]=ca(Ie["anthropic-beta"]));}catch{}
|
|
943
|
+
if(b.method==="POST"&&x.pathname==="/v1/messages"&&(V??"")==="")try{let E=xl(M.toString("utf8")),T=Sl(E);T&&(Z("gateway-busqueda-herramientas",T),Ul(b.headers)&&D.anotar("busquedaApagada",he)&&a(ks("b\
|
|
944
|
+
usquedaApagada",{sesion:he,definiciones:E.definiciones})));}catch{}let Ys=j&&!q&&e.modeloHermano===!0&&b.method==="POST"&&(x.pathname==="/v1/messages"||x.pathname==="/v1/messages/count_tokens");if(Ys&&
|
|
945
|
+
!O.tiene("sibling_model_routing")&&Z("gateway-hermano-sin-feature","[bvsala gateway] sibling model routing: the flag is set but your org's license does not include sibling_model_routing; the request i\
|
|
946
|
+
s forwarded unchanged (fail-closed)."),Ys&&O.tiene("sibling_model_routing"))try{let T=Br(ue,ue===M?V:"identity",{betas:Ie["anthropic-beta"]});T!==null&&(ue=T.cuerpo,Le=T.cambio);}catch{}let to=!1;if(j&&
|
|
947
|
+
!q&&$r(e.esfuerzo)&&b.method==="POST"&&x.pathname==="/v1/messages"&&O.tiene("per_turn_effort"))try{let E=ue===M?V:"identity",T=ma(ue,e.esfuerzo,E);T!==null&&(ue=T.cuerpo,Ie["anthropic-beta"]=ha(Ie["an\
|
|
948
|
+
thropic-beta"]),to=!0);}catch{}let Wt=null,ht=null;if(j&&!q&&b.method==="POST"&&x.pathname==="/v1/messages"&&O.tiene("cache_ttl_tuning"))try{let T=gt(ue,ue===M?V:"identity");if(T!==null){let X=Ir(T),ve=`${Me?.
|
|
949
|
+
sessionId??"sin-sesion"}:${X.system}`,$e=Date.now(),Ne=w.ultima(ve,$e);if(w.anotar(ve,X,$e),ht=I.abrir(ve,X,$e,!1),Pr({fraccionNueva:Dr(Ne,X)})){let ot=Lr(T);ot!==null&&(ht.rebajado=!0,ue=ot.cuerpo,Wt=
|
|
950
|
+
{rebajadas:ot.rebajadas,yaEran5m:ot.yaEran5m,herramientaDeServidor:ot.herramientaDeServidor},et=!0);}}}catch{}let vr=null;if(q&&e.elision!==!1&&b.method==="POST"&&x.pathname==="/v1/messages")try{let E=gt(
|
|
951
|
+
M,V);if(E!==null){let T=Ir(E),X=`${Me?.sessionId??"sin-sesion"}:${T.system}`,ve=Date.now(),$e=w.ultima(X,ve);if(w.anotar(X,T,ve),ht=I.abrir(X,T,ve,!1),Pr({fraccionNueva:Dr($e,T)})){let Ne=Lr(E);Ne!==null&&
|
|
952
|
+
(ht.rebajado=!0,vr={rebajadas:Ne.rebajadas,yaEran5m:Ne.yaEran5m,herramientaDeServidor:Ne.herramientaDeServidor});}}}catch{}let Jt=!1,no=null;if(b.method==="POST"&&x.pathname.endsWith("/chat/completions")&&
|
|
953
|
+
h&&e.usageInject===!0&&!q)if(Re)no="rechazada-por-el-upstream";else try{let E=rl(M,V);no=E.motivo,E.cuerpo&&(ue=E.cuerpo,Jt=!0);}catch{}let z,yr=ue,kr=Ie;try{z=await s(x,{method:b.method,headers:Ie,body:[
|
|
954
|
+
"GET","HEAD"].includes(b.method??"")?void 0:ue,redirect:"manual",signal:xe.signal});}catch(E){Ze?.abortar(),_.headersSent||(_.writeHead(502,{"content-type":"application/json"}),_.end(JSON.stringify({error:"\
|
|
955
|
+
bvsala gateway: upstream unreachable",detail:dn(E)}))),a(`[gateway] ${b.method} ${x.pathname} \u2192 upstream unreachable: ${dn(E)}`);return}if(((yr!==M||!Gl(kr,tt))&&z.status===400||Jt&&(z.status===400||
|
|
956
|
+
z.status===422))&&!xe.signal.aborted){let E="";try{E=(await z.text()).slice(0,300).replace(/\s+/g," ");}catch{}let T=Jt;a(T?`[gateway] the upstream rejected (${z.status}) the request with stream_option\
|
|
957
|
+
s.include_usage added; forwarding it unchanged \xB7 ${E}`:`[gateway] the upstream rejected (400) the rewritten request${Le?` to ${Le.servido}`:""}${to?" (per-turn effort)":""}${Wt?" (cache TTL)":""}${Oe?
|
|
958
|
+
" (context editing dials)":""}; forwarding it unchanged \xB7 ${E}`),Le=null,to=!1,Wt=null,ht&&et&&(ht.rebajado=!1),et=!1,Oe=null,Jt=!1,T&&(no="rechazada-por-el-upstream"),yr=M,kr=tt;try{z=await s(x,{method:b.
|
|
959
|
+
method,headers:tt,body:M,redirect:"manual",signal:xe.signal});}catch(X){Ze?.abortar(),_.headersSent||(_.writeHead(502,{"content-type":"application/json"}),_.end(JSON.stringify({error:"bvsala gateway: u\
|
|
960
|
+
pstream unreachable",detail:dn(X)}))),a(`[gateway] ${b.method} ${x.pathname} \u2192 upstream unreachable on retry: ${dn(X)}`);return}T&&z.ok&&(Re=!0,Z("gateway-sin-stream-options","[bvsala gateway] th\
|
|
961
|
+
e 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 metered (stream=false answers still are)."));}
|
|
962
|
+
let wr=Lg(Object.fromEntries(z.headers.entries()));for(let E of Pg)delete wr[E];_.writeHead(z.status,Ht(wr)),Ve=z.status;let gn=z.headers.get("content-type")??"",Pd=Ki(x.pathname)==="stream"&&gn.includes(
|
|
963
|
+
"application/json"),oo=gn.includes("text/event-stream")||Pd||gn===""&&z.ok&&Pe(x.pathname)!==null&&!x.pathname.endsWith("/chat/completions");B=oo?Pe(x.pathname):null,eo=z.ok;let nt=!oo&&z.ok&&h!==void 0&&
|
|
964
|
+
b.method==="POST"&&jt(x.pathname)&&(z.headers.get("content-type")??"").includes("application/json")?[]:null,Qs=0,Xs=!1;if(z.body)for await(let E of z.body){let T=Buffer.from(E);_.write(T),B?.observar(
|
|
965
|
+
T),se?.observar(T),nt&&(Qs+=T.length,Qs>ms?(nt=null,Xs=!0):nt.push(T)),Ze?.capturar(T);}if(_.end(),se&&S.anotarRespuesta(L,se.valor()??(nt?vs(Buffer.concat(nt)):null)),Ze){let E=Le===null&&!to&&Oe===null&&
|
|
966
|
+
!Jt&&Wt===null&&yr===M&&Gl(kr,tt),T=nt?Buffer.concat(nt):null,X=z.ok&&(B?B.usageFinal()!==null:T!==null&&Ho(x.pathname,T)!==null),ve=B instanceof cn&&B.estadoFinal()==="failed"||T!==null&&Xc(x.pathname,
|
|
967
|
+
T),$e=B!==null&&B.negativa()||T!==null&&el(x.pathname,T),Ne=!$e&&nl(B!==null?B.textoInicial():T!==null?tl(x.pathname,T):"");Ze.terminar(z.status,wr,{requestId:L,at:Date.now(),intacta:E,proveedorOficial:i,
|
|
968
|
+
conContador:X,suscripcion:oe,fallida:ve,...$e?{negativa:$e}:{},...Ne?{negativaEnTexto:!0}:{}});}if(B&&z.ok){pt=!0;let E=B.usageFinal();if(E===null&&h){let T=Xe(B,M,V,Jt?"inyectado":no);Ce(L,b.method??"\
|
|
969
|
+
POST",x.pathname,z.status,!0,T.motivo,T.aviso);}else {let T=Te(B instanceof Je?B.elision():null,E),X=x.pathname==="/v1/messages"&&B instanceof Je&&B.negativaNoCobrada();Ae(L,M,E,!1,x.pathname,V,Me,T,Wt,
|
|
970
|
+
U,Le,oe,void 0,void 0,X,vr,ht,B instanceof sn?Fo(x.pathname):void 0),qt(x.pathname,M,V,E,et,he);}h||a(`[gateway] ${b.method} ${x.pathname} \u2192 ${z.status} (stream) \xB7 not metered: no BIVELIO_SERVICE_\
|
|
971
|
+
KEY`);}else if(nt){let E=Buffer.concat(nt),T=Ho(x.pathname,E);if(T===null)Ce(L,b.method??"POST",x.pathname,z.status,!1,"the response carried no usage","uso");else {let X=x.pathname==="/v1/messages"?Gc(E):
|
|
972
|
+
null;Ae(L,M,T,!1,x.pathname,V,Me,Te(X,T),Wt,U,Le,oe,void 0,void 0,ns(x.pathname,E),vr,ht,x.pathname.endsWith(":generateContent")?Fo(x.pathname):void 0),qt(x.pathname,M,V,T,et,he);}}else Xs?Ce(L,b.method??
|
|
973
|
+
"POST",x.pathname,z.status,!1,"the response was too large to read its usage",null):h&&b.method==="POST"&&z.ok&&jt(x.pathname)?Ce(L,b.method,x.pathname,z.status,!1,`the response is neither JSON nor an \
|
|
974
|
+
event stream (content-type: ${gn===""?"none":gn.slice(0,80)})`,null):h&&b.method==="POST"&&z.ok&&!jt(x.pathname)&&!Hl.test(x.pathname)?Ce(L,b.method,x.pathname,z.status,oo,"no usage dialect for this r\
|
|
975
|
+
oute",x.pathname.startsWith("/v1/")?"dialecto":null):a(`[gateway] ${b.method} ${x.pathname} \u2192 ${z.status}${oo?" (stream)":""}`);}catch(H){if(Ze?.abortar(),xe.signal.aborted){let M=!pt&&B?B.usageFinal():
|
|
976
|
+
null;if(M){a(`[gateway] ${b.method} ${x.pathname} \u2192 client closed after the final usage; metered anyway`);let qe=Te(B instanceof Je?B.elision():null,M),ge=x.pathname==="/v1/messages"&&B instanceof
|
|
977
|
+
Je&&B.negativaNoCobrada();Ae(L,Ct,M,false,x.pathname,V,Me,qe,void 0,U,Le,oe,void 0,void 0,ge,void 0,void 0,B instanceof sn?Fo(x.pathname):void 0),qt(x.pathname,Ct,V,M,et,he);}else a(`[gateway] ${b.method}\
|
|
978
|
+
${x.pathname} \u2192 client aborted; upstream cancelled`),B&&eo&&!pt&&P.noMedida("the client closed the stream before the provider's final usage");}else if(a(`[gateway] ${b.method} ${x.pathname} \u2192 err\
|
|
979
|
+
or while serving: ${dn(H)}`),!_.headersSent){_.writeHead(502,{"content-type":"application/json"}),_.end(JSON.stringify({error:"bvsala gateway: stream interrupted",detail:dn(H)}));return}_.writableEnded||
|
|
980
|
+
_.end();}finally{te&&S.noMedido(L,xe.signal.aborted?"the client closed the connection before the provider's final usage":Ve===null?"the request did not get an answer from the provider":`no usage was re\
|
|
981
|
+
ad from the provider's answer (HTTP ${Ve})`);}});dt.on("upgrade",(b,_)=>{a(`[gateway] ${b.method} ${new URL(b.url??"/","http://x").pathname} \u2192 426 (WebSocket not supported; the client falls back to HTT\
|
|
982
|
+
P)`),_.once("error",()=>{}),_.once("finish",()=>_.destroy()),_.end(`HTTP/1.1 426 Upgrade Required\r
|
|
892
983
|
connection: close\r
|
|
893
984
|
content-length: 0\r
|
|
894
985
|
\r
|
|
895
|
-
`);});let
|
|
896
|
-
address().port;return
|
|
897
|
-
fetchImpl}:{},silenceWarnings:true,onEvent:
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
cerrar:async()=>{if(
|
|
901
|
-
|
|
902
|
-
) still in flight after ${
|
|
903
|
-
medicion:()=>
|
|
904
|
-
let n=t.path??process.env.PATH??"",
|
|
905
|
-
".cmd",".bat"]){let a=join(i,e+s);if(
|
|
906
|
-
"api-key"||n==="apikey")return "api-key";if(n==="chatgpt")return "chatgpt";let
|
|
907
|
-
auth_mode=="string"?
|
|
908
|
-
https://api.openai.com",prefijo:"/v1"},chatgpt:{upstream:"https://chatgpt.com",prefijo:"/backend-api/codex"}},
|
|
909
|
-
|
|
910
|
-
a;}let
|
|
911
|
-
{...n,provider:{...
|
|
912
|
-
|
|
913
|
-
meter BYOK with Anthropic, export COPILOT_PROVIDER_TYPE=anthropic, COPILOT_PROVIDER_BASE_URL=https://api.anthropic.com, COPILOT_PROVIDER_API_KEY and
|
|
914
|
-
COPILOT_PROVIDER_TYPE?.trim().toLowerCase()||"openai";if(n==="openai")return {ok:false,error:"`bvsala copilot` wraps the anthropic provider type only for
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
1")===null?`${n} is set but is not a JSON object with an object at provider.anthropic.options, so the wrapper cannot add the gateway's baseURL without
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
args:n,env:{ANTHROPIC_BASE_URL:i},nota:'Qwen Code only routes through here with `security.auth.selectedType: "anthropic"` in ~/.qwen/settings.json (see `bvsala doctor`).'};case "
|
|
924
|
-
a=
|
|
925
|
-
nothing is written to disk. Other providers`+(e==="kilo"?", the Kilo Gateway included,":"")+" go straight to their API and are not metered."}}case "copilot":{let s=
|
|
926
|
-
env:{COPILOT_PROVIDER_BASE_URL:`${i}${s.ruta}`},nota:"BYOK with Anthropic: the gateway routes to api.anthropic.com. Your key and model stay as you exported them."}:{bin:"
|
|
927
|
-
|
|
928
|
-
the gateway (Anthropic ones go direct in this run). "+(s?"Usage injection is on: streamed replies ask for their usage.":"litellm asks for streamed usage only when it talks
|
|
929
|
-
|
|
930
|
-
through the gateway; OpenAI and other providers go direct and are not metered (for OpenAI models: BVSALA_GATEWAY_UPSTREAM=openai bvsala aider)."}}case "
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
{tipo:"
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
986
|
+
`);});let Zn=e.puerto??8402;try{await new Promise((b,_)=>{dt.once("error",_),dt.listen(Zn,"127.0.0.1",()=>b());});}catch(b){h?.stop();let _=b?.code;throw new ws(typeof _=="string"?_:"EUNKNOWN",Zn,b)}let Ks=dt.
|
|
987
|
+
address().port;return d&&f&&e.license&&(R=new Rn({url:`${d}/licenses/revocations`,publicKeyPem:n,snapshot:u,getRefreshAfter:()=>f?.gate.refreshAfter?.(),nowSeconds:()=>Math.floor(c()/1e3),...e.fetchImpl?
|
|
988
|
+
{fetchImpl:e.fetchImpl}:{},silenceWarnings:true,onEvent:b=>{b.type==="rejected"&&fe(`poller:${b.reason}`,`[gateway] revocation list rejected (${b.reason}); known revocations still apply`);},...e.license.
|
|
989
|
+
revocations??{}}),R.start(),e.serviceAccountKey&&($=new Yo({licenseServerUrl:d,serviceAccountKey:e.serviceAccountKey,publicKey:n,revocation:u,current:()=>f.license,onAdopt:b=>{f=fs(b,n,u,c),a(`[gatewa\
|
|
990
|
+
y] renewed license adopted (expires ${ze(b.payload.expires_at)})`),C(J());},onWarning:l,...e.fetchImpl?{fetchImpl:e.fetchImpl}:{},now:c,...e.license.renewal??{}}),$.start({checkNow:e.license.checkOnStart===
|
|
991
|
+
true}))),{puerto:Ks,cerrar:async()=>{if($?.stop(),R?.stop(),g.size>0){let b=[...g];a(`[gateway] closing: waiting for ${b.length} in-flight measurement(s) before draining usage`);let _=e.topeMedicionesAlCerrarMs??
|
|
992
|
+
Mg,L,U=new Promise(q=>{L=setTimeout(()=>q("vencido"),_),L.unref?.();}),K=await Promise.race([Promise.all(b).then(()=>"ok"),U]);clearTimeout(L),K==="vencido"&&l(`[bvsala gateway] shutting down with ${g.
|
|
993
|
+
size} measurement(s) still in flight after ${_} ms: that usage will not reach your dashboard.`);}await h?.stopAndDrain(),await new Promise(b=>dt.close(()=>b()));},licenseStatus:()=>J().state,degradaciones:()=>D.
|
|
994
|
+
contadores(),medicion:()=>P.estado()}}var xs=["claude","codex","goose","qwen","opencode","kilo","copilot","aider","gemini"];function Un(e){return xs.includes(e??"")}function Ss(e,t={}){
|
|
995
|
+
let n=t.path??process.env.PATH??"",o=t.existe??existsSync,r=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(o(a))return {tipo:"exe",ruta:a}}if(r===null)for(let s of [
|
|
996
|
+
".cmd",".bat"]){let a=join(i,e+s);if(o(a)){r=a;break}}}return r!==null?{tipo:"solo-shim",ruta:r}:{tipo:"no-encontrado"}}function Xl(e={}){let n=(e.env??process.env).BVSALA_CODEX_AUTH?.toLowerCase();if(n===
|
|
997
|
+
"api-key"||n==="apikey")return "api-key";if(n==="chatgpt")return "chatgpt";let o=null;try{o=e.leerAuth?e.leerAuth():null;}catch{o=null;}if(o===null)return "api-key";try{let r=JSON.parse(o);return typeof r.
|
|
998
|
+
auth_mode=="string"?r.auth_mode.toLowerCase().replace(/[^a-z]/g,"")==="apikey"?"api-key":"chatgpt":r.tokens!==void 0&&r.tokens!==null?"chatgpt":"api-key"}catch{return "api-key"}}var Bg={"api-key":{upstream:"\
|
|
999
|
+
https://api.openai.com",prefijo:"/v1"},chatgpt:{upstream:"https://chatgpt.com",prefijo:"/backend-api/codex"}},Yl="https://api.anthropic.com",Ql="https://api.openai.com",Ug="https://generativelanguage.\
|
|
1000
|
+
googleapis.com",Zl={opencode:"OPENCODE_CONFIG_CONTENT",kilo:"KILO_CONFIG_CONTENT"};function eu(e,t){let n={};if(e!==void 0&&e.trim()!==""){let a;try{a=JSON.parse(e);}catch{return null}if(typeof a!="obj\
|
|
1001
|
+
ect"||a===null||Array.isArray(a))return null;n=a;}let o=(a,l)=>{let c=a[l];return c===void 0?{}:typeof c=="object"&&c!==null&&!Array.isArray(c)?c:null},r=o(n,"provider"),i=r&&o(r,"anthropic"),s=i&&o(i,
|
|
1002
|
+
"options");return !r||!i||!s?null:JSON.stringify({...n,provider:{...r,anthropic:{...i,options:{...s,baseURL:t}}}})}function tu(e){let t=e.COPILOT_PROVIDER_BASE_URL?.trim()??"";if(t==="")return {ok:false,error:"\
|
|
1003
|
+
Copilot CLI goes through a base URL only with 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 me\
|
|
1004
|
+
ter (its /usage shows those AI credits). To meter BYOK with Anthropic, export COPILOT_PROVIDER_TYPE=anthropic, COPILOT_PROVIDER_BASE_URL=https://api.anthropic.com, COPILOT_PROVIDER_API_KEY and COPILOT\
|
|
1005
|
+
_MODEL, and run `bvsala copilot` again."};let n=e.COPILOT_PROVIDER_TYPE?.trim().toLowerCase()||"openai";if(n==="openai")return {ok:false,error:"`bvsala copilot` wraps the anthropic provider type only for \
|
|
1006
|
+
now. With the openai type (the default) Copilot CLI 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 an\
|
|
1007
|
+
d check the log, see `bvsala doctor`."};if(n!=="anthropic")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 (\
|
|
1008
|
+
Azure, a local model or a reseller bills differently, or not at all), so `bvsala copilot` wraps the anthropic type only."};let o;try{o=new URL(t);}catch{return {ok:false,error:"COPILOT_PROVIDER_BASE_URL is\
|
|
1009
|
+
not a URL: fix it so Copilot CLI works directly first."}}return o.origin!==Yl?{ok:false,error:`COPILOT_PROVIDER_BASE_URL does not point at ${Yl}: the gateway prices only the provider's own API at its li\
|
|
1010
|
+
st price (a local model or a reseller bills differently, or not at all), so it does not wrap it.`}:{ok:true,ruta:o.pathname.replace(/\/+$/,"")}}function nu(e,t=process.env){if(e==="opencode"||e==="kilo"){
|
|
1011
|
+
let n=Zl[e];return eu(t[n],"http://127.0.0.1:1/v1")===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 g\
|
|
1012
|
+
uessing (its value is not shown). Unset it, or use the manual recipe in \`bvsala doctor\`.`:null}if(e==="copilot"){let n=tu(t);return n.ok?null:n.error}return null}function ir(e,t,n,o={},r=process.env){
|
|
1013
|
+
let i=`http://127.0.0.1:${t}`;switch(e){case "claude":return {bin:"claude",args:n,env:{ANTHROPIC_BASE_URL:i,ENABLE_TOOL_SEARCH:r.ENABLE_TOOL_SEARCH??"true"}};case "goose":return {bin:"goose",args:n,env:{ANTHROPIC_HOST:i}};case "\
|
|
1014
|
+
qwen":return {bin:"qwen",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 "\
|
|
1015
|
+
opencode":case "kilo":{let s=Zl[e],a=eu(r[s],`${i}/v1`),l=e==="opencode"?"opencode":"Kilo";return {bin:e,args:n,env:a===null?{}:{[s]:a},nota:`routes ${l}'s \`anthropic\` provider (your Anthropic API key) \
|
|
1016
|
+
through the gateway, with ${s}: 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=tu(r);
|
|
1017
|
+
return s.ok?{bin:"copilot",args:n,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:"\
|
|
1018
|
+
copilot",args:n,env:{}}}case "aider":{if(o.upstreamElegido===Ql){let s=r.BVSALA_GATEWAY_USAGE_INJECT==="1";return {bin:"aider",args:n,env:{OPENAI_BASE_URL:`${i}/v1`,OPENAI_API_BASE:`${i}/v1`},upstream:Ql,
|
|
1019
|
+
nota:"OpenAI models through 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 \
|
|
1020
|
+
to api.openai.com itself: streamed 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},
|
|
1021
|
+
nota:"Anthropic models through the gateway; OpenAI and other providers go direct and are not metered (for OpenAI models: BVSALA_GATEWAY_UPSTREAM=openai bvsala aider)."}}case "gemini":return {bin:"gemini",
|
|
1022
|
+
args:n,env:{GOOGLE_GEMINI_BASE_URL:i},upstream:Ug,nota:"Gemini CLI through the gateway (GOOGLE_GEMINI_BASE_URL): usage is read from the Gemini responses, metered for models with a list price. Your GEM\
|
|
1023
|
+
INI_API_KEY stays yours and never reaches BiVelio."};case "codex":{let s=o.modoCodex??"api-key",a=Bg[s];return {bin:"codex",args:["-c",`openai_base_url="${i}${a.prefijo}"`,...n],env:{},upstream:a.upstream,
|
|
1024
|
+
nota:s==="chatgpt"?"ChatGPT auth detected: the gateway routes to chatgpt.com/backend-api/codex. Subscription traffic is metered at list-price equivalent with no commission (there is no per-token invoi\
|
|
1025
|
+
ce); the per-seat license applies as for any other use.":"API key auth: the gateway routes to api.openai.com/v1."}}}}var Fg=["gateway","doctor","skill","init","mcp"],ou=new Set(["help","--help","-h"]),ru=new Set(["version","--version","-v"]);function iu(e){let[t,...n]=e;return t===void 0||ou.has(t)?{tipo:"ayuda",salida:0}:
|
|
1026
|
+
ru.has(t)?{tipo:"version"}:Un(t)?{tipo:"arrancar",comando:t,resto:n}:Fg.includes(t)?n.some(o=>ou.has(o))?{tipo:"ayuda",salida:0}:n.some(o=>ru.has(o))?{tipo:"version"}:{tipo:"arrancar",comando:t,resto:n}:
|
|
1027
|
+
{tipo:"ayuda",salida:1}}function su(e){return e.length===1&&(e[0]==="--help"||e[0]==="-h"||e[0]==="--version")}function au(e,t,n){let o=e??{},r=typeof o.puerto=="number"?o.puerto:n;if(o.code==="EADDRI\
|
|
1028
|
+
NUSE")return `port ${r} is already in use (another gateway, or a terminal launched earlier?): use --port ${r+1} or stop the other process`;if(o.code==="EACCES")return `port ${r} cannot be opened: permis\
|
|
1029
|
+
sion denied (EACCES; ports below 1024 need privileges): use --port ${Math.max(1024,r)} or higher`;let i=e instanceof Error?e.message:String(e);return `could not start the gateway for \`bvsala ${t}\`: ${i}`}
|
|
1030
|
+
var zg={"--puerto":"--port","--proyecto":"--project","--forzar":"--force"},Vg={BVSALA_GATEWAY_ESFUERZO:"BVSALA_GATEWAY_EFFORT",BVSALA_GATEWAY_MODELO_HERMANO:"BVSALA_GATEWAY_SIBLING_MODEL"};function cu(e,t,{
|
|
1031
|
+
checkEnv:n}){let o=[],r=new Set;for(let i of e){let s=i.split("=")[0],a=zg[s];a===void 0||r.has(s)||(r.add(s),o.push(`[bvsala] ${s} was removed in 0.5: use ${a}.`));}if(n)for(let[i,s]of Object.entries(
|
|
1032
|
+
Vg))t[i]!==void 0&&o.push(`[bvsala] ${i} was removed in 0.5 and is no longer read: rename it to ${s} (same values), or unset it.`);return o}function qg(e){let t=Number.parseInt(e.slice(8,10),10);return Number.isFinite(t)&&t%2===0?"palanca":"control"}function lu(e){let t;try{t=JSON.parse(e());}catch{return null}if(typeof t!="object"||t===null)return null;let n=t,o=n.espia;return typeof o!="number"||!Number.isInteger(o)||o<1||o>65535?null:{activo:n.
|
|
1033
|
+
activo!==false,espia:o}}function uu(e){let{enrolamiento:t,espiaVivo:n,upstreamEnv:o,elisionEnv:r,hoyUtcIso:i}=e;if(!t)return {linea:"",aviso:false};if(!t.activo)return {linea:"A/B plan: enrolment paused (acti\
|
|
942
1034
|
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\
|
|
943
|
-
2:espia\`.`,aviso:true};let s=
|
|
944
|
-
ag"?"--upstream":"the environment";return d.push(
|
|
945
|
-
OFF (2026-09-09): the arm no longer turns them on"),d.push("assignment PER SESSION since 2026-09-10 (brazoDeSesion), not by day parity"),{...
|
|
946
|
-
/messages`, there is one /v1 too many; if you see a bare `POST /messages`, one is missing.",
|
|
1035
|
+
2:espia\`.`,aviso:true};let s=qg(i),a=`http://127.0.0.1:${t.espia}`,l=o!==void 0&&o!=="",c=r!==void 0&&r!=="",d=[];d.push(`A/B plan: ${i} UTC \u2192 arm ${s.toUpperCase()}`);let u=e.upstreamOrigen==="fl\
|
|
1036
|
+
ag"?"--upstream":"the environment";return d.push(l?`upstream kept from ${u} (${o})`:`chained to :${t.espia}`),c&&d.push(`elision flag kept from the environment (=${r})`),d.push("context elision dials \
|
|
1037
|
+
OFF (2026-09-09): the arm no longer turns them on"),d.push("assignment PER SESSION since 2026-09-10 (brazoDeSesion), not by day parity"),{...l?{}:{upstream:a},brazo:s,linea:d.join(", "),aviso:false}}var Jg="check: the gateway log must show `[gateway] POST /v1/messages \u2026`; if you see `/v1/v1\
|
|
1038
|
+
/messages`, there is one /v1 too many; if you see a bare `POST /messages`, one is missing.",Kg=[{id:"claude",nombre:"Claude Code",binario:"claude",configs:[],detectable:true,receta:({base:e})=>["use `bv\
|
|
947
1039
|
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\
|
|
948
1040
|
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\
|
|
949
1041
|
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\
|
|
@@ -978,220 +1070,318 @@ L).',`Base URL: ${e}`]},{id:"continue",nombre:"Continue (cn CLI and IDE extensio
|
|
|
978
1070
|
del id>"," apiKey: <your Anthropic API key>",` apiBase: ${e}`]},{id:"vscode-copilot",nombre:"GitHub Copilot in VS Code (your own key, BYOK)",configs:[],detectable:false,receta:({baseV1:e})=>["mecha\
|
|
979
1071
|
nism: Manage Language Models \u2192 Add Models \u2192 Custom Endpoint, API type Messages; VS Code opens","chatLanguageModels.json. Put the FULL path in the model's url (VS Code uses an explicit /messa\
|
|
980
1072
|
ges path as-is):",`"url": "${e}/messages"`,"BYOK covers chat and utility tasks: inline suggestions and embeddings stay on GitHub and are not metered here."]},{id:"gemini",nombre:"Gemini CLI",binario:"\
|
|
981
|
-
gemini",configs:[join(".gemini","settings.json")],detectable:true,comprobar:null,receta:()=>[
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
nombre:"
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1073
|
+
gemini",configs:[join(".gemini","settings.json")],detectable:true,comprobar:null,receta:({base:e,puerto:t})=>[`one command: bvsala gemini (wraps the CLI: GOOGLE_GEMINI_BASE_URL=${e} and the gateway's ow\
|
|
1074
|
+
n --upstream gemini)`,`manual: start \`bvsala gateway --upstream gemini --port ${t}\`, then run the Gemini CLI with GOOGLE_GEMINI_BASE_URL=${e}`,"The gateway reads usage from :generateContent / :strea\
|
|
1075
|
+
mGenerateContent responses and meters models with a","list price; your GEMINI_API_KEY travels in x-goog-api-key, intact, and never reaches BiVelio."]},{id:"cursor",nombre:"Cursor (your own OpenAI-comp\
|
|
1076
|
+
atible key, BYOK)",binario:"cursor",configs:[".cursor"],detectable:true,comprobar:null,receta:({baseV1:e,puerto:t})=>["mechanism: Cursor \u2192 Settings \u2192 Models \u2192 OpenAI API Base URL override (BYOK: your ow\
|
|
1077
|
+
n API key for OpenAI-compatible models).",`start: bvsala gateway --upstream openai --port ${t} (deepseek, qwen, glm, moonshot and ollama work the same)`,`base URL: ${e} (WITH /v1)`,"Only requests \
|
|
1078
|
+
Cursor sends with YOUR key to that base URL pass through the gateway; its own models go","through Cursor's servers and cannot reach a gateway on 127.0.0.1 (their usage dashboard meters those)."]},{id:"\
|
|
1079
|
+
claude-via-deepseek",nombre:"Claude Code with DeepSeek (its Anthropic-format endpoint)",configs:[],detectable:false,estadoSinDeteccion:"no detection: it is a Claude Code configuration, not a new binary",
|
|
1080
|
+
comprobar:"check: the gateway log must show [gateway] POST /v1/messages \u2192 \u2026 with the model id in the line.",receta:({base:e,puerto:t})=>[`start: bvsala gateway --upstream deepseek --port ${t}\
|
|
1081
|
+
(the gateway rewrites /v1/messages to DeepSeek's /anthropic endpoint)`,`env: ANTHROPIC_BASE_URL=${e} ANTHROPIC_AUTH_TOKEN=<your DeepSeek API key> ANTHROPIC_MODEL=deepseek-flash`,"Why: DeepSee\
|
|
1082
|
+
k cache reads cost $0.003/1M and off-peak input $0.15/1M \u2014 the cheapest sibling for Claude traffic,","served in Anthropic's own protocol. Metered for models with a list price in the catalog."]},{
|
|
1083
|
+
id:"openai-compat-cn",nombre:"DeepSeek, Qwen, GLM, Moonshot \u2014 any OpenAI SDK (Chat Completions)",configs:[],detectable:false,estadoSinDeteccion:"no detection: any language, through the SDK's base UR\
|
|
1084
|
+
L",comprobar:"check: the gateway log must show `[gateway] POST /v1/chat/completions \u2026`; if you see `/v1/v1/chat/completions`, there is one /v1 too many.",receta:({baseV1:e,puerto:t})=>[`start: bv\
|
|
1085
|
+
sala gateway --upstream deepseek --port ${t} (qwen, glm, moonshot, minimax and openrouter work the same: one gateway per upstream)`,`python: client = OpenAI(base_url="${e}", api_key="\u2026") (WITH /v1\
|
|
1086
|
+
: the SDK appends /chat/completions)`,`node: const client = new OpenAI({ baseURL: "${e}" })`,'streaming: pass stream_options={"include_usage": True} or the stream is forwarded but NOT metered; the l\
|
|
1087
|
+
ast chunk then has an empty choices list.',"Metered for models with a list price in the catalog; a model without one is forwarded but not metered."]},{id:"ollama-local",nombre:"Ollama (or vLLM / LM St\
|
|
1088
|
+
udio) \u2014 local open-weight models",configs:[],detectable:false,estadoSinDeteccion:"no detection: any OpenAI SDK, pointed at your local server through the gateway",receta:({baseV1:e,puerto:t})=>[`star\
|
|
1089
|
+
t: bvsala gateway --upstream ollama --port ${t} (vllm \u2192 localhost:8000, lmstudio \u2192 localhost:1234)`,`python: client = OpenAI(base_url="${e}", api_key="ollama") (WITH /v1)`,"Local models \
|
|
1090
|
+
have no list price, so this traffic is forwarded and logged, not metered in dollars:","use it to give coding agents a local free tier while the gateway keeps metering the paid calls."]},{id:"claude-de\
|
|
1091
|
+
sktop",nombre:"Claude Desktop (MCP: estado y coste de la sesi\xF3n)",configs:[],detectable:false,estadoSinDeteccion:"no detection: the recipe is a JSON block for claude_desktop_config.json",receta:({base:e})=>[
|
|
1092
|
+
"mechanism: Claude Desktop \u2192 Settings \u2192 Developer \u2192 Edit Config (claude_desktop_config.json), add this mcpServers entry:",`"mcpServers": { "bvsala": { "command": "bvsala", "args": ["mcp\
|
|
1093
|
+
", "--gateway", "${e}"] } }`,"The MCP server is read-only: gateway status, cost per session and tool-output compaction","decisions, read from the local routes. Metadata only: no request ids, no conten\
|
|
1094
|
+
t."]},{id:"python-openai",nombre:"Python, or any OpenAI SDK (Chat Completions)",configs:[],detectable:false,estadoSinDeteccion:"no detection: any language, through the SDK's base URL",comprobar:"check: t\
|
|
1095
|
+
he gateway log must show `[gateway] POST /v1/chat/completions \u2026`; if you see `/v1/v1/chat/completions`, there is one /v1 too many.",receta:({baseV1:e,puerto:t})=>[`start: bvsala gateway --upstrea\
|
|
1096
|
+
m openai --port ${t} (one gateway per upstream: if Claude Code already uses this port, pick another and change the URL below to match)`,`python: client = OpenAI(base_url="${e}") (WITH /v1: the SDK\
|
|
1097
|
+
appends /chat/completions)`,`node: const client = new OpenAI({ baseURL: "${e}" })`,'streaming: pass stream_options={"include_usage": True} (Node: stream_options: { include_usage: true }) or the str\
|
|
1098
|
+
eam is forwarded but NOT metered; the last chunk then has an empty choices list, so read chunk.choices only when it is not empty.',"stream=False is metered from the usage in the JSON body, and so is c\
|
|
1099
|
+
lient.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",nombre:"\
|
|
1100
|
+
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 gateway --port\
|
|
1101
|
+
${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}" })`,"streame\
|
|
1102
|
+
d and stream=False requests are both metered."]}];function Yg(e,t){let n=e.split(delimiter).filter(r=>r.length>0),o=process.platform==="win32"?["",".exe",".cmd",".bat"]:[""];return r=>n.some(i=>o.some(s=>t(join(
|
|
1103
|
+
i,r+s))))}async function du(e,t={}){if(!Number.isInteger(e)||e<1||e>65535)throw new RangeError(`[bvsala doctor] invalid port: ${String(e)}`);let n=t.home??homedir(),o=t.existe??existsSync,r=t.enPath??Yg(t.path??process.
|
|
1104
|
+
env.PATH??"",o),i=`http://127.0.0.1:${e}`,s=`${i}/v1`,a=[],l=[`bvsala doctor \u2014 local gateway at ${i}`,"Print only: it writes no configuration. Detection by existence (binaries on the PATH and","u\
|
|
1105
|
+
ser configuration files); the contents of a file are never read.","The gateway starts with no keys at all (COMMUNITY mode: every local saving lever on, nothing sent to BiVelio).","BIVELIO_SERVICE_KEY \
|
|
1106
|
+
adds the cloud dashboard, org entitlements and team metering.",""];for(let c of Kg){let d=c.configs.map(v=>join(n,v)),u=c.binario!==void 0&&r(c.binario),f=d.filter(v=>o(v)),m=u||f.length>0;m&&a.push(c.id);
|
|
1107
|
+
let h;c.detectable?m?h=`detected \u2014 ${[...u?[`binary \`${c.binario}\` on PATH`]:[],...f.map(g=>`config present: ${g}`)].join("; ")}`:h="not detected":h=c.estadoSinDeteccion??"no automatic detectio\
|
|
1108
|
+
n (editor extension)",l.push(`\xBB ${c.id}: ${h}`),l.push(` ${c.nombre}`);for(let v of c.receta({base:i,baseV1:s,puerto:e,rutas:d}))l.push(` ${v}`);c.comprobar!==null&&l.push(` ${c.comprobar??Jg}`),
|
|
1109
|
+
l.push("");}return l.push("BYOK 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 OAu\
|
|
1110
|
+
th of a Claude Pro/Max subscription 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, \
|
|
1111
|
+
with no commission (there is 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",
|
|
1112
|
+
"Completions and Responses) 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 Anthropi\
|
|
1113
|
+
c /v1/messages with a PRO license.","Per-terminal detail: docs/terminales/<terminal>.md"),{texto:l.join(`
|
|
1114
|
+
`),detectados:a}}var _s=["ai-sdk","mastra","langchain","anthropic-sdk","sdk"],zn={"ai-sdk":["openai","anthropic"],mastra:["openai","anthropic"],langchain:["openai","anthropic"],"anthropic-sdk":["anthropic"],sdk:["open\
|
|
1115
|
+
ai","anthropic"]},pn={"ai-sdk":"Vercel AI SDK",mastra:"Mastra",langchain:"LangChain.js","anthropic-sdk":"Anthropic TypeScript SDK",sdk:"the SDK directly (no framework)"},Cs={"ai-sdk":"@bivelio/savings\
|
|
1116
|
+
-layer/ai-sdk",mastra:"@bivelio/savings-layer/mastra",langchain:"@bivelio/savings-layer/langchain","anthropic-sdk":"@bivelio/savings-layer/anthropic-sdk",sdk:"@bivelio/savings-layer"},Qg={openai:"gpt-\
|
|
1117
|
+
4o-mini",anthropic:"claude-haiku-4-5"},fu="What is 2 + 2 * 3?",Fn=["// OPEN CORE: no license needed \u2014 the layer runs with every local saving lever on, zero telemetry.","// A license key that IS s\
|
|
1118
|
+
et but invalid still fails closed. For the cloud dashboard,","// team metering and license auto-renewal, add these lines (all optional):","licenseKey: process.env.BIVELIO_LICENSE_KEY || undefined,",'/\
|
|
1119
|
+
/ licenseServerUrl: "https://savings.bivelio.com",',"// serviceAccountKey: process.env.BIVELIO_SERVICE_KEY,"],Xg=["onReport: (report) => {"," seen.calls += 1;"," seen.avoidedLlm = report.calls.avoid\
|
|
1120
|
+
edLlm;"," seen.basis = report.cost.basis;","},"];function mu(e,t){switch(e){case "ai-sdk":return ["ai",t==="openai"?"@ai-sdk/openai":"@ai-sdk/anthropic"];case "mastra":return ["@mastra/core"];case "langch\
|
|
1121
|
+
ain":return ["langchain","@langchain/core",t==="openai"?"@langchain/openai":"@langchain/anthropic"];case "anthropic-sdk":return ["@anthropic-ai/sdk"];case "sdk":return []}}function Ke(e,t){let n=" ".repeat(
|
|
1122
|
+
t);return e.map(o=>o===""?"":n+o)}function ut(e){return e?"export ":""}function fn(e,t){let n=Qg[t];switch(e){case "ai-sdk":{let o=t==="openai"?"openai":"anthropic";return {imports:['import { wrapLangua\
|
|
1123
|
+
geModel } from "ai";',`import { ${o} } from "@ai-sdk/${o}";`,'import { savingsMiddleware } from "@bivelio/savings-layer/ai-sdk";'],adaptador:"savings",construir:(r,i)=>[`${ut(i)}const savings = saving\
|
|
1124
|
+
sMiddleware({`,...Ke([...Fn,...r],2),"});",...i?["","// Pass `model` wherever you pass a model today (generateText, streamText\u2026).","// `savings` goes LAST in the middleware list: nothing between \
|
|
1125
|
+
it and the model."]:[],`${ut(i)}const model = wrapLanguageModel({ model: ${o}("${n}"), middleware: savings });`],exporta:["model"],importsDeUso:['import { generateText } from "ai";','import { getSavin\
|
|
1126
|
+
gsReport } from "@bivelio/savings-layer/ai-sdk";'],llamar:r=>[`const result = await generateText({ model, ${r==="prompt"?"prompt":`prompt: ${r}`} });`,"const text = result.text;","const basis = getSav\
|
|
1127
|
+
ingsReport(result)?.cost.basis;"],daBasis:true,importsDeComprobacion:['import { generateText } from "ai";'],preguntar:r=>[`const { text } = await generateText({ model, prompt: ${r} });`]}}case "mastra":return {
|
|
1128
|
+
imports:['import { Agent } from "@mastra/core/agent";','import { savingsProcessor } from "@bivelio/savings-layer/mastra";'],adaptador:"bivelio",construir:(o,r)=>[`${ut(r)}const bivelio = savingsProces\
|
|
1129
|
+
sor({`,...Ke([...Fn,...o],2),"});",...r?["","// Add `bivelio` LAST to the inputProcessors of each agent you already have;","// this one shows where. Its reports go to `onReport` if you pass one above."]:
|
|
1130
|
+
[],`${ut(r)}const agent = new Agent({`,' id: "assistant",',' name: "Assistant",',' instructions: "Answer briefly.",',` model: "${t}/${n}",`," inputProcessors: [bivelio],","});"],exporta:["agent"],
|
|
1131
|
+
importsDeUso:[],llamar:o=>[`const result = await agent.generate(${o});`,"const text = result.text;"],daBasis:false,importsDeComprobacion:[],preguntar:o=>[`const { text } = await agent.generate(${o});`]};case "\
|
|
1132
|
+
langchain":return {imports:['import { createAgent } from "langchain";','import { savingsAgentMiddleware } from "@bivelio/savings-layer/langchain";'],adaptador:"savings",construir:(o,r)=>[`${ut(r)}const\
|
|
1133
|
+
savings = savingsAgentMiddleware({`,...Ke([...Fn,...o],2),"});",...r?["","// Add `savings` LAST to the middleware of each agent you already have; this one shows where."]:[],`${ut(r)}const agent = cre\
|
|
1134
|
+
ateAgent({ model: "${t}:${n}", tools: [], middleware: [savings] });`],exporta:["agent"],importsDeUso:['import { getSavingsReportFromMessage } from "@bivelio/savings-layer/langchain";'],llamar:o=>[`con\
|
|
1135
|
+
st state = await agent.invoke({ messages: [{ role: "user", content: ${o} }] });`,"const last = state.messages.at(-1);",'const text = last?.text ?? "";',"const basis = getSavingsReportFromMessage(last)\
|
|
1136
|
+
?.cost.basis;"],daBasis:true,importsDeComprobacion:[],preguntar:o=>[`const state = await agent.invoke({ messages: [{ role: "user", content: ${o} }] });`,'const text = state.messages.at(-1)?.text ?? "";']};case "\
|
|
1137
|
+
anthropic-sdk":{let o=i=>`const message = await client.messages.create({ model: "${n}", max_tokens: 1024, messages: [{ role: "user", content: ${i} }] });`,r='const text = message.content.map((block) =\
|
|
1138
|
+
> (block.type === "text" ? block.text : "")).join("");';return {imports:['import Anthropic from "@anthropic-ai/sdk";','import { anthropicSavings } from "@bivelio/savings-layer/anthropic-sdk";'],adaptador:"\
|
|
1139
|
+
claudeSavings",construir:(i,s)=>[`${ut(s)}const claudeSavings = anthropicSavings({`,...Ke([...Fn,...i],2),"});",...s?["","// Use `client` for messages.create(); `claudeSavings.middleware` goes LAST in\
|
|
1140
|
+
the list."]:[],`${ut(s)}const client = new Anthropic({ middleware: [claudeSavings.middleware] });`],exporta:["client","claudeSavings"],importsDeUso:[],llamar:i=>[o(i),r,"const basis = claudeSavings.r\
|
|
1141
|
+
eportFor(message)?.cost.basis;"],daBasis:true,importsDeComprobacion:[],preguntar:i=>[o(i),r]}}case "sdk":{let o=`${t}/${n}`,r=t==="openai"?'provider: new OpenAICompatibleProvider({ baseUrl: "https://api.\
|
|
1142
|
+
openai.com/v1", apiKey: process.env.OPENAI_API_KEY }),':"provider: new AnthropicProvider({ apiKey: process.env.ANTHROPIC_API_KEY }),",i=t==="openai"?"OpenAICompatibleProvider":"AnthropicProvider";return {
|
|
1143
|
+
imports:[t==="openai"?`import { createSavingsLayer, ${i} } from "@bivelio/savings-layer";`:`import { ${i}, createSavingsLayer } from "@bivelio/savings-layer";`],adaptador:"layer",construir:(a,l)=>[...l?
|
|
1144
|
+
["// Your provider. LLM traffic goes straight to it: the layer is not a proxy."]:[],`${ut(l)}const layer = createSavingsLayer({`,...Ke([r,...Fn,...a],2),"});"],exporta:["layer"],importsDeUso:[],llamar:a=>[
|
|
1145
|
+
`const { text, report } = await layer.generate({ model: "${o}", messages: [{ role: "user", content: ${a} }] });`,"const basis = report.cost.basis;"],daBasis:true,importsDeComprobacion:[],preguntar:a=>[`\
|
|
1146
|
+
const { text, report } = await layer.generate({ model: "${o}", messages: [{ role: "user", content: ${a} }] });`]}}}}var Ts=["off","measure","on"];function hu(e,t){return e!=="sdk"?{admite:false,motivo:`t\
|
|
1147
|
+
he ${pn[e]} adapter forwards the request your framework built to the model as it is, and refuses a rewritten one, so the layer has no copy of its own to compact. Only a request the layer sends itself \
|
|
1148
|
+
(createSavingsLayer with AnthropicProvider, without streaming in this pilot) can be compacted`}:t!=="anthropic"?{admite:false,motivo:"this pilot covers Anthropic Messages without streaming, through the S\
|
|
1149
|
+
DK; OpenAI requests stay as they are"}:{admite:true}}var gu=["// Opt-in and lossless: removes only the whitespace between JSON tokens of tool outputs","// that are strict JSON, in the copy sent to the m\
|
|
1150
|
+
odel (your history is not touched).","// Every tool output gets an explained decision in report.toolOutputCompaction.","// Verified for layer.generate() (no streaming). It also runs in generateStream(\
|
|
1151
|
+
): pass","// savings: { toolOutputCompaction: false } on a request to leave it as it is. Delete these lines to revert.",'toolOutputCompaction: { profile: "lossless-data" },'];function bu(){return ["// \
|
|
1152
|
+
BiVelio Savings Layer: MEASURE ONLY, generated by `bvsala init --compaction measure`.","// Nothing sent to the model changes: measureToolOutput returns the tool output exactly as","// it came, and rec\
|
|
1153
|
+
ords what the lossless-data profile WOULD do with it (applied, or","// bypassed and why). Token counts are local estimates, not your provider's count and not","// a saving. Delete this file to stop me\
|
|
1154
|
+
asuring.",'import { compactToolOutput } from "@bivelio/savings-layer";',"","export const measured = { outputs: 0, applied: 0, tokensBefore: 0, tokensAfter: 0, reasons: new Map() };","","// Call it whe\
|
|
1155
|
+
re a tool result is produced, before it goes into your history.",'export function measureToolOutput(output = "") {',' const { decision } = compactToolOutput(output, { profile: "lossless-data" });'," \
|
|
1156
|
+
if (decision) {"," measured.outputs += 1;",' if (decision.status === "applied") measured.applied += 1;'," measured.tokensBefore += decision.tokensBefore;"," measured.tokensAfter += decisi\
|
|
1157
|
+
on.tokensAfter;"," measured.reasons.set(decision.reason, (measured.reasons.get(decision.reason) ?? 0) + 1);"," }"," return output;","}","","// Coverage first: with few outputs applied, there is n\
|
|
1158
|
+
othing to turn on.","export function measuredSummary() {"," const coverage = measured.outputs === 0 ? 0 : measured.applied / measured.outputs;"," return `${measured.applied} of ${measured.outputs} t\
|
|
1159
|
+
ool outputs would be compacted (${Math.round(coverage * 100)}%), ` +"," `${measured.tokensBefore} -> ${measured.tokensAfter} estimated tokens. Reasons: ${JSON.stringify(Object.fromEntries(measured.\
|
|
1160
|
+
reasons))}`;","}",""].join(`
|
|
1161
|
+
`)}var pu=Array.from({length:12},(e,t)=>({id:t,sku:`SKU-${1e3+t}`,stock:t*7,price:1.1+t})),Zg=[{id:"toolu_verify_1",name:"query_inventory",output:JSON.stringify({items:pu},null,2)},{id:"toolu_verify_2",
|
|
1162
|
+
name:"query_prices",output:`{
|
|
1163
|
+
"currency": "USD",
|
|
1164
|
+
"currency": "EUR",
|
|
1165
|
+
"items": ${JSON.stringify(pu,null,2)}
|
|
1166
|
+
}`},{id:"toolu_verify_3",name:"sync_log",output:`sync started
|
|
1167
|
+
fetched 12 rows
|
|
1168
|
+
sync finished in 0.4s
|
|
1169
|
+
`.repeat(8)}],Es=["inventory","prices","syncLog"];function vu(e){let t=e==="on";return [`// BiVelio Savings Layer: tool-output compaction check (${e}), generated by \`bvsala init\`.`,"// ONE call to a \
|
|
1170
|
+
fake model that lives in this file: no network, nothing billed. The","// layer runs in COMMUNITY mode (open core): no license, no licenseServerUrl, no usage","// sent anywhere. It prints the receipt (\
|
|
1171
|
+
applied, or bypassed and why) and the","// coverage of a built-in SAMPLE, which is not your traffic: no saving is promised.","// Delete this file once it says ok.",`import { ${t?"LicenseError, createS\
|
|
1172
|
+
avingsLayer":"LicenseError, compactToolOutput, createSavingsLayer"} } from "@bivelio/savings-layer";`,"",...Zg.map((n,o)=>`const ${Es[o]} = { id: ${JSON.stringify(n.id)}, name: ${JSON.stringify(n.name)}\
|
|
1173
|
+
, output: ${JSON.stringify(n.output)} };`),`const outputs = [${Es.join(", ")}];`,"","// What the fake model received: the checks compare it with the outputs above.","let calls = 0;",'let receivedIds =\
|
|
1174
|
+
"";',"const received = new Map();","const layer = createSavingsLayer({"," provider: {",' id: "bivelio-verify",'," async generate(request) {"," calls += 1;",' const tools = request.me\
|
|
1175
|
+
ssages.filter((m) => m.role === "tool");'," receivedIds = tools.map((m) => m.toolCallId).join();"," for (const m of tools) received.set(m.toolCallId, m.content);",' return { text: "Two \
|
|
1176
|
+
SKUs are low on stock.", usage: { inputTokens: 1000, outputTokens: 8 } };'," },"," },"," licenseKey: process.env.BIVELIO_LICENSE_KEY || undefined,",...t?[' toolOutputCompaction: { profile: "loss\
|
|
1177
|
+
less-data" },']:[],"});","",'const pad = (s = "", n = 0) => s.padEnd(n);',"// Bounded: one call, and 10 s at most.","const timer = setTimeout(() => {",' console.log("not ok: the local call took more \
|
|
1178
|
+
than 10 s");'," process.exit(1);","}, 10_000);","timer.unref();","let ok = false;","try {"," const { report } = await layer.generate({",' model: "anthropic/claude-haiku-4-5",'," messages: [",'\
|
|
1179
|
+
{ role: "system", content: "You are an inventory assistant." },',' { role: "user", content: "Check stock for the spring catalog and tell me what is low." },',' { role: "assistant", con\
|
|
1180
|
+
tent: "", toolCalls: outputs.map((t) => ({ id: t.id, name: t.name, arguments: "{}" })) },',...Es.map(n=>` { role: "tool", toolCallId: ${n}.id, name: ${n}.name, content: ${n}.output },`)," ],",
|
|
1181
|
+
" savings: { exactCache: false },"," });"," clearTimeout(timer);",...t?[" const receipt = report.toolOutputCompaction;"," if (!receipt) {",' throw new Error("the layer did not run tool-outpu\
|
|
1182
|
+
t compaction: is it included in your license (long_context_compression)?");'," }"," const decisions = receipt.decisions;"," console.log(`receipt: report.toolOutputCompaction, profile ${receipt.prof\
|
|
1183
|
+
ile}, tokens ${receipt.tokenBasis} (${receipt.estimator.id})`);"]:[' const decisions = outputs.map((t) => ({ toolCallId: t.id, ...compactToolOutput(t.output, { profile: "lossless-data" }).decision })\
|
|
1184
|
+
);',' console.log("receipt: what lossless-data WOULD do (measure only), tokens estimated");']," for (const d of decisions) {"," console.log(` ${pad(d.toolCallId, 16)} ${pad(d.status, 9)} ${pad(d\
|
|
1185
|
+
.reason, 16)} ${d.tokensBefore} -> ${d.tokensAfter} tokens`);"," }"," // Each check against what the model RECEIVED, not against the receipt.",' const failed = [""].slice(1);'," if (calls !== 1) f\
|
|
1186
|
+
ailed.push(`expected one call to the model, saw ${calls}`);",' if (receivedIds !== outputs.map((t) => t.id).join()) failed.push("tool ids changed");',...t?[]:[' if (report.toolOutputCompaction) fail\
|
|
1187
|
+
ed.push("the layer compacted tool outputs: measure must change nothing");']," for (const t of outputs) {"," const got = received.get(t.id);"," const d = decisions.find((x) => x.toolCallId === t\
|
|
1188
|
+
.id);",...t?[' if (d?.status !== "applied") {'," if (got !== t.output) failed.push(`${t.id} was not sent byte for byte`);",' } else if (!(typeof got === "string" && got.length < t.output.le\
|
|
1189
|
+
ngth && JSON.stringify(JSON.parse(got)) === JSON.stringify(JSON.parse(t.output)))) {'," failed.push(`${t.id} was compacted into something that does not read as the same JSON`);"," }"]:[" if\
|
|
1190
|
+
(got !== t.output) failed.push(`${t.id} was not sent byte for byte`);"," if (!d) failed.push(`${t.id} has no decision`);"]," }",' const applied = decisions.filter((d) => d.status === "applied").\
|
|
1191
|
+
length;'," console.log(`coverage: ${applied} of ${outputs.length} tool outputs (${Math.round((applied / outputs.length) * 100)}%) on this built-in SAMPLE.`);",' console.log("That is not your traffic\
|
|
1192
|
+
, so no saving is promised: measure your own tool outputs (bvsala init --compaction measure).");'," ok = failed.length === 0;",' console.log(ok ? "ok: the receipt matches what the model received." :\
|
|
1193
|
+
`not ok: ${failed.join("; ")}`);',"} catch (err) {"," clearTimeout(timer);"," // Never echo a license error as it is: say which variable to look at, by name."," console.log("," err instanceof L\
|
|
1194
|
+
icenseError",' ? "not ok: BIVELIO_LICENSE_KEY is set but does not verify. Fix it or unset it (without a key the layer runs in COMMUNITY mode). Copy a valid key from https://savings.bivelio.com/da\
|
|
1195
|
+
shboard/install."'," : `not ok: ${err instanceof Error ? err.message : String(err)}`,"," );","} finally {"," layer.close();","}","if (!ok) process.exitCode = 1;",""].join(`
|
|
1196
|
+
`)}function Vn(e,t,n=[]){let o=fn(e,t);return ["// BiVelio Savings Layer: created once, when this module loads, and reused by every","// request. The exact cache lives in this instance, so do not creat\
|
|
1197
|
+
e one per request.",...o.imports,"",...o.construir(n,true),""].join(`
|
|
1198
|
+
`)}var yu=["// 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 \
|
|
1199
|
+
is not called and your provider bills nothing for it.","// The saving is `estimated`, and estimated savings are never billed. Open core:","// no keys are needed \u2014 the layer runs in COMMUNITY mode with\
|
|
1200
|
+
zero telemetry.","// Delete this file once it says ok."];function ku(e){return e==="sdk"?['const ok = text.trim() === "8" && report.calls.avoidedLlm === 1;',"const line = ok",' ? `ok: the layer answ\
|
|
1201
|
+
ered "8" on this machine without calling 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.`;"]:
|
|
1202
|
+
['const ok = text.trim() === "8" && seen.avoidedLlm === 1;',"const line = ok",' ? `ok: the layer answered "8" on this machine without calling the model (basis: ${seen.basis}).`'," : seen.calls === 0",
|
|
1203
|
+
' ? "not ok: the layer did not 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 thi\
|
|
1204
|
+
s output to support@bivelio.com.`;"]}function wu(e,t){let n=fn(e,t),o=Rs([...n.importsDeComprobacion,...n.imports]),r=e==="sdk"?n.construir([],false):['const seen = { calls: 0, avoidedLlm: 0, basis: "" }\
|
|
1205
|
+
;',...n.construir(Xg,false)];return {imports:o,cuerpo:r}}function Rs(e){let t=new Map,n=[];for(let o of e){let r=/^import \{ ([^}]+) \} from "([^"]+)";$/.exec(o);if(!r){n.includes(o)||n.push(o);continue}let[
|
|
1206
|
+
,i="",s=""]=r,a=t.get(s);a||(a=new Set,t.set(s,a),n.push({modulo:s}));for(let l of i.split(", "))a.add(l);}return n.map(o=>typeof o=="string"?o:`import { ${[...t.get(o.modulo)??[]].sort().join(", ")} }\
|
|
1207
|
+
from "${o.modulo}";`)}function xu(e,t){let n=fn(e,t),{imports:o,cuerpo:r}=wu(e,t);return [...yu,...o,"",...r,"","try {",...Ke([...n.preguntar(JSON.stringify(fu)),...ku(e),"console.log(line);","if (!ok\
|
|
1208
|
+
) process.exitCode = 1;"],2),"} catch (err) {"," console.log(`not ok: ${err instanceof Error ? err.message : String(err)}`);"," process.exitCode = 1;","} finally {",` ${n.adaptador}.close();`,"}",""].
|
|
1209
|
+
join(`
|
|
1210
|
+
`)}function Su(e,t){let n=fn(e,t),{imports:o,cuerpo:r}=wu(e,t);return [...yu,"// It answers only in development: in production it is a 404.",...o,"","// Run on each request, never at build time.",'expo\
|
|
1211
|
+
rt const dynamic = "force-dynamic";',"","export async function GET() {",' if (process.env.NODE_ENV === "production") {',' return new Response("Not found", { status: 404 });'," }",...Ke(r,2)," tr\
|
|
1212
|
+
y {",...Ke([...n.preguntar(JSON.stringify(fu)),...ku(e),"return Response.json({ ok, message: line }, { status: ok ? 200 : 500 });"],4)," } catch (err) {"," return Response.json({ ok: false, messag\
|
|
1052
1213
|
e: `not ok: ${err instanceof Error ? err.message : String(err)}` }, { status: 500 });"," } finally {",` ${n.adaptador}.close();`," }","}",""].join(`
|
|
1053
|
-
`)}function
|
|
1054
|
-
async function POST(req${n.ts?": Request":""}) {`,` const { prompt } = ${n.ts?"(await req.json()) as { prompt: string }":"await req.json()"};`,...
|
|
1214
|
+
`)}function Eu(e,t,n){let o=fn(e,t),r=o.daBasis?"{ text, basis }":"{ text }";return [...Rs(o.importsDeUso),`import { ${o.exporta.slice().sort().join(", ")} } from "${n.importeDelCableado}";`,"",`export\
|
|
1215
|
+
async function POST(req${n.ts?": Request":""}) {`,` const { prompt } = ${n.ts?"(await req.json()) as { prompt: string }":"await req.json()"};`,...Ke(o.llamar("prompt"),2),` return Response.json(${r}\
|
|
1055
1216
|
);`,"}",""].join(`
|
|
1056
|
-
`)}function
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
`)}var
|
|
1060
|
-
for(let
|
|
1061
|
-
json=true;else if(
|
|
1062
|
-
${
|
|
1063
|
-
${
|
|
1064
|
-
${
|
|
1065
|
-
${
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1217
|
+
`)}function sr(e,t,n=[]){let o=fn(e,t),r=o.daBasis?"{ text, basis }":"{ text }";return ['import express from "express";',...Rs([...o.imports,...o.importsDeUso]),"","// Created once, at startup, not ins\
|
|
1218
|
+
ide the handler: the exact cache lives in this instance.",...o.construir(n,false),"","const app = express();","app.use(express.json());","",'app.post("/api/chat", async (req, res, next) => {'," try {",...Ke(
|
|
1219
|
+
o.llamar('String(req.body?.prompt ?? "")'),4),` res.json(${r});`," } catch (err) {"," next(err);"," }","});","","app.listen(Number(process.env.PORT ?? 3000));",""].join(`
|
|
1220
|
+
`)}var qn="usage: bvsala init [--write [--yes]] [--json] [--stack ai-sdk|mastra|langchain|anthropic-sdk|sdk] [--provider openai|anthropic] [--compaction off|measure|on] [--cwd <dir>]";function Au(e,t){let n={
|
|
1221
|
+
cwd:t,escribir:false,si:false,json:false};for(let o=0;o<e.length;o++){let r=e[o],i=()=>{let s=e[o+1];if(!(s===void 0||s.startsWith("-")))return o++,s};if(r==="--write")n.escribir=true;else if(r==="--yes"||r==="-\
|
|
1222
|
+
y")n.si=true;else if(r==="--json")n.json=true;else if(r==="--stack"){let s=i();if(!s||!_s.includes(s))return {ok:false,mensaje:`--stack needs one of: ${_s.join(", ")}.
|
|
1223
|
+
${qn}`};n.capa=s;}else if(r==="--provider"){let s=i();if(s!=="openai"&&s!=="anthropic")return {ok:false,mensaje:`--provider needs openai or anthropic.
|
|
1224
|
+
${qn}`};n.proveedor=s;}else if(r==="--compaction"){let s=i();if(!s||!Ts.includes(s))return {ok:false,mensaje:`--compaction needs one of: ${Ts.join(", ")}.
|
|
1225
|
+
${qn}`};n.compactacion=s;}else if(r==="--cwd"){let s=i();if(!s)return {ok:false,mensaje:`--cwd needs a directory.
|
|
1226
|
+
${qn}`};n.cwd=s.startsWith("/")||/^[A-Za-z]:[\\/]/.test(s)?s:join(t,s);}else return {ok:false,mensaje:`unknown option: ${r}
|
|
1227
|
+
${qn}`}}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 \
|
|
1228
|
+
--yes."}:n.capa&&n.proveedor&&!zn[n.capa].includes(n.proveedor)?{ok:false,mensaje:`--stack ${n.capa} only works with --provider ${zn[n.capa].join(" or ")}.`}:{ok:true,valor:n}}var eb=[["pnpm-lock.yaml","pn\
|
|
1229
|
+
pm"],["yarn.lock","yarn"],["bun.lock","bun"],["bun.lockb","bun"],["package-lock.json","npm"]];function tb(e,t,n){if(typeof e.packageManager=="string"){let o=e.packageManager.split("@")[0];if(o==="pnpm"||
|
|
1230
|
+
o==="yarn"||o==="bun"||o==="npm")return o}for(let o=t,r=0;r<20;r++){for(let[s,a]of eb)if(n.existe(join(o,s)))return a;let i=dirname(o);if(i===o)break;o=i;}return "npm"}function nb(e){let t={};for(let n of [e.devDependencies,
|
|
1231
|
+
e.dependencies])if(n&&typeof n=="object")for(let[o,r]of Object.entries(n))typeof r=="string"&&(t[o]=r);return t}function ob(e,t,n,o){let r=o.leer(join(n,"node_modules",...e.split("/"),"package.json"));if(r)
|
|
1232
|
+
try{let s=JSON.parse(r).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(
|
|
1233
|
+
t)))return `${i[1]}.${i[2]??0}.${i[3]??0}`}function Is(e){let[t=0,n=0,o=0]=e.split(/[.+-]/).map(r=>Number.parseInt(r,10)||0);return [t,n,o]}function Ds(e,t){let n=Is(e),o=Is(t);for(let r=0;r<3;r++)if(n[r]!==
|
|
1234
|
+
o[r])return n[r]>o[r];return true}var Iu=[{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\
|
|
1073
1235
|
\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\
|
|
1074
|
-
angchain/core \u2265 1.1 < 2"},{paquete:"@anthropic-ai/sdk",capa:"anthropic-sdk",desde:"0.103.0",hasta:"1.0.0",texto:"@anthropic-ai/sdk \u2265 0.103 < 1"}],
|
|
1075
|
-
langchain"],["ai","ai-sdk"],["@anthropic-ai/sdk","anthropic-sdk"],["openai","sdk"]];function
|
|
1236
|
+
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"}],Du=[["@mastra/core","mastra"],["langchain","\
|
|
1237
|
+
langchain"],["ai","ai-sdk"],["@anthropic-ai/sdk","anthropic-sdk"],["openai","sdk"]];function Pu(e,t){let n=t.leer(join(e,"package.json"));if(n===void 0){let u=["pyproject.toml","requirements.txt","setup\
|
|
1076
1238
|
.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\
|
|
1077
1239
|
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\
|
|
1078
|
-
rints the recipe for each SDK.`}:{ok:false,mensaje:`no package.json in ${e}. Run this from your project's root, or pass --cwd <dir>.`}}let
|
|
1079
|
-
kage.json")} is not valid JSON (${u instanceof Error?u.message:String(u)}). Fix it and run init again.`}}if(!
|
|
1080
|
-
t a JSON object. Fix it and run init again.`};let
|
|
1081
|
-
xpress"in i?"express":"node",
|
|
1082
|
-
e,"src")),capas:
|
|
1083
|
-
d=a==="node"?void 0:i[a];return d&&(
|
|
1084
|
-
var
|
|
1240
|
+
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 o;try{o=JSON.parse(n);}catch(u){return {ok:false,mensaje:`${join(e,"pac\
|
|
1241
|
+
kage.json")} is not valid JSON (${u instanceof Error?u.message:String(u)}). Fix it and run init again.`}}if(!o||typeof o!="object"||Array.isArray(o))return {ok:false,mensaje:`${join(e,"package.json")} is no\
|
|
1242
|
+
t a JSON object. Fix it and run init again.`};let r=nb(o),i={};for(let[u,f]of Object.entries(r))i[u]=ob(u,f,e,t);let s=["app","src/app"].find(u=>t.existe(join(e,...u.split("/")))),a="next"in i?"next":"e\
|
|
1243
|
+
xpress"in i?"express":"node",l=Du.filter(([u])=>u in i).map(([,u])=>u),c={dir:e,gestor:tb(o,e,t),ts:"typescript"in i||t.existe(join(e,"tsconfig.json")),esm:o.type==="module",anfitrion:a,src:t.existe(join(
|
|
1244
|
+
e,"src")),capas:l,deps:i,monorepo:o.workspaces!==void 0||t.existe(join(e,"pnpm-workspace.yaml")),ficherosEnv:[".env",".env.local"].filter(u=>t.existe(join(e,u))),scriptDev:typeof o.scripts?.dev=="string"},
|
|
1245
|
+
d=a==="node"?void 0:i[a];return d&&(c.versionDelAnfitrion=d),a==="next"&&s&&(c.appDir=s),"@bivelio/savings-layer"in r&&(c.yaInstalado=i["@bivelio/savings-layer"]??r["@bivelio/savings-layer"]),{ok:true,valor:c}}
|
|
1246
|
+
var Cu=(e,t)=>t.some(n=>n in e.deps),rb=["openai","@ai-sdk/openai","@langchain/openai"],ib=["@anthropic-ai/sdk","@ai-sdk/anthropic","@langchain/anthropic"];function sb(e,t){if(e==="anthropic-sdk")return "\
|
|
1085
1247
|
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\
|
|
1086
|
-
ain/anthropic"in t.deps)return "anthropic"}return
|
|
1087
|
-
|
|
1088
|
-
`node --env-file=${t} bivelio-check.mjs`:"node bivelio-check.mjs"}function
|
|
1089
|
-
. Upgrade Node and run init again.`};let
|
|
1090
|
-
i=
|
|
1248
|
+
ain/anthropic"in t.deps)return "anthropic"}return Cu(t,ib)&&!Cu(t,rb)?"anthropic":"openai"}function Tu(e,t){for(let n of Iu){if(n.capa!==e)continue;let o=t.deps[n.paquete];if(o!==void 0&&(!Ds(o,n.desde)||
|
|
1249
|
+
Ds(o,n.hasta)))return `${n.paquete} ${o} is outside what the adapter supports (${n.texto})`}}var As={npm:"npm i",pnpm:"pnpm add",yarn:"yarn add",bun:"bun add"};function ab(e){let t=e.ficherosEnv[0];return t?
|
|
1250
|
+
`node --env-file=${t} bivelio-check.mjs`:"node bivelio-check.mjs"}function Ou(e,t,n){let[o=0]=Is(n.node);if(o<20)return {ok:false,mensaje:`Node ${n.node} is too old: @bivelio/savings-layer needs Node \u2265 20\
|
|
1251
|
+
. Upgrade Node and run init again.`};let r=[],i=t.capa,s=[];if(i){let h=Tu(i,e);h&&r.push(`${h}: the snippets below will not work until you upgrade it.`);}else for(let h of e.capas){let v=Tu(h,e);if(!v){
|
|
1252
|
+
i=h;break}s.push({capa:h,motivo:v});}i||(i="sdk",e.capas.length===0&&r.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\
|
|
1091
1253
|
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`."));
|
|
1092
|
-
for(let
|
|
1093
|
-
gestor]} ${
|
|
1094
|
-
savings-layer");for(let
|
|
1095
|
-
"0.4.25")&&
|
|
1096
|
-
"7"))&&
|
|
1254
|
+
for(let h of s){let v=Iu.find(g=>g.capa===h.capa&&h.motivo.startsWith(`${g.paquete} `))?.paquete??"";r.push(`${h.motivo}: showing ${pn[i]} instead. To use the ${pn[h.capa]} adapter, upgrade it: ${As[e.
|
|
1255
|
+
gestor]} ${v}@latest`);}let a=t.proveedor??sb(i,e);if(!zn[i].includes(a))return {ok:false,mensaje:`--stack ${i} only works with --provider ${zn[i].join(" or ")}.`};let l=[];e.yaInstalado||l.push("@bivelio/\
|
|
1256
|
+
savings-layer");for(let h of mu(i,a))h in e.deps||l.push(h);a==="openai"&&!("gpt-tokenizer"in e.deps)&&l.push("gpt-tokenizer");let c=e.deps["@bivelio/savings-layer"];e.yaInstalado&&i!=="sdk"&&c&&!Ds(c,
|
|
1257
|
+
"0.4.25")&&r.push(`@bivelio/savings-layer ${c} has no framework adapters (they arrived in 0.4.25): ${As[e.gestor]} @bivelio/savings-layer@latest`),o<22&&(i==="mastra"||i==="ai-sdk"&&(e.deps.ai??"7").startsWith(
|
|
1258
|
+
"7"))&&r.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"&&r.push('Your package.json has no "type": "module\
|
|
1097
1259
|
" and the package is ESM-only. The check is a .mjs file and runs as is; from your own CommonJS files, load it with `await import(\u2026)`, or with require() on Node \u2265 22.');let d=[{nombre:"BIVELI\
|
|
1098
|
-
O_LICENSE_KEY",puesta:n.env("BIVELIO_LICENSE_KEY"),para:"
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
"your provider key; the free check does not need it";d.push({nombre:
|
|
1102
|
-
|
|
1103
|
-
it to node with --env-file (Node \u2265 20.6).",f={deteccion:e,capa:i,proveedor:a,
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1260
|
+
O_LICENSE_KEY",puesta:n.env("BIVELIO_LICENSE_KEY"),para:"OPTIONAL (open core): without it the layer runs in COMMUNITY mode with every local lever on; a key adds cloud dashboard + team metering"},{nombre:"\
|
|
1261
|
+
BIVELIO_SERVICE_KEY",puesta:n.env("BIVELIO_SERVICE_KEY"),para:"OPTIONAL: seat metering, license auto-renewal and the cloud dashboard"}];if(i==="anthropic-sdk")d.push({nombre:"ANTHROPIC_API_KEY",puesta:n.
|
|
1262
|
+
env("ANTHROPIC_API_KEY")||n.env("ANTHROPIC_AUTH_TOKEN"),para:"needed even by the free check: the Anthropic SDK builds no request without credentials"});else {let h=a==="openai"?"OPENAI_API_KEY":"ANTHRO\
|
|
1263
|
+
PIC_API_KEY",v=i==="mastra"?"your provider key; the free check works without it, but Mastra logs a warning with a stack trace":"your provider key; the free check does not need it";d.push({nombre:h,puesta:n.
|
|
1264
|
+
env(h),para:v});}let u=e.anfitrion==="next"?"Put them in .env.local (Next.js loads it) or in your host's environment settings.":e.ficherosEnv.length>0?`Export them, or keep them in ${e.ficherosEnv[0]} \
|
|
1265
|
+
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 it to node with --env-file (Node \u2265 20.6).",f={deteccion:e,capa:i,proveedor:a,
|
|
1266
|
+
alternativas:e.capas.filter(h=>h!==i),instalar:l,claves:d,dondeVanLasClaves:u,ficheros:[],usos:[],comoComprobar:[],avisos:r};l.length>0&&(f.comandoDeInstalacion=`${As[e.gestor]} ${l.join(" ")}`);let m=t.
|
|
1267
|
+
compactacion??"off";if(m!=="off"){let h=hu(i,a);f.compactacion={pedido:m,efectivo:m==="on"&&!h.admite?"off":m,admite:h.admite,...h.admite?{}:{motivo:h.motivo}};}return {ok:true,valor:f}}function Lu(e,t){let n=e.
|
|
1268
|
+
deteccion,{capa:o,proveedor:r}=e,i=n.ts?"ts":n.esm||n.anfitrion==="next"?"js":"mjs",s=v=>t.existe(join(n.dir,...v.split("/"))),a=[],l=[],c=[],d=n.anfitrion==="next"?`${n.appDir?.startsWith("src/")?"src/":
|
|
1269
|
+
""}lib/savings.${i}`:`${n.src?"src/":""}savings.${i}`,u=e.compactacion?.efectivo==="on",f=u?gu:[];if(n.anfitrion==="next"&&n.appDir){a.push({ruta:d,proposito:"wiring",contenido:Vn(o,r,f),existe:s(d)});
|
|
1270
|
+
let v=`${n.appDir}/api/chat/route.${i}`,g=posix.relative(posix.dirname(v),d.replace(/\.[^.]+$/,""));l.push({titulo:`Use it in a route handler (example: ${v})`,ruta:v,contenido:Eu(o,r,{ts:n.ts,importeDelCableado:g.
|
|
1271
|
+
startsWith(".")?g:`./${g}`})});let y=`${n.appDir}/api/bivelio-check/route.${i}`;a.push({ruta:y,proposito:"check",contenido:Su(o,r),existe:s(y)});let k=n.scriptDev?n.gestor==="npm"?"npm run dev":`${n.gestor}\
|
|
1272
|
+
dev`:"next dev";c.push(`Start your dev server (${k}) and open http://localhost:3000/api/bivelio-check (or your dev port).`,'It answers {"ok":true,\u2026} when the layer is in place, and a message that say\
|
|
1273
|
+
s what to fix when it is not.');}else n.anfitrion==="express"?l.push({titulo:"In your Express server: the layer is created once at startup, then used by the route",ruta:`server.${i}`,contenido:sr(o,r,f)}):
|
|
1274
|
+
a.push({ruta:d,proposito:"wiring",contenido:Vn(o,r,f),existe:s(d)}),a.push({ruta:"bivelio-check.mjs",proposito:"check",contenido:xu(o,r),existe:s("bivelio-check.mjs")}),c.push(`Run it: ${ab(n)}`,'It p\
|
|
1275
|
+
rints "ok: \u2026" and exits 0 when the layer is in place, or "not ok: \u2026" with what to fix and exits 1.');let m=[...e.avisos];n.anfitrion==="next"&&!n.appDir&&m.push("No app/ directory (Pages Rou\
|
|
1276
|
+
ter?): the check is a script instead of a route. The wiring works the same from an API route."),c.push("The question (2 + 2 * 3) is answered on your machine: with the layer in place the model is not c\
|
|
1277
|
+
alled, so your provider bills nothing for it,","and the saving is `estimated`, which is never billed. Delete the check once it says ok.");let h=e.compactacion;if(h?.efectivo==="measure"){let g=`${n.anfitrion===
|
|
1278
|
+
"next"?`${n.appDir?.startsWith("src/")?"src/":""}lib/`:n.src?"src/":""}measure-tool-outputs.${i}`;a.push({ruta:g,proposito:"measure",contenido:bu(),existe:s(g)});}if(h){let v="bivelio-verify-compaction\
|
|
1279
|
+
.mjs",g=h.efectivo==="on"?"on":"measure";a.push({ruta:v,proposito:"verify",contenido:vu(g),existe:s(v)});}if(u&&h){let v=n.anfitrion==="express",g=v?`server.${i}`:d,y=v?sr(o,r):Vn(o,r),k=v?sr(o,r,f):Vn(
|
|
1280
|
+
o,r,f);h={...h,diff:cb(g,y,k)};}return {...e,ficheros:a,usos:l,comoComprobar:c,avisos:m,...h?{compactacion:h}:{}}}function cb(e,t,n,o=3){let i=y=>{if(y==="")return [];if(y.endsWith(`
|
|
1281
|
+
`))return y.slice(0,-1).split(`
|
|
1282
|
+
`);let k=y.split(`
|
|
1283
|
+
`);return k[k.length-1]+="\0",k},s=i(t),a=i(n),l=0;for(;l<s.length&&l<a.length&&s[l]===a[l];)l++;let c=s.length,d=a.length;for(;c>l&&d>l&&s[c-1]===a[d-1];)c--,d--;if(l===s.length&&l===a.length)return "";
|
|
1284
|
+
let u=Math.max(0,l-o),f=Math.min(s.length,c+o),m=Math.min(a.length,d+o),h=y=>k=>k.endsWith("\0")?[`${y}${k.slice(0,-1)}`,"\"]:[`${y}${k}`],v=y=>`${y===0?u:u+1},${y}`;return `${[
|
|
1285
|
+
`--- a/${e}`,`+++ b/${e}`,`@@ -${v(f-u)} +${v(m-u)} @@`,...s.slice(u,l).flatMap(h(" ")),...s.slice(l,c).flatMap(h("-")),...a.slice(l,d).flatMap(h("+")),...s.slice(c,f).flatMap(h(" "))].join(`
|
|
1286
|
+
`)}
|
|
1287
|
+
`}function mn(e,t){let n="-".repeat(Math.max(8,Math.min(72,e.length+12)));return `----- ${e} -----
|
|
1115
1288
|
${t.replace(/\n$/,"")}
|
|
1116
|
-
${n}`}function
|
|
1117
|
-
push(`Express${e.versionDelAnfitrion?` ${e.versionDelAnfitrion}`:""}`):t.push("Node.js"),t.push(e.ts?"TypeScript":e.esm?"JavaScript (ESM)":"JavaScript (CommonJS)"),t.push(e.gestor),t.join(", ")}function
|
|
1118
|
-
let t=e.deteccion,n=
|
|
1119
|
-
yet)"} with ${e.proveedor==="openai"?"OpenAI":"Anthropic"} models \u2192 ${
|
|
1120
|
-
${
|
|
1121
|
-
alled: @bivelio/savings-layer ${u??`(declared as "${
|
|
1289
|
+
${n}`}function lb(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.
|
|
1290
|
+
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 ub(e){
|
|
1291
|
+
let t=e.deteccion,n=Du.find(([,s])=>s===e.capa)?.[0],o=n?t.deps[n]:void 0,r=t.capas.includes(e.capa);return `${`${pn[e.capa]}${r&&o&&e.capa!=="sdk"?` ${o}`:""}`}${r||e.capa==="sdk"?"":" (not installed \
|
|
1292
|
+
yet)"} with ${e.proveedor==="openai"?"OpenAI":"Anthropic"} models \u2192 ${Cs[e.capa]}`}function Mu(e,t,n,o={}){let r=e.deteccion,i=[t,"",`Detected in ${r.dir}`,` app: ${lb(r)}`,` LLM calls: \
|
|
1293
|
+
${ub(e)}`];if(e.alternativas.length>0&&i.push(` also found: ${e.alternativas.map(u=>`${pn[u]} (${n} --stack ${u})`).join(", ")}`),r.yaInstalado){let u=r.deps["@bivelio/savings-layer"];i.push(` inst\
|
|
1294
|
+
alled: @bivelio/savings-layer ${u??`(declared as "${r.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}`:
|
|
1122
1295
|
" 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.
|
|
1123
|
-
map(u=>u.nombre.length));for(let u of e.claves)i.push(` ${u.nombre.padEnd(a)} ${u.puesta?"set ":"not set"} ${u.para}`);i.push("
|
|
1124
|
-
|
|
1125
|
-
i.push("",`${s++} \xB7 Wire it`),
|
|
1126
|
-
find(u=>u.proposito==="check");i.push("",`${s++} \xB7 Check it, for free`),
|
|
1127
|
-
i.push(` ${u}`);
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
already
|
|
1135
|
-
|
|
1136
|
-
"
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1296
|
+
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(" OPEN CORE: no keys are required \u2014 without them the layer runs in \
|
|
1297
|
+
COMMUNITY mode with every local lever on"," and nothing sent to BiVelio. The BiVelio keys (https://savings.bivelio.com/dashboard/install) add the cloud"," dashboard, team metering and license auto-r\
|
|
1298
|
+
enewal.",` ${e.dondeVanLasClaves}`);let l=e.ficheros.find(u=>u.proposito==="wiring");i.push("",`${s++} \xB7 Wire it`),l&&i.push(mn(`${l.ruta} (new file${l.existe?"; it already exists, compare it":""}\
|
|
1299
|
+
)`,l.contenido));for(let u of e.usos)i.push(mn(u.titulo,u.contenido));let c=e.ficheros.find(u=>u.proposito==="check");i.push("",`${s++} \xB7 Check it, for free`),c&&i.push(mn(`${c.ruta} (new file${c.existe?
|
|
1300
|
+
"; it already exists, compare it":""})`,c.contenido));for(let u of e.comoComprobar)i.push(` ${u}`);e.compactacion&&i.push("",`${s++} \xB7 Tool-output compaction (opt-in, lossless)`,...db(e,n));let d=e.
|
|
1301
|
+
ficheros.filter(u=>!u.existe);return o.escribira||(i.push(""),d.length>0?i.push(`Nothing was written. To create ${d.length===1?"the new file":`the ${d.length} new files`} above (${d.map(u=>u.ruta).join(
|
|
1302
|
+
", ")}): ${n}${e.compactacion?` --compaction ${e.compactacion.pedido}`:""} --write. It asks first and never overwrites; nothing else is touched.`):i.push("Nothing was written: the files above already \
|
|
1303
|
+
exist in your project.")),i.join(`
|
|
1304
|
+
`)}function db(e,t){let n=e.compactacion,o=[];if(n.efectivo==="on")o.push(" ON in the wiring above. This is the whole change, as a diff to review:",mn("diff",n.diff??"")," To revert: delete those li\
|
|
1305
|
+
nes (or pass savings: { toolOutputCompaction: false } on one request)."," Only strict-JSON tool outputs change, and only their whitespace; system, user and assistant text,"," tool ids and arguments \
|
|
1306
|
+
are never touched. Each request's report says, per tool output, applied or"," bypassed and why (report.toolOutputCompaction). Token counts there are estimates, not a saving."),(e.deteccion.anfitrion===
|
|
1307
|
+
"express"||e.ficheros.some(i=>i.proposito==="wiring"&&i.existe))&&o.push(" If you already have this file, add only the + lines to your createSavingsLayer options.");else if(n.efectivo==="measure"){let i=e.
|
|
1308
|
+
ficheros.find(s=>s.proposito==="measure");o.push(" MEASURE ONLY: nothing sent to the model changes, and the wiring above is the usual one.",mn(`${i.ruta} (new file${i.existe?"; it already exists, com\
|
|
1309
|
+
pare it":""})`,i.contenido)," Pass each tool output through measureToolOutput() where it is produced; it returns it unchanged."," measuredSummary() prints the coverage first: how many outputs would \
|
|
1310
|
+
be compacted, and why the others not.",n.admite?` When the coverage justifies it, ${t} --compaction on adds the one option that turns it on.`:` Turning it on is not available for this stack: ${n.motivo}\
|
|
1311
|
+
.`);}else o.push(` NOT turned on: ${n.motivo}.`," Nothing in the wiring above changed.",` You can still measure it without changing anything: ${t} --compaction measure`);let r=e.ficheros.find(i=>i.proposito===
|
|
1312
|
+
"verify");if(r){let i=e.deteccion.ficherosEnv[0];o.push(mn(`${r.ruta} (new file${r.existe?"; it already exists, compare it":""})`,r.contenido),` Verify it: ${i?`node --env-file=${i} ${r.ruta}`:`node ${r.
|
|
1313
|
+
ruta}`}`," ONE call to a fake model inside that file: no network, nothing billed. It prints the receipt"," (applied, or bypassed and why) and the coverage of a built-in sample, which is not your tra\
|
|
1314
|
+
ffic.");}return o}function $u(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,
|
|
1315
|
+
esm:n.esm,packageManager:n.gestor,stacks:n.capas,installed:n.yaInstalado?n.deps["@bivelio/savings-layer"]??n.yaInstalado:null},stack:e.capa,provider:e.proveedor,adapter:Cs[e.capa],install:e.comandoDeInstalacion??
|
|
1316
|
+
null,keys:e.claves.map(o=>({name:o.nombre,set:o.puesta,purpose:o.para})),files:e.ficheros.map(o=>({path:o.ruta,purpose:o.proposito,exists:o.existe,content:o.contenido})),snippets:e.usos.map(o=>({title:o.
|
|
1317
|
+
titulo,content:o.contenido})),check:e.comoComprobar,notes:e.avisos,...e.compactacion?{toolOutputCompaction:{requested:e.compactacion.pedido,effective:e.compactacion.efectivo,supported:e.compactacion.admite,
|
|
1318
|
+
reason:e.compactacion.motivo??null,diff:e.compactacion.diff??null}}:{}},null,2)}async function Nu(e,t){let n=[],o=[],r=e.ficheros.filter(a=>!a.existe);for(let a of e.ficheros.filter(l=>l.existe))n.push(
|
|
1319
|
+
`left as is: ${a.ruta} already exists (compare it with the code above).`);if(r.length===0)return n.push("Nothing to write."),{salida:0,lineas:n,creados:o};n.push(`About to create ${r.length===1?"1 new\
|
|
1320
|
+
file":`${r.length} new files`} in ${e.deteccion.dir}:`);for(let a of r)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)
|
|
1321
|
+
return n.push("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:o};let a=await t.preguntar(
|
|
1322
|
+
"Create them? [y/N] ");if(i=/^(y|yes)$/i.test(a.trim()),!i)return n.push("Nothing written."),{salida:0,lineas:n,creados:o}}let s=0;for(let a of r){let l=join(e.deteccion.dir,...a.ruta.split("/"));try{t.
|
|
1323
|
+
crearDir(dirname(l)),t.crearExclusivo(l,a.contenido),o.push(a.ruta),n.push(`created ${a.ruta}`);}catch(c){c.code==="EEXIST"?n.push(`left as is: ${a.ruta} appeared while we asked; it was not overwritten.`):(s=
|
|
1324
|
+
1,n.push(`could not create ${a.ruta}: ${c instanceof Error?c.message:String(c)}`));}}return {salida:s,lineas:n,creados:o}}var ju="savings-mode";function Bu(e,t){for(let n of e){let o=join(n,"skills",ju,"SKILL.md");if(t.existe(o))return o}return null}var Uu="<!-- bvsala:savings-mode:inicio -->",
|
|
1325
|
+
ar="<!-- bvsala:savings-mode:fin -->";function pb(e){let t=e.replace(/^---\n[\s\S]*?\n---\n*/,"").trim();return `${Uu}
|
|
1141
1326
|
${t}
|
|
1142
1327
|
|
|
1143
1328
|
_Always on (AGENTS.md has no activation step). Delete this block to turn it off; \`bvsala skill --codex --force\` restores it._
|
|
1144
|
-
${
|
|
1145
|
-
|
|
1146
|
-
`),{ok:true,destino:
|
|
1329
|
+
${ar}`}function Fu(e){let t=Bu(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=pb(e.fs.leer(t)),
|
|
1330
|
+
o=e.proyecto?e.cwd:join(e.home,".codex"),r=join(o,"AGENTS.md");if(!e.fs.existe(r))return e.fs.crearDir(o),e.fs.escribir(r,n+`
|
|
1331
|
+
`),{ok:true,destino:r,mensaje:Ps(r,"installed")};let i=e.fs.leer(r),s=i.indexOf(Uu),a=i.indexOf(ar);return s===-1||a===-1||a<s?(e.fs.escribir(r,i.trimEnd()+`
|
|
1147
1332
|
|
|
1148
1333
|
`+n+`
|
|
1149
|
-
`),{ok:true,destino:
|
|
1150
|
-
|
|
1151
|
-
it; use --force to update it`}}function
|
|
1334
|
+
`),{ok:true,destino:r,mensaje:Ps(r,"appended to the existing AGENTS.md")}):i.slice(s,a+ar.length)===n?{ok:true,destino:r,mensaje:`[bvsala skill] already installed and up to date: ${r}`}:e.forzar?(e.fs.escribir(
|
|
1335
|
+
r,i.slice(0,s)+n+i.slice(a+ar.length)),{ok:true,destino:r,mensaje:Ps(r,"block updated")}):{ok:false,destino:r,mensaje:`[bvsala skill] the savings-mode block in ${r} has DIFFERENT content \u2014 not overwriting \
|
|
1336
|
+
it; use --force to update it`}}function Ps(e,t){return `[bvsala skill] ${t}: ${e}
|
|
1152
1337
|
[bvsala skill] AGENTS.md is ALWAYS active in Codex (there is no activation step); delete the block to turn it off.
|
|
1153
|
-
[bvsala skill] to measure its effect: work a few days with it and a few without, under \`bvsala codex\`, and compare in the dashboard.`}function
|
|
1154
|
-
mensaje:`[bvsala skill] cannot find the bundled SKILL.md (roots tried: ${e.origenes.join(", ")})`};let n=e.proyecto?join(e.cwd,".claude","skills"):join(e.home,".claude","skills"),
|
|
1155
|
-
md"),i=e.fs.leer(t);if(e.fs.existe(
|
|
1156
|
-
h DIFFERENT content \u2014 not overwriting it; use --force to overwrite`}}return e.fs.crearDir(
|
|
1338
|
+
[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 zu(e){let t=Bu(e.origenes,e.fs);if(!t)return {ok:false,destino:"",
|
|
1339
|
+
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"),o=join(n,ju),r=join(o,"SKILL.\
|
|
1340
|
+
md"),i=e.fs.leer(t);if(e.fs.existe(r)&&!e.forzar){let s=e.fs.leer(r)===i;return {ok:s,destino:r,mensaje:s?`[bvsala skill] already installed and up to date: ${r}`:`[bvsala skill] ${r} already exists wit\
|
|
1341
|
+
h DIFFERENT content \u2014 not overwriting it; use --force to overwrite`}}return e.fs.crearDir(o),e.fs.escribir(r,i),{ok:true,destino:r,mensaje:`[bvsala skill] installed: ${r}
|
|
1157
1342
|
[bvsala skill] start (or restart) Claude Code and ask for "savings mode" \u2014 or let it activate on its own when you mention limits.
|
|
1158
|
-
[bvsala skill] to measure its real effect: work a few days with it and a few without, under \`bvsala claude\`, and compare in the dashboard.`}}var
|
|
1159
|
-
match(/\n/g)??[]).length;
|
|
1160
|
-
Math.ceil(t.length/4))}},
|
|
1161
|
-
return this.modelToTokenizer.set(t,n),this}resolve(t){let n=t.tokenizer?this.estimators.get(t.tokenizer):void 0;if(n)return n;if(t.model){let
|
|
1162
|
-
get(
|
|
1163
|
-
"text-embedding-3-large"]};var
|
|
1164
|
-
"fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"];
|
|
1165
|
-
decena",v:20+10*t}));
|
|
1166
|
-
econd","third","fourth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelfth","thirteenth","fourteenth","fifteenth","sixteenth","seventeenth","eighteenth","nineteenth"];
|
|
1167
|
-
e&&(
|
|
1168
|
-
t}),
|
|
1169
|
-
token",t:"f:1/2"});
|
|
1170
|
-
ling",{k:"token",t:"m:3"});
|
|
1171
|
-
"and",{k:"conector"});var
|
|
1172
|
-
forEach((e,t)=>e&&
|
|
1173
|
-
(e,t)=>
|
|
1343
|
+
[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 cr=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)??[],o=0;for(let r of n){let i=r[0];if(/\s/.test(i)){let s=(r.
|
|
1344
|
+
match(/\n/g)??[]).length;o+=s+Math.floor(Math.max(0,r.length-1)/2);}else /[A-Za-z]/.test(i)?o+=Math.max(1,Math.ceil(r.length/4)):/\d/.test(i)?o+=Math.max(1,Math.ceil(r.length/2)):o+=1;}return Math.max(o,
|
|
1345
|
+
Math.ceil(t.length/4))}},Hn=new cr;var lr=class{estimators=new Map;modelToTokenizer=new Map;fallbackId;constructor(t=Hn){this.fallbackId=t.id,this.estimators.set(t.id,t);}register(t){return this.estimators.set(t.id,t),this}mapModel(t,n){
|
|
1346
|
+
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 o=this.modelToTokenizer.get(t.model);if(o){let r=this.estimators.
|
|
1347
|
+
get(o);if(r)return r}}return this.estimators.get(this.fallbackId)}count(t,n){return this.resolve(n).count(t)}};new lr;var Os={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",
|
|
1348
|
+
"text-embedding-3-large"]};var hb=new Map;function A(e,t){for(let n of e.split(/\s+/).filter(Boolean))hb.set(n,t);}var gb=["zero","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen",
|
|
1349
|
+
"fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"];gb.forEach((e,t)=>A(e,{k:"unidad",v:t}));["twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"].forEach((e,t)=>A(e,{k:"\
|
|
1350
|
+
decena",v:20+10*t}));A("hundred hundreds",{k:"cien"});A("thousand thousands",{k:"escala",v:1e3});A("million millions",{k:"escala",v:1e6});A("billion billions",{k:"escala",v:1e9});var bb=["","first","s\
|
|
1351
|
+
econd","third","fourth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelfth","thirteenth","fourteenth","fifteenth","sixteenth","seventeenth","eighteenth","nineteenth"];bb.forEach((e,t)=>{
|
|
1352
|
+
e&&(A(e,{k:"ordinal",v:t}),t>=3&&A(`${e}s`,{k:"ordinal",v:t}));});["twentieth","thirtieth","fortieth","fiftieth","sixtieth","seventieth","eightieth","ninetieth"].forEach((e,t)=>{A(e,{k:"ordinal",v:20+10*
|
|
1353
|
+
t}),A(`${e}s`,{k:"ordinal",v:20+10*t});});A("hundredth hundredths",{k:"ordinal",v:100});A("thousandth thousandths",{k:"ordinal",v:1e3});A("millionth millionths",{k:"ordinal",v:1e6});A("half halves",{k:"\
|
|
1354
|
+
token",t:"f:1/2"});A("quarter quarters",{k:"token",t:"f:1/4"});A("once single",{k:"token",t:"m:1"});A("twice double doubled doubles doubling",{k:"token",t:"m:2"});A("thrice triple tripled triples trip\
|
|
1355
|
+
ling",{k:"token",t:"m:3"});A("quadruple quadrupled quadruples quadrupling",{k:"token",t:"m:4"});A("dozen dozens",{k:"token",t:"c:12"});A("pair pairs",{k:"token",t:"c:2"});A("times time",{k:"veces"});A(
|
|
1356
|
+
"and",{k:"conector"});var vb=["cero","uno","dos","tres","cuatro","cinco","seis","siete","ocho","nueve","diez","","doce","trece","catorce","quince","dieciseis","diecisiete","dieciocho","diecinueve"];vb.
|
|
1357
|
+
forEach((e,t)=>e&&A(e,{k:"unidad",v:t}));A("veinte",{k:"decena",v:20});["veintiuno","veintidos","veintitres","veinticuatro","veinticinco","veintiseis","veintisiete","veintiocho","veintinueve"].forEach(
|
|
1358
|
+
(e,t)=>A(e,{k:"unidad",v:21+t}));["treinta","cuarenta","cincuenta","sesenta","setenta","ochenta","noventa"].forEach((e,t)=>A(e,{k:"decena",v:30+10*t}));A("cien ciento",{k:"centena",v:100});[["doscient\
|
|
1174
1359
|
os doscientas",200],["trescientos trescientas",300],["cuatrocientos cuatrocientas",400],["quinientos quinientas",500],["seiscientos seiscientas",600],["setecientos setecientas",700],["ochocientos ocho\
|
|
1175
|
-
cientas",800],["novecientos novecientas",900]].forEach(([e,t])=>
|
|
1360
|
+
cientas",800],["novecientos novecientas",900]].forEach(([e,t])=>A(e,{k:"centena",v:t}));A("mil miles",{k:"escala",v:1e3});A("millon millones",{k:"escala",v:1e6});A("billon billones",{k:"escala",v:1e12});
|
|
1176
1361
|
[["primero primera primer primeros primeras",1],["segundo segunda segundos segundas",2],["tercero tercera tercer terceros terceras tercio tercios",3],["cuarto cuarta cuartos cuartas",4],["quinto quint\
|
|
1177
1362
|
a quintos quintas",5],["sexto sexta sextos sextas",6],["septimo septima septimos septimas",7],["octavo octava octavos octavas",8],["noveno novena novenos novenas",9],["decimo decima decimos decimas",10]].
|
|
1178
|
-
forEach(([e,t])=>
|
|
1179
|
-
{k:"token",t:"c:12"});
|
|
1180
|
-
10],["onze",11],["dotze",12],["tretze",13],["catorze",14],["quinze",15],["setze",16],["disset",17],["divuit",18],["dinou",19]].forEach(([e,t])=>
|
|
1181
|
-
uanta","seixanta","setanta","vuitanta","noranta"].forEach((e,t)=>
|
|
1363
|
+
forEach(([e,t])=>A(e,{k:"ordinal",v:t}));A("mitad mitades medio media medios medias",{k:"token",t:"f:1/2"});A("doble dobles",{k:"token",t:"m:2"});A("cuadruple",{k:"token",t:"m:4"});A("docena docenas",
|
|
1364
|
+
{k:"token",t:"c:12"});A("par pares",{k:"token",t:"c:2"});A("veces vez",{k:"veces"});A("y",{k:"conector"});[["zero",0],["dues",2],["quatre",4],["cinc",5],["sis",6],["set",7],["vuit",8],["nou",9],["deu",
|
|
1365
|
+
10],["onze",11],["dotze",12],["tretze",13],["catorze",14],["quinze",15],["setze",16],["disset",17],["divuit",18],["dinou",19]].forEach(([e,t])=>A(e,{k:"unidad",v:t}));["vint","trenta","quaranta","cinq\
|
|
1366
|
+
uanta","seixanta","setanta","vuitanta","noranta"].forEach((e,t)=>A(e,{k:"decena",v:20+10*t}));A("cent",{k:"centena",v:100});A("cents centes",{k:"cien"});A("milio milions",{k:"escala",v:1e6});[["segon \
|
|
1182
1367
|
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(
|
|
1183
|
-
([e,t])=>
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
argv.slice(2));function
|
|
1368
|
+
([e,t])=>A(e,{k:"ordinal",v:t}));A("meitat meitats mig mitja",{k:"token",t:"f:1/2"});A("dotzena dotzenes",{k:"token",t:"c:12"});A("parell parells",{k:"token",t:"c:2"});A("vegades vegada",{k:"veces"});
|
|
1369
|
+
A("i",{k:"conector"});var Wb={"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}};
|
|
1370
|
+
jr(Wb);new Set(Object.values(Os).flatMap(e=>e.flatMap(t=>[t,`openai/${t}`])));function Cv(e,t=300){return new Promise(n=>{let o=connect({port:e,host:"127.0.0.1"}),r=i=>{o.destroy(),n(i);};o.setTimeout(t,()=>r(false)),o.once("connect",()=>r(true)),o.once("error",()=>r(false));})}var Xn=iu(process.
|
|
1371
|
+
argv.slice(2));function Tv(){console.log(`bvsala ${ye} \u2014 BiVelio Savings Layer
|
|
1187
1372
|
|
|
1188
1373
|
Commands:
|
|
1189
1374
|
gateway [--port N] [--upstream U]
|
|
1190
|
-
Local metering proxy (default port 8402) for anything that honours a
|
|
1375
|
+
Local saving + metering proxy (default port 8402) for anything that honours a
|
|
1191
1376
|
base URL: Claude Code, opencode, Goose, Crush\u2026 and the official OpenAI
|
|
1192
1377
|
and Anthropic SDKs in any language, Python included.
|
|
1193
|
-
|
|
1194
|
-
|
|
1378
|
+
Works out of the box \u2014 no keys needed (COMMUNITY mode: every local lever
|
|
1379
|
+
on, zero telemetry). BIVELIO_SERVICE_KEY adds the cloud dashboard,
|
|
1380
|
+
org entitlements and team metering.
|
|
1381
|
+
--upstream openai | anthropic | gemini | deepseek | qwen | glm |
|
|
1382
|
+
moonshot | minimax | openrouter | ollama | vllm | lmstudio | an
|
|
1383
|
+
origin URL (default: anthropic). DeepSeek rewrites Anthropic
|
|
1384
|
+
traffic to its /anthropic endpoint automatically.
|
|
1195
1385
|
One gateway talks to ONE upstream: run a second one on another port
|
|
1196
1386
|
for the other provider. Behind an origin that is not the provider's
|
|
1197
1387
|
own API (a proxy such as LiteLLM), requests are metered but no
|
|
@@ -1210,6 +1400,8 @@ Commands:
|
|
|
1210
1400
|
use a base URL and are not metered.
|
|
1211
1401
|
aider [args\u2026] Run Aider through the gateway: Anthropic models by default
|
|
1212
1402
|
(ANTHROPIC_API_BASE); OpenAI with BVSALA_GATEWAY_UPSTREAM=openai.
|
|
1403
|
+
gemini [args\u2026] Run the Gemini CLI through the gateway (GOOGLE_GEMINI_BASE_URL,
|
|
1404
|
+
upstream gemini): usage read from :generateContent responses.
|
|
1213
1405
|
Every wrapper prints, on exit, how many requests it metered and
|
|
1214
1406
|
which ones it forwarded without metering, and why.
|
|
1215
1407
|
doctor [--port N] Detect installed terminals and print the exact configuration for each.
|
|
@@ -1221,7 +1413,13 @@ Commands:
|
|
|
1221
1413
|
(~/.codex; with --project, ./AGENTS.md) \u2014 Codex has no skills and
|
|
1222
1414
|
AGENTS.md is always active. Its effect is measured by the gateway,
|
|
1223
1415
|
not promised.
|
|
1224
|
-
|
|
1416
|
+
mcp [--gateway URL | --port N]
|
|
1417
|
+
A read-only MCP server on stdio for your MCP client (Claude Code, Codex,
|
|
1418
|
+
an IDE): the local gateway's status, cost per session and tool-output
|
|
1419
|
+
compaction decisions, read from its local routes (default
|
|
1420
|
+
http://127.0.0.1:8402). Metadata only: no request ids, no content, and
|
|
1421
|
+
no tool that changes anything.
|
|
1422
|
+
init [--write [--yes]] [--stack S] [--provider P] [--compaction M] [--cwd DIR] [--json]
|
|
1225
1423
|
Set up the SDK in a JavaScript/TypeScript project (also:
|
|
1226
1424
|
npx @bivelio/savings-layer@latest init). Detects Next.js, Express, the
|
|
1227
1425
|
Vercel AI SDK, Mastra, LangChain.js, the Anthropic SDK and the OpenAI SDK,
|
|
@@ -1233,6 +1431,11 @@ Commands:
|
|
|
1233
1431
|
--stack ai-sdk | mastra | langchain | anthropic-sdk | sdk (default: detected)
|
|
1234
1432
|
--provider openai | anthropic (default: detected)
|
|
1235
1433
|
--json prints the plan for a script or a coding agent.
|
|
1434
|
+
--compaction off | measure | on (default: off)
|
|
1435
|
+
opt-in lossless compaction of JSON tool outputs: "on" adds one option to
|
|
1436
|
+
the wiring where the stack supports it (shown as a diff to review),
|
|
1437
|
+
"measure" adds a module that measures and changes nothing; both add a
|
|
1438
|
+
local check that prints the receipt and the coverage.
|
|
1236
1439
|
--version | -v Print the version only.
|
|
1237
1440
|
--help | -h This help; also accepted after gateway, doctor, skill or init
|
|
1238
1441
|
(\`bvsala gateway --help\` starts nothing; \`bvsala claude --help\` or
|
|
@@ -1241,8 +1444,10 @@ Commands:
|
|
|
1241
1444
|
The Spanish spellings --puerto, --proyecto and --forzar were removed in 0.5: they now
|
|
1242
1445
|
fail with an error that names the English flag.
|
|
1243
1446
|
Environment:
|
|
1244
|
-
BIVELIO_SERVICE_KEY Service key (bvk_\u2026):
|
|
1447
|
+
BIVELIO_SERVICE_KEY Service key (bvk_\u2026): OPTIONAL. Identifies your organization, collects its
|
|
1245
1448
|
license (renewed by itself) and enables metering and seat identity.
|
|
1449
|
+
Without it the gateway runs in COMMUNITY mode: all local levers on,
|
|
1450
|
+
nothing sent to BiVelio.
|
|
1246
1451
|
BIVELIO_LICENSE_KEY License key (optional fallback): used only if savings.bivelio.com cannot be
|
|
1247
1452
|
reached at start; verified on this machine. Replace it every billing period.
|
|
1248
1453
|
BVSALA_SEAT_ID Stable seat identity per replica (optional).
|
|
@@ -1300,56 +1505,60 @@ Environment:
|
|
|
1300
1505
|
default so it does not overwrite the TUI; use the dashboard instead).
|
|
1301
1506
|
CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1 (Claude Code, API key only) your models in /model.
|
|
1302
1507
|
|
|
1303
|
-
The gateway is
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1508
|
+
The gateway is open core: it starts with no keys at all (COMMUNITY mode) and arms every local
|
|
1509
|
+
saving lever, with zero telemetry. With a license (service key or offline fallback) an invalid
|
|
1510
|
+
or expired key still fails closed, and if a live license lapses only NEW requests are refused
|
|
1511
|
+
(HTTP 402) until it is renewed \u2014 a request in flight is never interrupted. Metering is
|
|
1512
|
+
best-effort: with ingestion down, it forwards and warns. On a Claude or ChatGPT subscription
|
|
1513
|
+
there is no per-token invoice: that traffic is metered at list-price equivalent and never
|
|
1514
|
+
carries commission.
|
|
1308
1515
|
Your prompts, completions and provider keys never reach BiVelio: what it receives is per-request
|
|
1309
|
-
usage (token counts, cost, the model id and opaque ids); LICENSE \xA75 lists every field.
|
|
1310
|
-
More: savings.bivelio.com`);}
|
|
1311
|
-
checkEnv:
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
o.
|
|
1315
|
-
process.exit(
|
|
1316
|
-
|
|
1317
|
-
c
|
|
1318
|
-
|
|
1319
|
-
"--
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
join(homedir(),".
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
{
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
:
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
`[bvsala ${
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1516
|
+
usage (token counts, cost, the model id and opaque ids); LICENSE-CLOUD.md \xA75 lists every field.
|
|
1517
|
+
More: savings.bivelio.com`);}Xn.tipo==="ayuda"&&(Tv(),process.exit(Xn.salida));Xn.tipo==="version"&&(console.log(ye),process.exit(0));var{comando:W}=Xn,_t=Un(W),we=Xn.resto,xd=cu(_t?[]:we,process.env,{
|
|
1518
|
+
checkEnv:_t||W==="gateway"});if(xd.length>0){for(let e of xd)console.error(e);process.exit(1);}var Hs=process.env.BVSALA_GATEWAY_EFFORT,Rd=process.env.BVSALA_GATEWAY_SIBLING_MODEL;if(W==="mcp"){let{servirPorStdio:e,
|
|
1519
|
+
urlDelGateway:t}=await Promise.resolve().then(()=>(wd(),kd)),n=t(we);n.ok||(console.error(`[bvsala mcp] ${n.mensaje}`),process.exit(1)),await e(process.stdin,process.stdout,{gateway:n.url,version:ye}),
|
|
1520
|
+
process.exit(0);}if(W==="init"){let e=Au(we,process.cwd());e.ok||(console.error(`[bvsala init] ${e.mensaje}`),process.exit(1));let t=e.valor,n={leer:l=>{try{return readFileSync(l,"utf8")}catch{return}},existe:existsSync},
|
|
1521
|
+
o=Pu(t.cwd,n);o.ok||(console.error(`[bvsala init] ${o.mensaje}`),process.exit(1));let r=Ou(o.valor,t,{node:process.versions.node,env:l=>!!process.env[l]?.trim()});r.ok||(console.error(`[bvsala init] ${r.
|
|
1522
|
+
mensaje}`),process.exit(1));let i=Lu(r.valor,n);t.json&&(console.log($u(i,ye)),process.exit(0)),console.log(Mu(i,`bvsala init \xB7 BiVelio Savings Layer ${ye}`,"npx @bivelio/savings-layer@latest init",
|
|
1523
|
+
{escribira:t.escribir})),t.escribir||process.exit(0),console.log("");let{createInterface:s}=await import('readline/promises'),a=await Nu(i,{si:t.si,esTerminal:!!process.stdin.isTTY,preguntar:async l=>{
|
|
1524
|
+
let c=s({input:process.stdin,output:process.stdout});try{return await c.question(l)}finally{c.close();}},crearDir:l=>mkdirSync(l,{recursive:true}),crearExclusivo:(l,c)=>writeFileSync(l,c,{flag:"wx"})});for(let l of a.lineas)
|
|
1525
|
+
(a.salida===0?console.log:console.error)(l);process.exit(a.salida);}if(W==="skill"){let e=dirname(fileURLToPath(import.meta.url)),t={origenes:[join(e,"..",".."),join(e,"..")],home:homedir(),cwd:process.cwd(),proyecto:we.includes(
|
|
1526
|
+
"--project"),forzar:we.includes("--force"),fs:{existe:existsSync,leer:o=>readFileSync(o,"utf8"),escribir:(o,r)=>writeFileSync(o,r),crearDir:o=>mkdirSync(o,{recursive:true})}},n=we.includes("--codex")?Fu(t):zu(t);console.log(n.mensaje),process.
|
|
1527
|
+
exit(n.ok?0:1);}var Gs=we.indexOf("--port"),Vt=_t?0:Gs>=0?Number(we[Gs+1]):8402;(!Number.isInteger(Vt)||(W==="doctor"?Vt<1:Vt<0)||Vt>65535)&&(console.error(`[bvsala ${W}] invalid port: ${we[Gs+1]}`),process.
|
|
1528
|
+
exit(1));if(W==="doctor"){we.includes("--write")&&(console.error("[bvsala doctor] --write does not exist yet: the doctor only prints; copy the block by hand."),process.exit(1));let e=await du(Vt);console.
|
|
1529
|
+
log(e.texto),process.exit(0);}function Rv(e,t){Un(e)||process.exit(1);let n=ir(e,0,[],{}).bin;if(process.platform==="win32"){let r=Ss(n);r.tipo==="exe"?n=r.ruta:r.tipo==="solo-shim"&&(console.error(`[b\
|
|
1530
|
+
vsala ${e}] \`${n}\` is installed as an npm shim (${r.ruta}) and Windows cannot launch it safely with arguments (CVE-2024-27980). Install it with its native installer (which leaves a ${n}.exe on the P\
|
|
1531
|
+
ATH) or use the manual recipe in docs/terminales/.`),process.exit(127));}let o=spawn(n,t,{stdio:"inherit"});return o.on("error",r=>{console.error(`[bvsala ${e}] could not launch \`${n}\`: ${String(r)}. Is\
|
|
1532
|
+
it installed and on the PATH?`),process.exit(127);}),o.on("exit",(r,i)=>process.exit(r??(i?1:0))),new Promise(()=>{})}_t&&su(we)&&await Rv(W,we);if(_t){let e=nu(W);e&&(console.error(`[bvsala ${W}] ${e}`),
|
|
1533
|
+
process.exit(1));}var Av=W==="gateway"?Al(we):void 0,me=Il({flag:Av,env:process.env.BVSALA_GATEWAY_UPSTREAM});me.ok||(console.error(me.error),process.exit(1));var gr=process.env.BIVELIO_SERVICE_KEY?.trim()||
|
|
1534
|
+
void 0,Et=await yl({serviceAccountKey:gr,licenseKey:process.env.BIVELIO_LICENSE_KEY,licenseServerUrl:us});Et.ok||(console.error(`[bvsala ${W}] ${Et.message}`),process.exit(1));var Qe=_t?ir(
|
|
1535
|
+
W,0,we,{modoCodex:W==="codex"?Xl({leerAuth:()=>readFileSync(join(homedir(),".codex","auth.json"),"utf8")}):void 0,...me.upstream?{upstreamElegido:me.upstream}:{}}):null,Iv=_t&&process.env.BVSALA_GATEWAY_LOG!=="1",qs=Qe?.
|
|
1536
|
+
upstream?null:lu(()=>readFileSync(process.env.BVSALA_ANILLO2_FICHERO??join(homedir(),".bvsala","anillo2.json"),"utf8")),Qn=uu({enrolamiento:qs,espiaVivo:qs!==null&&await Cv(qs.espia),upstreamEnv:me.upstream,...me.origen!==
|
|
1537
|
+
"none"?{upstreamOrigen:me.origen}:{},elisionEnv:process.env.BVSALA_GATEWAY_ELISION,hoyUtcIso:new Date().toISOString().slice(0,10)}),Ws=me.upstream??Qn.upstream,mr=process.env.BVSALA_GATEWAY_ELISION??Qn.
|
|
1538
|
+
elision,De;try{De=await Jl({puerto:Vt,...Iv?{log:()=>{},avisosDeNoMedido:!1}:{},...Et.license?{license:{token:Et.license.token,publicKey:Lt,licenseServerUrl:us,checkOnStart:Et.source==="offline"}}:{},
|
|
1539
|
+
warn:e=>console.error(e),...gr?{serviceAccountKey:gr}:{},...process.env.BVSALA_SEAT_ID?{seatId:process.env.BVSALA_SEAT_ID}:{},...Ws?{upstream:Ws}:Qe?.upstream?{upstream:Qe.upstream}:{},...process.env.
|
|
1540
|
+
BVSALA_GATEWAY_COALESCE==="1"?{coalescer:!0}:{},...process.env.BVSALA_GATEWAY_USAGE_INJECT==="1"?{usageInject:!0}:{},...process.env.BVSALA_GATEWAY_SHADOW==="1"?{sombra:!0}:{},elision:mr!=="0",...process.
|
|
1541
|
+
env.BVSALA_GATEWAY_DIALES_ELISION==="1"?{dialesElision:!0}:{},...Rd==="1"?{modeloHermano:!0}:{},...Hs?{esfuerzo:Hs}:{},...process.env.BVSALA_METERING_URL?{meteringUrl:process.env.BVSALA_METERING_URL}:
|
|
1542
|
+
{}});}catch(e){console.error(`[bvsala ${W}] ${au(e,W,Vt)}`),process.exit(1);}var Ad=Ws??Qe?.upstream??"https://api.anthropic.com";console.log(`[bvsala gateway] v${ye} listening on http://127.0.0.1:${De.
|
|
1543
|
+
puerto} \u2192 ${Ad}`);(Et.lineIsWarning?console.error:console.log)(`[bvsala gateway] ${Et.line}`);for(let e of Et.warnings)console.error(`[bvsala gateway] ${e}`);console.log(gr?"[bvsala gateway] mete\
|
|
1544
|
+
ring: ON (service key present)":"[bvsala gateway] metering: OFF (community mode \u2014 no BiVelio service key; local reports stay available with x-bvsala-report)");process.env.BVSALA_METERING_URL&&console.
|
|
1545
|
+
error(`[bvsala gateway] WARNING: BVSALA_METERING_URL=${process.env.BVSALA_METERING_URL} redirects usage reporting away from savings.bivelio.com (development only): your dashboard will not see this usa\
|
|
1546
|
+
ge. The license and the entitlements channel still use savings.bivelio.com.`);me.aviso&&console.error(me.aviso);process.env.BVSALA_GATEWAY_USAGE_INJECT==="1"&&console.log("[bvsala gateway] usage injec\
|
|
1547
|
+
tion: ON (BVSALA_GATEWAY_USAGE_INJECT=1) \u2014 streamed chat completions without stream_options get include_usage; their last chunk has an empty choices list.");{let e=aa(mr,true,process.env.BVSALA_GATEWAY_DIALES_ELISION===
|
|
1548
|
+
"1");(e.aviso?console.error:console.log)(`[bvsala gateway] ${e.linea}`);let t=wa(Rd,true,mr!=="0");(t.aviso?console.error:console.log)(`[bvsala gateway] ${t.linea}`);let n=ga(Hs,true,mr!=="0");(n.aviso?console.
|
|
1549
|
+
error:console.log)(`[bvsala gateway] ${n.linea}`),Qn.linea&&(Qn.aviso?console.error:console.log)(`[bvsala gateway] ${Qn.linea}`);}me.upstream&&Qe?.upstream&&me.upstream!==Qe.upstream&&console.error(`[b\
|
|
1550
|
+
vsala ${W}] WARNING: BVSALA_GATEWAY_UPSTREAM=${me.upstream} overrides this terminal's upstream (${Qe.upstream}). If that is not what you want, unset the variable.`);W==="codex"&&!Qc()&&console.error(`\
|
|
1551
|
+
[bvsala codex] WARNING: this Node (${process.version}) cannot decompress zstd and Codex sends its body in zstd: traffic passes through but is NOT metered. Use Node >= 22.15.`);var Sd=false;function Id(){
|
|
1552
|
+
if(Sd)return;Sd=true;let e=ql(De.degradaciones());e&&console.error(e),console.error(Dl(De.medicion(),W));}if(Qe&&_t){let e=ir(W,De.puerto,we,{...Qe.upstream?{modoCodex:Qe.upstream.includes("chatgpt.com")?
|
|
1553
|
+
"chatgpt":"api-key"}:{},...me.upstream?{upstreamElegido:me.upstream}:{}});e.nota&&console.log(`[bvsala ${W}] ${e.nota}`);let t=e.bin;if(process.platform==="win32"){let o=Ss(e.bin);o.tipo==="exe"?t=o.ruta:
|
|
1554
|
+
o.tipo==="solo-shim"&&(console.error(`[bvsala ${W}] \`${e.bin}\` is installed as an npm shim (${o.ruta}) and Windows cannot launch it safely with arguments (CVE-2024-27980). Install it with its native\
|
|
1555
|
+
installer (which leaves a ${e.bin}.exe on the PATH) or use the manual recipe in docs/terminales/.`),await De.cerrar(),process.exit(127));}let n=spawn(t,e.args,{stdio:"inherit",env:{...process.env,...e.env}});
|
|
1556
|
+
n.on("error",o=>{console.error(`[bvsala ${W}] could not launch \`${e.bin}\`: ${String(o)}. Is it installed and on the PATH?`),De.cerrar().then(()=>process.exit(127));}),n.on("exit",(o,r)=>{Id(),De.cerrar().
|
|
1557
|
+
then(()=>process.exit(o??(r?1:0)));});}else {let e=new URL(Ad).hostname;e==="api.openai.com"?console.log(`[bvsala gateway] point your SDK at it: base_url=http://127.0.0.1:${De.puerto}/v1 (OpenAI SDKs) \xB7 \
|
|
1558
|
+
streamed chat completions are metered when the request sets stream_options.include_usage \xB7 bvsala doctor for recipes`):e==="api.anthropic.com"||me.upstream===void 0?console.log(`[bvsala gateway] po\
|
|
1559
|
+
int your terminal at it (or use \`bvsala ${xs.join("|")}\`): ANTHROPIC_BASE_URL=http://127.0.0.1:${De.puerto} claude \xB7 bvsala doctor for the others`):console.log(`[bvsala gateway] point your c\
|
|
1560
|
+
lient at http://127.0.0.1:${De.puerto} plus the path prefix it already uses (for example /v1) \xB7 bvsala doctor for recipes`);}var Dd=async()=>{Id(),await De.cerrar(),process.exit(0);};process.on("SIGI\
|
|
1561
|
+
NT",()=>{Dd();});process.on("SIGTERM",()=>{Dd();});
|
|
1353
1562
|
/*! Bundled license information:
|
|
1354
1563
|
|
|
1355
1564
|
@noble/curves/utils.js:
|