@bivelio/savings-layer 0.5.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,93 +1,93 @@
1
- import {createSavingsLayer,LicenseError}from'@bivelio/savings-layer';import {AsyncLocalStorage}from'async_hooks';var _=new Set;function F(t,e,n){t===true||_.has(e)||(_.add(e),console.warn(n));}var V=Symbol.for("@bivelio/savings-layer:provider-origin");var me="[bvsala] internal: the layer changed a request this adapter must forward unchanged; nothing was sent.",ve="[bvsala] internal: the layer asked for a second model call within one framework call;\
2
- nothing more was sent.",ye="[bvsala] internal: the layer called the model outside a framework call; nothing was sent.";function j(t,e,n,r){return {renderizado:t,generar:e,...n?{transmitir:n}:{},invocada:false,
3
- completada:false,...{}}}async function P(t,e){try{let n=await e();return t.completada=!0,n}catch(n){throw t.errorDelMarco={error:n},n}}function he(t,e){if(t===e)return true;try{return W(
4
- t)===W(e)}catch{return false}}function J(t,e){let n=t??[],r=e??[];return n.length===r.length&&n.every((a,s)=>he(a,r[s]))}function xe(t,e){return t.model===e.model&&J(t.messages,e.messages)&&J(t.tools,e.tools)}
5
- function B(t,e){let n=a=>{let s=e.getStore();if(!s)throw new Error(ye);if(s.invocada)throw new Error(ve);if(!xe(a,s.renderizado))throw new Error(me);return s.invocada=true,s},r={id:`bivelio-adapter:${t}`,
6
- async generate(a,s){return n(a).generar(s?.signal)},async*generateStream(a,s){let o=n(a);if(o.transmitir){yield*o.transmitir(s?.signal);return}let i=await o.generar(s?.signal);i.text!==""&&(yield {type:"\
7
- text",delta:i.text}),yield {type:"done",response:i};}};return Object.defineProperty(r,V,{value:()=>e.getStore()?.origen}),r}function K(){return new AsyncLocalStorage}function W(t){return JSON.stringify(E(t))}function E(t){
8
- if(Array.isArray(t))return t.map(E);if(t&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=E(t[n]);return e}return t}var we=["licenseKey","licenseServerUrl","serviceAccountKey","licenseRefresh","licenseRevocation","licensePollIntervalSeconds","licenseFetch","metering","meteringUrl","meteringFetch","costModels","defa\
9
- ultCostModel","exactCache","exactCacheTtlMs","resolvers","exactTokenizer","silenceWarnings","failOpen"];function H(t,e){return e instanceof LicenseError||t.errorDelMarco&&t.errorDelMarco.error===e?false:t.invocada&&
10
- t.completada}var Z="[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(t,e){
11
- let n=K(),r={};for(let o of we)e[o]!==void 0&&(r[o]=e[o]);let a=createSavingsLayer({...r,provider:B(t,n)}),s=(o,i)=>F(e.silenceWarnings,`${t}:${o}`,i);return {ejecutar(o,i){return n.run(i,()=>a.generate(o))},async generar(o,i){
12
- try{let u=await n.run(i,()=>a.generate(o));return i.invocada?{tipo:"vivo",result:u}:{tipo:"atajo",result:u}}catch(u){if(H(i,u))return s("sin-informe",Z),{tipo:"sin-informe"};throw u}},async transmitir(o,i,u){
13
- let d=n.run(i,()=>a.generateStream(o,u?{signal:u}:{})).result;i.resultado=d,d.catch(()=>{});let f;try{f=await Promise.race([i.abierta.then(()=>"abierta"),d.then(()=>"resuelta")]);}catch(l){if(H(i,l))return s(
14
- "sin-informe",Z),{tipo:"sin-informe"};throw l}if(f==="abierta")return {tipo:"abierto"};let g=await d;return i.invocada?{tipo:"entero",result:g}:{tipo:"atajo",result:g}},informe(o){let i=JSON.parse(JSON.
15
- stringify(o));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(){a.close();}}}function X(){
1
+ import {createSavingsLayer,LicenseError}from'@bivelio/savings-layer';import {AsyncLocalStorage}from'async_hooks';var G=new Set;function _(t,e,n){t===true||G.has(e)||(G.add(e),console.warn(n));}var B=Symbol.for("@bivelio/savings-layer:provider-origin");var ge="[bvsala] internal: the layer changed a request this adapter must forward unchanged; nothing was sent.",me="[bvsala] internal: the layer asked for a second model call within one framework call;\
2
+ nothing more was sent.",ve="[bvsala] internal: the layer called the model outside a framework call; nothing was sent.";function T(t,e,n,r){return {renderizado:t,generar:e,...n?{transmitir:n}:{},invocada:false,
3
+ completada:false,...{}}}async function C(t,e){try{let n=await e();return t.completada=!0,n}catch(n){throw t.errorDelMarco={error:n},n}}function ye(t,e){if(t===e)return true;try{return V(
4
+ t)===V(e)}catch{return false}}function F(t,e){let n=t??[],r=e??[];return n.length===r.length&&n.every((i,a)=>ye(i,r[a]))}function he(t,e){return t.model===e.model&&F(t.messages,e.messages)&&F(t.tools,e.tools)}
5
+ function J(t,e){let n=i=>{let a=e.getStore();if(!a)throw new Error(ve);if(a.invocada)throw new Error(me);if(!he(i,a.renderizado))throw new Error(ge);return a.invocada=true,a},r={id:`bivelio-adapter:${t}`,
6
+ async generate(i,a){return n(i).generar(a?.signal)},async*generateStream(i,a){let o=n(i);if(o.transmitir){yield*o.transmitir(a?.signal);return}let s=await o.generar(a?.signal);s.text!==""&&(yield {type:"\
7
+ text",delta:s.text}),yield {type:"done",response:s};}};return Object.defineProperty(r,B,{value:()=>e.getStore()?.origen}),r}function Q(){return new AsyncLocalStorage}function V(t){return JSON.stringify(I(t))}function I(t){
8
+ if(Array.isArray(t))return t.map(I);if(t&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=I(t[n]);return e}return t}var be=["licenseKey","licenseServerUrl","serviceAccountKey","licenseRefresh","licenseRevocation","licensePollIntervalSeconds","licenseFetch","metering","meteringUrl","meteringFetch","costModels","defa\
9
+ ultCostModel","exactCache","exactCacheTtlMs","resolvers","exactTokenizer","silenceWarnings","failOpen"];function W(t,e){return e instanceof LicenseError||t.errorDelMarco&&t.errorDelMarco.error===e?false:t.invocada&&
10
+ t.completada}var K="[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 H(t,e){
11
+ let n=Q(),r={};for(let o of be)e[o]!==void 0&&(r[o]=e[o]);let i=createSavingsLayer({...r,provider:J(t,n)}),a=(o,s)=>_(e.silenceWarnings,`${t}:${o}`,s);return {ejecutar(o,s){return n.run(s,()=>i.generate(o))},async generar(o,s){
12
+ try{let d=await n.run(s,()=>i.generate(o));return s.invocada?{tipo:"vivo",result:d}:{tipo:"atajo",result:d}}catch(d){if(W(s,d))return a("sin-informe",K),{tipo:"sin-informe"};throw d}},async transmitir(o,s,d){
13
+ let l=n.run(s,()=>i.generateStream(o,d?{signal:d}:{})).result;s.resultado=l,l.catch(()=>{});let f;try{f=await Promise.race([s.abierta.then(()=>"abierta"),l.then(()=>"resuelta")]);}catch(u){if(W(s,u))return a(
14
+ "sin-informe",K),{tipo:"sin-informe"};throw u}if(f==="abierta")return {tipo:"abierto"};let g=await l;return s.invocada?{tipo:"entero",result:g}:{tipo:"atajo",result:g}},informe(o){let s=JSON.parse(JSON.
15
+ stringify(o));if(e.onReport)try{e.onReport(s);}catch{a("onreport","[bvsala] `onReport` threw; the error was caught and the model call was not affected.");}return s},avisar:a,close(){i.close();}}}function Z(){
16
16
  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.
17
17
  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||
18
18
  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](){
19
19
  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(
20
- (e,n)=>{this.esperando={resolver:e,rechazar:n};}),return:()=>(this.terminada=true,this.pendientes.length=0,Promise.resolve({value:void 0,done:true}))}}};function m(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Y(t){return typeof t=="string"?[{type:"text",text:t}]:Array.isArray(t)?t.filter(m):[]}function O(t){return t.filter(e=>e.type===
20
+ (e,n)=>{this.esperando={resolver:e,rechazar:n};}),return:()=>(this.terminada=true,this.pendientes.length=0,Promise.resolve({value:void 0,done:true}))}}};function m(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function X(t){return typeof t=="string"?[{type:"text",text:t}]:Array.isArray(t)?t.filter(m):[]}function O(t){return t.filter(e=>e.type===
21
21
  "text"&&typeof e.text=="string").map(e=>e.text).join(`
22
- `)}function w(t){if(typeof t=="string")return t;try{return JSON.stringify(t??{})}catch{return "{}"}}function Se(t){if(!m(t))return w(t);switch(t.type){case "text":case "error-text":return typeof t.value==
22
+ `)}function w(t){if(typeof t=="string")return t;try{return JSON.stringify(t??{})}catch{return "{}"}}function we(t){if(!m(t))return w(t);switch(t.type){case "text":case "error-text":return typeof t.value==
23
23
  "string"?t.value:w(t.value);case "json":case "error-json":return w(t.value);case "execution-denied":return `execution denied${typeof t.reason=="string"?`: ${t.reason}`:""}`;case "content":return O(e(t.value));default:
24
- return w(t)}function e(n){return Array.isArray(n)?n.filter(m):[]}}function ee(t){let e=[];for(let n of Array.isArray(t)?t:[]){if(!m(n))continue;let r=Y(n.content);switch(n.role){case "system":e.push({role:"\
25
- system",content:typeof n.content=="string"?n.content:O(r)});break;case "user":e.push({role:"user",content:O(r)});break;case "assistant":{let a=r.filter(s=>s.type==="tool-call"&&s.providerExecuted!==true).
26
- map(s=>({...typeof s.toolCallId=="string"?{id:s.toolCallId}:{},name:String(s.toolName??""),arguments:w(s.input??s.args)}));e.push({role:"assistant",content:O(r),...a.length>0?{toolCalls:a}:{}});break}case "\
27
- tool":for(let a of r)a.type==="tool-result"&&e.push({role:"tool",content:Se(a.output??a.result),...typeof a.toolCallId=="string"?{toolCallId:a.toolCallId}:{},...typeof a.toolName=="string"?{name:a.toolName}:
28
- {}});break}}return e}var Ae=new Set(["bivelio","mastra"]);function T(t){if(!m(t))return t;let e={};for(let[n,r]of Object.entries(t))Ae.has(n)||(e[n]=r);return e}function ke(t){let e={};for(let[n,r]of Object.
29
- entries(t))if(!(n==="toolCallId"||n==="id")&&!(n==="text"&&t.type==="text")){if(n==="providerOptions"||n==="providerMetadata"){e[n]=T(r);continue}e[n]=r;}return e}function De(t){return (Array.isArray(t)?
30
- t:[]).map(e=>m(e)?{role:e.role,content:typeof e.content=="string"?"$text":Y(e.content).map(ke),providerOptions:T(e.providerOptions)}:e)}var Me=new Set(["anthropic-beta","openai-beta"]);function Ce(t){
31
- if(!m(t))return;let e={};for(let[n,r]of Object.entries(t))Me.has(n.toLowerCase())&&r!==void 0&&(e[n.toLowerCase()]=r);return Object.keys(e).length>0?e:void 0}function te(t){let e={};for(let[n,r]of Object.
32
- entries(t))n==="prompt"||n==="abortSignal"||n==="headers"||n==="providerOptions"||(e[n]=r);return e.prompt=De(t.prompt),e.headers=Ce(t.headers),e.providerOptions=T(t.providerOptions),e}function ne(t){
33
- let e=t.responseFormat;if(m(e)&&e.type==="json")return true;let n=t.toolChoice;return m(n)&&(n.type==="required"||n.type==="tool")?true:n==="required"}function b(t){return typeof t=="number"&&Number.isFinite(
34
- t)?t:void 0}function Pe(t,e){let n=m(t)?t:{},r=m(n.inputTokens)?n.inputTokens:void 0,a=m(n.outputTokens)?n.outputTokens:void 0;if(!r||!a){let f=b(n.inputTokens),g=b(n.outputTokens);return {inputTokens:f??
35
- 0,outputTokens:g??0,complete:false}}let s=b(r.total),o=b(r.cacheRead),i=b(r.cacheWrite),u=b(a.total),c=b(a.reasoning);return {inputTokens:s??0,outputTokens:u??0,...o!==void 0?{cachedInputTokens:o}:{},...i!==
36
- void 0?{cacheWriteInputTokens:i}:{},...c!==void 0?{reasoningTokens:c}:{},...s!==void 0&&u!==void 0&&!e?{}:{complete:false}}}function Le(t){if(typeof t=="string")return t;if(m(t)&&typeof t.unified=="strin\
37
- g")return t.unified}function Oe(t){switch(t){case void 0:return;case "tool-calls":return "tool_calls";case "content-filter":return "content_filter";default:return t}}function Te(t){return m(t)&&Object.keys(
38
- T(t)).length>0}var D=class{texto="";toolCalls=[];reproducible=true;finish;error;anadir(e){switch(e.type){case "text-delta":{let n=typeof e.delta=="string"?e.delta:typeof e.textDelta=="string"?e.textDelta:
24
+ return w(t)}function e(n){return Array.isArray(n)?n.filter(m):[]}}function Y(t){let e=[];for(let n of Array.isArray(t)?t:[]){if(!m(n))continue;let r=X(n.content);switch(n.role){case "system":e.push({role:"\
25
+ system",content:typeof n.content=="string"?n.content:O(r)});break;case "user":e.push({role:"user",content:O(r)});break;case "assistant":{let i=r.filter(a=>a.type==="tool-call"&&a.providerExecuted!==true).
26
+ map(a=>({...typeof a.toolCallId=="string"?{id:a.toolCallId}:{},name:String(a.toolName??""),arguments:w(a.input??a.args)}));e.push({role:"assistant",content:O(r),...i.length>0?{toolCalls:i}:{}});break}case "\
27
+ tool":for(let i of r)i.type==="tool-result"&&e.push({role:"tool",content:we(i.output??i.result),...typeof i.toolCallId=="string"?{toolCallId:i.toolCallId}:{},...typeof i.toolName=="string"?{name:i.toolName}:
28
+ {}});break}}return e}var Se=new Set(["bivelio","mastra"]);function P(t){if(!m(t))return t;let e={};for(let[n,r]of Object.entries(t))Se.has(n)||(e[n]=r);return e}function Ae(t){let e={};for(let[n,r]of Object.
29
+ entries(t))if(!(n==="toolCallId"||n==="id")&&!(n==="text"&&t.type==="text")){if(n==="providerOptions"||n==="providerMetadata"){e[n]=P(r);continue}e[n]=r;}return e}function ke(t){return (Array.isArray(t)?
30
+ t:[]).map(e=>m(e)?{role:e.role,content:typeof e.content=="string"?"$text":X(e.content).map(Ae),providerOptions:P(e.providerOptions)}:e)}var De=new Set(["anthropic-beta","openai-beta"]);function Me(t){
31
+ if(!m(t))return;let e={};for(let[n,r]of Object.entries(t))De.has(n.toLowerCase())&&r!==void 0&&(e[n.toLowerCase()]=r);return Object.keys(e).length>0?e:void 0}function ee(t){let e={};for(let[n,r]of Object.
32
+ entries(t))n==="prompt"||n==="abortSignal"||n==="headers"||n==="providerOptions"||(e[n]=r);return e.prompt=ke(t.prompt),e.headers=Me(t.headers),e.providerOptions=P(t.providerOptions),e}function te(t){
33
+ let e=t.responseFormat;if(m(e)&&e.type==="json")return true;let n=t.toolChoice;return m(n)&&(n.type==="required"||n.type==="tool")?true:n==="required"}function R(t){return typeof t=="number"&&Number.isFinite(
34
+ t)?t:void 0}function Ce(t,e){let n=m(t)?t:{},r=m(n.inputTokens)?n.inputTokens:void 0,i=m(n.outputTokens)?n.outputTokens:void 0;if(!r||!i){let f=R(n.inputTokens),g=R(n.outputTokens);return {inputTokens:f??
35
+ 0,outputTokens:g??0,complete:false}}let a=R(r.total),o=R(r.cacheRead),s=R(r.cacheWrite),d=R(i.total),c=R(i.reasoning);return {inputTokens:a??0,outputTokens:d??0,...o!==void 0?{cachedInputTokens:o}:{},...s!==
36
+ void 0?{cacheWriteInputTokens:s}:{},...c!==void 0?{reasoningTokens:c}:{},...a!==void 0&&d!==void 0&&!e?{}:{complete:false}}}function Le(t){if(typeof t=="string")return t;if(m(t)&&typeof t.unified=="strin\
37
+ g")return t.unified}function Oe(t){switch(t){case void 0:return;case "tool-calls":return "tool_calls";case "content-filter":return "content_filter";default:return t}}function Pe(t){return m(t)&&Object.keys(
38
+ P(t)).length>0}var k=class{texto="";toolCalls=[];reproducible=true;finish;error;anadir(e){switch(e.type){case "text-delta":{let n=typeof e.delta=="string"?e.delta:typeof e.textDelta=="string"?e.textDelta:
39
39
  "";return this.texto+=n,n===""?void 0:n}case "text":{let n=typeof e.text=="string"?e.text:"";return this.texto+=n,n===""?void 0:n}case "tool-call":e.providerExecuted===true?this.reproducible=false:this.toolCalls.
40
40
  push({...typeof e.toolCallId=="string"?{id:e.toolCallId}:{},name:String(e.toolName??""),arguments:w(e.input??e.args)});return;case "reasoning":case "reasoning-start":case "reasoning-delta":case "reasoning\
41
- -end":Te(e.providerMetadata)&&(this.reproducible=false);return;case "text-start":case "text-end":case "tool-input-start":case "tool-input-delta":case "tool-input-end":case "stream-start":case "response-metadata":case "\
42
- raw":return;case "finish":this.finish=e;return;case "error":this.error={error:e.error};return;default:this.reproducible=false;return}}respuesta(e,n,r){let a=Le(n),s=Oe(a),o=this.reproducible&&a==="stop";return {
43
- text:this.texto,...this.toolCalls.length>0?{toolCalls:this.toolCalls}:{},...s?{finishReason:s}:{},usage:Pe(e,r),...o?{}:{replayable:false}}}};function q(t,e){let n=new D;for(let r of Array.isArray(t.content)?
44
- t.content:[])m(r)&&n.anadir(r);return n.respuesta(t.usage,t.finishReason,e)}var U={inputTokens:{total:0,noCache:0,cacheRead:0,cacheWrite:0},outputTokens:{total:0,text:0,reasoning:0}};function N(t){let e=[];
45
- return t.text!==""&&e.push({type:"text",text:t.text}),(t.toolCalls??[]).forEach((n,r)=>{e.push({type:"tool-call",toolCallId:n.id??`bvsala-${t.requestId}-${r}`,toolName:n.name,input:n.arguments});}),e}function $(t){
46
- return {unified:(t.toolCalls?.length??0)>0?"tool-calls":"stop",raw:void 0}}function z(t,e,n){let r=[{type:"stream-start",warnings:Array.isArray(n.warnings)?n.warnings:[]}];return n.response&&r.push({type:"\
47
- response-metadata",...n.response}),t.forEach((a,s)=>{if(!m(a))return;let o=`bvsala-${s}`;if(a.type==="text"){let i=a.providerMetadata!==void 0?{providerMetadata:a.providerMetadata}:{};r.push({type:"te\
48
- xt-start",id:o,...i}),typeof a.text=="string"&&a.text!==""&&r.push({type:"text-delta",id:o,delta:a.text}),r.push({type:"text-end",id:o,...i});}else if(a.type==="reasoning"){let i=a.providerMetadata!==void 0?
49
- {providerMetadata:a.providerMetadata}:{};r.push({type:"reasoning-start",id:o,...i}),typeof a.text=="string"&&a.text!==""&&r.push({type:"reasoning-delta",id:o,delta:a.text}),r.push({type:"reasoning-end",
50
- id:o,...i});}else r.push(a);}),r.push({type:"finish",usage:e.usage,finishReason:e.finishReason,...e.providerMetadata!==void 0?{providerMetadata:e.providerMetadata}:{}}),r}function G(t){let e=0;return new ReadableStream(
51
- {pull(n){e<t.length?n.enqueue(t[e++]):n.close();}})}function re(t){let e=String(t.modelId??"");if(e.includes("/"))return e;let n=String(t.provider??"").split(".")[0]??"";return n!==""?`${n}/${e}`:e}function oe(t){
52
- return typeof t.provider=="string"&&t.provider.toLowerCase().startsWith("mock")}function S(t,e){return {...m(t)?t:{},bivelio:{savingsReport:e}}}var Ie=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,
41
+ -end":Pe(e.providerMetadata)&&(this.reproducible=false);return;case "text-start":case "text-end":case "tool-input-start":case "tool-input-delta":case "tool-input-end":case "stream-start":case "response-metadata":case "\
42
+ raw":return;case "finish":this.finish=e;return;case "error":this.error={error:e.error};return;default:this.reproducible=false;return}}respuesta(e,n,r){let i=Le(n),a=Oe(i),o=this.reproducible&&i==="stop";return {
43
+ text:this.texto,...this.toolCalls.length>0?{toolCalls:this.toolCalls}:{},...a?{finishReason:a}:{},usage:Ce(e,r),...o?{}:{replayable:false}}}};function q(t,e){let n=new k;for(let r of Array.isArray(t.content)?
44
+ t.content:[])m(r)&&n.anadir(r);return n.respuesta(t.usage,t.finishReason,e)}var U={inputTokens:{total:0,noCache:0,cacheRead:0,cacheWrite:0},outputTokens:{total:0,text:0,reasoning:0}};function j(t){let e=[];
45
+ return t.text!==""&&e.push({type:"text",text:t.text}),(t.toolCalls??[]).forEach((n,r)=>{e.push({type:"tool-call",toolCallId:n.id??`bvsala-${t.requestId}-${r}`,toolName:n.name,input:n.arguments});}),e}function N(t){
46
+ return {unified:(t.toolCalls?.length??0)>0?"tool-calls":"stop",raw:void 0}}function $(t,e,n){let r=[{type:"stream-start",warnings:Array.isArray(n.warnings)?n.warnings:[]}];return n.response&&r.push({type:"\
47
+ response-metadata",...n.response}),t.forEach((i,a)=>{if(!m(i))return;let o=`bvsala-${a}`;if(i.type==="text"){let s=i.providerMetadata!==void 0?{providerMetadata:i.providerMetadata}:{};r.push({type:"te\
48
+ xt-start",id:o,...s}),typeof i.text=="string"&&i.text!==""&&r.push({type:"text-delta",id:o,delta:i.text}),r.push({type:"text-end",id:o,...s});}else if(i.type==="reasoning"){let s=i.providerMetadata!==void 0?
49
+ {providerMetadata:i.providerMetadata}:{};r.push({type:"reasoning-start",id:o,...s}),typeof i.text=="string"&&i.text!==""&&r.push({type:"reasoning-delta",id:o,delta:i.text}),r.push({type:"reasoning-end",
50
+ id:o,...s});}else r.push(i);}),r.push({type:"finish",usage:e.usage,finishReason:e.finishReason,...e.providerMetadata!==void 0?{providerMetadata:e.providerMetadata}:{}}),r}function z(t){let e=0;return new ReadableStream(
51
+ {pull(n){e<t.length?n.enqueue(t[e++]):n.close();}})}function ne(t){let e=String(t.modelId??"");if(e.includes("/"))return e;let n=String(t.provider??"").split(".")[0]??"";return n!==""?`${n}/${e}`:e}function re(t){
52
+ return typeof t.provider=="string"&&t.provider.toLowerCase().startsWith("mock")}function S(t,e){return {...m(t)?t:{},bivelio:{savingsReport:e}}}var Ee=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,
53
53
  4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,
54
54
  1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,
55
- 1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ee=new TextEncoder;function h(t,e){return t>>>e|t<<32-e}function ae(t){let e=Ee.encode(t),n=e.length*
56
- 8,r=(e.length+8>>6)+1,a=new Uint8Array(r*64);a.set(e),a[e.length]=128;let s=new DataView(a.buffer);s.setUint32(a.length-8,Math.floor(n/4294967296)),s.setUint32(a.length-4,n>>>0);let o=new Uint32Array(
57
- [1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),i=new Uint32Array(64);for(let c=0;c<a.length;c+=64){for(let p=0;p<16;p++)i[p]=s.getUint32(c+p*4);for(let p=16;p<
58
- 64;p++){let A=i[p-15],k=i[p-2],C=h(A,7)^h(A,18)^A>>>3,I=h(k,17)^h(k,19)^k>>>10;i[p]=i[p-16]+C+i[p-7]+I|0;}let d=o[0],f=o[1],g=o[2],l=o[3],v=o[4],y=o[5],x=o[6],R=o[7];for(let p=0;p<64;p++){let A=h(v,6)^
59
- h(v,11)^h(v,25),k=v&y^~v&x,C=R+A+k+Ie[p]+i[p]|0,I=h(d,2)^h(d,13)^h(d,22),fe=d&f^d&g^f&g,pe=I+fe|0;R=x,x=y,y=v,v=l+C|0,l=g,g=f,f=d,d=C+pe|0;}o[0]=o[0]+d|0,o[1]=o[1]+f|0,o[2]=o[2]+g|0,o[3]=o[3]+l|0,o[4]=
60
- o[4]+v|0,o[5]=o[5]+y|0,o[6]=o[6]+x|0,o[7]=o[7]+R|0;}let u="";for(let c=0;c<8;c++)u+=(o[c]>>>0).toString(16).padStart(8,"0");return u}var je={router:false,compression:false,elision:false,serialization:false,toolDiscovery:false,modelCascade:"off",outputCodebook:false,deferrable:false,semanticCache:false,verification:false};function qe(t,e,n={}){let r=a=>t?.[a]!==
61
- false&&e?.[a]!==false;return {...je,exactCache:r("exactCache")&&n.sinReutilizar!==true,singleflight:r("singleflight")&&n.sinReutilizar!==true,deterministicResolvers:r("deterministicResolvers")&&n.sinResolvers!==
62
- true}}function Ue(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 se(t,e){let n=e.delProveedor!==true&&Ue(t,e.nombre);
55
+ 1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ie=new TextEncoder;function h(t,e){return t>>>e|t<<32-e}function oe(t){return Te(Ie.encode(t))}function Te(t){
56
+ let e=t.length*8,n=(t.length+8>>6)+1,r=new Uint8Array(n*64);r.set(t),r[t.length]=128;let i=new DataView(r.buffer);i.setUint32(r.length-8,Math.floor(e/4294967296)),i.setUint32(r.length-4,e>>>0);let a=new Uint32Array(
57
+ [1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),o=new Uint32Array(64);for(let d=0;d<r.length;d+=64){for(let p=0;p<16;p++)o[p]=i.getUint32(d+p*4);for(let p=16;p<
58
+ 64;p++){let y=o[p-15],A=o[p-2],M=h(y,7)^h(y,18)^y>>>3,E=h(A,17)^h(A,19)^A>>>10;o[p]=o[p-16]+M+o[p-7]+E|0;}let c=a[0],l=a[1],f=a[2],g=a[3],u=a[4],x=a[5],v=a[6],b=a[7];for(let p=0;p<64;p++){let y=h(u,6)^
59
+ h(u,11)^h(u,25),A=u&x^~u&v,M=b+y+A+Ee[p]+o[p]|0,E=h(c,2)^h(c,13)^h(c,22),ce=c&l^c&f^l&f,fe=E+ce|0;b=v,v=x,x=u,u=g+M|0,g=f,f=l,l=c,c=M+fe|0;}a[0]=a[0]+c|0,a[1]=a[1]+l|0,a[2]=a[2]+f|0,a[3]=a[3]+g|0,a[4]=
60
+ a[4]+u|0,a[5]=a[5]+x|0,a[6]=a[6]+v|0,a[7]=a[7]+b|0;}let s="";for(let d=0;d<8;d++)s+=(a[d]>>>0).toString(16).padStart(8,"0");return s}var qe={router:false,compression:false,elision:false,serialization:false,toolDiscovery:false,modelCascade:"off",outputCodebook:false,deferrable:false,semanticCache:false,verification:false};function Ue(t,e,n={}){let r=i=>t?.[i]!==
61
+ false&&e?.[i]!==false;return {...qe,exactCache:r("exactCache")&&n.sinReutilizar!==true,singleflight:r("singleflight")&&n.sinReutilizar!==true,deterministicResolvers:r("deterministicResolvers")&&n.sinResolvers!==
62
+ true}}function je(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){let n=e.delProveedor!==true&&je(t,e.nombre);
63
63
  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.
64
- descripcion}:{}}}function M(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 "\
64
+ descripcion}:{}}}function D(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 "\
65
65
  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.
66
66
  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\
67
- alid":r.toISOString()};if(n.has(r))return "$cycle";n.add(r);try{if(Array.isArray(r))return r.map(s=>{let o=M(s,e,n);return o===void 0?null:o});if(r instanceof Map)return {$map:[...r.entries()].map(s=>M(
68
- s,e,n))};if(r instanceof Set)return {$set:[...r.values()].map(s=>M(s,e,n))};let a={};for(let s of Object.keys(r).sort()){let o=M(r[s],e,n);o!==void 0&&(a[s]=o);}return a}finally{n.delete(r);}}async function ie(t){
69
- let e=globalThis.crypto?.subtle;if(e){let r=new Uint8Array(await e.digest("SHA-256",t));return Array.from(r,a=>a.toString(16).padStart(2,"0")).join("")}let n="";for(let r=0;r<t.length;r+=32768)n+=String.
70
- fromCharCode(...t.subarray(r,r+32768));return ae(n)}async function Ne(t){try{let e=[],n=JSON.stringify(M(t,e,new WeakSet))??"null",r=await Promise.all(e.map(ie)),a=new TextEncoder().encode(`${n}|${r.join(
71
- ",")}`);return await ie(a)}catch{return null}}async function de(t,e){let n=await Ne(e.proyeccion),r=`${e.context?.authorizationScope??"default"}|bvsala-adapter:${n??"none"}`;return {model:e.model,messages:e.
67
+ alid":r.toISOString()};if(n.has(r))return "$cycle";n.add(r);try{if(Array.isArray(r))return r.map(a=>{let o=D(a,e,n);return o===void 0?null:o});if(r instanceof Map)return {$map:[...r.entries()].map(a=>D(
68
+ a,e,n))};if(r instanceof Set)return {$set:[...r.values()].map(a=>D(a,e,n))};let i={};for(let a of Object.keys(r).sort()){let o=D(r[a],e,n);o!==void 0&&(i[a]=o);}return i}finally{n.delete(r);}}async function ae(t){
69
+ let e=globalThis.crypto?.subtle;if(e){let r=new Uint8Array(await e.digest("SHA-256",t));return Array.from(r,i=>i.toString(16).padStart(2,"0")).join("")}let n="";for(let r=0;r<t.length;r+=32768)n+=String.
70
+ fromCharCode(...t.subarray(r,r+32768));return oe(n)}async function Ne(t){try{let e=[],n=JSON.stringify(D(t,e,new WeakSet))??"null",r=await Promise.all(e.map(ae)),i=new TextEncoder().encode(`${n}|${r.join(
71
+ ",")}`);return await ae(i)}catch{return null}}async function se(t,e){let n=await Ne(e.proyeccion),r=`${e.context?.authorizationScope??"default"}|bvsala-adapter:${n??"none"}`;return {model:e.model,messages:e.
72
72
  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},
73
- savings:qe(t.savings,e.savings,{...e.restricciones,...n===null?{sinReutilizar:true}:{}})}}function ue(t,e){if(!(!t&&!e))return {...t??{},...e??{}}}function le(t){if(!t||typeof t!="object")return {};let e=t,
74
- n={};return e.context&&typeof e.context=="object"&&(n.context=e.context),e.savings&&typeof e.savings=="object"&&(n.savings=e.savings),n}var $e="[bvsala] a streamed call finished but its savings report could not be produced; the model answer was delivered unchanged.";function dt(t){let e=Q("ai-sdk",t),n=t.reportInMetadata!==false;async function r(o,i){
75
- let u=le(o.providerOptions?.bivelio),c;t.context&&(c=t.context({provider:i.provider,modelId:i.modelId,params:o}));let d=t.modelId?t.modelId({provider:i.provider,modelId:i.modelId}):re(i),f=(Array.isArray(
76
- o.tools)?o.tools:[]).map(l=>se(t,{nombre:String(l.name??l.id??""),descripcion:typeof l.description=="string"?l.description:void 0,parametros:l.inputSchema??l.parameters,delProveedor:l.type==="provider"||
77
- l.type==="provider-defined"}));return {req:await de(t,{model:d,messages:ee(o.prompt),tools:f,temperature:typeof o.temperature=="number"?o.temperature:void 0,seed:typeof o.seed=="number"?o.seed:void 0,context:ue(
78
- c,u.context),savings:u.savings,proyeccion:{modelo:d,parametros:te(o)},restricciones:{sinResolvers:ne(o)}}),simulado:oe(i)}}function a(o){return {model:o.model,messages:o.messages,...o.tools?{tools:o.tools}:
79
- {}}}return {specificationVersion:"v3",async wrapGenerate(o){let{req:i,simulado:u}=await r(o.params,o.model),c,d=j(a(i),async()=>(c=await P(d,()=>o.doGenerate()),q(c,u))),f=await e.generar(i,d);if(f.tipo===
80
- "sin-informe")return c;let g=e.informe(f.result.report);if(f.tipo==="vivo"){let l=c;return n?{...l,providerMetadata:S(l.providerMetadata,g)}:l}return Ge(f.result,n?g:void 0,o.model)},async wrapStream(o){
81
- let{req:i,simulado:u}=await r(o.params,o.model),{abierta:c,abrir:d}=X(),f,g,l=Object.assign(j(a(i),async()=>(f=await P(l,()=>o.doGenerate()),q(f,u)),()=>{let R=new L;return P(l,()=>o.doStream()).then(
82
- p=>{g={...p,stream:ze(p.stream,R,e,l,u,n)},d();},p=>R.fail(p)),R}),{abierta:c}),v=o.params.abortSignal instanceof AbortSignal?o.params.abortSignal:void 0,y=await e.transmitir(i,l,v);if(y.tipo==="abiert\
83
- o")return g;if(y.tipo==="sin-informe")return ce(f,void 0);let x=e.informe(y.result.report);return y.tipo==="entero"?ce(f,n?x:void 0):_e(y.result,n?x:void 0,o.model)},close(){e.close();}}}function ze(t,e,n,r,a,s){
84
- let o=t.getReader(),i=new D;return new ReadableStream({async pull(u){let c;try{c=await o.read();}catch(l){e.fail(l),u.error(l);return}if(c.done){e.fail(new Error("[bvsala] the model stream ended withou\
85
- t a finish part; nothing was measured.")),u.close();return}let d=c.value,f=i.anadir(d);if(d.type==="error"){e.fail(d.error??new Error("[bvsala] the model stream reported an error")),u.enqueue(d);return}
86
- if(f!==void 0&&e.push({type:"text",delta:f}),d.type!=="finish"||e.cerrada){u.enqueue(d);return}e.push({type:"done",response:i.respuesta(d.usage,d.finishReason,a)}),e.end();let g=d;try{let l=await r.resultado,
87
- v=n.informe(l.report);s&&(g={...d,providerMetadata:S(d.providerMetadata,v)});}catch{n.avisar("informe-del-stream",$e);}u.enqueue(g);},cancel(u){return e.fail(new Error("[bvsala] the stream was cancelled \
88
- by its reader; nothing was measured.")),o.cancel(u)}})}function Ge(t,e,n){return {content:N(t),finishReason:$(t),usage:U,...e?{providerMetadata:S(void 0,e)}:{},response:{id:`bvsala-${t.requestId}`,modelId:n.
89
- modelId,timestamp:new Date},warnings:[]}}function _e(t,e,n){let r=z(N(t),{usage:U,finishReason:$(t),...e?{providerMetadata:S(void 0,e)}:{}},{warnings:[],response:{id:`bvsala-${t.requestId}`,modelId:n.
90
- modelId,timestamp:new Date}});return {stream:G(r)}}function ce(t,e){let n=t.response,r=z(Array.isArray(t.content)?t.content:[],{usage:t.usage,finishReason:t.finishReason,...e?{providerMetadata:S(t.providerMetadata,
91
- e)}:t.providerMetadata!==void 0?{providerMetadata:t.providerMetadata}:{}},{warnings:t.warnings,response:n?Object.fromEntries(Object.entries(n).filter(([a])=>a!=="headers"&&a!=="body")):void 0});return {
92
- stream:G(r),...t.request!==void 0?{request:t.request}:{},...n?.headers!==void 0?{response:{headers:n.headers}}:{}}}function ut(t){let n=t?.providerMetadata?.bivelio?.savingsReport;if(!(!n||typeof n!="\
73
+ savings:Ue(t.savings,e.savings,{...e.restricciones,...n===null?{sinReutilizar:true}:{}})}}function de(t,e){if(!(!t&&!e))return {...t??{},...e??{}}}function ue(t){if(!t||typeof t!="object")return {};let e=t,
74
+ n={};return e.context&&typeof e.context=="object"&&(n.context=e.context),e.savings&&typeof e.savings=="object"&&(n.savings=e.savings),n}var $e="[bvsala] a streamed call finished but its savings report could not be produced; the model answer was delivered unchanged.";function dt(t){let e=H("ai-sdk",t),n=t.reportInMetadata!==false;async function r(o,s){
75
+ let d=ue(o.providerOptions?.bivelio),c;t.context&&(c=t.context({provider:s.provider,modelId:s.modelId,params:o}));let l=t.modelId?t.modelId({provider:s.provider,modelId:s.modelId}):ne(s),f=(Array.isArray(
76
+ o.tools)?o.tools:[]).map(u=>ie(t,{nombre:String(u.name??u.id??""),descripcion:typeof u.description=="string"?u.description:void 0,parametros:u.inputSchema??u.parameters,delProveedor:u.type==="provider"||
77
+ u.type==="provider-defined"}));return {req:await se(t,{model:l,messages:Y(o.prompt),tools:f,temperature:typeof o.temperature=="number"?o.temperature:void 0,seed:typeof o.seed=="number"?o.seed:void 0,context:de(
78
+ c,d.context),savings:d.savings,proyeccion:{modelo:l,parametros:ee(o)},restricciones:{sinResolvers:te(o)}}),simulado:re(s)}}function i(o){return {model:o.model,messages:o.messages,...o.tools?{tools:o.tools}:
79
+ {}}}return {specificationVersion:"v3",async wrapGenerate(o){let{req:s,simulado:d}=await r(o.params,o.model),c,l=T(i(s),async()=>(c=await C(l,()=>o.doGenerate()),q(c,d))),f=await e.generar(s,l);if(f.tipo===
80
+ "sin-informe")return c;let g=e.informe(f.result.report);if(f.tipo==="vivo"){let u=c;return n?{...u,providerMetadata:S(u.providerMetadata,g)}:u}return Ge(f.result,n?g:void 0,o.model)},async wrapStream(o){
81
+ let{req:s,simulado:d}=await r(o.params,o.model),{abierta:c,abrir:l}=Z(),f,g,u=Object.assign(T(i(s),async()=>(f=await C(u,()=>o.doGenerate()),q(f,d)),()=>{let p=new L;return C(u,()=>o.doStream()).then(
82
+ y=>{g={...y,stream:ze(y.stream,p,e,u,d,n)},l();},y=>p.fail(y)),p}),{abierta:c}),x=o.params.abortSignal instanceof AbortSignal?o.params.abortSignal:void 0,v=await e.transmitir(s,u,x);if(v.tipo==="abiert\
83
+ o")return g;if(v.tipo==="sin-informe")return le(f,void 0);let b=e.informe(v.result.report);return v.tipo==="entero"?le(f,n?b:void 0):_e(v.result,n?b:void 0,o.model)},close(){e.close();}}}function ze(t,e,n,r,i,a){
84
+ let o=t.getReader(),s=new k;return new ReadableStream({async pull(d){let c;try{c=await o.read();}catch(u){e.fail(u),d.error(u);return}if(c.done){e.fail(new Error("[bvsala] the model stream ended withou\
85
+ t a finish part; nothing was measured.")),d.close();return}let l=c.value,f=s.anadir(l);if(l.type==="error"){e.fail(l.error??new Error("[bvsala] the model stream reported an error")),d.enqueue(l);return}
86
+ if(f!==void 0&&e.push({type:"text",delta:f}),l.type!=="finish"||e.cerrada){d.enqueue(l);return}e.push({type:"done",response:s.respuesta(l.usage,l.finishReason,i)}),e.end();let g=l;try{let u=await r.resultado,
87
+ x=n.informe(u.report);a&&(g={...l,providerMetadata:S(l.providerMetadata,x)});}catch{n.avisar("informe-del-stream",$e);}d.enqueue(g);},cancel(d){return e.fail(new Error("[bvsala] the stream was cancelled \
88
+ by its reader; nothing was measured.")),o.cancel(d)}})}function Ge(t,e,n){return {content:j(t),finishReason:N(t),usage:U,...e?{providerMetadata:S(void 0,e)}:{},response:{id:`bvsala-${t.requestId}`,modelId:n.
89
+ modelId,timestamp:new Date},warnings:[]}}function _e(t,e,n){let r=$(j(t),{usage:U,finishReason:N(t),...e?{providerMetadata:S(void 0,e)}:{}},{warnings:[],response:{id:`bvsala-${t.requestId}`,modelId:n.
90
+ modelId,timestamp:new Date}});return {stream:z(r)}}function le(t,e){let n=t.response,r=$(Array.isArray(t.content)?t.content:[],{usage:t.usage,finishReason:t.finishReason,...e?{providerMetadata:S(t.providerMetadata,
91
+ e)}:t.providerMetadata!==void 0?{providerMetadata:t.providerMetadata}:{}},{warnings:t.warnings,response:n?Object.fromEntries(Object.entries(n).filter(([i])=>i!=="headers"&&i!=="body")):void 0});return {
92
+ stream:z(r),...t.request!==void 0?{request:t.request}:{},...n?.headers!==void 0?{response:{headers:n.headers}}:{}}}function ut(t){let n=t?.providerMetadata?.bivelio?.savingsReport;if(!(!n||typeof n!="\
93
93
  object"||typeof n.requestId!="string"))return n}export{ut as getSavingsReport,dt as savingsMiddleware};
@@ -1,124 +1,124 @@
1
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
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
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??
4
+ function W(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 a=n??(o[1]!==void 0&&o[1]!==""?o[1]:void 0);return {finishReason:"content_filter",...a!==void 0?{finishReasonDetail:a}:{}}}return {finishReason:Ae[t]??"other",finishReasonDetail:n??
6
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
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}
8
+ s=O(o?.ephemeral_5m_input_tokens),a=O(o?.ephemeral_1h_input_tokens),i=typeof r.cache_creation_input_tokens=="number"?O(r.cache_creation_input_tokens):s+a;e.cacheWrite+=i,e.cacheWrite1h+=Math.min(a,i);}
9
+ return e.iteraciones>0?e:null}function H(t,e,n){let r=t??{},o=V(r.iterations),s=G(r.cache_read_input_tokens,o?.cacheRead),a=G(r.cache_creation_input_tokens,o?.cacheWrite),i=r.cache_creation?.ephemeral_1h_input_tokens,l=typeof i=="\
10
+ number"||(o?.cacheWrite1h??0)>0?Math.min(Math.max(0,(typeof i=="number"?i:0)+(o?.cacheWrite1h??0)),a??0):void 0,u=(r.input_tokens??0)+(o?.input??0)+(a??0)+(s??0),p=(e??0)+(o?.output??0),h=typeof r.input_tokens!=
11
+ "number",m=typeof e!="number";return {usage:{inputTokens:u,outputTokens:p,...s!=null?{cachedInputTokens:s}:{},...a!=null?{cacheWriteInputTokens:a}:{},...l!==void 0?{cacheWrite1hInputTokens:l}:{},...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 Q(t){let e=t?.service_tier;return typeof e=="string"&&e!==""?e:void 0}
13
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!==
14
+ ...n,...r?{cache_creation:r}:{}}}function K(t){return t==="thinking"||t==="redacted_thinking"}function Y(t,e){return W(t,Ce(t,e))}var De=new Set([null,"cyber","general_harms"]);function Z(t){if(t.stopReason!==
15
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
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(
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"],Oe=["claude-opus-4-7","claude-opus-4-8","claude-opus-5","claude-sonnet-5","claude-fable-5","claude-mythos-5"];function Ee(t){return /claude-[a-z]+-\d[a-z0-9-]*/.exec(t.toLowerCase())?.[0]}function X(t,e){let n=Ee(t);return n===void 0?false:e.some(r=>n===r||n.startsWith(`${r}-`))}function ee(t){return X(t,Pe)}function te(t){
18
+ return X(t,Oe)}var Te={"api.anthropic.com":"anthropic","api.openai.com":"openai","generativelanguage.googleapis.com":"google"};function Me(t){if(typeof t!="string")return null;try{let e=new URL(t);return e.protocol!==
19
+ "https:"||e.port!==""?null:Te[e.hostname.toLowerCase()]??null}catch{return null}}function ne(t){return Me(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(
20
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,
21
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(
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\
22
+ 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.
23
+ 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),
24
+ s=e.slice(r+1),s.charCodeAt(0)===32&&(s=s.slice(1))),o){case "data":this.datos+=s+`
25
+ `;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":
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 Ue="[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.",je="[bvsala] internal: the layer called the model outside a framework call; nothing was sent.";function B(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,s)=>qe(o,r[s]))}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 s=e.getStore();if(!s)throw new Error(je);if(s.invocada)throw new Error(Ie);if(!Ne(o,s.renderizado))throw new Error(
30
+ Ue);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}
31
+ let i=await a.generar(s?.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 Be=["licenseKey","licenseServerUrl","serviceAccountKey","licenseRefresh","licenseRevocation","licensePollIntervalSeconds","licenseFetch","metering","meteringUrl","meteringFetch","costModels","defa\
33
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
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(){
35
+ let n=le(),r={};for(let a of Be)e[a]!==void 0&&(r[a]=e[a]);let o=createSavingsLayer({...r,provider:ce(t,n)}),s=(a,i)=>se(e.silenceWarnings,`${t}:${a}`,i);return {ejecutar(a,i){return n.run(i,()=>o.generate(a))},async generar(a,i){
36
+ try{let l=await n.run(i,()=>o.generate(a));return i.invocada?{tipo:"vivo",result:l}:{tipo:"atajo",result:l}}catch(l){if(ue(i,l))return s("sin-informe",de),{tipo:"sin-informe"};throw l}},async transmitir(a,i,l){
37
+ let p=n.run(i,()=>o.generateStream(a,l?{signal:l}:{})).result;i.resultado=p,p.catch(()=>{});let h;try{h=await Promise.race([i.abierta.then(()=>"abierta"),p.then(()=>"resuelta")]);}catch(y){if(ue(i,y))return s(
38
+ "sin-informe",de),{tipo:"sin-informe"};throw y}if(h==="abierta")return {tipo:"abierto"};let m=await p;return i.invocada?{tipo:"entero",result:m}:{tipo:"atajo",result:m}},informe(a){let i=JSON.parse(JSON.
39
+ 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 pe(){
40
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.
41
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||
42
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](){
43
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(
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,
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 Fe=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,
45
45
  4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,
46
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);
47
+ 1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Je=new TextEncoder;function w(t,e){return t>>>e|t<<32-e}function ge(t){return We(Je.encode(t))}function We(t){
48
+ let e=t.length*8,n=(t.length+8>>6)+1,r=new Uint8Array(n*64);r.set(t),r[t.length]=128;let o=new DataView(r.buffer);o.setUint32(r.length-8,Math.floor(e/4294967296)),o.setUint32(r.length-4,e>>>0);let s=new Uint32Array(
49
+ [1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),a=new Uint32Array(64);for(let l=0;l<r.length;l+=64){for(let f=0;f<16;f++)a[f]=o.getUint32(l+f*4);for(let f=16;f<
50
+ 64;f++){let R=a[f-15],S=a[f-2],A=w(R,7)^w(R,18)^R>>>3,k=w(S,17)^w(S,19)^S>>>10;a[f]=a[f-16]+A+a[f-7]+k|0;}let u=s[0],p=s[1],h=s[2],m=s[3],y=s[4],d=s[5],b=s[6],x=s[7];for(let f=0;f<64;f++){let R=w(y,6)^
51
+ w(y,11)^w(y,25),S=y&d^~y&b,A=x+R+S+Fe[f]+a[f]|0,k=w(u,2)^w(u,13)^w(u,22),T=u&p^u&h^p&h,D=k+T|0;x=b,b=d,d=y,y=m+A|0,m=h,h=p,p=u,u=A+D|0;}s[0]=s[0]+u|0,s[1]=s[1]+p|0,s[2]=s[2]+h|0,s[3]=s[3]+m|0,s[4]=s[4]+
52
+ y|0,s[5]=s[5]+d|0,s[6]=s[6]+b|0,s[7]=s[7]+x|0;}let i="";for(let l=0;l<8;l++)i+=(s[l]>>>0).toString(16).padStart(8,"0");return i}var Ve={router:false,compression:false,elision:false,serialization:false,toolDiscovery:false,modelCascade:"off",outputCodebook:false,deferrable:false,semanticCache:false,verification:false};function Ge(t,e,n={}){let r=o=>t?.[o]!==
53
+ false&&e?.[o]!==false;return {...Ve,exactCache:r("exactCache")&&n.sinReutilizar!==true,singleflight:r("singleflight")&&n.sinReutilizar!==true,deterministicResolvers:r("deterministicResolvers")&&n.sinResolvers!==
54
+ true}}function He(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&&He(t,e.nombre);
55
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 "\
56
+ descripcion}:{}}}function U(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
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
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){
59
+ alid":r.toISOString()};if(n.has(r))return "$cycle";n.add(r);try{if(Array.isArray(r))return r.map(s=>{let a=U(s,e,n);return a===void 0?null:a});if(r instanceof Map)return {$map:[...r.entries()].map(s=>U(
60
+ s,e,n))};if(r instanceof Set)return {$set:[...r.values()].map(s=>U(s,e,n))};let o={};for(let s of Object.keys(r).sort()){let a=U(r[s],e,n);a!==void 0&&(o[s]=a);}return o}finally{n.delete(r);}}async function he(t){
61
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.
62
+ fromCharCode(...t.subarray(r,r+32768));return ge(n)}async function Qe(t){try{let e=[],n=JSON.stringify(U(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 Qe(e.proyeccion),r=`${e.context?.authorizationScope??"default"}|bvsala-adapter:${n??"none"}`;return {model:e.model,messages:e.
64
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){
65
+ savings:Ge(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 F="[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 E(t){return typeof t=="string"?[{type:"text",text:t}]:Array.isArray(t)?t.filter(g):[]}function j(t){
68
68
  return t.filter(e=>e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(`
69
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\
70
+ m",content:typeof n=="string"?n:j(E(n))});for(let r of Array.isArray(t.messages)?t.messages:[]){if(!g(r))continue;let o=E(r.content);if(r.role==="assistant"){let a=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:j(o),...a.length>0?{toolCalls:a}:{}});continue}for(let a of o)a.type==="too\
72
+ l_result"&&e.push({role:"tool",content:typeof a.content=="string"?a.content:j(E(a.content)),...typeof a.tool_use_id=="string"?{toolCallId:a.tool_use_id}:{}});let s=j(o);(s!==""||!o.some(a=>a.type==="t\
73
+ ool_result"))&&e.push({role:"user",content:s});}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":E(t.system).map(xe),n.messages=(Array.isArray(
75
+ t.messages)?t.messages:[]).filter(g).map(r=>({role:r.role,content:E(r.content).map(xe)})),e&&(n["anthropic-beta"]=e),n}function et(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 tt(t){let e=typeof t.model=="string"?t.model:"";if(e==="")return [];let n=[],r=t.tool_choice;g(r)&&(r.type==="an\
77
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
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\
79
+ com/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&&te(e)&&
80
+ n.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 i\
81
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.
82
+ this.bloquesVistos+=1,K(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 E(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
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
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
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
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(
88
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==
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.
89
+ "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=g(n.delta)?n.delta:{};typeof o.
90
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
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}
100
- data: ${JSON.stringify(u)}
92
+ [...this.herramientas.entries()].sort((e,n)=>e[0]-n[0]).map(([,e])=>({...e.id?{id:e.id}:{},name:e.name,arguments:nt(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,s=Q(e);
94
+ return {text:this.texto,...o.length>0?{toolCalls:o}:{},...Y(this.parada,this.detallesDeParada),...this.vioDelta&&Z({stopReason:this.parada,stopDetails:this.detallesDeParada,bloques:this.bloquesVistos,outputTokens:this.
95
+ usoDelta?.output_tokens,iterations:r})?{unbilledRefusal:true}:{},...s?{servedServiceTier:s}:{},usage:n,...this.reproducible&&this.parada==="end_turn"?{}:{replayable:false}}}};function nt(t){try{return JSON.
96
+ stringify(JSON.parse(t===""?"{}":t))}catch{return t}}function rt(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||
97
+ "{}");}catch{s={};}n.push({type:"tool_use",id:r.id??`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.
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=rt(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 s=(i,l)=>`event: ${i}
100
+ data: ${JSON.stringify(l)}
101
101
 
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};
102
+ `,a=s("message_start",{type:"message_start",message:{...r,content:[],stop_reason:null,stop_sequence:null}});return r.content.forEach((i,l)=>{i.type==="text"?(a+=s("content_block_start",{type:"content_\
103
+ block_start",index:l,content_block:{type:"text",text:""}}),a+=s("content_block_delta",{type:"content_block_delta",index:l,delta:{type:"text_delta",text:i.text}})):(a+=s("content_block_start",{type:"co\
104
+ ntent_block_start",index:l,content_block:{type:"tool_use",id:i.id,name:i.name,input:{}}}),a+=s("content_block_delta",{type:"content_block_delta",index:l,delta:{type:"input_json_delta",partial_json:JSON.
105
+ stringify(i.input)}})),a+=s("content_block_stop",{type:"content_block_stop",index:l});}),a+=s("message_delta",{type:"message_delta",delta:{stop_reason:r.stop_reason,stop_sequence:null},usage:{output_tokens:0}}),
106
+ a+=s("message_stop",{type:"message_stop"}),new Response(a,{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 Tt(t){let e=fe("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(
108
+ r.keys().next().value);};return {middleware:async(a,i,l)=>{if(!Ye(a))return i(a);if(typeof a.body!="string")throw new Error(F);let u;try{let c=JSON.parse(a.body);if(!g(c))throw new Error(F);u=c;}catch{throw new Error(
109
+ F)}for(let c of tt(u))e.avisar(c.clave,c.mensaje);let p=l.options,h=be(p?.bivelio),m=t.context?.({body:u,requestOptions:p}),y=(Array.isArray(u.tools)?u.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"})),d=await ye(t,{model:`\
111
+ anthropic/${String(u.model??"")}`,messages:Ze(u),tools:y,temperature:typeof u.temperature=="number"?u.temperature:void 0,context:ve(m,h.context),savings:h.savings,proyeccion:Xe(u,a.headers.get("anthro\
112
+ pic-beta")),restricciones:{sinResolvers:et(u)}}),b={model:d.model,messages:d.messages,...d.tools?{tools:d.tools}:{}},x=ne(a.url),f=async c=>{let v;try{v=await i(a);}catch(_){throw c.errorDelMarco={error:_},
113
+ _}if(!v.ok){let _=new N(v);throw c.errorDelMarco={error:_},_}return c.completada=true,v},R=c=>{if(c instanceof N)return c.respuesta;throw c};if(u.stream!==true){let c,v,_=B(b,async()=>{c=await f(_);let M=new q;
114
+ return M.json(await c.clone().json()),v=M.id,M.respuesta()},void 0,x),P;try{P=await e.generar(d,_);}catch(M){return R(M)}if(P.tipo==="sin-informe")return c;let J=e.informe(P.result.report);return P.tipo===
115
+ "atajo"?(o(`msg_bvsala_${P.result.requestId}`,J),_e(P.result,u.model,false)):(o(v,J),c)}let{abierta:S,abrir:A}=pe(),k,T,D=Object.assign(B(b,async()=>{let c=await f(D),v=new L;T=we(c,v,e,D,o),A();for await(let _ of v)
116
+ if(_.type==="done")return _.response;throw new Error("[bvsala] the model stream ended before completion; nothing was measured.")},()=>{let c=new L;return f(D).then(v=>{k=we(v,c,e,D,o),A();},v=>c.fail(v)),
117
+ c},x),{abierta:S}),C;try{C=await e.transmitir(d,D,a.signal??void 0);}catch(c){return R(c)}if(C.tipo==="abierto")return k??T;if(C.tipo==="atajo"){let c=e.informe(C.result.report);return o(`msg_bvsala_${C.
118
+ result.requestId}`,c),_e(C.result,u.model,true)}return k??T},reportFor(a){let i=typeof a=="string"?a:a?.id;return typeof i=="string"?r.get(i):void 0},close(){e.close();}}}function we(t,e,n,r,o){let s=new q,
119
+ a,i=async()=>{try{let d=await r.resultado;o(s.id,n.informe(d.report));}catch{}},l=()=>{e.cerrada||(s.error?e.fail(new Error(`[bvsala] provider stream error: ${s.error}`)):s.vioDelta||s.vioStop?(e.push(
120
+ {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\
121
+ plication/json"))return t.clone().json().then(d=>{s.json(g(d)?d:{}),s.texto!==""&&e.push({type:"text",delta:s.texto}),l();},d=>e.fail(d)),t;let u=t.body;if(!u)return e.fail(new Error("[bvsala] the mode\
122
+ l stream had no body; nothing was measured.")),t;let p=u.getReader(),h=new I,m=d=>{for(let b of d){let x=s.evento(b);x!==void 0&&e.push({type:"text",delta:x}),(s.vioStop||s.error)&&l();}},y=new ReadableStream(
123
+ {async pull(d){let b;try{b=await p.read();}catch(f){e.fail(f),d.error(f);return}if(b.done){m(h.end()),l(),await a,d.close();return}let x=b.value;d.enqueue(x),m(h.push(x));},cancel(d){return e.fail(new Error(
124
+ "[bvsala] the stream was cancelled by its reader; nothing was measured.")),p.cancel(d)}});return new Response(y,{status:t.status,statusText:t.statusText,headers:t.headers})}export{Tt as anthropicSavings};