@bivelio/savings-layer 0.4.26 → 0.4.29

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,77 +1,78 @@
1
- import {createSavingsLayer,LicenseError,sha256,stableStringify}from'@bivelio/savings-layer';import {AsyncLocalStorage}from'async_hooks';var w=t=>typeof t=="number"&&Number.isFinite(t)&&t>0?t:0;function N(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+=w(r.input_tokens),e.output+=w(r.output_tokens),e.cacheRead+=w(r.cache_read_input_tokens);let o=r.cache_creation,
3
- s=w(o?.ephemeral_5m_input_tokens),a=w(o?.ephemeral_1h_input_tokens),i=typeof r.cache_creation_input_tokens=="number"?w(r.cache_creation_input_tokens):s+a;e.cacheWrite+=i,e.cacheWrite1h+=Math.min(a,i);}
4
- return e.iteraciones>0?e:null}function W(t,e,n){let r=t??{},o=N(r.iterations),s=J(r.cache_read_input_tokens,o?.cacheRead),a=J(r.cache_creation_input_tokens,o?.cacheWrite),i=r.cache_creation?.ephemeral_1h_input_tokens,u=typeof i=="\
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 J(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 F(t,e,n){let r=t??{},o=J(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
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
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 J(t,e){return e?(t??0)+e:t}function B(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 F(t){return t==="thinking"||t==="redacted_thinking"}function V(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 M=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(
7
+ h||o?{}:{reasoningTokens:0},...m||h?{complete:false}:{}},entradaAusente:m,salidaAusente:h}}function W(t,e){return e?(t??0)+e:t}function B(t){let e=t?.service_tier;return typeof e=="string"&&e!==""?e:void 0}
8
+ function U(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 V(t){return t==="thinking"||t==="redacted_thinking"}function G(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 he={"api.anthropic.com":"anthropic","api.openai.com":"openai","generativelanguage.googleapis.com":"google"};function ye(t){if(typeof t!="string")return null;try{let e=new URL(t);return e.protocol!==
11
+ "https:"||e.port!==""?null:he[e.hostname.toLowerCase()]??null}catch{return null}}function H(t){return ye(t)!==null?"oficial":"no-oficial"}var K=Symbol.for("@bivelio/savings-layer:provider-origin");var L=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(
11
12
  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,
12
13
  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(
13
14
  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.
14
15
  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),
15
16
  s=e.slice(r+1),s.charCodeAt(0)===32&&(s=s.slice(1))),o){case "data":this.datos+=s+`
16
17
  `;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":
17
- this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};var G=new Set;function H(t,e,n){t===true||G.has(e)||(G.add(e),console.warn(n));}var ge="[bvsala] internal: the layer changed a request this adapter must forward unchanged; no\
18
- thing was sent.",me="[bvsala] internal: the layer asked for a second model call within one framework call; nothing more was sent.",he="[bvsala] internal: the layer called the model outside a framework\
19
- call; nothing was sent.";function U(t,e,n){return {renderizado:t,generar:e,...n?{transmitir:n}:{},invocada:false,completada:false}}function ye(t,e){if(t===e)return true;try{return stableStringify(t)===stableStringify(e)}catch{return false}}function Z(t,e){let n=t??[],r=e??[];return n.length===r.length&&n.every((o,s)=>ye(o,r[s]))}function ve(t,e){return t.model===e.
20
- model&&Z(t.messages,e.messages)&&Z(t.tools,e.tools)}function Q(t,e){let n=r=>{let o=e.getStore();if(!o)throw new Error(he);if(o.invocada)throw new Error(me);if(!ve(r,o.renderizado))throw new Error(ge);
21
- return o.invocada=true,o};return {id:`bivelio-adapter:${t}`,async generate(r,o){return n(r).generar(o?.signal)},async*generateStream(r,o){let s=n(r);if(s.transmitir){yield*s.transmitir(o?.signal);return}
22
- let a=await s.generar(o?.signal);a.text!==""&&(yield {type:"text",delta:a.text}),yield {type:"done",response:a};}}}function X(){return new AsyncLocalStorage}var Se=["licenseKey","licenseServerUrl","serviceAccountKey","licenseRefresh","licenseRevocation","licensePollIntervalSeconds","licenseFetch","metering","meteringUrl","meteringFetch","costModels","defa\
23
- ultCostModel","exactCache","exactCacheTtlMs","resolvers","exactTokenizer","silenceWarnings","failOpen"];function Y(t,e){return e instanceof LicenseError||t.errorDelMarco&&t.errorDelMarco.error===e?false:t.invocada&&
24
- t.completada}var ee="[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 te(t,e){
25
- let n=X(),r={};for(let a of Se)e[a]!==void 0&&(r[a]=e[a]);let o=createSavingsLayer({...r,provider:Q(t,n)}),s=(a,i)=>H(e.silenceWarnings,`${t}:${a}`,i);return {ejecutar(a,i){return n.run(i,()=>o.generate(a))},async generar(a,i){
26
- try{let u=await n.run(i,()=>o.generate(a));return i.invocada?{tipo:"vivo",result:u}:{tipo:"atajo",result:u}}catch(u){if(Y(i,u))return s("sin-informe",ee),{tipo:"sin-informe"};throw u}},async transmitir(a,i,u){
27
- 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(Y(i,b))return s(
28
- "sin-informe",ee),{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.
29
- 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 ne(){
18
+ this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};var Z=new Set;function Q(t,e,n){t===true||Z.has(e)||(Z.add(e),console.warn(n));}var _e="[bvsala] internal: the layer changed a request this adapter must forward unchanged; nothing was sent.",be="[bvsala] internal: the layer asked for a second model call within one framework call;\
19
+ nothing more was sent.",Se="[bvsala] internal: the layer called the model outside a framework call; nothing was sent.";function q(t,e,n,r){return {renderizado:t,generar:e,...n?{transmitir:n}:{},invocada:false,
20
+ completada:false,...r!==void 0?{origen:r}:{}}}function Re(t,e){if(t===e)return true;try{return stableStringify(t)===stableStringify(e)}catch{return false}}function Y(t,e){let n=t??[],r=e??[];return n.length===r.length&&n.every((o,s)=>Re(o,r[s]))}function we(t,e){return t.model===e.
21
+ model&&Y(t.messages,e.messages)&&Y(t.tools,e.tools)}function ee(t,e){let n=o=>{let s=e.getStore();if(!s)throw new Error(Se);if(s.invocada)throw new Error(be);if(!we(o,s.renderizado))throw new Error(_e);
22
+ 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}let i=await a.
23
+ generar(s?.signal);i.text!==""&&(yield {type:"text",delta:i.text}),yield {type:"done",response:i};}};return Object.defineProperty(r,K,{value:()=>e.getStore()?.origen}),r}function te(){return new AsyncLocalStorage}var ke=["licenseKey","licenseServerUrl","serviceAccountKey","licenseRefresh","licenseRevocation","licensePollIntervalSeconds","licenseFetch","metering","meteringUrl","meteringFetch","costModels","defa\
24
+ ultCostModel","exactCache","exactCacheTtlMs","resolvers","exactTokenizer","silenceWarnings","failOpen"];function ne(t,e){return e instanceof LicenseError||t.errorDelMarco&&t.errorDelMarco.error===e?false:t.invocada&&
25
+ t.completada}var re="[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 oe(t,e){
26
+ let n=te(),r={};for(let a of ke)e[a]!==void 0&&(r[a]=e[a]);let o=createSavingsLayer({...r,provider:ee(t,n)}),s=(a,i)=>Q(e.silenceWarnings,`${t}:${a}`,i);return {ejecutar(a,i){return n.run(i,()=>o.generate(a))},async generar(a,i){
27
+ try{let u=await n.run(i,()=>o.generate(a));return i.invocada?{tipo:"vivo",result:u}:{tipo:"atajo",result:u}}catch(u){if(ne(i,u))return s("sin-informe",re),{tipo:"sin-informe"};throw u}},async transmitir(a,i,u){
28
+ 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(ne(i,b))return s(
29
+ "sin-informe",re),{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.
30
+ 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 se(){
30
31
  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.
31
32
  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||
32
33
  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](){
33
34
  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(
34
- (e,n)=>{this.esperando={resolver:e,rechazar:n};}),return:()=>(this.terminada=true,this.pendientes.length=0,Promise.resolve({value:void 0,done:true}))}}};var we={router:false,compression:false,elision:false,serialization:false,toolDiscovery:false,modelCascade:"off",outputCodebook:false,deferrable:false,semanticCache:false,verification:false};
35
- function xe(t,e,n={}){let r=o=>t?.[o]!==false&&e?.[o]!==false;return {...we,exactCache:r("exactCache")&&n.sinReutilizar!==true,singleflight:r("singleflight")&&n.sinReutilizar!==true,deterministicResolvers:r("det\
36
- erministicResolvers")&&n.sinResolvers!==true}}function Ae(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 oe(t,e){
37
- let n=e.delProveedor!==true&&Ae(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}:{},
35
+ (e,n)=>{this.esperando={resolver:e,rechazar:n};}),return:()=>(this.terminada=true,this.pendientes.length=0,Promise.resolve({value:void 0,done:true}))}}};var Ce={router:false,compression:false,elision:false,serialization:false,toolDiscovery:false,modelCascade:"off",outputCodebook:false,deferrable:false,semanticCache:false,verification:false};
36
+ function Pe(t,e,n={}){let r=o=>t?.[o]!==false&&e?.[o]!==false;return {...Ce,exactCache:r("exactCache")&&n.sinReutilizar!==true,singleflight:r("singleflight")&&n.sinReutilizar!==true,deterministicResolvers:r("det\
37
+ erministicResolvers")&&n.sinResolvers!==true}}function Le(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 ie(t,e){
38
+ let n=e.delProveedor!==true&&Le(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}:{},
38
39
  ...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)?
39
40
  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)
40
41
  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};
