@bivelio/savings-layer 0.4.36 → 0.5.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.
@@ -1,111 +1,124 @@
1
- import {createSavingsLayer,LicenseError,sha256,stableStringify}from'@bivelio/savings-layer';import {AsyncLocalStorage}from'async_hooks';var x=t=>typeof t=="number"&&Number.isFinite(t)&&t>0?t:0;function F(t){if(!Array.isArray(t))return null;let e={input:0,output:0,cacheRead:0,cacheWrite:0,cacheWrite1h:0,iteraciones:0};for(let n of t){if(n===
2
- null||typeof n!="object")continue;let r=n;if(r.type!=="compaction")continue;e.iteraciones++,e.input+=x(r.input_tokens),e.output+=x(r.output_tokens),e.cacheRead+=x(r.cache_read_input_tokens);let o=r.cache_creation,
3
- s=x(o?.ephemeral_5m_input_tokens),a=x(o?.ephemeral_1h_input_tokens),i=typeof r.cache_creation_input_tokens=="number"?x(r.cache_creation_input_tokens):s+a;e.cacheWrite+=i,e.cacheWrite1h+=Math.min(a,i);}
4
- return e.iteraciones>0?e:null}function B(t,e,n){let r=t??{},o=F(r.iterations),s=W(r.cache_read_input_tokens,o?.cacheRead),a=W(r.cache_creation_input_tokens,o?.cacheWrite),i=r.cache_creation?.ephemeral_1h_input_tokens,u=typeof i=="\
5
- number"||(o?.cacheWrite1h??0)>0?Math.min(Math.max(0,(typeof i=="number"?i:0)+(o?.cacheWrite1h??0)),a??0):void 0,d=(r.input_tokens??0)+(o?.input??0)+(a??0)+(s??0),g=(e??0)+(o?.output??0),m=typeof r.input_tokens!=
6
- "number",h=typeof e!="number";return {usage:{inputTokens:d,outputTokens:g,...s!=null?{cachedInputTokens:s}:{},...a!=null?{cacheWriteInputTokens:a}:{},...u!==void 0?{cacheWrite1hInputTokens:u}:{},...n||
7
- h||o?{}:{reasoningTokens:0},...m||h?{complete:false}:{}},entradaAusente:m,salidaAusente:h}}function W(t,e){return e?(t??0)+e:t}function V(t){let e=t?.service_tier;return typeof e=="string"&&e!==""?e:void 0}
8
- function q(t,e){let n=Object.fromEntries(Object.entries(e??{}).filter(([,o])=>o!=null)),r=t?.cache_creation||e?.cache_creation?{...t?.cache_creation??{},...e?.cache_creation??{}}:void 0;return {...t??{},
9
- ...n,...r?{cache_creation:r}:{}}}function G(t){return t==="thinking"||t==="redacted_thinking"}function H(t){switch(t){case "end_turn":return "stop";case "max_tokens":return "length";case "tool_use":return "\
10
- tool_calls";case "refusal":return "content_filter";default:return t}}var we=new Set([null,"cyber","general_harms"]);function K(t){if(t.stopReason!=="refusal")return false;let e=t.stopDetails;if(e===null||typeof e!=
11
- "object"||Array.isArray(e))return false;let n=e;if(n.type!=="refusal"||!("category"in n))return false;let r=n.category;return !(r!==null&&typeof r!="string"||!we.has(r)||t.bloques!==0||t.outputTokens!==0||Array.
12
- isArray(t.iterations)&&t.iterations.length>1)}function I(t,e){if(t!=="refusal"||e===null||typeof e!="object"||Array.isArray(e))return;let n=e.category;return typeof n=="string"&&n!==""?n:void 0}var Re=["claude-opus-5-5","claude-sonnet-5-5","claude-fable-5-1","claude-mythos-5-1"],Se=["claude-opus-4-7","claude-opus-4-8","claude-opus-5","claude-sonnet-5","claude-fable-5","claude-mythos-5"];function xe(t){return /claude-[a-z]+-\d[a-z0-9-]*/.exec(t.toLowerCase())?.[0]}function Z(t,e){let n=xe(t);return n===void 0?false:e.some(r=>n===r||n.startsWith(`${r}-`))}function Q(t){return Z(t,Re)}function X(t){
13
- return Z(t,Se)}var Ae={"api.anthropic.com":"anthropic","api.openai.com":"openai","generativelanguage.googleapis.com":"google"};function ke(t){if(typeof t!="string")return null;try{let e=new URL(t);return e.protocol!==
14
- "https:"||e.port!==""?null:Ae[e.hostname.toLowerCase()]??null}catch{return null}}function Y(t){return ke(t)!==null?"oficial":"no-oficial"}var ee=Symbol.for("@bivelio/savings-layer:provider-origin");var O=class{decoder;resto="";crPendiente=false;alPrincipio=true;datos="";evento="";ultimoId;push(e){let n=typeof e=="string"?e:(this.decoder??=new TextDecoder("utf-8")).decode(e,{stream:true});return this.procesar(
1
+ import {createSavingsLayer,LicenseError}from'@bivelio/savings-layer';import {AsyncLocalStorage}from'async_hooks';var Se={stop:"stop",end_turn:"stop",STOP:"stop",length:"length",max_tokens:"length",MAX_TOKENS:"length",tool_calls:"tool_calls",tool_use:"tool_calls",content_filter:"content_filter",other:"other"},Ae={
2
+ stop_sequence:"stop",eos:"stop",eos_token:"stop",model_context_window_exceeded:"length",function_call:"tool_calls",refusal:"content_filter",SAFETY:"content_filter",RECITATION:"content_filter",BLOCKLIST:"\
3
+ content_filter",PROHIBITED_CONTENT:"content_filter",SPII:"content_filter",IMAGE_SAFETY:"content_filter",IMAGE_PROHIBITED_CONTENT:"content_filter",IMAGE_RECITATION:"content_filter"},ke=/^content_filter\s*:\s*(.*?)\s*$/;
4
+ function B(t,e){let n=typeof e=="string"&&e!==""?e:void 0;if(typeof t!="string"||t==="")return n!==void 0?{finishReasonDetail:n}:{};let r=Se[t];if(r!==void 0)return {finishReason:r,...n!==void 0?{finishReasonDetail:n}:
5
+ {}};let o=ke.exec(t);if(o!==null){let s=n??(o[1]!==void 0&&o[1]!==""?o[1]:void 0);return {finishReason:"content_filter",...s!==void 0?{finishReasonDetail:s}:{}}}return {finishReason:Ae[t]??"other",finishReasonDetail:n??
6
+ t}}var O=t=>typeof t=="number"&&Number.isFinite(t)&&t>0?t:0;function V(t){if(!Array.isArray(t))return null;let e={input:0,output:0,cacheRead:0,cacheWrite:0,cacheWrite1h:0,iteraciones:0};for(let n of t){if(n===
7
+ null||typeof n!="object")continue;let r=n;if(r.type!=="compaction")continue;e.iteraciones++,e.input+=O(r.input_tokens),e.output+=O(r.output_tokens),e.cacheRead+=O(r.cache_read_input_tokens);let o=r.cache_creation,
8
+ a=O(o?.ephemeral_5m_input_tokens),s=O(o?.ephemeral_1h_input_tokens),i=typeof r.cache_creation_input_tokens=="number"?O(r.cache_creation_input_tokens):a+s;e.cacheWrite+=i,e.cacheWrite1h+=Math.min(s,i);}
9
+ return e.iteraciones>0?e:null}function H(t,e,n){let r=t??{},o=V(r.iterations),a=G(r.cache_read_input_tokens,o?.cacheRead),s=G(r.cache_creation_input_tokens,o?.cacheWrite),i=r.cache_creation?.ephemeral_1h_input_tokens,u=typeof i=="\
10
+ number"||(o?.cacheWrite1h??0)>0?Math.min(Math.max(0,(typeof i=="number"?i:0)+(o?.cacheWrite1h??0)),s??0):void 0,d=(r.input_tokens??0)+(o?.input??0)+(s??0)+(a??0),f=(e??0)+(o?.output??0),h=typeof r.input_tokens!=
11
+ "number",m=typeof e!="number";return {usage:{inputTokens:d,outputTokens:f,...a!=null?{cachedInputTokens:a}:{},...s!=null?{cacheWriteInputTokens:s}:{},...u!==void 0?{cacheWrite1hInputTokens:u}:{},...n||
12
+ m||o?{}:{reasoningTokens:0},...h||m?{complete:false}:{}},entradaAusente:h,salidaAusente:m}}function G(t,e){return e?(t??0)+e:t}function K(t){let e=t?.service_tier;return typeof e=="string"&&e!==""?e:void 0}
13
+ function z(t,e){let n=Object.fromEntries(Object.entries(e??{}).filter(([,o])=>o!=null)),r=t?.cache_creation||e?.cache_creation?{...t?.cache_creation??{},...e?.cache_creation??{}}:void 0;return {...t??{},
14
+ ...n,...r?{cache_creation:r}:{}}}function Y(t){return t==="thinking"||t==="redacted_thinking"}function Z(t,e){return B(t,Ce(t,e))}var De=new Set([null,"cyber","general_harms"]);function X(t){if(t.stopReason!==
15
+ "refusal")return false;let e=t.stopDetails;if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=e;if(n.type!=="refusal"||!("category"in n))return false;let r=n.category;return !(r!==null&&typeof r!=
16
+ "string"||!De.has(r)||t.bloques!==0||t.outputTokens!==0||Array.isArray(t.iterations)&&t.iterations.length>1)}function Ce(t,e){if(t!=="refusal"||e===null||typeof e!="object"||Array.isArray(e))return;let n=e.
17
+ category;return typeof n=="string"&&n!==""?n:void 0}var Pe=["claude-opus-5-5","claude-sonnet-5-5","claude-fable-5-1","claude-mythos-5-1"],Te=["claude-opus-4-7","claude-opus-4-8","claude-opus-5","claude-sonnet-5","claude-fable-5","claude-mythos-5"];function Oe(t){return /claude-[a-z]+-\d[a-z0-9-]*/.exec(t.toLowerCase())?.[0]}function Q(t,e){let n=Oe(t);return n===void 0?false:e.some(r=>n===r||n.startsWith(`${r}-`))}function ee(t){return Q(t,Pe)}function te(t){
18
+ return Q(t,Te)}var Me={"api.anthropic.com":"anthropic","api.openai.com":"openai","generativelanguage.googleapis.com":"google"};function Ee(t){if(typeof t!="string")return null;try{let e=new URL(t);return e.protocol!==
19
+ "https:"||e.port!==""?null:Me[e.hostname.toLowerCase()]??null}catch{return null}}function ne(t){return Ee(t)!==null?"oficial":"no-oficial"}var re=Symbol.for("@bivelio/savings-layer:provider-origin");var I=class{decoder;resto="";crPendiente=false;alPrincipio=true;datos="";evento="";ultimoId;push(e){let n=typeof e=="string"?e:(this.decoder??=new TextDecoder("utf-8")).decode(e,{stream:true});return this.procesar(
15
20
  n)}end(){let e=[];if(this.decoder){let n=this.decoder.decode();n!==""&&e.push(...this.procesar(n));}return this.resto!==""&&(this.linea(this.resto,e),this.resto=""),this.despachar(e),this.crPendiente=false,
16
21
  e}procesar(e){let n=[];if(e==="")return n;let r=e;if(this.alPrincipio&&(this.alPrincipio=false,r.charCodeAt(0)===65279&&(r=r.slice(1)),r===""))return n;let o=0;this.crPendiente&&(this.crPendiente=false,r.charCodeAt(
17
- 0)===10&&(o=1));let s=o;for(;o<r.length;){let a=r.charCodeAt(o);if(a!==10&&a!==13){o++;continue}this.linea(this.resto+r.slice(s,o),n),this.resto="",a===13&&(o+1<r.length?r.charCodeAt(o+1)===10&&o++:this.
18
- crPendiente=true),o++,s=o;}return this.resto+=r.slice(s),n}linea(e,n){if(e===""){this.despachar(n);return}if(e.charCodeAt(0)===58)return;let r=e.indexOf(":"),o,s;switch(r===-1?(o=e,s=""):(o=e.slice(0,r),
19
- s=e.slice(r+1),s.charCodeAt(0)===32&&(s=s.slice(1))),o){case "data":this.datos+=s+`
20
- `;break;case "event":this.evento=s;break;case "id":s.includes("\0")||(this.ultimoId=s);break;}}despachar(e){if(this.datos===""){this.evento="";return}e.push({event:this.evento===""?"message":
21
- this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};var te=new Set;function ne(t,e,n){t===true||te.has(e)||(te.add(e),console.warn(n));}var Ce="[bvsala] internal: the layer changed a request this adapter must forward unchanged; nothing was sent.",Pe="[bvsala] internal: the layer asked for a second model call within one framework call;\
22
- nothing more was sent.",Oe="[bvsala] internal: the layer called the model outside a framework call; nothing was sent.";function U(t,e,n,r){return {renderizado:t,generar:e,...n?{transmitir:n}:{},invocada:false,
23
- completada:false,...r!==void 0?{origen:r}:{}}}function Te(t,e){if(t===e)return true;try{return stableStringify(t)===stableStringify(e)}catch{return false}}function oe(t,e){let n=t??[],r=e??[];return n.length===r.length&&n.every((o,s)=>Te(o,r[s]))}function Me(t,e){return t.model===
24
- e.model&&oe(t.messages,e.messages)&&oe(t.tools,e.tools)}function se(t,e){let n=o=>{let s=e.getStore();if(!s)throw new Error(Oe);if(s.invocada)throw new Error(Pe);if(!Me(o,s.renderizado))throw new Error(
25
- Ce);return s.invocada=true,s},r={id:`bivelio-adapter:${t}`,async generate(o,s){return n(o).generar(s?.signal)},async*generateStream(o,s){let a=n(o);if(a.transmitir){yield*a.transmitir(s?.signal);return}
26
- let i=await a.generar(s?.signal);i.text!==""&&(yield {type:"text",delta:i.text}),yield {type:"done",response:i};}};return Object.defineProperty(r,ee,{value:()=>e.getStore()?.origen}),r}function ae(){return new AsyncLocalStorage}var je=["licenseKey","licenseServerUrl","serviceAccountKey","licenseRefresh","licenseRevocation","licensePollIntervalSeconds","licenseFetch","metering","meteringUrl","meteringFetch","costModels","defa\
27
- ultCostModel","exactCache","exactCacheTtlMs","resolvers","exactTokenizer","silenceWarnings","failOpen"];function ie(t,e){return e instanceof LicenseError||t.errorDelMarco&&t.errorDelMarco.error===e?false:t.invocada&&
28
- t.completada}var ce="[bvsala] the model answered, but the savings layer failed while accounting for it; the answer is returned unchanged, without a savings report and without a usage record.";function ue(t,e){
29
- let n=ae(),r={};for(let a of je)e[a]!==void 0&&(r[a]=e[a]);let o=createSavingsLayer({...r,provider:se(t,n)}),s=(a,i)=>ne(e.silenceWarnings,`${t}:${a}`,i);return {ejecutar(a,i){return n.run(i,()=>o.generate(a))},async generar(a,i){
30
- try{let u=await n.run(i,()=>o.generate(a));return i.invocada?{tipo:"vivo",result:u}:{tipo:"atajo",result:u}}catch(u){if(ie(i,u))return s("sin-informe",ce),{tipo:"sin-informe"};throw u}},async transmitir(a,i,u){
31
- let g=n.run(i,()=>o.generateStream(a,u?{signal:u}:{})).result;i.resultado=g,g.catch(()=>{});let m;try{m=await Promise.race([i.abierta.then(()=>"abierta"),g.then(()=>"resuelta")]);}catch(b){if(ie(i,b))return s(
32
- "sin-informe",ce),{tipo:"sin-informe"};throw b}if(m==="abierta")return {tipo:"abierto"};let h=await g;return i.invocada?{tipo:"entero",result:h}:{tipo:"atajo",result:h}},informe(a){let i=JSON.parse(JSON.
33
- stringify(a));if(e.onReport)try{e.onReport(i);}catch{s("onreport","[bvsala] `onReport` threw; the error was caught and the model call was not affected.");}return i},avisar:s,close(){o.close();}}}function le(){
34
- let t;return {abierta:new Promise(n=>{t=n;}),abrir:t}}var C=class{pendientes=[];esperando;terminada=false;fallo;push(e){if(this.terminada||this.fallo)return;let n=this.esperando;if(n){this.esperando=void 0,n.resolver({value:e,done:false});return}this.pendientes.
22
+ 0)===10&&(o=1));let a=o;for(;o<r.length;){let s=r.charCodeAt(o);if(s!==10&&s!==13){o++;continue}this.linea(this.resto+r.slice(a,o),n),this.resto="",s===13&&(o+1<r.length?r.charCodeAt(o+1)===10&&o++:this.
23
+ crPendiente=true),o++,a=o;}return this.resto+=r.slice(a),n}linea(e,n){if(e===""){this.despachar(n);return}if(e.charCodeAt(0)===58)return;let r=e.indexOf(":"),o,a;switch(r===-1?(o=e,a=""):(o=e.slice(0,r),
24
+ a=e.slice(r+1),a.charCodeAt(0)===32&&(a=a.slice(1))),o){case "data":this.datos+=a+`
25
+ `;break;case "event":this.evento=a;break;case "id":a.includes("\0")||(this.ultimoId=a);break;}}despachar(e){if(this.datos===""){this.evento="";return}e.push({event:this.evento===""?"message":
26
+ this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};var oe=new Set;function se(t,e,n){t===true||oe.has(e)||(oe.add(e),console.warn(n));}var je="[bvsala] internal: the layer changed a request this adapter must forward unchanged; nothing was sent.",Ie="[bvsala] internal: the layer asked for a second model call within one framework call;\
27
+ nothing more was sent.",Ue="[bvsala] internal: the layer called the model outside a framework call; nothing was sent.";function F(t,e,n,r){return {renderizado:t,generar:e,...n?{transmitir:n}:{},invocada:false,
28
+ completada:false,...r!==void 0?{origen:r}:{}}}function qe(t,e){if(t===e)return true;try{return ie(t)===ie(e)}catch{return false}}function ae(t,e){let n=t??[],r=e??[];return n.length===r.length&&n.every((o,a)=>qe(o,r[a]))}function Ne(t,e){return t.model===
29
+ e.model&&ae(t.messages,e.messages)&&ae(t.tools,e.tools)}function ce(t,e){let n=o=>{let a=e.getStore();if(!a)throw new Error(Ue);if(a.invocada)throw new Error(Ie);if(!Ne(o,a.renderizado))throw new Error(
30
+ je);return a.invocada=true,a},r={id:`bivelio-adapter:${t}`,async generate(o,a){return n(o).generar(a?.signal)},async*generateStream(o,a){let s=n(o);if(s.transmitir){yield*s.transmitir(a?.signal);return}
31
+ let i=await s.generar(a?.signal);i.text!==""&&(yield {type:"text",delta:i.text}),yield {type:"done",response:i};}};return Object.defineProperty(r,re,{value:()=>e.getStore()?.origen}),r}function le(){return new AsyncLocalStorage}
32
+ function ie(t){return JSON.stringify($(t))}function $(t){if(Array.isArray(t))return t.map($);if(t&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=$(t[n]);return e}return t}var Fe=["licenseKey","licenseServerUrl","serviceAccountKey","licenseRefresh","licenseRevocation","licensePollIntervalSeconds","licenseFetch","metering","meteringUrl","meteringFetch","costModels","defa\
33
+ ultCostModel","exactCache","exactCacheTtlMs","resolvers","exactTokenizer","silenceWarnings","failOpen"];function ue(t,e){return e instanceof LicenseError||t.errorDelMarco&&t.errorDelMarco.error===e?false:t.invocada&&
34
+ t.completada}var de="[bvsala] the model answered, but the savings layer failed while accounting for it; the answer is returned unchanged, without a savings report and without a usage record.";function fe(t,e){
35
+ let n=le(),r={};for(let s of Fe)e[s]!==void 0&&(r[s]=e[s]);let o=createSavingsLayer({...r,provider:ce(t,n)}),a=(s,i)=>se(e.silenceWarnings,`${t}:${s}`,i);return {ejecutar(s,i){return n.run(i,()=>o.generate(s))},async generar(s,i){
36
+ try{let u=await n.run(i,()=>o.generate(s));return i.invocada?{tipo:"vivo",result:u}:{tipo:"atajo",result:u}}catch(u){if(ue(i,u))return a("sin-informe",de),{tipo:"sin-informe"};throw u}},async transmitir(s,i,u){
37
+ let f=n.run(i,()=>o.generateStream(s,u?{signal:u}:{})).result;i.resultado=f,f.catch(()=>{});let h;try{h=await Promise.race([i.abierta.then(()=>"abierta"),f.then(()=>"resuelta")]);}catch(_){if(ue(i,_))return a(
38
+ "sin-informe",de),{tipo:"sin-informe"};throw _}if(h==="abierta")return {tipo:"abierto"};let m=await f;return i.invocada?{tipo:"entero",result:m}:{tipo:"atajo",result:m}},informe(s){let i=JSON.parse(JSON.
39
+ stringify(s));if(e.onReport)try{e.onReport(i);}catch{a("onreport","[bvsala] `onReport` threw; the error was caught and the model call was not affected.");}return i},avisar:a,close(){o.close();}}}function pe(){
40
+ let t;return {abierta:new Promise(n=>{t=n;}),abrir:t}}var L=class{pendientes=[];esperando;terminada=false;fallo;push(e){if(this.terminada||this.fallo)return;let n=this.esperando;if(n){this.esperando=void 0,n.resolver({value:e,done:false});return}this.pendientes.
35
41
  push(e);}end(){if(this.terminada||this.fallo)return;this.terminada=true;let e=this.esperando;e&&this.pendientes.length===0&&(this.esperando=void 0,e.resolver({value:void 0,done:true}));}fail(e){if(this.terminada||
36
42
  this.fallo)return;this.fallo={error:e};let n=this.esperando;n&&this.pendientes.length===0&&(this.esperando=void 0,n.rechazar(e));}get cerrada(){return this.terminada||this.fallo!==void 0}[Symbol.asyncIterator](){
37
43
  return {next:()=>this.pendientes.length>0?Promise.resolve({value:this.pendientes.shift(),done:false}):this.fallo?Promise.reject(this.fallo.error):this.terminada?Promise.resolve({value:void 0,done:true}):new Promise(
38
- (e,n)=>{this.esperando={resolver:e,rechazar:n};}),return:()=>(this.terminada=true,this.pendientes.length=0,Promise.resolve({value:void 0,done:true}))}}};var Ie={router:false,compression:false,elision:false,serialization:false,toolDiscovery:false,modelCascade:"off",outputCodebook:false,deferrable:false,semanticCache:false,verification:false};
39
- function Ue(t,e,n={}){let r=o=>t?.[o]!==false&&e?.[o]!==false;return {...Ie,exactCache:r("exactCache")&&n.sinReutilizar!==true,singleflight:r("singleflight")&&n.sinReutilizar!==true,deterministicResolvers:r("det\
40
- erministicResolvers")&&n.sinResolvers!==true}}function ze(t,e){let n=t.readOnlyTools;if(typeof n=="function")try{return n(e)===!0}catch{return false}return Array.isArray(n)?n.includes(e):false}function pe(t,e){
41
- let n=e.delProveedor!==true&&ze(t,e.nombre);return {id:e.nombre,intents:[],risk:n?"read":"write",...e.parametros!==void 0&&e.parametros!==null&&typeof e.parametros=="object"?{parameters:e.parametros}:{},
42
- ...typeof e.descripcion=="string"?{description:e.descripcion}:{}}}function P(t,e,n){if(t===null)return null;switch(typeof t){case "string":case "boolean":return t;case "number":return Number.isFinite(t)?
43
- t:String(t);case "bigint":return `${t.toString()}n`;case "undefined":case "function":case "symbol":return}let r=t;if(r instanceof Uint8Array)return e.push(r),{$bytes:e.length-1};if(r instanceof ArrayBuffer)
44
- return e.push(new Uint8Array(r)),{$bytes:e.length-1};if(ArrayBuffer.isView(r))return e.push(new Uint8Array(r.buffer,r.byteOffset,r.byteLength)),{$bytes:e.length-1};if(r instanceof URL)return {$url:r.href};
45
- if(r instanceof Date)return {$date:Number.isNaN(r.getTime())?"invalid":r.toISOString()};if(n.has(r))return "$cycle";n.add(r);try{if(Array.isArray(r))return r.map(s=>{let a=P(s,e,n);return a===void 0?null:
46
- a});if(r instanceof Map)return {$map:[...r.entries()].map(s=>P(s,e,n))};if(r instanceof Set)return {$set:[...r.values()].map(s=>P(s,e,n))};let o={};for(let s of Object.keys(r).sort()){let a=P(r[s],e,n);
47
- a!==void 0&&(o[s]=a);}return o}finally{n.delete(r);}}async function de(t){let e=globalThis.crypto?.subtle;if(e){let r=new Uint8Array(await e.digest("SHA-256",t));return Array.from(r,o=>o.toString(16).padStart(
48
- 2,"0")).join("")}let n="";for(let r=0;r<t.length;r+=32768)n+=String.fromCharCode(...t.subarray(r,r+32768));return sha256(n)}async function $e(t){try{let e=[],n=JSON.stringify(P(t,e,new WeakSet))??"null",r=await Promise.
49
- all(e.map(de)),o=new TextEncoder().encode(`${n}|${r.join(",")}`);return await de(o)}catch{return null}}async function fe(t,e){let n=await $e(e.proyeccion),r=`${e.context?.authorizationScope??"default"}\
50
- |bvsala-adapter:${n??"none"}`;return {model:e.model,messages:e.messages,...e.tools.length>0?{tools:e.tools}:{},...typeof e.temperature=="number"?{temperature:e.temperature}:{},...typeof e.seed=="number"?
51
- {seed:e.seed}:{},context:{...e.context??{},authorizationScope:r},savings:Ue(t.savings,e.savings,{...e.restricciones,...n===null?{sinReutilizar:true}:{}})}}function ge(t,e){if(!(!t&&!e))return {...t??{},...e??
52
- {}}}function me(t){if(!t||typeof t!="object")return {};let e=t,n={};return e.context&&typeof e.context=="object"&&(n.context=e.context),e.savings&&typeof e.savings=="object"&&(n.savings=e.savings),n}var z="[bvsala] could not read the request body; nothing was sent.";function p(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Je(t){if((t.method??"GET").toUpperCase()!=="POST")return false;
53
- try{return new URL(t.url).pathname.replace(/\/+$/,"").endsWith("/v1/messages")}catch{return false}}function A(t){return typeof t=="string"?[{type:"text",text:t}]:Array.isArray(t)?t.filter(p):[]}function T(t){
44
+ (e,n)=>{this.esperando={resolver:e,rechazar:n};}),return:()=>(this.terminada=true,this.pendientes.length=0,Promise.resolve({value:void 0,done:true}))}}};var Je=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,
45
+ 4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,
46
+ 1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,
47
+ 1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),We=new TextEncoder;function R(t,e){return t>>>e|t<<32-e}function ge(t){let e=We.encode(t),n=e.length*
48
+ 8,r=(e.length+8>>6)+1,o=new Uint8Array(r*64);o.set(e),o[e.length]=128;let a=new DataView(o.buffer);a.setUint32(o.length-8,Math.floor(n/4294967296)),a.setUint32(o.length-4,n>>>0);let s=new Uint32Array(
49
+ [1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),i=new Uint32Array(64);for(let d=0;d<o.length;d+=64){for(let p=0;p<16;p++)i[p]=a.getUint32(d+p*4);for(let p=16;p<
50
+ 64;p++){let D=i[p-15],S=i[p-2],A=R(D,7)^R(D,18)^D>>>3,C=R(S,17)^R(S,19)^S>>>10;i[p]=i[p-16]+A+i[p-7]+C|0;}let f=s[0],h=s[1],m=s[2],_=s[3],l=s[4],v=s[5],b=s[6],w=s[7];for(let p=0;p<64;p++){let D=R(l,6)^
51
+ R(l,11)^R(l,25),S=l&v^~l&b,A=w+D+S+Je[p]+i[p]|0,C=R(f,2)^R(f,13)^R(f,22),P=f&h^f&m^h&m,k=C+P|0;w=b,b=v,v=l,l=_+A|0,_=m,m=h,h=f,f=A+k|0;}s[0]=s[0]+f|0,s[1]=s[1]+h|0,s[2]=s[2]+m|0,s[3]=s[3]+_|0,s[4]=s[4]+
52
+ l|0,s[5]=s[5]+v|0,s[6]=s[6]+b|0,s[7]=s[7]+w|0;}let u="";for(let d=0;d<8;d++)u+=(s[d]>>>0).toString(16).padStart(8,"0");return u}var Be={router:false,compression:false,elision:false,serialization:false,toolDiscovery:false,modelCascade:"off",outputCodebook:false,deferrable:false,semanticCache:false,verification:false};function Ve(t,e,n={}){let r=o=>t?.[o]!==
53
+ false&&e?.[o]!==false;return {...Be,exactCache:r("exactCache")&&n.sinReutilizar!==true,singleflight:r("singleflight")&&n.sinReutilizar!==true,deterministicResolvers:r("deterministicResolvers")&&n.sinResolvers!==
54
+ true}}function Ge(t,e){let n=t.readOnlyTools;if(typeof n=="function")try{return n(e)===!0}catch{return false}return Array.isArray(n)?n.includes(e):false}function me(t,e){let n=e.delProveedor!==true&&Ge(t,e.nombre);
55
+ return {id:e.nombre,intents:[],risk:n?"read":"write",...e.parametros!==void 0&&e.parametros!==null&&typeof e.parametros=="object"?{parameters:e.parametros}:{},...typeof e.descripcion=="string"?{description:e.
56
+ descripcion}:{}}}function j(t,e,n){if(t===null)return null;switch(typeof t){case "string":case "boolean":return t;case "number":return Number.isFinite(t)?t:String(t);case "bigint":return `${t.toString()}n`;case "\
57
+ undefined":case "function":case "symbol":return}let r=t;if(r instanceof Uint8Array)return e.push(r),{$bytes:e.length-1};if(r instanceof ArrayBuffer)return e.push(new Uint8Array(r)),{$bytes:e.length-1};if(ArrayBuffer.
58
+ isView(r))return e.push(new Uint8Array(r.buffer,r.byteOffset,r.byteLength)),{$bytes:e.length-1};if(r instanceof URL)return {$url:r.href};if(r instanceof Date)return {$date:Number.isNaN(r.getTime())?"inv\
59
+ alid":r.toISOString()};if(n.has(r))return "$cycle";n.add(r);try{if(Array.isArray(r))return r.map(a=>{let s=j(a,e,n);return s===void 0?null:s});if(r instanceof Map)return {$map:[...r.entries()].map(a=>j(
60
+ a,e,n))};if(r instanceof Set)return {$set:[...r.values()].map(a=>j(a,e,n))};let o={};for(let a of Object.keys(r).sort()){let s=j(r[a],e,n);s!==void 0&&(o[a]=s);}return o}finally{n.delete(r);}}async function he(t){
61
+ let e=globalThis.crypto?.subtle;if(e){let r=new Uint8Array(await e.digest("SHA-256",t));return Array.from(r,o=>o.toString(16).padStart(2,"0")).join("")}let n="";for(let r=0;r<t.length;r+=32768)n+=String.
62
+ fromCharCode(...t.subarray(r,r+32768));return ge(n)}async function He(t){try{let e=[],n=JSON.stringify(j(t,e,new WeakSet))??"null",r=await Promise.all(e.map(he)),o=new TextEncoder().encode(`${n}|${r.join(
63
+ ",")}`);return await he(o)}catch{return null}}async function ye(t,e){let n=await He(e.proyeccion),r=`${e.context?.authorizationScope??"default"}|bvsala-adapter:${n??"none"}`;return {model:e.model,messages:e.
64
+ messages,...e.tools.length>0?{tools:e.tools}:{},...typeof e.temperature=="number"?{temperature:e.temperature}:{},...typeof e.seed=="number"?{seed:e.seed}:{},context:{...e.context??{},authorizationScope:r},
65
+ savings:Ve(t.savings,e.savings,{...e.restricciones,...n===null?{sinReutilizar:true}:{}})}}function ve(t,e){if(!(!t&&!e))return {...t??{},...e??{}}}function be(t){if(!t||typeof t!="object")return {};let e=t,
66
+ n={};return e.context&&typeof e.context=="object"&&(n.context=e.context),e.savings&&typeof e.savings=="object"&&(n.savings=e.savings),n}var J="[bvsala] could not read the request body; nothing was sent.";function g(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ye(t){if((t.method??"GET").toUpperCase()!=="POST")return false;
67
+ try{return new URL(t.url).pathname.replace(/\/+$/,"").endsWith("/v1/messages")}catch{return false}}function M(t){return typeof t=="string"?[{type:"text",text:t}]:Array.isArray(t)?t.filter(g):[]}function U(t){
54
68
  return t.filter(e=>e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(`
55
- `)}function _e(t){if(typeof t=="string")return t;try{return JSON.stringify(t??{})}catch{return "{}"}}function Fe(t){let e=[],n=t.system;(typeof n=="string"?n!=="":Array.isArray(n))&&e.push({role:"syste\
56
- m",content:typeof n=="string"?n:T(A(n))});for(let r of Array.isArray(t.messages)?t.messages:[]){if(!p(r))continue;let o=A(r.content);if(r.role==="assistant"){let a=o.filter(i=>i.type==="tool_use").map(
57
- i=>({...typeof i.id=="string"?{id:i.id}:{},name:String(i.name??""),arguments:_e(i.input)}));e.push({role:"assistant",content:T(o),...a.length>0?{toolCalls:a}:{}});continue}for(let a of o)a.type==="too\
58
- l_result"&&e.push({role:"tool",content:typeof a.content=="string"?a.content:T(A(a.content)),...typeof a.tool_use_id=="string"?{toolCallId:a.tool_use_id}:{}});let s=T(o);(s!==""||!o.some(a=>a.type==="t\
59
- ool_result"))&&e.push({role:"user",content:s});}return e}function he(t){let e={};for(let[n,r]of Object.entries(t))n==="id"||n==="tool_use_id"||n==="text"&&t.type==="text"||(e[n]=r);return e}function We(t,e){
60
- let n={};for(let[r,o]of Object.entries(t))r==="stream"||r==="metadata"||r==="messages"||r==="system"||(n[r]=o);return n.system=typeof t.system=="string"?"$text":A(t.system).map(he),n.messages=(Array.isArray(
61
- t.messages)?t.messages:[]).filter(p).map(r=>({role:r.role,content:A(r.content).map(he)})),e&&(n["anthropic-beta"]=e),n}function Be(t){let e=t.tool_choice;return p(e)&&(e.type==="any"||e.type==="tool")||
62
- p(t.output_config)&&t.output_config.format!==void 0?true:t.output_format!==void 0}function Ve(t){let e=typeof t.model=="string"?t.model:"";if(e==="")return [];let n=[],r=t.tool_choice;p(r)&&(r.type==="an\
63
- y"||r.type==="tool")&&Q(e)&&n.push({clave:`tool-choice-forzado:${e}`,mensaje:`[bvsala] Model "${e}" rejects a forced \`tool_choice\` (\`any\` or \`tool\`) with a 400, with or without thinking. This adapter \
64
- forwards your request unchanged, so the API will reject it: use \`tool_choice: {type: "auto"}\` with \`strict: true\` tools, or \`output_config.format\` for a fixed JSON shape. See https://platform.claude.c\
65
- om/docs/en/agents-and-tools/tool-use/define-tools#forcing-tool-use`});let o=["temperature","top_p","top_k"].filter(s=>typeof t[s]=="number"&&!(s==="temperature"&&t[s]===1));return o.length>0&&X(e)&&n.
66
- push({clave:`muestreo:${e}`,mensaje:`[bvsala] Model "${e}" rejects a non-default ${o.map(s=>`\`${s}\``).join(", ")} with a 400. This adapter forwards your request unchanged, so the API will reject it:\
67
- drop the parameter for this model. See https://platform.claude.com/docs/en/models/sonnet-5-5/overview`}),n}var M=class{id;texto="";razono=false;reproducible=true;parada;detallesDeParada;bloquesVistos=0;usoInicio;usoDelta;vioDelta=false;vioStop=false;error;herramientas=new Map;toolCallsJson=[];bloque(e){
68
- this.bloquesVistos+=1,G(e.type)?(this.razono=true,this.reproducible=false):e.type==="text"?Array.isArray(e.citations)&&e.citations.length>0&&(this.reproducible=false):e.type!=="tool_use"&&(this.reproducible=false);}json(e){
69
- this.id=typeof e.id=="string"?e.id:void 0;for(let n of A(e.content))this.bloque(n),n.type==="text"&&typeof n.text=="string"&&(this.texto+=n.text),n.type==="tool_use"&&this.toolCallsJson.push({...typeof n.
70
- id=="string"?{id:n.id}:{},name:String(n.name??""),arguments:_e(n.input)});this.parada=typeof e.stop_reason=="string"?e.stop_reason:void 0,this.detallesDeParada=e.stop_details,this.usoInicio=p(e.usage)?
71
- e.usage:void 0,this.usoDelta=this.usoInicio,this.vioDelta=true,this.vioStop=true;}evento(e){let n;try{n=JSON.parse(e.data);}catch{return}if(!p(n))return;switch(e.event!=="message"?e.event:String(n.type??e.event)){case "\
72
- message_start":{let o=p(n.message)?n.message:{};typeof o.id=="string"&&(this.id=o.id),p(o.usage)&&(this.usoInicio=o.usage);return}case "content_block_start":{let o=p(n.content_block)?n.content_block:{};
73
- this.bloque(o),o.type==="tool_use"&&typeof n.index=="number"&&this.herramientas.set(n.index,{...typeof o.id=="string"?{id:o.id}:{},name:String(o.name??""),json:""});return}case "content_block_delta":{let o=p(
69
+ `)}function Re(t){if(typeof t=="string")return t;try{return JSON.stringify(t??{})}catch{return "{}"}}function Ze(t){let e=[],n=t.system;(typeof n=="string"?n!=="":Array.isArray(n))&&e.push({role:"syste\
70
+ m",content:typeof n=="string"?n:U(M(n))});for(let r of Array.isArray(t.messages)?t.messages:[]){if(!g(r))continue;let o=M(r.content);if(r.role==="assistant"){let s=o.filter(i=>i.type==="tool_use").map(
71
+ i=>({...typeof i.id=="string"?{id:i.id}:{},name:String(i.name??""),arguments:Re(i.input)}));e.push({role:"assistant",content:U(o),...s.length>0?{toolCalls:s}:{}});continue}for(let s of o)s.type==="too\
72
+ l_result"&&e.push({role:"tool",content:typeof s.content=="string"?s.content:U(M(s.content)),...typeof s.tool_use_id=="string"?{toolCallId:s.tool_use_id}:{}});let a=U(o);(a!==""||!o.some(s=>s.type==="t\
73
+ ool_result"))&&e.push({role:"user",content:a});}return e}function xe(t){let e={};for(let[n,r]of Object.entries(t))n==="id"||n==="tool_use_id"||n==="text"&&t.type==="text"||(e[n]=r);return e}function Xe(t,e){
74
+ let n={};for(let[r,o]of Object.entries(t))r==="stream"||r==="metadata"||r==="messages"||r==="system"||(n[r]=o);return n.system=typeof t.system=="string"?"$text":M(t.system).map(xe),n.messages=(Array.isArray(
75
+ t.messages)?t.messages:[]).filter(g).map(r=>({role:r.role,content:M(r.content).map(xe)})),e&&(n["anthropic-beta"]=e),n}function Qe(t){let e=t.tool_choice;return g(e)&&(e.type==="any"||e.type==="tool")||
76
+ g(t.output_config)&&t.output_config.format!==void 0?true:t.output_format!==void 0}function et(t){let e=typeof t.model=="string"?t.model:"";if(e==="")return [];let n=[],r=t.tool_choice;g(r)&&(r.type==="an\
77
+ y"||r.type==="tool")&&ee(e)&&n.push({clave:`tool-choice-forzado:${e}`,mensaje:`[bvsala] Model "${e}" rejects a forced \`tool_choice\` (\`any\` or \`tool\`) with a 400, with or without thinking. This adapter\
78
+ forwards your request unchanged, so the API will reject it: use \`tool_choice: {type: "auto"}\` with \`strict: true\` tools, or \`output_config.format\` for a fixed JSON shape. See https://platform.claude.\
79
+ com/docs/en/agents-and-tools/tool-use/define-tools#forcing-tool-use`});let o=["temperature","top_p","top_k"].filter(a=>typeof t[a]=="number"&&!(a==="temperature"&&t[a]===1));return o.length>0&&te(e)&&
80
+ n.push({clave:`muestreo:${e}`,mensaje:`[bvsala] Model "${e}" rejects a non-default ${o.map(a=>`\`${a}\``).join(", ")} with a 400. This adapter forwards your request unchanged, so the API will reject i\
81
+ t: drop the parameter for this model. See https://platform.claude.com/docs/en/models/sonnet-5-5/overview`}),n}var q=class{id;texto="";razono=false;reproducible=true;parada;detallesDeParada;bloquesVistos=0;usoInicio;usoDelta;vioDelta=false;vioStop=false;error;herramientas=new Map;toolCallsJson=[];bloque(e){
82
+ this.bloquesVistos+=1,Y(e.type)?(this.razono=true,this.reproducible=false):e.type==="text"?Array.isArray(e.citations)&&e.citations.length>0&&(this.reproducible=false):e.type!=="tool_use"&&(this.reproducible=false);}json(e){
83
+ this.id=typeof e.id=="string"?e.id:void 0;for(let n of M(e.content))this.bloque(n),n.type==="text"&&typeof n.text=="string"&&(this.texto+=n.text),n.type==="tool_use"&&this.toolCallsJson.push({...typeof n.
84
+ id=="string"?{id:n.id}:{},name:String(n.name??""),arguments:Re(n.input)});this.parada=typeof e.stop_reason=="string"?e.stop_reason:void 0,this.detallesDeParada=e.stop_details,this.usoInicio=g(e.usage)?
85
+ e.usage:void 0,this.usoDelta=this.usoInicio,this.vioDelta=true,this.vioStop=true;}evento(e){let n;try{n=JSON.parse(e.data);}catch{return}if(!g(n))return;switch(e.event!=="message"?e.event:String(n.type??e.event)){case "\
86
+ message_start":{let o=g(n.message)?n.message:{};typeof o.id=="string"&&(this.id=o.id),g(o.usage)&&(this.usoInicio=o.usage);return}case "content_block_start":{let o=g(n.content_block)?n.content_block:{};
87
+ this.bloque(o),o.type==="tool_use"&&typeof n.index=="number"&&this.herramientas.set(n.index,{...typeof o.id=="string"?{id:o.id}:{},name:String(o.name??""),json:""});return}case "content_block_delta":{let o=g(
74
88
  n.delta)?n.delta:{};if(o.type==="text_delta"&&typeof o.text=="string")return this.texto+=o.text,o.text===""?void 0:o.text;if(o.type==="input_json_delta"&&typeof o.partial_json=="string"&&typeof n.index==
75
- "number"){let s=this.herramientas.get(n.index);s&&(s.json+=o.partial_json);}o.type==="citations_delta"&&(this.reproducible=false);return}case "message_delta":{this.vioDelta=true;let o=p(n.delta)?n.delta:{};typeof o.
76
- stop_reason=="string"&&(this.parada=o.stop_reason),"stop_details"in o&&(this.detallesDeParada=o.stop_details),p(n.usage)&&(this.usoDelta=q(this.usoDelta,n.usage));return}case "message_stop":this.vioStop=
77
- true;return;case "error":{let o=p(n.error)?n.error:{};this.error=`${String(o.type??"error")}: ${String(o.message??"")}`;return}default:return}}get toolCalls(){return this.toolCallsJson.length>0?this.toolCallsJson:
78
- [...this.herramientas.entries()].sort((e,n)=>e[0]-n[0]).map(([,e])=>({...e.id?{id:e.id}:{},name:e.name,arguments:Ge(e.json)})).filter(e=>e.name!=="")}respuesta(){let e=q(this.usoInicio,this.usoDelta),
79
- n=this.vioDelta?B(e,this.usoDelta?.output_tokens,this.razono).usage:{inputTokens:0,outputTokens:0,complete:false},r=e.iterations;Array.isArray(r)&&r.length>1&&(n.complete=false);let o=this.toolCalls,s=V(e);
80
- return {text:this.texto,...o.length>0?{toolCalls:o}:{},...this.parada?{finishReason:H(this.parada)}:{},...I(this.parada,this.detallesDeParada)!==void 0?{finishReasonDetail:I(this.parada,this.detallesDeParada)}:
81
- {},...this.vioDelta&&K({stopReason:this.parada,stopDetails:this.detallesDeParada,bloques:this.bloquesVistos,outputTokens:this.usoDelta?.output_tokens,iterations:r})?{unbilledRefusal:true}:{},...s?{servedServiceTier:s}:
82
- {},usage:n,...this.reproducible&&this.parada==="end_turn"?{}:{replayable:false}}}};function Ge(t){try{return JSON.stringify(JSON.parse(t===""?"{}":t))}catch{return t}}function He(t,e){let n=[];return t.text!==
83
- ""&&n.push({type:"text",text:t.text}),(t.toolCalls??[]).forEach((r,o)=>{let s={};try{s=JSON.parse(r.arguments||"{}");}catch{s={};}n.push({type:"tool_use",id:r.id??`toolu_bvsala_${t.requestId}_${o}`,name:r.
84
- name,input:s});}),{id:`msg_bvsala_${t.requestId}`,type:"message",role:"assistant",model:e,content:n,stop_reason:(t.toolCalls?.length??0)>0?"tool_use":"end_turn",stop_sequence:null,usage:{input_tokens:0,
85
- output_tokens:0}}}function ye(t,e,n){let r=He(t,e),o={"request-id":`bvsala_${t.requestId}`};if(!n)return new Response(JSON.stringify(r),{status:200,headers:{...o,"content-type":"application/json"}});let s=(i,u)=>`\
86
- event: ${i}
89
+ "number"){let a=this.herramientas.get(n.index);a&&(a.json+=o.partial_json);}o.type==="citations_delta"&&(this.reproducible=false);return}case "message_delta":{this.vioDelta=true;let o=g(n.delta)?n.delta:{};typeof o.
90
+ stop_reason=="string"&&(this.parada=o.stop_reason),"stop_details"in o&&(this.detallesDeParada=o.stop_details),g(n.usage)&&(this.usoDelta=z(this.usoDelta,n.usage));return}case "message_stop":this.vioStop=
91
+ true;return;case "error":{let o=g(n.error)?n.error:{};this.error=`${String(o.type??"error")}: ${String(o.message??"")}`;return}default:return}}get toolCalls(){return this.toolCallsJson.length>0?this.toolCallsJson:
92
+ [...this.herramientas.entries()].sort((e,n)=>e[0]-n[0]).map(([,e])=>({...e.id?{id:e.id}:{},name:e.name,arguments:tt(e.json)})).filter(e=>e.name!=="")}respuesta(){let e=z(this.usoInicio,this.usoDelta),
93
+ n=this.vioDelta?H(e,this.usoDelta?.output_tokens,this.razono).usage:{inputTokens:0,outputTokens:0,complete:false},r=e.iterations;Array.isArray(r)&&r.length>1&&(n.complete=false);let o=this.toolCalls,a=K(e);
94
+ return {text:this.texto,...o.length>0?{toolCalls:o}:{},...Z(this.parada,this.detallesDeParada),...this.vioDelta&&X({stopReason:this.parada,stopDetails:this.detallesDeParada,bloques:this.bloquesVistos,outputTokens:this.
95
+ usoDelta?.output_tokens,iterations:r})?{unbilledRefusal:true}:{},...a?{servedServiceTier:a}:{},usage:n,...this.reproducible&&this.parada==="end_turn"?{}:{replayable:false}}}};function tt(t){try{return JSON.
96
+ stringify(JSON.parse(t===""?"{}":t))}catch{return t}}function nt(t,e){let n=[];return t.text!==""&&n.push({type:"text",text:t.text}),(t.toolCalls??[]).forEach((r,o)=>{let a={};try{a=JSON.parse(r.arguments||
97
+ "{}");}catch{a={};}n.push({type:"tool_use",id:r.id??`toolu_bvsala_${t.requestId}_${o}`,name:r.name,input:a});}),{id:`msg_bvsala_${t.requestId}`,type:"message",role:"assistant",model:e,content:n,stop_reason:(t.
98
+ toolCalls?.length??0)>0?"tool_use":"end_turn",stop_sequence:null,usage:{input_tokens:0,output_tokens:0}}}function _e(t,e,n){let r=nt(t,e),o={"request-id":`bvsala_${t.requestId}`};if(!n)return new Response(
99
+ JSON.stringify(r),{status:200,headers:{...o,"content-type":"application/json"}});let a=(i,u)=>`event: ${i}
87
100
  data: ${JSON.stringify(u)}
88
101
 
89
- `,a=s("message_start",{type:"message_start",message:{...r,content:[],stop_reason:null,stop_sequence:null}});return r.content.forEach((i,u)=>{i.type==="text"?(a+=s("content_block_start",{type:"content_\
90
- block_start",index:u,content_block:{type:"text",text:""}}),a+=s("content_block_delta",{type:"content_block_delta",index:u,delta:{type:"text_delta",text:i.text}})):(a+=s("content_block_start",{type:"co\
91
- ntent_block_start",index:u,content_block:{type:"tool_use",id:i.id,name:i.name,input:{}}}),a+=s("content_block_delta",{type:"content_block_delta",index:u,delta:{type:"input_json_delta",partial_json:JSON.
92
- stringify(i.input)}})),a+=s("content_block_stop",{type:"content_block_stop",index:u});}),a+=s("message_delta",{type:"message_delta",delta:{stop_reason:r.stop_reason,stop_sequence:null},usage:{output_tokens:0}}),
93
- a+=s("message_stop",{type:"message_stop"}),new Response(a,{status:200,headers:{...o,"content-type":"text/event-stream"}})}var E=class extends Error{constructor(n){super(`[bvsala] provider responded ${n.
94
- status}`);this.respuesta=n;}respuesta};function wt(t){let e=ue("anthropic-sdk",t),n=Math.max(1,Math.floor(t.reportCacheSize??1e3)),r=new Map,o=(a,i)=>{if(a)for(r.delete(a),r.set(a,i);r.size>n;)r.delete(
95
- r.keys().next().value);};return {middleware:async(a,i,u)=>{if(!Je(a))return i(a);if(typeof a.body!="string")throw new Error(z);let d;try{let c=JSON.parse(a.body);if(!p(c))throw new Error(z);d=c;}catch{throw new Error(
96
- z)}for(let c of Ve(d))e.avisar(c.clave,c.mensaje);let g=u.options,m=me(g?.bivelio),h=t.context?.({body:d,requestOptions:g}),b=(Array.isArray(d.tools)?d.tools:[]).filter(p).map(c=>pe(t,{nombre:String(c.
97
- name??""),descripcion:typeof c.description=="string"?c.description:void 0,parametros:c.input_schema,delProveedor:c.input_schema===void 0&&typeof c.type=="string"&&c.type!=="custom"})),l=await fe(t,{model:`\
98
- anthropic/${String(d.model??"")}`,messages:Fe(d),tools:b,temperature:typeof d.temperature=="number"?d.temperature:void 0,context:ge(h,m.context),savings:m.savings,proyeccion:We(d,a.headers.get("anthro\
99
- pic-beta")),restricciones:{sinResolvers:Be(d)}}),v={model:l.model,messages:l.messages,...l.tools?{tools:l.tools}:{}},_=Y(a.url),w=async c=>{let f;try{f=await i(a);}catch(y){throw c.errorDelMarco={error:y},
100
- y}if(!f.ok){let y=new E(f);throw c.errorDelMarco={error:y},y}return c.completada=true,f},$=c=>{if(c instanceof E)return c.respuesta;throw c};if(d.stream!==true){let c,f,y=U(v,async()=>{c=await w(y);let D=new M;
101
- return D.json(await c.clone().json()),f=D.id,D.respuesta()},void 0,_),S;try{S=await e.generar(l,y);}catch(D){return $(D)}if(S.tipo==="sin-informe")return c;let J=e.informe(S.result.report);return S.tipo===
102
- "atajo"?(o(`msg_bvsala_${S.result.requestId}`,J),ye(S.result,d.model,false)):(o(f,J),c)}let{abierta:be,abrir:N}=le(),L,j,k=Object.assign(U(v,async()=>{let c=await w(k),f=new C;j=ve(c,f,e,k,o),N();for await(let y of f)
103
- if(y.type==="done")return y.response;throw new Error("[bvsala] the model stream ended before completion; nothing was measured.")},()=>{let c=new C;return w(k).then(f=>{L=ve(f,c,e,k,o),N();},f=>c.fail(f)),
104
- c},_),{abierta:be}),R;try{R=await e.transmitir(l,k,a.signal??void 0);}catch(c){return $(c)}if(R.tipo==="abierto")return L??j;if(R.tipo==="atajo"){let c=e.informe(R.result.report);return o(`msg_bvsala_${R.
105
- result.requestId}`,c),ye(R.result,d.model,true)}return L??j},reportFor(a){let i=typeof a=="string"?a:a?.id;return typeof i=="string"?r.get(i):void 0},close(){e.close();}}}function ve(t,e,n,r,o){let s=new M,
106
- a,i=async()=>{try{let l=await r.resultado;o(s.id,n.informe(l.report));}catch{}},u=()=>{e.cerrada||(s.error?e.fail(new Error(`[bvsala] provider stream error: ${s.error}`)):s.vioDelta||s.vioStop?(e.push(
107
- {type:"done",response:s.respuesta()}),e.end(),a=i()):e.fail(new Error("[bvsala] the model stream ended before completion; nothing was measured.")));};if((t.headers.get("content-type")??"").includes("ap\
108
- plication/json"))return t.clone().json().then(l=>{s.json(p(l)?l:{}),s.texto!==""&&e.push({type:"text",delta:s.texto}),u();},l=>e.fail(l)),t;let d=t.body;if(!d)return e.fail(new Error("[bvsala] the mode\
109
- l stream had no body; nothing was measured.")),t;let g=d.getReader(),m=new O,h=l=>{for(let v of l){let _=s.evento(v);_!==void 0&&e.push({type:"text",delta:_}),(s.vioStop||s.error)&&u();}},b=new ReadableStream(
110
- {async pull(l){let v;try{v=await g.read();}catch(w){e.fail(w),l.error(w);return}if(v.done){h(m.end()),u(),await a,l.close();return}let _=v.value;l.enqueue(_),h(m.push(_));},cancel(l){return e.fail(new Error(
111
- "[bvsala] the stream was cancelled by its reader; nothing was measured.")),g.cancel(l)}});return new Response(b,{status:t.status,statusText:t.statusText,headers:t.headers})}export{wt as anthropicSavings};
102
+ `,s=a("message_start",{type:"message_start",message:{...r,content:[],stop_reason:null,stop_sequence:null}});return r.content.forEach((i,u)=>{i.type==="text"?(s+=a("content_block_start",{type:"content_\
103
+ block_start",index:u,content_block:{type:"text",text:""}}),s+=a("content_block_delta",{type:"content_block_delta",index:u,delta:{type:"text_delta",text:i.text}})):(s+=a("content_block_start",{type:"co\
104
+ ntent_block_start",index:u,content_block:{type:"tool_use",id:i.id,name:i.name,input:{}}}),s+=a("content_block_delta",{type:"content_block_delta",index:u,delta:{type:"input_json_delta",partial_json:JSON.
105
+ stringify(i.input)}})),s+=a("content_block_stop",{type:"content_block_stop",index:u});}),s+=a("message_delta",{type:"message_delta",delta:{stop_reason:r.stop_reason,stop_sequence:null},usage:{output_tokens:0}}),
106
+ s+=a("message_stop",{type:"message_stop"}),new Response(s,{status:200,headers:{...o,"content-type":"text/event-stream"}})}var N=class extends Error{constructor(n){super(`[bvsala] provider responded ${n.
107
+ status}`);this.respuesta=n;}respuesta};function Ot(t){let e=fe("anthropic-sdk",t),n=Math.max(1,Math.floor(t.reportCacheSize??1e3)),r=new Map,o=(s,i)=>{if(s)for(r.delete(s),r.set(s,i);r.size>n;)r.delete(
108
+ r.keys().next().value);};return {middleware:async(s,i,u)=>{if(!Ye(s))return i(s);if(typeof s.body!="string")throw new Error(J);let d;try{let c=JSON.parse(s.body);if(!g(c))throw new Error(J);d=c;}catch{throw new Error(
109
+ J)}for(let c of et(d))e.avisar(c.clave,c.mensaje);let f=u.options,h=be(f?.bivelio),m=t.context?.({body:d,requestOptions:f}),_=(Array.isArray(d.tools)?d.tools:[]).filter(g).map(c=>me(t,{nombre:String(c.
110
+ name??""),descripcion:typeof c.description=="string"?c.description:void 0,parametros:c.input_schema,delProveedor:c.input_schema===void 0&&typeof c.type=="string"&&c.type!=="custom"})),l=await ye(t,{model:`\
111
+ anthropic/${String(d.model??"")}`,messages:Ze(d),tools:_,temperature:typeof d.temperature=="number"?d.temperature:void 0,context:ve(m,h.context),savings:h.savings,proyeccion:Xe(d,s.headers.get("anthro\
112
+ pic-beta")),restricciones:{sinResolvers:Qe(d)}}),v={model:l.model,messages:l.messages,...l.tools?{tools:l.tools}:{}},b=ne(s.url),w=async c=>{let y;try{y=await i(s);}catch(x){throw c.errorDelMarco={error:x},
113
+ x}if(!y.ok){let x=new N(y);throw c.errorDelMarco={error:x},x}return c.completada=true,y},p=c=>{if(c instanceof N)return c.respuesta;throw c};if(d.stream!==true){let c,y,x=F(v,async()=>{c=await w(x);let E=new q;
114
+ return E.json(await c.clone().json()),y=E.id,E.respuesta()},void 0,b),T;try{T=await e.generar(l,x);}catch(E){return p(E)}if(T.tipo==="sin-informe")return c;let W=e.informe(T.result.report);return T.tipo===
115
+ "atajo"?(o(`msg_bvsala_${T.result.requestId}`,W),_e(T.result,d.model,false)):(o(y,W),c)}let{abierta:D,abrir:S}=pe(),A,C,P=Object.assign(F(v,async()=>{let c=await w(P),y=new L;C=we(c,y,e,P,o),S();for await(let x of y)
116
+ if(x.type==="done")return x.response;throw new Error("[bvsala] the model stream ended before completion; nothing was measured.")},()=>{let c=new L;return w(P).then(y=>{A=we(y,c,e,P,o),S();},y=>c.fail(y)),
117
+ c},b),{abierta:D}),k;try{k=await e.transmitir(l,P,s.signal??void 0);}catch(c){return p(c)}if(k.tipo==="abierto")return A??C;if(k.tipo==="atajo"){let c=e.informe(k.result.report);return o(`msg_bvsala_${k.
118
+ result.requestId}`,c),_e(k.result,d.model,true)}return A??C},reportFor(s){let i=typeof s=="string"?s:s?.id;return typeof i=="string"?r.get(i):void 0},close(){e.close();}}}function we(t,e,n,r,o){let a=new q,
119
+ s,i=async()=>{try{let l=await r.resultado;o(a.id,n.informe(l.report));}catch{}},u=()=>{e.cerrada||(a.error?e.fail(new Error(`[bvsala] provider stream error: ${a.error}`)):a.vioDelta||a.vioStop?(e.push(
120
+ {type:"done",response:a.respuesta()}),e.end(),s=i()):e.fail(new Error("[bvsala] the model stream ended before completion; nothing was measured.")));};if((t.headers.get("content-type")??"").includes("ap\
121
+ plication/json"))return t.clone().json().then(l=>{a.json(g(l)?l:{}),a.texto!==""&&e.push({type:"text",delta:a.texto}),u();},l=>e.fail(l)),t;let d=t.body;if(!d)return e.fail(new Error("[bvsala] the mode\
122
+ l stream had no body; nothing was measured.")),t;let f=d.getReader(),h=new I,m=l=>{for(let v of l){let b=a.evento(v);b!==void 0&&e.push({type:"text",delta:b}),(a.vioStop||a.error)&&u();}},_=new ReadableStream(
123
+ {async pull(l){let v;try{v=await f.read();}catch(w){e.fail(w),l.error(w);return}if(v.done){m(h.end()),u(),await s,l.close();return}let b=v.value;l.enqueue(b),m(h.push(b));},cancel(l){return e.fail(new Error(
124
+ "[bvsala] the stream was cancelled by its reader; nothing was measured.")),f.cancel(l)}});return new Response(_,{status:t.status,statusText:t.statusText,headers:t.headers})}export{Ot as anthropicSavings};
@@ -1,60 +1,69 @@
1
- import {createMiddleware}from'langchain';import {AIMessage}from'@langchain/core/messages';import {toJsonSchema}from'@langchain/core/utils/json_schema';import {createSavingsLayer,LicenseError,sha256,stableStringify}from'@bivelio/savings-layer';import {AsyncLocalStorage}from'async_hooks';var H={"api.anthropic.com":"anthropic","api.openai.com":"openai","generativelanguage.googleapis.com":"google"};function K(e){if(typeof e!="string")return null;try{let n=new URL(e);return n.protocol!==
2
- "https:"||n.port!==""?null:H[n.hostname.toLowerCase()]??null}catch{return null}}function b(e){return K(e)!==null?"oficial":"no-oficial"}var M=Symbol.for("@bivelio/savings-layer:provider-origin");var C=new Set;function L(e,n,t){e===true||C.has(n)||(C.add(n),console.warn(t));}var Z="[bvsala] internal: the layer changed a request this adapter must forward unchanged; nothing was sent.",Q="[bvsala] internal: the layer asked for a second model call within one framework call; n\
3
- othing more was sent.",Y="[bvsala] internal: the layer called the model outside a framework call; nothing was sent.";function T(e,n,t,r){return {renderizado:e,generar:n,...{},invocada:false,
4
- completada:false,...r!==void 0?{origen:r}:{}}}async function E(e,n){try{let t=await n();return e.completada=!0,t}catch(t){throw e.errorDelMarco={error:t},t}}function ee(e,n){if(e===n)return true;try{return stableStringify(
5
- e)===stableStringify(n)}catch{return false}}function O(e,n){let t=e??[],r=n??[];return t.length===r.length&&t.every((o,a)=>ee(o,r[a]))}function ne(e,n){return e.model===n.model&&O(e.messages,n.messages)&&O(e.tools,n.tools)}
6
- function I(e,n){let t=o=>{let a=n.getStore();if(!a)throw new Error(Y);if(a.invocada)throw new Error(Q);if(!ne(o,a.renderizado))throw new Error(Z);return a.invocada=true,a},r={id:`bivelio-adapter:${e}`,async generate(o,a){
7
- return t(o).generar(a?.signal)},async*generateStream(o,a){let s=t(o);if(s.transmitir){yield*s.transmitir(a?.signal);return}let i=await s.generar(a?.signal);i.text!==""&&(yield {type:"text",delta:i.text}),
8
- yield {type:"done",response:i};}};return Object.defineProperty(r,M,{value:()=>n.getStore()?.origen}),r}function j(){return new AsyncLocalStorage}var oe=["licenseKey","licenseServerUrl","serviceAccountKey","licenseRefresh","licenseRevocation","licensePollIntervalSeconds","licenseFetch","metering","meteringUrl","meteringFetch","costModels","defa\
9
- ultCostModel","exactCache","exactCacheTtlMs","resolvers","exactTokenizer","silenceWarnings","failOpen"];function q(e,n){return n instanceof LicenseError||e.errorDelMarco&&e.errorDelMarco.error===n?false:e.invocada&&
10
- e.completada}var $="[bvsala] the model answered, but the savings layer failed while accounting for it; the answer is returned unchanged, without a savings report and without a usage record.";function z(e,n){
11
- let t=j(),r={};for(let s of oe)n[s]!==void 0&&(r[s]=n[s]);let o=createSavingsLayer({...r,provider:I(e,t)}),a=(s,i)=>L(n.silenceWarnings,`${e}:${s}`,i);return {ejecutar(s,i){return t.run(i,()=>o.generate(s))},async generar(s,i){
12
- try{let l=await t.run(i,()=>o.generate(s));return i.invocada?{tipo:"vivo",result:l}:{tipo:"atajo",result:l}}catch(l){if(q(i,l))return a("sin-informe",$),{tipo:"sin-informe"};throw l}},async transmitir(s,i,l){
13
- let u=t.run(i,()=>o.generateStream(s,l?{signal:l}:{})).result;i.resultado=u,u.catch(()=>{});let f;try{f=await Promise.race([i.abierta.then(()=>"abierta"),u.then(()=>"resuelta")]);}catch(h){if(q(i,h))return a(
14
- "sin-informe",$),{tipo:"sin-informe"};throw h}if(f==="abierta")return {tipo:"abierto"};let g=await u;return i.invocada?{tipo:"entero",result:g}:{tipo:"atajo",result:g}},informe(s){let i=JSON.parse(JSON.
15
- stringify(s));if(n.onReport)try{n.onReport(i);}catch{a("onreport","[bvsala] `onReport` threw; the error was caught and the model call was not affected.");}return i},avisar:a,close(){o.close();}}}var se={router:false,compression:false,elision:false,serialization:false,toolDiscovery:false,modelCascade:"off",outputCodebook:false,deferrable:false,semanticCache:false,verification:false};
16
- function ie(e,n,t={}){let r=o=>e?.[o]!==false&&n?.[o]!==false;return {...se,exactCache:r("exactCache")&&t.sinReutilizar!==true,singleflight:r("singleflight")&&t.sinReutilizar!==true,deterministicResolvers:r("det\
17
- erministicResolvers")&&t.sinResolvers!==true}}function ce(e,n){let t=e.readOnlyTools;if(typeof t=="function")try{return t(n)===!0}catch{return false}return Array.isArray(t)?t.includes(n):false}function R(e,n){
18
- let t=n.delProveedor!==true&&ce(e,n.nombre);return {id:n.nombre,intents:[],risk:t?"read":"write",...n.parametros!==void 0&&n.parametros!==null&&typeof n.parametros=="object"?{parameters:n.parametros}:{},
19
- ...typeof n.descripcion=="string"?{description:n.descripcion}:{}}}function y(e,n,t){if(e===null)return null;switch(typeof e){case "string":case "boolean":return e;case "number":return Number.isFinite(e)?
20
- e:String(e);case "bigint":return `${e.toString()}n`;case "undefined":case "function":case "symbol":return}let r=e;if(r instanceof Uint8Array)return n.push(r),{$bytes:n.length-1};if(r instanceof ArrayBuffer)
21
- return n.push(new Uint8Array(r)),{$bytes:n.length-1};if(ArrayBuffer.isView(r))return n.push(new Uint8Array(r.buffer,r.byteOffset,r.byteLength)),{$bytes:n.length-1};if(r instanceof URL)return {$url:r.href};
22
- if(r instanceof Date)return {$date:Number.isNaN(r.getTime())?"invalid":r.toISOString()};if(t.has(r))return "$cycle";t.add(r);try{if(Array.isArray(r))return r.map(a=>{let s=y(a,n,t);return s===void 0?null:
23
- s});if(r instanceof Map)return {$map:[...r.entries()].map(a=>y(a,n,t))};if(r instanceof Set)return {$set:[...r.values()].map(a=>y(a,n,t))};let o={};for(let a of Object.keys(r).sort()){let s=y(r[a],n,t);
24
- s!==void 0&&(o[a]=s);}return o}finally{t.delete(r);}}async function N(e){let n=globalThis.crypto?.subtle;if(n){let r=new Uint8Array(await n.digest("SHA-256",e));return Array.from(r,o=>o.toString(16).padStart(
25
- 2,"0")).join("")}let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return sha256(t)}async function le(e){try{let n=[],t=JSON.stringify(y(e,n,new WeakSet))??"null",r=await Promise.
26
- all(n.map(N)),o=new TextEncoder().encode(`${t}|${r.join(",")}`);return await N(o)}catch{return null}}async function U(e,n){let t=await le(n.proyeccion),r=`${n.context?.authorizationScope??"default"}|b\
27
- vsala-adapter:${t??"none"}`;return {model:n.model,messages:n.messages,...n.tools.length>0?{tools:n.tools}:{},...typeof n.temperature=="number"?{temperature:n.temperature}:{},...typeof n.seed=="number"?
28
- {seed:n.seed}:{},context:{...n.context??{},authorizationScope:r},savings:ie(e.savings,n.savings,{...n.restricciones,...t===null?{sinReutilizar:true}:{}})}}function c(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function J(e){let n=e;try{if(typeof n.getType=="function")return n.getType();if(typeof n._getType=="function")return n._getType()}catch{}
29
- return typeof n.type=="string"?n.type:""}function v(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(n=>c(n)&&n.type==="text"&&typeof n.text=="string").map(n=>n.text).join(`
30
- `):""}function B(e){if(typeof e=="string")return e;try{return JSON.stringify(e??{})}catch{return "{}"}}function k(e){return (Array.isArray(e.tool_calls)?e.tool_calls:[]).filter(c).map(t=>({...typeof t.id==
31
- "string"?{id:t.id}:{},name:String(t.name??""),arguments:B(t.args)}))}function pe(e,n){let t=[],r=v(e?.content);r!==""&&t.push({role:"system",content:r});for(let o of n){if(!c(o))continue;let a=J(o);if(a===
32
- "system")t.push({role:"system",content:v(o.content)});else if(a==="human")t.push({role:"user",content:v(o.content)});else if(a==="ai"){let s=k(o);t.push({role:"assistant",content:v(o.content),...s.length>
33
- 0?{toolCalls:s}:{}});}else a==="tool"&&t.push({role:"tool",content:typeof o.content=="string"?o.content:B(o.content),...typeof o.tool_call_id=="string"?{toolCallId:o.tool_call_id}:{},...typeof o.name==
34
- "string"?{name:o.name}:{}});}return t}function F(e){if(!c(e))return e;let n=e.content,t=J(e),r={};for(let[o,a]of Object.entries(c(e.additional_kwargs)?e.additional_kwargs:{}))o==="tool_calls"||o==="fun\
35
- ction_call"||o.startsWith("__")||(r[o]=a);return {type:t,name:e.name,content:t==="tool"?n:typeof n=="string"?"$text":Array.isArray(n)?n.map(o=>c(o)&&o.type==="text"?{...o,text:void 0,id:void 0}:o):n,tool_calls:k(
36
- e).map(o=>({name:o.name,arguments:o.arguments})),status:e.status,additional_kwargs:r}}function ge(e,n){let t=[],r=[];for(let o of n){if(!c(o))continue;if(typeof o.name=="string"&&"schema"in o){let s,i=true;
37
- try{s=toJsonSchema(o.schema);}catch{i=false;}let l=R(e,{nombre:o.name,descripcion:typeof o.description=="string"?o.description:void 0,parametros:s});t.push(i?l:{...l,risk:"write"}),r.push({name:o.name,description:o.
38
- description,parametros:s,returnDirect:o.returnDirect});continue}let a=c(o.function)?o.function:void 0;if(o.type==="function"&&a&&typeof a.name=="string"){t.push(R(e,{nombre:a.name,descripcion:typeof a.
39
- description=="string"?a.description:void 0,parametros:a.parameters})),r.push(o);continue}t.push(R(e,{nombre:String(o.name??o.type??"server-tool"),delProveedor:true})),r.push(o);}return {tools:t,definiciones:r}}
40
- function x(e){try{let n=e._llmType?.();return typeof n=="string"?n:""}catch{return ""}}function me(e){if(typeof e=="string")return e.replace(":","/");let n=e,t=n._defaultConfig;if(t&&typeof t=="object"&&
1
+ import {createMiddleware}from'langchain';import {AIMessage}from'@langchain/core/messages';import {toJsonSchema}from'@langchain/core/utils/json_schema';import {createSavingsLayer,LicenseError}from'@bivelio/savings-layer';import {AsyncLocalStorage}from'async_hooks';var Y={"api.anthropic.com":"anthropic","api.openai.com":"openai","generativelanguage.googleapis.com":"google"};function ee(e){if(typeof e!="string")return null;try{let n=new URL(e);return n.protocol!==
2
+ "https:"||n.port!==""?null:Y[n.hostname.toLowerCase()]??null}catch{return null}}function C(e){return ee(e)!==null?"oficial":"no-oficial"}var T=Symbol.for("@bivelio/savings-layer:provider-origin");var E=new Set;function j(e,n,t){e===true||E.has(n)||(E.add(n),console.warn(t));}var te="[bvsala] internal: the layer changed a request this adapter must forward unchanged; nothing was sent.",re="[bvsala] internal: the layer asked for a second model call within one framework call;\
3
+ nothing more was sent.",oe="[bvsala] internal: the layer called the model outside a framework call; nothing was sent.";function q(e,n,t,r){return {renderizado:e,generar:n,...{},invocada:false,
4
+ completada:false,...r!==void 0?{origen:r}:{}}}async function $(e,n){try{let t=await n();return e.completada=!0,t}catch(t){throw e.errorDelMarco={error:t},t}}function ae(e,n){if(e===n)return true;try{return U(
5
+ e)===U(n)}catch{return false}}function I(e,n){let t=e??[],r=n??[];return t.length===r.length&&t.every((o,s)=>ae(o,r[s]))}function se(e,n){return e.model===n.model&&I(e.messages,n.messages)&&I(e.tools,n.tools)}
6
+ function z(e,n){let t=o=>{let s=n.getStore();if(!s)throw new Error(oe);if(s.invocada)throw new Error(re);if(!se(o,s.renderizado))throw new Error(te);return s.invocada=true,s},r={id:`bivelio-adapter:${e}`,
7
+ async generate(o,s){return t(o).generar(s?.signal)},async*generateStream(o,s){let a=t(o);if(a.transmitir){yield*a.transmitir(s?.signal);return}let i=await a.generar(s?.signal);i.text!==""&&(yield {type:"\
8
+ text",delta:i.text}),yield {type:"done",response:i};}};return Object.defineProperty(r,T,{value:()=>n.getStore()?.origen}),r}function N(){return new AsyncLocalStorage}function U(e){return JSON.stringify(L(e))}function L(e){
9
+ if(Array.isArray(e))return e.map(L);if(e&&typeof e=="object"){let n={};for(let t of Object.keys(e).sort())n[t]=L(e[t]);return n}return e}var le=["licenseKey","licenseServerUrl","serviceAccountKey","licenseRefresh","licenseRevocation","licensePollIntervalSeconds","licenseFetch","metering","meteringUrl","meteringFetch","costModels","defa\
10
+ ultCostModel","exactCache","exactCacheTtlMs","resolvers","exactTokenizer","silenceWarnings","failOpen"];function F(e,n){return n instanceof LicenseError||e.errorDelMarco&&e.errorDelMarco.error===n?false:e.invocada&&
11
+ e.completada}var J="[bvsala] the model answered, but the savings layer failed while accounting for it; the answer is returned unchanged, without a savings report and without a usage record.";function V(e,n){
12
+ let t=N(),r={};for(let a of le)n[a]!==void 0&&(r[a]=n[a]);let o=createSavingsLayer({...r,provider:z(e,t)}),s=(a,i)=>j(n.silenceWarnings,`${e}:${a}`,i);return {ejecutar(a,i){return t.run(i,()=>o.generate(a))},async generar(a,i){
13
+ try{let u=await t.run(i,()=>o.generate(a));return i.invocada?{tipo:"vivo",result:u}:{tipo:"atajo",result:u}}catch(u){if(F(i,u))return s("sin-informe",J),{tipo:"sin-informe"};throw u}},async transmitir(a,i,u){
14
+ let d=t.run(i,()=>o.generateStream(a,u?{signal:u}:{})).result;i.resultado=d,d.catch(()=>{});let p;try{p=await Promise.race([i.abierta.then(()=>"abierta"),d.then(()=>"resuelta")]);}catch(h){if(F(i,h))return s(
15
+ "sin-informe",J),{tipo:"sin-informe"};throw h}if(p==="abierta")return {tipo:"abierto"};let g=await d;return i.invocada?{tipo:"entero",result:g}:{tipo:"atajo",result:g}},informe(a){let i=JSON.parse(JSON.
16
+ stringify(a));if(n.onReport)try{n.onReport(i);}catch{s("onreport","[bvsala] `onReport` threw; the error was caught and the model call was not affected.");}return i},avisar:s,close(){o.close();}}}var ue=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,
17
+ 4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,
18
+ 1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,
19
+ 1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),de=new TextEncoder;function x(e,n){return e>>>n|e<<32-n}function B(e){let n=de.encode(e),t=n.length*
20
+ 8,r=(n.length+8>>6)+1,o=new Uint8Array(r*64);o.set(n),o[n.length]=128;let s=new DataView(o.buffer);s.setUint32(o.length-8,Math.floor(t/4294967296)),s.setUint32(o.length-4,t>>>0);let a=new Uint32Array(
21
+ [1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),i=new Uint32Array(64);for(let f=0;f<o.length;f+=64){for(let c=0;c<16;c++)i[c]=s.getUint32(f+c*4);for(let c=16;c<
22
+ 64;c++){let b=i[c-15],y=i[c-2],w=x(b,7)^x(b,18)^b>>>3,S=x(y,17)^x(y,19)^y>>>10;i[c]=i[c-16]+w+i[c-7]+S|0;}let d=a[0],p=a[1],g=a[2],h=a[3],m=a[4],R=a[5],A=a[6],v=a[7];for(let c=0;c<64;c++){let b=x(m,6)^
23
+ x(m,11)^x(m,25),y=m&R^~m&A,w=v+b+y+ue[c]+i[c]|0,S=x(d,2)^x(d,13)^x(d,22),Z=d&p^d&g^p&g,Q=S+Z|0;v=A,A=R,R=m,m=h+w|0,h=g,g=p,p=d,d=w+Q|0;}a[0]=a[0]+d|0,a[1]=a[1]+p|0,a[2]=a[2]+g|0,a[3]=a[3]+h|0,a[4]=a[4]+
24
+ m|0,a[5]=a[5]+R|0,a[6]=a[6]+A|0,a[7]=a[7]+v|0;}let u="";for(let f=0;f<8;f++)u+=(a[f]>>>0).toString(16).padStart(8,"0");return u}var fe={router:false,compression:false,elision:false,serialization:false,toolDiscovery:false,modelCascade:"off",outputCodebook:false,deferrable:false,semanticCache:false,verification:false};function pe(e,n,t={}){let r=o=>e?.[o]!==
25
+ false&&n?.[o]!==false;return {...fe,exactCache:r("exactCache")&&t.sinReutilizar!==true,singleflight:r("singleflight")&&t.sinReutilizar!==true,deterministicResolvers:r("deterministicResolvers")&&t.sinResolvers!==
26
+ true}}function ge(e,n){let t=e.readOnlyTools;if(typeof t=="function")try{return t(n)===!0}catch{return false}return Array.isArray(t)?t.includes(n):false}function M(e,n){let t=n.delProveedor!==true&&ge(e,n.nombre);
27
+ return {id:n.nombre,intents:[],risk:t?"read":"write",...n.parametros!==void 0&&n.parametros!==null&&typeof n.parametros=="object"?{parameters:n.parametros}:{},...typeof n.descripcion=="string"?{description:n.
28
+ descripcion}:{}}}function D(e,n,t){if(e===null)return null;switch(typeof e){case "string":case "boolean":return e;case "number":return Number.isFinite(e)?e:String(e);case "bigint":return `${e.toString()}n`;case "\
29
+ undefined":case "function":case "symbol":return}let r=e;if(r instanceof Uint8Array)return n.push(r),{$bytes:n.length-1};if(r instanceof ArrayBuffer)return n.push(new Uint8Array(r)),{$bytes:n.length-1};if(ArrayBuffer.
30
+ isView(r))return n.push(new Uint8Array(r.buffer,r.byteOffset,r.byteLength)),{$bytes:n.length-1};if(r instanceof URL)return {$url:r.href};if(r instanceof Date)return {$date:Number.isNaN(r.getTime())?"inv\
31
+ alid":r.toISOString()};if(t.has(r))return "$cycle";t.add(r);try{if(Array.isArray(r))return r.map(s=>{let a=D(s,n,t);return a===void 0?null:a});if(r instanceof Map)return {$map:[...r.entries()].map(s=>D(
32
+ s,n,t))};if(r instanceof Set)return {$set:[...r.values()].map(s=>D(s,n,t))};let o={};for(let s of Object.keys(r).sort()){let a=D(r[s],n,t);a!==void 0&&(o[s]=a);}return o}finally{t.delete(r);}}async function W(e){
33
+ let n=globalThis.crypto?.subtle;if(n){let r=new Uint8Array(await n.digest("SHA-256",e));return Array.from(r,o=>o.toString(16).padStart(2,"0")).join("")}let t="";for(let r=0;r<e.length;r+=32768)t+=String.
34
+ fromCharCode(...e.subarray(r,r+32768));return B(t)}async function me(e){try{let n=[],t=JSON.stringify(D(e,n,new WeakSet))??"null",r=await Promise.all(n.map(W)),o=new TextEncoder().encode(`${t}|${r.join(
35
+ ",")}`);return await W(o)}catch{return null}}async function K(e,n){let t=await me(n.proyeccion),r=`${n.context?.authorizationScope??"default"}|bvsala-adapter:${t??"none"}`;return {model:n.model,messages:n.
36
+ messages,...n.tools.length>0?{tools:n.tools}:{},...typeof n.temperature=="number"?{temperature:n.temperature}:{},...typeof n.seed=="number"?{seed:n.seed}:{},context:{...n.context??{},authorizationScope:r},
37
+ savings:pe(e.savings,n.savings,{...n.restricciones,...t===null?{sinReutilizar:true}:{}})}}function l(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function H(e){let n=e;try{if(typeof n.getType=="function")return n.getType();if(typeof n._getType=="function")return n._getType()}catch{}
38
+ return typeof n.type=="string"?n.type:""}function _(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(n=>l(n)&&n.type==="text"&&typeof n.text=="string").map(n=>n.text).join(`
39
+ `):""}function X(e){if(typeof e=="string")return e;try{return JSON.stringify(e??{})}catch{return "{}"}}function P(e){return (Array.isArray(e.tool_calls)?e.tool_calls:[]).filter(l).map(t=>({...typeof t.id==
40
+ "string"?{id:t.id}:{},name:String(t.name??""),arguments:X(t.args)}))}function he(e,n){let t=[],r=_(e?.content);r!==""&&t.push({role:"system",content:r});for(let o of n){if(!l(o))continue;let s=H(o);if(s===
41
+ "system")t.push({role:"system",content:_(o.content)});else if(s==="human")t.push({role:"user",content:_(o.content)});else if(s==="ai"){let a=P(o);t.push({role:"assistant",content:_(o.content),...a.length>
42
+ 0?{toolCalls:a}:{}});}else s==="tool"&&t.push({role:"tool",content:typeof o.content=="string"?o.content:X(o.content),...typeof o.tool_call_id=="string"?{toolCallId:o.tool_call_id}:{},...typeof o.name==
43
+ "string"?{name:o.name}:{}});}return t}function G(e){if(!l(e))return e;let n=e.content,t=H(e),r={};for(let[o,s]of Object.entries(l(e.additional_kwargs)?e.additional_kwargs:{}))o==="tool_calls"||o==="fun\
44
+ ction_call"||o.startsWith("__")||(r[o]=s);return {type:t,name:e.name,content:t==="tool"?n:typeof n=="string"?"$text":Array.isArray(n)?n.map(o=>l(o)&&o.type==="text"?{...o,text:void 0,id:void 0}:o):n,tool_calls:P(
45
+ e).map(o=>({name:o.name,arguments:o.arguments})),status:e.status,additional_kwargs:r}}function be(e,n){let t=[],r=[];for(let o of n){if(!l(o))continue;if(typeof o.name=="string"&&"schema"in o){let a,i=true;
46
+ try{a=toJsonSchema(o.schema);}catch{i=false;}let u=M(e,{nombre:o.name,descripcion:typeof o.description=="string"?o.description:void 0,parametros:a});t.push(i?u:{...u,risk:"write"}),r.push({name:o.name,description:o.
47
+ description,parametros:a,returnDirect:o.returnDirect});continue}let s=l(o.function)?o.function:void 0;if(o.type==="function"&&s&&typeof s.name=="string"){t.push(M(e,{nombre:s.name,descripcion:typeof s.
48
+ description=="string"?s.description:void 0,parametros:s.parameters})),r.push(o);continue}t.push(M(e,{nombre:String(o.name??o.type??"server-tool"),delProveedor:true})),r.push(o);}return {tools:t,definiciones:r}}
49
+ function O(e){try{let n=e._llmType?.();return typeof n=="string"?n:""}catch{return ""}}function we(e){if(typeof e=="string")return e.replace(":","/");let n=e,t=n._defaultConfig;if(t&&typeof t=="object"&&
41
50
  typeof t.model=="string"&&t.model!=="")return t.model.includes("/")?t.model:typeof t.modelProvider=="string"&&t.modelProvider!==""?`${t.modelProvider}/${t.model}`:t.model;let r=typeof n.model=="string"?
42
- n.model:typeof n.modelName=="string"?n.modelName:"";if(r.includes("/"))return r;let o=x(e);return o!==""?`${o}/${r}`:r}function ye(e){if(!c(e))return;try{if(typeof e.identifyingParams=="function"){let t=e.
43
- identifyingParams.call(e),r=c(t)?t.baseURL:void 0;if(typeof r=="string"&&r!=="")return b(r)}}catch{}let n=e.apiUrl;if(x(e)==="anthropic"&&typeof n=="string"&&n!=="")return b(n)}function ve(e){try{return e.
44
- invocationParams?.({})??null}catch{return null}}function he(e){let n=e.toolChoice;return n==="required"||c(n)?true:e.responseFormat!==void 0}function p(e){return typeof e=="number"&&Number.isFinite(e)?e:
45
- void 0}function we(e,n){let t=c(e.usage_metadata)?e.usage_metadata:void 0,r=p(t?.input_tokens),o=p(t?.output_tokens),a=c(t?.input_token_details)?t.input_token_details:{},s=c(t?.output_token_details)?t.
46
- output_token_details:{},i=p(a.cache_read),l=p(a.cache_creation),d=p(s.reasoning),u=r!==void 0&&(i??0)+(l??0)<=r;return {inputTokens:r??0,outputTokens:o??0,...i!==void 0?{cachedInputTokens:i}:{},...l!==
47
- void 0?{cacheWriteInputTokens:l}:{},...d!==void 0?{reasoningTokens:d}:{},...n&&r!==void 0&&o!==void 0&&u?{}:{complete:false}}}function Se(e){let n=c(e.response_metadata)?e.response_metadata:{},t=n.finish_reason??
51
+ n.model:typeof n.modelName=="string"?n.modelName:"";if(r.includes("/"))return r;let o=O(e);return o!==""?`${o}/${r}`:r}function Se(e){if(!l(e))return;try{if(typeof e.identifyingParams=="function"){let t=e.
52
+ identifyingParams.call(e),r=l(t)?t.baseURL:void 0;if(typeof r=="string"&&r!=="")return C(r)}}catch{}let n=e.apiUrl;if(O(e)==="anthropic"&&typeof n=="string"&&n!=="")return C(n)}function Re(e){try{return e.
53
+ invocationParams?.({})??null}catch{return null}}function Ae(e){let n=e.toolChoice;return n==="required"||l(n)?true:e.responseFormat!==void 0}function k(e){return typeof e=="number"&&Number.isFinite(e)?e:
54
+ void 0}function ke(e,n){let t=l(e.usage_metadata)?e.usage_metadata:void 0,r=k(t?.input_tokens),o=k(t?.output_tokens),s=l(t?.input_token_details)?t.input_token_details:{},a=l(t?.output_token_details)?t.
55
+ output_token_details:{},i=k(s.cache_read),u=k(s.cache_creation),f=k(a.reasoning),d=r!==void 0&&(i??0)+(u??0)<=r;return {inputTokens:r??0,outputTokens:o??0,...i!==void 0?{cachedInputTokens:i}:{},...u!==
56
+ void 0?{cacheWriteInputTokens:u}:{},...f!==void 0?{reasoningTokens:f}:{},...n&&r!==void 0&&o!==void 0&&d?{}:{complete:false}}}function De(e){let n=l(e.response_metadata)?e.response_metadata:{},t=n.finish_reason??
48
57
  n.stop_reason??n.finishReason;switch(t){case "end_turn":case "stop":case "STOP":return "stop";case "max_tokens":case "length":case "MAX_TOKENS":return "length";case "tool_use":case "tool_calls":return "tool_call\
49
- s";default:return typeof t=="string"?t:void 0}}function Re(e,n){if(n!=="stop")return false;if(Array.isArray(e.content)){for(let r of e.content)if(!c(r)||r.type!=="text"||Array.isArray(r.citations)&&r.citations.
50
- length>0||Array.isArray(r.annotations)&&r.annotations.length>0)return false}let t=c(e.additional_kwargs)?e.additional_kwargs:{};return !("reasoning"in t||"reasoning_content"in t||"audio"in t)}function Ae(e,n){
51
- let t=Se(e),r=k(e);return {text:v(e.content),...r.length>0?{toolCalls:r}:{},...t?{finishReason:t}:{},usage:we(e,n),...Re(e,t)?{}:{replayable:false}}}function be(e,n){return new AIMessage({content:e.text,tool_calls:(e.
52
- toolCalls??[]).map((t,r)=>{let o={};try{let a=JSON.parse(t.arguments||"{}");c(a)&&(o=a);}catch{o={};}return {id:t.id??`bvsala-${e.requestId}-${r}`,name:t.name,args:o,type:"tool_call"}}),usage_metadata:{input_tokens:0,
53
- output_tokens:0,total_tokens:0},response_metadata:n?{bivelio:{savingsReport:n}}:{}})}var ke="[bvsala] this LangChain model has its own `cache` set, so a usage counter can be a cached copy rather than \
54
- a provider bill; its calls are reported as unmeasured.";function Be(e){let n=z("langchain",e),t=e.reportInMetadata!==false,r=createMiddleware({name:"BivelioSavings",wrapModelCall:async(o,a)=>{let s=o,i=s.model,l=x(i),
55
- d=c(i)&&i.cache!==void 0&&i.cache!==null&&i.cache!==false;d&&n.avisar("cache-del-modelo",ke);let u=!l.toLowerCase().includes("fake")&&!d,f=e.modelId?e.modelId(i):me(i),g=Array.isArray(s.messages)?s.messages:
56
- [],{tools:h,definiciones:V}=ge(e,Array.isArray(s.tools)?s.tools:[]),W=he(s),G=p(i?.temperature),m=await U(e,{model:f,messages:pe(s.systemMessage,g),tools:h,temperature:G,context:e.context?.(o),proyeccion:{
57
- modelo:f,parametros:ve(i),sistema:F(s.systemMessage),mensajes:g.map(F),herramientas:V,toolChoice:s.toolChoice,responseFormat:s.responseFormat,modelSettings:s.modelSettings},restricciones:{sinResolvers:W,
58
- sinReutilizar:s.responseFormat!==void 0}}),w,D=T({model:m.model,messages:m.messages,...m.tools?{tools:m.tools}:{}},async()=>(w=await E(D,async()=>a(o)),Ae(w,u)),void 0,ye(i)),S=await n.generar(m,D);if(S.
59
- tipo==="sin-informe")return w;let _=n.informe(S.result.report);if(S.tipo==="atajo")return be(S.result,t?_:void 0);let A=w;return t&&(A.response_metadata={...A.response_metadata??{},bivelio:{savingsReport:_}}),
60
- A}});return Object.assign(r,{close:()=>n.close()})}function Ve(e){let n=e?.response_metadata,t=c(n)?n.bivelio:void 0,r=c(t)?t.savingsReport:void 0;if(!(!c(r)||typeof r.requestId!="string"))return r}export{Ve as getSavingsReportFromMessage,Be as savingsAgentMiddleware};
58
+ s";default:return typeof t=="string"?t:void 0}}function _e(e,n){if(n!=="stop")return false;if(Array.isArray(e.content)){for(let r of e.content)if(!l(r)||r.type!=="text"||Array.isArray(r.citations)&&r.citations.
59
+ length>0||Array.isArray(r.annotations)&&r.annotations.length>0)return false}let t=l(e.additional_kwargs)?e.additional_kwargs:{};return !("reasoning"in t||"reasoning_content"in t||"audio"in t)}function Me(e,n){
60
+ let t=De(e),r=P(e);return {text:_(e.content),...r.length>0?{toolCalls:r}:{},...t?{finishReason:t}:{},usage:ke(e,n),..._e(e,t)?{}:{replayable:false}}}function Ce(e,n){return new AIMessage({content:e.text,tool_calls:(e.
61
+ toolCalls??[]).map((t,r)=>{let o={};try{let s=JSON.parse(t.arguments||"{}");l(s)&&(o=s);}catch{o={};}return {id:t.id??`bvsala-${e.requestId}-${r}`,name:t.name,args:o,type:"tool_call"}}),usage_metadata:{input_tokens:0,
62
+ output_tokens:0,total_tokens:0},response_metadata:n?{bivelio:{savingsReport:n}}:{}})}var Le="[bvsala] this LangChain model has its own `cache` set, so a usage counter can be a cached copy rather than \
63
+ a provider bill; its calls are reported as unmeasured.";function Xe(e){let n=V("langchain",e),t=e.reportInMetadata!==false,r=createMiddleware({name:"BivelioSavings",wrapModelCall:async(o,s)=>{let a=o,i=a.model,u=O(i),
64
+ f=l(i)&&i.cache!==void 0&&i.cache!==null&&i.cache!==false;f&&n.avisar("cache-del-modelo",Le);let d=!u.toLowerCase().includes("fake")&&!f,p=e.modelId?e.modelId(i):we(i),g=Array.isArray(a.messages)?a.messages:
65
+ [],{tools:h,definiciones:m}=be(e,Array.isArray(a.tools)?a.tools:[]),R=Ae(a),A=k(i?.temperature),v=await K(e,{model:p,messages:he(a.systemMessage,g),tools:h,temperature:A,context:e.context?.(o),proyeccion:{
66
+ modelo:p,parametros:Re(i),sistema:G(a.systemMessage),mensajes:g.map(G),herramientas:m,toolChoice:a.toolChoice,responseFormat:a.responseFormat,modelSettings:a.modelSettings},restricciones:{sinResolvers:R,
67
+ sinReutilizar:a.responseFormat!==void 0}}),c,b=q({model:v.model,messages:v.messages,...v.tools?{tools:v.tools}:{}},async()=>(c=await $(b,async()=>s(o)),Me(c,d)),void 0,Se(i)),y=await n.generar(v,b);if(y.
68
+ tipo==="sin-informe")return c;let w=n.informe(y.result.report);if(y.tipo==="atajo")return Ce(y.result,t?w:void 0);let S=c;return t&&(S.response_metadata={...S.response_metadata??{},bivelio:{savingsReport:w}}),
69
+ S}});return Object.assign(r,{close:()=>n.close()})}function Ze(e){let n=e?.response_metadata,t=l(n)?n.bivelio:void 0,r=l(t)?t.savingsReport:void 0;if(!(!l(r)||typeof r.requestId!="string"))return r}export{Ze as getSavingsReportFromMessage,Xe as savingsAgentMiddleware};