41
42
  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:
42
43
  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);
43
- a!==void 0&&(o[s]=a);}return o}finally{n.delete(r);}}async function re(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(
44
- 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 ke(t){try{let e=[],n=JSON.stringify(P(t,e,new WeakSet))??"null",r=await Promise.
45
- all(e.map(re)),o=new TextEncoder().encode(`${n}|${r.join(",")}`);return await re(o)}catch{return null}}async function se(t,e){let n=await ke(e.proyeccion),r=`${e.context?.authorizationScope??"default"}\
44
+ a!==void 0&&(o[s]=a);}return o}finally{n.delete(r);}}async function ae(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(
45
+ 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 Me(t){try{let e=[],n=JSON.stringify(P(t,e,new WeakSet))??"null",r=await Promise.
46
+ all(e.map(ae)),o=new TextEncoder().encode(`${n}|${r.join(",")}`);return await ae(o)}catch{return null}}async function ce(t,e){let n=await Me(e.proyeccion),r=`${e.context?.authorizationScope??"default"}\
46
47
  |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"?
47
- {seed:e.seed}:{},context:{...e.context??{},authorizationScope:r},savings:xe(t.savings,e.savings,{...e.restricciones,...n===null?{sinReutilizar:true}:{}})}}function ae(t,e){if(!(!t&&!e))return {...t??{},...e??
48
- {}}}function ie(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 I="[bvsala] could not read the request body; nothing was sent.";function p(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function De(t){if((t.method??"GET").toUpperCase()!=="POST")return false;
49
- try{return new URL(t.url).pathname.replace(/\/+$/,"").endsWith("/v1/messages")}catch{return false}}function x(t){return typeof t=="string"?[{type:"text",text:t}]:Array.isArray(t)?t.filter(p):[]}function L(t){
48
+ {seed:e.seed}:{},context:{...e.context??{},authorizationScope:r},savings:Pe(t.savings,e.savings,{...e.restricciones,...n===null?{sinReutilizar:true}:{}})}}function ue(t,e){if(!(!t&&!e))return {...t??{},...e??
49
+ {}}}function le(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 I="[bvsala] could not read the request body; nothing was sent.";function p(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Oe(t){if((t.method??"GET").toUpperCase()!=="POST")return false;
50
+ 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 M(t){
50
51
  return t.filter(e=>e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(`
51
- `)}function de(t){if(typeof t=="string")return t;try{return JSON.stringify(t??{})}catch{return "{}"}}function Ce(t){let e=[],n=t.system;(typeof n=="string"?n!=="":Array.isArray(n))&&e.push({role:"syste\
52
- m",content:typeof n=="string"?n:L(x(n))});for(let r of Array.isArray(t.messages)?t.messages:[]){if(!p(r))continue;let o=x(r.content);if(r.role==="assistant"){let a=o.filter(i=>i.type==="tool_use").map(
53
- i=>({...typeof i.id=="string"?{id:i.id}:{},name:String(i.name??""),arguments:de(i.input)}));e.push({role:"assistant",content:L(o),...a.length>0?{toolCalls:a}:{}});continue}for(let a of o)a.type==="too\
54
- l_result"&&e.push({role:"tool",content:typeof a.content=="string"?a.content:L(x(a.content)),...typeof a.tool_use_id=="string"?{toolCallId:a.tool_use_id}:{}});let s=L(o);(s!==""||!o.some(a=>a.type==="t\
55
- ool_result"))&&e.push({role:"user",content:s});}return e}function ce(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 Pe(t,e){
56
- 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":x(t.system).map(ce),n.messages=(Array.isArray(
57
- t.messages)?t.messages:[]).filter(p).map(r=>({role:r.role,content:x(r.content).map(ce)})),e&&(n["anthropic-beta"]=e),n}function Me(t){let e=t.tool_choice;return p(e)&&(e.type==="any"||e.type==="tool")||
58
- p(t.output_config)&&t.output_config.format!==void 0?true:t.output_format!==void 0}var T=class{id;texto="";razono=false;reproducible=true;parada;usoInicio;usoDelta;vioDelta=false;vioStop=false;error;herramientas=new Map;toolCallsJson=[];bloque(e){
59
- F(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){this.id=typeof e.
60
- id=="string"?e.id:void 0;for(let n of x(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.id=="string"?
61
- {id:n.id}:{},name:String(n.name??""),arguments:de(n.input)});this.parada=typeof e.stop_reason=="string"?e.stop_reason:void 0,this.usoInicio=p(e.usage)?e.usage:void 0,this.usoDelta=this.usoInicio,this.
52
+ `)}function ge(t){if(typeof t=="string")return t;try{return JSON.stringify(t??{})}catch{return "{}"}}function Ee(t){let e=[],n=t.system;(typeof n=="string"?n!=="":Array.isArray(n))&&e.push({role:"syste\
53
+ m",content:typeof n=="string"?n:M(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(
54
+ i=>({...typeof i.id=="string"?{id:i.id}:{},name:String(i.name??""),arguments:ge(i.input)}));e.push({role:"assistant",content:M(o),...a.length>0?{toolCalls:a}:{}});continue}for(let a of o)a.type==="too\
55
+ l_result"&&e.push({role:"tool",content:typeof a.content=="string"?a.content:M(A(a.content)),...typeof a.tool_use_id=="string"?{toolCallId:a.tool_use_id}:{}});let s=M(o);(s!==""||!o.some(a=>a.type==="t\
56
+ ool_result"))&&e.push({role:"user",content:s});}return e}function de(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 Te(t,e){
57
+ 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(de),n.messages=(Array.isArray(
58
+ t.messages)?t.messages:[]).filter(p).map(r=>({role:r.role,content:A(r.content).map(de)})),e&&(n["anthropic-beta"]=e),n}function je(t){let e=t.tool_choice;return p(e)&&(e.type==="any"||e.type==="tool")||
59
+ p(t.output_config)&&t.output_config.format!==void 0?true:t.output_format!==void 0}var O=class{id;texto="";razono=false;reproducible=true;parada;usoInicio;usoDelta;vioDelta=false;vioStop=false;error;herramientas=new Map;toolCallsJson=[];bloque(e){
60
+ V(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){this.id=typeof e.
61
+ 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.id=="string"?
62
+ {id:n.id}:{},name:String(n.name??""),arguments:ge(n.input)});this.parada=typeof e.stop_reason=="string"?e.stop_reason:void 0,this.usoInicio=p(e.usage)?e.usage:void 0,this.usoDelta=this.usoInicio,this.
62
63
  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 "message_start":{let o=p(n.message)?n.
63
64
  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:{};this.bloque(o),o.type==="tool_use"&&
64
65
  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(n.delta)?n.delta:{};if(o.type===
65
66
  "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=="number"){let s=this.herramientas.
66
67
  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.stop_reason=="string"&&(this.
67
- parada=o.stop_reason),p(n.usage)&&(this.usoDelta=q(this.usoDelta,n.usage));return}case "message_stop":this.vioStop=true;return;case "error":{let o=p(n.error)?n.error:{};this.error=`${String(o.type??"error")}\
68
+ parada=o.stop_reason),p(n.usage)&&(this.usoDelta=U(this.usoDelta,n.usage));return}case "message_stop":this.vioStop=true;return;case "error":{let o=p(n.error)?n.error:{};this.error=`${String(o.type??"error")}\
68
69
  : ${String(o.message??"")}`;return}default:return}}get toolCalls(){return this.toolCallsJson.length>0?this.toolCallsJson:[...this.herramientas.entries()].sort((e,n)=>e[0]-n[0]).map(([,e])=>({...e.id?{
69
- id:e.id}:{},name:e.name,arguments:Le(e.json)})).filter(e=>e.name!=="")}respuesta(){let e=q(this.usoInicio,this.usoDelta),n=this.vioDelta?W(e,this.usoDelta?.output_tokens,this.razono).usage:{inputTokens:0,
70
- outputTokens:0,complete:false},r=e.iterations;Array.isArray(r)&&r.length>1&&(n.complete=false);let o=this.toolCalls,s=B(e);return {text:this.texto,...o.length>0?{toolCalls:o}:{},...this.parada?{finishReason:V(
71
- this.parada)}:{},...s?{servedServiceTier:s}:{},usage:n,...this.reproducible&&this.parada==="end_turn"?{}:{replayable:false}}}};function Le(t){try{return JSON.stringify(JSON.parse(t===""?"{}":t))}catch{return t}}
72
- function Te(t,e){let n=[];return t.text!==""&&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??
70
+ id:e.id}:{},name:e.name,arguments:Ue(e.json)})).filter(e=>e.name!=="")}respuesta(){let e=U(this.usoInicio,this.usoDelta),n=this.vioDelta?F(e,this.usoDelta?.output_tokens,this.razono).usage:{inputTokens:0,
71
+ outputTokens:0,complete:false},r=e.iterations;Array.isArray(r)&&r.length>1&&(n.complete=false);let o=this.toolCalls,s=B(e);return {text:this.texto,...o.length>0?{toolCalls:o}:{},...this.parada?{finishReason:G(
72
+ this.parada)}:{},...s?{servedServiceTier:s}:{},usage:n,...this.reproducible&&this.parada==="end_turn"?{}:{replayable:false}}}};function Ue(t){try{return JSON.stringify(JSON.parse(t===""?"{}":t))}catch{return t}}
73
+ function qe(t,e){let n=[];return t.text!==""&&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??
73
74
  `toolu_bvsala_${t.requestId}_${o}`,name:r.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",
74
- stop_sequence:null,usage:{input_tokens:0,output_tokens:0}}}function ue(t,e,n){let r=Te(t,e),o={"request-id":`bvsala_${t.requestId}`};if(!n)return new Response(JSON.stringify(r),{status:200,headers:{...o,
75
+ stop_sequence:null,usage:{input_tokens:0,output_tokens:0}}}function pe(t,e,n){let r=qe(t,e),o={"request-id":`bvsala_${t.requestId}`};if(!n)return new Response(JSON.stringify(r),{status:200,headers:{...o,
75
76
  "content-type":"application/json"}});let s=(i,u)=>`event: ${i}
76
77
  data: ${JSON.stringify(u)}
77
78
 
@@ -80,21 +81,21 @@ block_start",index:u,content_block:{type:"text",text:""}}),a+=s("content_block_d
80
81
  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.
81
82
  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}}),
82
83
  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.
83
- status}`);this.respuesta=n;}respuesta};function et(t){let e=te("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(
84
- r.keys().next().value);};return {middleware:async(a,i,u)=>{if(!De(a))return i(a);if(typeof a.body!="string")throw new Error(I);let d;try{let c=JSON.parse(a.body);if(!p(c))throw new Error(I);d=c;}catch{throw new Error(
85
- I)}let g=u.options,m=ie(g?.bivelio),h=t.context?.({body:d,requestOptions:g}),b=(Array.isArray(d.tools)?d.tools:[]).filter(p).map(c=>oe(t,{nombre:String(c.name??""),descripcion:typeof c.description=="s\
86
- tring"?c.description:void 0,parametros:c.input_schema,delProveedor:c.input_schema===void 0&&typeof c.type=="string"&&c.type!=="custom"})),l=await se(t,{model:`anthropic/${String(d.model??"")}`,messages:Ce(
87
- d),tools:b,temperature:typeof d.temperature=="number"?d.temperature:void 0,context:ae(h,m.context),savings:m.savings,proyeccion:Pe(d,a.headers.get("anthropic-beta")),restricciones:{sinResolvers:Me(d)}}),
88
- _={model:l.model,messages:l.messages,...l.tools?{tools:l.tools}:{}},v=async c=>{let f;try{f=await i(a);}catch(y){throw c.errorDelMarco={error:y},y}if(!f.ok){let y=new E(f);throw c.errorDelMarco={error:y},
89
- y}return c.completada=true,f},A=c=>{if(c instanceof E)return c.respuesta;throw c};if(d.stream!==true){let c,f,y=U(_,async()=>{c=await v(y);let D=new T;return D.json(await c.clone().json()),f=D.id,D.respuesta()}),
90
- R;try{R=await e.generar(l,y);}catch(D){return A(D)}if(R.tipo==="sin-informe")return c;let $=e.informe(R.result.report);return R.tipo==="atajo"?(o(`msg_bvsala_${R.result.requestId}`,$),ue(R.result,d.model,
91
- false)):(o(f,$),c)}let{abierta:pe,abrir:z}=ne(),j,O,k=Object.assign(U(_,async()=>{let c=await v(k),f=new C;O=le(c,f,e,k,o),z();for await(let y of f)if(y.type==="done")return y.response;throw new Error("[\
92
- bvsala] the model stream ended before completion; nothing was measured.")},()=>{let c=new C;return v(k).then(f=>{j=le(f,c,e,k,o),z();},f=>c.fail(f)),c}),{abierta:pe}),S;try{S=await e.transmitir(l,k,a.signal??
93
- void 0);}catch(c){return A(c)}if(S.tipo==="abierto")return j??O;if(S.tipo==="atajo"){let c=e.informe(S.result.report);return o(`msg_bvsala_${S.result.requestId}`,c),ue(S.result,d.model,true)}return j??O},
94
- reportFor(a){let i=typeof a=="string"?a:a?.id;return typeof i=="string"?r.get(i):void 0},close(){e.close();}}}function le(t,e,n,r,o){let s=new T,a,i=async()=>{try{let l=await r.resultado;o(s.id,n.informe(
95
- l.report));}catch{}},u=()=>{e.cerrada||(s.error?e.fail(new Error(`[bvsala] provider stream error: ${s.error}`)):s.vioDelta||s.vioStop?(e.push({type:"done",response:s.respuesta()}),e.end(),a=i()):e.fail(
96
- new Error("[bvsala] the model stream ended before completion; nothing was measured.")));};if((t.headers.get("content-type")??"").includes("application/json"))return t.clone().json().then(l=>{s.json(p(l)?
97
- 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 model stream had no body; nothing was measured.")),t;let g=d.getReader(),
98
- m=new M,h=l=>{for(let _ of l){let v=s.evento(_);v!==void 0&&e.push({type:"text",delta:v}),(s.vioStop||s.error)&&u();}},b=new ReadableStream({async pull(l){let _;try{_=await g.read();}catch(A){e.fail(A),
99
- l.error(A);return}if(_.done){h(m.end()),u(),await a,l.close();return}let v=_.value;l.enqueue(v),h(m.push(v));},cancel(l){return e.fail(new Error("[bvsala] the stream was cancelled by its reader; nothin\
100
- g was measured.")),g.cancel(l)}});return new Response(b,{status:t.status,statusText:t.statusText,headers:t.headers})}export{et as anthropicSavings};
84
+ status}`);this.respuesta=n;}respuesta};function ct(t){let e=oe("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(
85
+ r.keys().next().value);};return {middleware:async(a,i,u)=>{if(!Oe(a))return i(a);if(typeof a.body!="string")throw new Error(I);let d;try{let c=JSON.parse(a.body);if(!p(c))throw new Error(I);d=c;}catch{throw new Error(
86
+ I)}let g=u.options,m=le(g?.bivelio),h=t.context?.({body:d,requestOptions:g}),b=(Array.isArray(d.tools)?d.tools:[]).filter(p).map(c=>ie(t,{nombre:String(c.name??""),descripcion:typeof c.description=="s\
87
+ tring"?c.description:void 0,parametros:c.input_schema,delProveedor:c.input_schema===void 0&&typeof c.type=="string"&&c.type!=="custom"})),l=await ce(t,{model:`anthropic/${String(d.model??"")}`,messages:Ee(
88
+ d),tools:b,temperature:typeof d.temperature=="number"?d.temperature:void 0,context:ue(h,m.context),savings:m.savings,proyeccion:Te(d,a.headers.get("anthropic-beta")),restricciones:{sinResolvers:je(d)}}),
89
+ v={model:l.model,messages:l.messages,...l.tools?{tools:l.tools}:{}},_=H(a.url),S=async c=>{let f;try{f=await i(a);}catch(y){throw c.errorDelMarco={error:y},y}if(!f.ok){let y=new E(f);throw c.errorDelMarco=
90
+ {error:y},y}return c.completada=true,f},z=c=>{if(c instanceof E)return c.respuesta;throw c};if(d.stream!==true){let c,f,y=q(v,async()=>{c=await S(y);let D=new O;return D.json(await c.clone().json()),f=D.id,
91
+ D.respuesta()},void 0,_),w;try{w=await e.generar(l,y);}catch(D){return z(D)}if(w.tipo==="sin-informe")return c;let N=e.informe(w.result.report);return w.tipo==="atajo"?(o(`msg_bvsala_${w.result.requestId}`,
92
+ N),pe(w.result,d.model,false)):(o(f,N),c)}let{abierta:me,abrir:$}=se(),T,j,k=Object.assign(q(v,async()=>{let c=await S(k),f=new C;j=fe(c,f,e,k,o),$();for await(let y of f)if(y.type==="done")return y.response;
93
+ throw new Error("[bvsala] the model stream ended before completion; nothing was measured.")},()=>{let c=new C;return S(k).then(f=>{T=fe(f,c,e,k,o),$();},f=>c.fail(f)),c},_),{abierta:me}),R;try{R=await e.
94
+ transmitir(l,k,a.signal??void 0);}catch(c){return z(c)}if(R.tipo==="abierto")return T??j;if(R.tipo==="atajo"){let c=e.informe(R.result.report);return o(`msg_bvsala_${R.result.requestId}`,c),pe(R.result,
95
+ d.model,true)}return T??j},reportFor(a){let i=typeof a=="string"?a:a?.id;return typeof i=="string"?r.get(i):void 0},close(){e.close();}}}function fe(t,e,n,r,o){let s=new O,a,i=async()=>{try{let l=await r.
96
+ 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({type:"done",response:s.respuesta()}),
97
+ 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("application/json"))return t.clone().json().
98
+ 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 model stream had no body; nothing was measure\
99
+ d.")),t;let g=d.getReader(),m=new L,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({async pull(l){let v;try{v=await g.
100
+ read();}catch(S){e.fail(S),l.error(S);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("[bvsala] the stream was cance\
101
+ lled by its reader; nothing was measured.")),g.cancel(l)}});return new Response(b,{status:t.status,statusText:t.statusText,headers:t.headers})}export{ct as anthropicSavings};
@@ -1,58 +1,60 @@
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 D=new Set;function _(n,e,t){n===true||D.has(e)||(D.add(e),console.warn(t));}var K="[bvsala] internal: the layer changed a request this adapter must forward unchanged; noth\
2
- ing was sent.",H="[bvsala] internal: the layer asked for a second model call within one framework call; nothing more was sent.",G="[bvsala] internal: the layer called the model outside a framework cal\
3
- l; nothing was sent.";function P(n,e,t){return {renderizado:n,generar:e,...{},invocada:false,completada:false}}async function L(n,e){try{let t=await e();return n.completada=!0,t}catch(t){throw n.
4
- errorDelMarco={error:t},t}}function X(n,e){if(n===e)return true;try{return stableStringify(n)===stableStringify(e)}catch{return false}}function C(n,e){let t=n??[],r=e??[];return t.length===r.length&&t.every((o,s)=>X(o,r[s]))}function Z(n,e){
5
- return n.model===e.model&&C(n.messages,e.messages)&&C(n.tools,e.tools)}function T(n,e){let t=r=>{let o=e.getStore();if(!o)throw new Error(G);if(o.invocada)throw new Error(H);if(!Z(r,o.renderizado))throw new Error(
6
- K);return o.invocada=true,o};return {id:`bivelio-adapter:${n}`,async generate(r,o){return t(r).generar(o?.signal)},async*generateStream(r,o){let s=t(r);if(s.transmitir){yield*s.transmitir(o?.signal);return}
7
- let a=await s.generar(o?.signal);a.text!==""&&(yield {type:"text",delta:a.text}),yield {type:"done",response:a};}}}function O(){return new AsyncLocalStorage}var ee=["licenseKey","licenseServerUrl","serviceAccountKey","licenseRefresh","licenseRevocation","licensePollIntervalSeconds","licenseFetch","metering","meteringUrl","meteringFetch","costModels","defa\
8
- ultCostModel","exactCache","exactCacheTtlMs","resolvers","exactTokenizer","silenceWarnings","failOpen"];function j(n,e){return e instanceof LicenseError||n.errorDelMarco&&n.errorDelMarco.error===e?false:n.invocada&&
9
- n.completada}var I="[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 q(n,e){
10
- let t=O(),r={};for(let a of ee)e[a]!==void 0&&(r[a]=e[a]);let o=createSavingsLayer({...r,provider:T(n,t)}),s=(a,i)=>_(e.silenceWarnings,`${n}:${a}`,i);return {ejecutar(a,i){return t.run(i,()=>o.generate(a))},async generar(a,i){
11
- try{let l=await t.run(i,()=>o.generate(a));return i.invocada?{tipo:"vivo",result:l}:{tipo:"atajo",result:l}}catch(l){if(j(i,l))return s("sin-informe",I),{tipo:"sin-informe"};throw l}},async transmitir(a,i,l){
12
- let u=t.run(i,()=>o.generateStream(a,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(j(i,h))return s(
13
- "sin-informe",I),{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(a){let i=JSON.parse(JSON.
14
- 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();}}}var te={router:false,compression:false,elision:false,serialization:false,toolDiscovery:false,modelCascade:"off",outputCodebook:false,deferrable:false,semanticCache:false,verification:false};
15
- function re(n,e,t={}){let r=o=>n?.[o]!==false&&e?.[o]!==false;return {...te,exactCache:r("exactCache")&&t.sinReutilizar!==true,singleflight:r("singleflight")&&t.sinReutilizar!==true,deterministicResolvers:r("det\
16
- erministicResolvers")&&t.sinResolvers!==true}}function oe(n,e){let t=n.readOnlyTools;if(typeof t=="function")try{return t(e)===!0}catch{return false}return Array.isArray(t)?t.includes(e):false}function R(n,e){
17
- let t=e.delProveedor!==true&&oe(n,e.nombre);return {id:e.nombre,intents:[],risk:t?"read":"write",...e.parametros!==void 0&&e.parametros!==null&&typeof e.parametros=="object"?{parameters:e.parametros}:{},
18
- ...typeof e.descripcion=="string"?{description:e.descripcion}:{}}}function y(n,e,t){if(n===null)return null;switch(typeof n){case "string":case "boolean":return n;case "number":return Number.isFinite(n)?
19
- n:String(n);case "bigint":return `${n.toString()}n`;case "undefined":case "function":case "symbol":return}let r=n;if(r instanceof Uint8Array)return e.push(r),{$bytes:e.length-1};if(r instanceof ArrayBuffer)
20
- 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};
21
- 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(s=>{let a=y(s,e,t);return a===void 0?null:
22
- a});if(r instanceof Map)return {$map:[...r.entries()].map(s=>y(s,e,t))};if(r instanceof Set)return {$set:[...r.values()].map(s=>y(s,e,t))};let o={};for(let s of Object.keys(r).sort()){let a=y(r[s],e,t);
23
- a!==void 0&&(o[s]=a);}return o}finally{t.delete(r);}}async function E(n){let e=globalThis.crypto?.subtle;if(e){let r=new Uint8Array(await e.digest("SHA-256",n));return Array.from(r,o=>o.toString(16).padStart(
24
- 2,"0")).join("")}let t="";for(let r=0;r<n.length;r+=32768)t+=String.fromCharCode(...n.subarray(r,r+32768));return sha256(t)}async function ae(n){try{let e=[],t=JSON.stringify(y(n,e,new WeakSet))??"null",r=await Promise.
25
- all(e.map(E)),o=new TextEncoder().encode(`${t}|${r.join(",")}`);return await E(o)}catch{return null}}async function $(n,e){let t=await ae(e.proyeccion),r=`${e.context?.authorizationScope??"default"}|b\
26
- vsala-adapter:${t??"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"?
27
- {seed:e.seed}:{},context:{...e.context??{},authorizationScope:r},savings:re(n.savings,e.savings,{...e.restricciones,...t===null?{sinReutilizar:true}:{}})}}function c(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function N(n){let e=n;try{if(typeof e.getType=="function")return e.getType();if(typeof e._getType=="function")return e._getType()}catch{}
28
- return typeof e.type=="string"?e.type:""}function v(n){return typeof n=="string"?n:Array.isArray(n)?n.filter(e=>c(e)&&e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(`
29
- `):""}function U(n){if(typeof n=="string")return n;try{return JSON.stringify(n??{})}catch{return "{}"}}function b(n){return (Array.isArray(n.tool_calls)?n.tool_calls:[]).filter(c).map(t=>({...typeof t.id==
30
- "string"?{id:t.id}:{},name:String(t.name??""),arguments:U(t.args)}))}function le(n,e){let t=[],r=v(n?.content);r!==""&&t.push({role:"system",content:r});for(let o of e){if(!c(o))continue;let s=N(o);if(s===
31
- "system")t.push({role:"system",content:v(o.content)});else if(s==="human")t.push({role:"user",content:v(o.content)});else if(s==="ai"){let a=b(o);t.push({role:"assistant",content:v(o.content),...a.length>
32
- 0?{toolCalls:a}:{}});}else s==="tool"&&t.push({role:"tool",content:typeof o.content=="string"?o.content:U(o.content),...typeof o.tool_call_id=="string"?{toolCallId:o.tool_call_id}:{},...typeof o.name==
33
- "string"?{name:o.name}:{}});}return t}function z(n){if(!c(n))return n;let e=n.content,t=N(n),r={};for(let[o,s]of Object.entries(c(n.additional_kwargs)?n.additional_kwargs:{}))o==="tool_calls"||o==="fun\
34
- ction_call"||o.startsWith("__")||(r[o]=s);return {type:t,name:n.name,content:t==="tool"?e:typeof e=="string"?"$text":Array.isArray(e)?e.map(o=>c(o)&&o.type==="text"?{...o,text:void 0,id:void 0}:o):e,tool_calls:b(
35
- n).map(o=>({name:o.name,arguments:o.arguments})),status:n.status,additional_kwargs:r}}function ue(n,e){let t=[],r=[];for(let o of e){if(!c(o))continue;if(typeof o.name=="string"&&"schema"in o){let a,i=true;
36
- try{a=toJsonSchema(o.schema);}catch{i=false;}let l=R(n,{nombre:o.name,descripcion:typeof o.description=="string"?o.description:void 0,parametros:a});t.push(i?l:{...l,risk:"write"}),r.push({name:o.name,description:o.
37
- description,parametros:a,returnDirect:o.returnDirect});continue}let s=c(o.function)?o.function:void 0;if(o.type==="function"&&s&&typeof s.name=="string"){t.push(R(n,{nombre:s.name,descripcion:typeof s.
38
- description=="string"?s.description:void 0,parametros:s.parameters})),r.push(o);continue}t.push(R(n,{nombre:String(o.name??o.type??"server-tool"),delProveedor:true})),r.push(o);}return {tools:t,definiciones:r}}
39
- function F(n){try{let e=n._llmType?.();return typeof e=="string"?e:""}catch{return ""}}function de(n){if(typeof n=="string")return n.replace(":","/");let e=n,t=e._defaultConfig;if(t&&typeof t=="object"&&
40
- 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 e.model=="string"?
41
- e.model:typeof e.modelName=="string"?e.modelName:"";if(r.includes("/"))return r;let o=F(n);return o!==""?`${o}/${r}`:r}function fe(n){try{return n.invocationParams?.({})??null}catch{return null}}function pe(n){
42
- let e=n.toolChoice;return e==="required"||c(e)?true:n.responseFormat!==void 0}function p(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function ge(n,e){let t=c(n.usage_metadata)?n.usage_metadata:
43
- void 0,r=p(t?.input_tokens),o=p(t?.output_tokens),s=c(t?.input_token_details)?t.input_token_details:{},a=c(t?.output_token_details)?t.output_token_details:{},i=p(s.cache_read),l=p(s.cache_creation),d=p(
44
- a.reasoning),u=r!==void 0&&(i??0)+(l??0)<=r;return {inputTokens:r??0,outputTokens:o??0,...i!==void 0?{cachedInputTokens:i}:{},...l!==void 0?{cacheWriteInputTokens:l}:{},...d!==void 0?{reasoningTokens:d}:
45
- {},...e&&r!==void 0&&o!==void 0&&u?{}:{complete:false}}}function me(n){let e=c(n.response_metadata)?n.response_metadata:{},t=e.finish_reason??e.stop_reason??e.finishReason;switch(t){case "end_turn":case "s\
46
- top":case "STOP":return "stop";case "max_tokens":case "length":case "MAX_TOKENS":return "length";case "tool_use":case "tool_calls":return "tool_calls";default:return typeof t=="string"?t:void 0}}function ye(n,e){
47
- if(e!=="stop")return false;if(Array.isArray(n.content)){for(let r of n.content)if(!c(r)||r.type!=="text"||Array.isArray(r.citations)&&r.citations.length>0||Array.isArray(r.annotations)&&r.annotations.length>
48
- 0)return false}let t=c(n.additional_kwargs)?n.additional_kwargs:{};return !("reasoning"in t||"reasoning_content"in t||"audio"in t)}function ve(n,e){let t=me(n),r=b(n);return {text:v(n.content),...r.length>0?
49
- {toolCalls:r}:{},...t?{finishReason:t}:{},usage:ge(n,e),...ye(n,t)?{}:{replayable:false}}}function he(n,e){return new AIMessage({content:n.text,tool_calls:(n.toolCalls??[]).map((t,r)=>{let o={};try{let s=JSON.parse(
50
- t.arguments||"{}");c(s)&&(o=s);}catch{o={};}return {id:t.id??`bvsala-${n.requestId}-${r}`,name:t.name,args:o,type:"tool_call"}}),usage_metadata:{input_tokens:0,output_tokens:0,total_tokens:0},response_metadata:e?
51
- {bivelio:{savingsReport:e}}:{}})}var we="[bvsala] this LangChain model has its own `cache` set, so a usage counter can be a cached copy rather than a provider bill; its calls are reported as unmeasure\
52
- d.";function qe(n){let e=q("langchain",n),t=n.reportInMetadata!==false,r=createMiddleware({name:"BivelioSavings",wrapModelCall:async(o,s)=>{let a=o,i=a.model,l=F(i),d=c(i)&&i.cache!==void 0&&i.cache!==null&&i.cache!==
53
- false;d&&e.avisar("cache-del-modelo",we);let u=!l.toLowerCase().includes("fake")&&!d,f=n.modelId?n.modelId(i):de(i),g=Array.isArray(a.messages)?a.messages:[],{tools:h,definiciones:J}=ue(n,Array.isArray(a.
54
- tools)?a.tools:[]),B=pe(a),W=p(i?.temperature),m=await $(n,{model:f,messages:le(a.systemMessage,g),tools:h,temperature:W,context:n.context?.(o),proyeccion:{modelo:f,parametros:fe(i),sistema:z(a.systemMessage),
55
- mensajes:g.map(z),herramientas:J,toolChoice:a.toolChoice,responseFormat:a.responseFormat,modelSettings:a.modelSettings},restricciones:{sinResolvers:B,sinReutilizar:a.responseFormat!==void 0}}),w,k=P({
56
- model:m.model,messages:m.messages,...m.tools?{tools:m.tools}:{}},async()=>(w=await L(k,async()=>s(o)),ve(w,u))),S=await e.generar(m,k);if(S.tipo==="sin-informe")return w;let x=e.informe(S.result.report);
57
- if(S.tipo==="atajo")return he(S.result,t?x:void 0);let A=w;return t&&(A.response_metadata={...A.response_metadata??{},bivelio:{savingsReport:x}}),A}});return Object.assign(r,{close:()=>e.close()})}function Ee(n){
58
- let e=n?.response_metadata,t=c(e)?e.bivelio:void 0,r=c(t)?t.savingsReport:void 0;if(!(!c(r)||typeof r.requestId!="string"))return r}export{Ee as getSavingsReportFromMessage,qe as savingsAgentMiddleware};
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"&&
41
+ 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??
48
+ 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};