@bivelio/savings-layer 0.4.25 → 0.4.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +328 -23
- package/dist/adapters/ai-sdk.js +73 -73
- package/dist/adapters/anthropic-sdk.js +69 -67
- package/dist/adapters/langchain.js +55 -52
- package/dist/adapters/mastra.js +65 -65
- package/dist/gateway/bin.js +906 -623
- package/dist/index.d.ts +928 -11
- package/dist/index.js +1398 -1004
- package/docs/terminales/README.md +59 -11
- package/docs/terminales/aider.md +74 -0
- package/docs/terminales/continue.md +47 -0
- package/docs/terminales/copilot.md +114 -0
- package/docs/terminales/kilo.md +54 -31
- package/docs/terminales/no-soportados.md +41 -0
- package/docs/terminales/opencode.md +33 -11
- package/package.json +24 -3
package/dist/adapters/ai-sdk.js
CHANGED
|
@@ -1,84 +1,84 @@
|
|
|
1
|
-
import {createSavingsLayer,LicenseError,sha256,stableStringify}from'@bivelio/savings-layer';import {AsyncLocalStorage}from'async_hooks';var j=new Set;function $(t,e,n){t===true||j.has(e)||(j.add(e),console.warn(n));}var
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
function
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
ultCostModel","exactCache","exactCacheTtlMs","resolvers","exactTokenizer","silenceWarnings","failOpen"];function
|
|
9
|
-
t.completada}var
|
|
10
|
-
let n=U(),r={};for(let
|
|
11
|
-
try{let d=await n.run(s,()=>
|
|
12
|
-
let u=n.run(s,()=>
|
|
13
|
-
"sin-informe",
|
|
14
|
-
stringify(
|
|
1
|
+
import {createSavingsLayer,LicenseError,sha256,stableStringify}from'@bivelio/savings-layer';import {AsyncLocalStorage}from'async_hooks';var j=new Set;function $(t,e,n){t===true||j.has(e)||(j.add(e),console.warn(n));}var N=Symbol.for("@bivelio/savings-layer:provider-origin");var ie="[bvsala] internal: the layer changed a request this adapter must forward unchanged; nothing was sent.",se="[bvsala] internal: the layer asked for a second model call within one framework call;\
|
|
2
|
+
nothing more was sent.",de="[bvsala] internal: the layer called the model outside a framework call; nothing was sent.";function C(t,e,n,r){return {renderizado:t,generar:e,...n?{transmitir:n}:{},invocada:false,
|
|
3
|
+
completada:false,...{}}}async function x(t,e){try{let n=await e();return t.completada=!0,n}catch(n){throw t.errorDelMarco={error:n},n}}function ue(t,e){if(t===e)return true;try{return stableStringify(
|
|
4
|
+
t)===stableStringify(e)}catch{return false}}function G(t,e){let n=t??[],r=e??[];return n.length===r.length&&n.every((a,i)=>ue(a,r[i]))}function le(t,e){return t.model===e.model&&G(t.messages,e.messages)&&G(t.tools,e.tools)}
|
|
5
|
+
function _(t,e){let n=a=>{let i=e.getStore();if(!i)throw new Error(de);if(i.invocada)throw new Error(se);if(!le(a,i.renderizado))throw new Error(ie);return i.invocada=true,i},r={id:`bivelio-adapter:${t}`,
|
|
6
|
+
async generate(a,i){return n(a).generar(i?.signal)},async*generateStream(a,i){let o=n(a);if(o.transmitir){yield*o.transmitir(i?.signal);return}let s=await o.generar(i?.signal);s.text!==""&&(yield {type:"\
|
|
7
|
+
text",delta:s.text}),yield {type:"done",response:s};}};return Object.defineProperty(r,N,{value:()=>e.getStore()?.origen}),r}function U(){return new AsyncLocalStorage}var fe=["licenseKey","licenseServerUrl","serviceAccountKey","licenseRefresh","licenseRevocation","licensePollIntervalSeconds","licenseFetch","metering","meteringUrl","meteringFetch","costModels","defa\
|
|
8
|
+
ultCostModel","exactCache","exactCacheTtlMs","resolvers","exactTokenizer","silenceWarnings","failOpen"];function F(t,e){return e instanceof LicenseError||t.errorDelMarco&&t.errorDelMarco.error===e?false:t.invocada&&
|
|
9
|
+
t.completada}var V="[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 W(t,e){
|
|
10
|
+
let n=U(),r={};for(let o of fe)e[o]!==void 0&&(r[o]=e[o]);let a=createSavingsLayer({...r,provider:_(t,n)}),i=(o,s)=>$(e.silenceWarnings,`${t}:${o}`,s);return {ejecutar(o,s){return n.run(s,()=>a.generate(o))},async generar(o,s){
|
|
11
|
+
try{let d=await n.run(s,()=>a.generate(o));return s.invocada?{tipo:"vivo",result:d}:{tipo:"atajo",result:d}}catch(d){if(F(s,d))return i("sin-informe",V),{tipo:"sin-informe"};throw d}},async transmitir(o,s,d){
|
|
12
|
+
let u=n.run(s,()=>a.generateStream(o,d?{signal:d}:{})).result;s.resultado=u,u.catch(()=>{});let c;try{c=await Promise.race([s.abierta.then(()=>"abierta"),u.then(()=>"resuelta")]);}catch(l){if(F(s,l))return i(
|
|
13
|
+
"sin-informe",V),{tipo:"sin-informe"};throw l}if(c==="abierta")return {tipo:"abierto"};let g=await u;return s.invocada?{tipo:"entero",result:g}:{tipo:"atajo",result:g}},informe(o){let s=JSON.parse(JSON.
|
|
14
|
+
stringify(o));if(e.onReport)try{e.onReport(s);}catch{i("onreport","[bvsala] `onReport` threw; the error was caught and the model call was not affected.");}return s},avisar:i,close(){a.close();}}}function B(){
|
|
15
15
|
let t;return {abierta:new Promise(n=>{t=n;}),abrir:t}}var b=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.
|
|
16
16
|
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||
|
|
17
17
|
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](){
|
|
18
18
|
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(
|
|
19
|
-
(e,n)=>{this.esperando={resolver:e,rechazar:n};}),return:()=>(this.terminada=true,this.pendientes.length=0,Promise.resolve({value:void 0,done:true}))}}};function
|
|
19
|
+
(e,n)=>{this.esperando={resolver:e,rechazar:n};}),return:()=>(this.terminada=true,this.pendientes.length=0,Promise.resolve({value:void 0,done:true}))}}};function f(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function J(t){return typeof t=="string"?[{type:"text",text:t}]:Array.isArray(t)?t.filter(f):[]}function A(t){return t.filter(e=>e.type===
|
|
20
20
|
"text"&&typeof e.text=="string").map(e=>e.text).join(`
|
|
21
|
-
`)}function v(t){if(typeof t=="string")return t;try{return JSON.stringify(t??{})}catch{return "{}"}}function
|
|
22
|
-
"string"?t.value:v(t.value);case "json":case "error-json":return v(t.value);case "execution-denied":return `execution denied${typeof t.reason=="string"?`: ${t.reason}`:""}`;case "content":return
|
|
23
|
-
return v(t)}function e(n){return Array.isArray(n)?n.filter(
|
|
24
|
-
system",content:typeof n.content=="string"?n.content:
|
|
25
|
-
map(i=>({...typeof i.toolCallId=="string"?{id:i.toolCallId}:{},name:String(i.toolName??""),arguments:v(i.input??i.args)}));e.push({role:"assistant",content:
|
|
26
|
-
tool":for(let
|
|
27
|
-
{}});break}}return e}var
|
|
28
|
-
entries(t))if(!(n==="toolCallId"||n==="id")&&!(n==="text"&&t.type==="text")){if(n==="providerOptions"||n==="providerMetadata"){e[n]=
|
|
29
|
-
t:[]).map(e=>
|
|
30
|
-
if(!
|
|
31
|
-
entries(t))n==="prompt"||n==="abortSignal"||n==="headers"||n==="providerOptions"||(e[n]=r);return e.prompt=
|
|
32
|
-
responseFormat;if(
|
|
33
|
-
void 0}function
|
|
34
|
-
outputTokens:g??0,complete:false}}let i=m(r.total),
|
|
35
|
-
void 0?{cacheWriteInputTokens:s}:{},...
|
|
36
|
-
g")return t.unified}function
|
|
37
|
-
|
|
21
|
+
`)}function v(t){if(typeof t=="string")return t;try{return JSON.stringify(t??{})}catch{return "{}"}}function ge(t){if(!f(t))return v(t);switch(t.type){case "text":case "error-text":return typeof t.value==
|
|
22
|
+
"string"?t.value:v(t.value);case "json":case "error-json":return v(t.value);case "execution-denied":return `execution denied${typeof t.reason=="string"?`: ${t.reason}`:""}`;case "content":return A(e(t.value));default:
|
|
23
|
+
return v(t)}function e(n){return Array.isArray(n)?n.filter(f):[]}}function H(t){let e=[];for(let n of Array.isArray(t)?t:[]){if(!f(n))continue;let r=J(n.content);switch(n.role){case "system":e.push({role:"\
|
|
24
|
+
system",content:typeof n.content=="string"?n.content:A(r)});break;case "user":e.push({role:"user",content:A(r)});break;case "assistant":{let a=r.filter(i=>i.type==="tool-call"&&i.providerExecuted!==true).
|
|
25
|
+
map(i=>({...typeof i.toolCallId=="string"?{id:i.toolCallId}:{},name:String(i.toolName??""),arguments:v(i.input??i.args)}));e.push({role:"assistant",content:A(r),...a.length>0?{toolCalls:a}:{}});break}case "\
|
|
26
|
+
tool":for(let a of r)a.type==="tool-result"&&e.push({role:"tool",content:ge(a.output??a.result),...typeof a.toolCallId=="string"?{toolCallId:a.toolCallId}:{},...typeof a.toolName=="string"?{name:a.toolName}:
|
|
27
|
+
{}});break}}return e}var me=new Set(["bivelio","mastra"]);function D(t){if(!f(t))return t;let e={};for(let[n,r]of Object.entries(t))me.has(n)||(e[n]=r);return e}function ve(t){let e={};for(let[n,r]of Object.
|
|
28
|
+
entries(t))if(!(n==="toolCallId"||n==="id")&&!(n==="text"&&t.type==="text")){if(n==="providerOptions"||n==="providerMetadata"){e[n]=D(r);continue}e[n]=r;}return e}function ye(t){return (Array.isArray(t)?
|
|
29
|
+
t:[]).map(e=>f(e)?{role:e.role,content:typeof e.content=="string"?"$text":J(e.content).map(ve),providerOptions:D(e.providerOptions)}:e)}var he=new Set(["anthropic-beta","openai-beta"]);function Re(t){
|
|
30
|
+
if(!f(t))return;let e={};for(let[n,r]of Object.entries(t))he.has(n.toLowerCase())&&r!==void 0&&(e[n.toLowerCase()]=r);return Object.keys(e).length>0?e:void 0}function K(t){let e={};for(let[n,r]of Object.
|
|
31
|
+
entries(t))n==="prompt"||n==="abortSignal"||n==="headers"||n==="providerOptions"||(e[n]=r);return e.prompt=ye(t.prompt),e.headers=Re(t.headers),e.providerOptions=D(t.providerOptions),e}function Z(t){let e=t.
|
|
32
|
+
responseFormat;if(f(e)&&e.type==="json")return true;let n=t.toolChoice;return f(n)&&(n.type==="required"||n.type==="tool")?true:n==="required"}function m(t){return typeof t=="number"&&Number.isFinite(t)?t:
|
|
33
|
+
void 0}function we(t,e){let n=f(t)?t:{},r=f(n.inputTokens)?n.inputTokens:void 0,a=f(n.outputTokens)?n.outputTokens:void 0;if(!r||!a){let c=m(n.inputTokens),g=m(n.outputTokens);return {inputTokens:c??0,
|
|
34
|
+
outputTokens:g??0,complete:false}}let i=m(r.total),o=m(r.cacheRead),s=m(r.cacheWrite),d=m(a.total),p=m(a.reasoning);return {inputTokens:i??0,outputTokens:d??0,...o!==void 0?{cachedInputTokens:o}:{},...s!==
|
|
35
|
+
void 0?{cacheWriteInputTokens:s}:{},...p!==void 0?{reasoningTokens:p}:{},...i!==void 0&&d!==void 0&&!e?{}:{complete:false}}}function Se(t){if(typeof t=="string")return t;if(f(t)&&typeof t.unified=="strin\
|
|
36
|
+
g")return t.unified}function xe(t){switch(t){case void 0:return;case "tool-calls":return "tool_calls";case "content-filter":return "content_filter";default:return t}}function be(t){return f(t)&&Object.keys(
|
|
37
|
+
D(t)).length>0}var R=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:
|
|
38
38
|
"";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.
|
|
39
39
|
push({...typeof e.toolCallId=="string"?{id:e.toolCallId}:{},name:String(e.toolName??""),arguments:v(e.input??e.args)});return;case "reasoning":case "reasoning-start":case "reasoning-delta":case "reasoning\
|
|
40
|
-
-end":
|
|
41
|
-
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
|
|
42
|
-
text:this.texto,...this.toolCalls.length>0?{toolCalls:this.toolCalls}:{},...i?{finishReason:i}:{},usage:
|
|
43
|
-
t.content:[])
|
|
44
|
-
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
|
|
45
|
-
return {unified:(t.toolCalls?.length??0)>0?"tool-calls":"stop",raw:void 0}}function
|
|
46
|
-
response-metadata",...n.response}),t.forEach((
|
|
47
|
-
xt-start",id:
|
|
48
|
-
{providerMetadata:
|
|
49
|
-
id:
|
|
50
|
-
{pull(n){e<t.length?n.enqueue(t[e++]):n.close();}})}function
|
|
51
|
-
return typeof t.provider=="string"&&t.provider.toLowerCase().startsWith("mock")}function y(t,e){return {...
|
|
52
|
-
function ke(t,e,n={}){let r=
|
|
53
|
-
erministicResolvers")&&n.sinResolvers!==true}}function
|
|
54
|
-
let n=e.delProveedor!==true&&
|
|
40
|
+
-end":be(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 "\
|
|
41
|
+
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=Se(n),i=xe(a),o=this.reproducible&&a==="stop";return {
|
|
42
|
+
text:this.texto,...this.toolCalls.length>0?{toolCalls:this.toolCalls}:{},...i?{finishReason:i}:{},usage:we(e,r),...o?{}:{replayable:false}}}};function P(t,e){let n=new R;for(let r of Array.isArray(t.content)?
|
|
43
|
+
t.content:[])f(r)&&n.anadir(r);return n.respuesta(t.usage,t.finishReason,e)}var L={inputTokens:{total:0,noCache:0,cacheRead:0,cacheWrite:0},outputTokens:{total:0,text:0,reasoning:0}};function O(t){let e=[];
|
|
44
|
+
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 I(t){
|
|
45
|
+
return {unified:(t.toolCalls?.length??0)>0?"tool-calls":"stop",raw:void 0}}function T(t,e,n){let r=[{type:"stream-start",warnings:Array.isArray(n.warnings)?n.warnings:[]}];return n.response&&r.push({type:"\
|
|
46
|
+
response-metadata",...n.response}),t.forEach((a,i)=>{if(!f(a))return;let o=`bvsala-${i}`;if(a.type==="text"){let s=a.providerMetadata!==void 0?{providerMetadata:a.providerMetadata}:{};r.push({type:"te\
|
|
47
|
+
xt-start",id:o,...s}),typeof a.text=="string"&&a.text!==""&&r.push({type:"text-delta",id:o,delta:a.text}),r.push({type:"text-end",id:o,...s});}else if(a.type==="reasoning"){let s=a.providerMetadata!==void 0?
|
|
48
|
+
{providerMetadata:a.providerMetadata}:{};r.push({type:"reasoning-start",id:o,...s}),typeof a.text=="string"&&a.text!==""&&r.push({type:"reasoning-delta",id:o,delta:a.text}),r.push({type:"reasoning-end",
|
|
49
|
+
id:o,...s});}else r.push(a);}),r.push({type:"finish",usage:e.usage,finishReason:e.finishReason,...e.providerMetadata!==void 0?{providerMetadata:e.providerMetadata}:{}}),r}function E(t){let e=0;return new ReadableStream(
|
|
50
|
+
{pull(n){e<t.length?n.enqueue(t[e++]):n.close();}})}function Q(t){let e=String(t.modelId??"");if(e.includes("/"))return e;let n=String(t.provider??"").split(".")[0]??"";return n!==""?`${n}/${e}`:e}function X(t){
|
|
51
|
+
return typeof t.provider=="string"&&t.provider.toLowerCase().startsWith("mock")}function y(t,e){return {...f(t)?t:{},bivelio:{savingsReport:e}}}var De={router:false,compression:false,elision:false,serialization:false,toolDiscovery:false,modelCascade:"off",outputCodebook:false,deferrable:false,semanticCache:false,verification:false};
|
|
52
|
+
function ke(t,e,n={}){let r=a=>t?.[a]!==false&&e?.[a]!==false;return {...De,exactCache:r("exactCache")&&n.sinReutilizar!==true,singleflight:r("singleflight")&&n.sinReutilizar!==true,deterministicResolvers:r("det\
|
|
53
|
+
erministicResolvers")&&n.sinResolvers!==true}}function Me(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 ee(t,e){
|
|
54
|
+
let n=e.delProveedor!==true&&Me(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}:{},
|
|
55
55
|
...typeof e.descripcion=="string"?{description:e.descripcion}:{}}}function w(t,e,n){if(t===null)return null;switch(typeof t){case "string":case "boolean":return t;case "number":return Number.isFinite(t)?
|
|
56
56
|
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)
|
|
57
57
|
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};
|
|
58
|
-
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(i=>{let
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
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
|
|
62
|
-
all(e.map(
|
|
58
|
+
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(i=>{let o=w(i,e,n);return o===void 0?null:
|
|
59
|
+
o});if(r instanceof Map)return {$map:[...r.entries()].map(i=>w(i,e,n))};if(r instanceof Set)return {$set:[...r.values()].map(i=>w(i,e,n))};let a={};for(let i of Object.keys(r).sort()){let o=w(r[i],e,n);
|
|
60
|
+
o!==void 0&&(a[i]=o);}return a}finally{n.delete(r);}}async function Y(t){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(
|
|
61
|
+
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 Ce(t){try{let e=[],n=JSON.stringify(w(t,e,new WeakSet))??"null",r=await Promise.
|
|
62
|
+
all(e.map(Y)),a=new TextEncoder().encode(`${n}|${r.join(",")}`);return await Y(a)}catch{return null}}async function te(t,e){let n=await Ce(e.proyeccion),r=`${e.context?.authorizationScope??"default"}|\
|
|
63
63
|
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"?
|
|
64
|
-
{seed:e.seed}:{},context:{...e.context??{},authorizationScope:r},savings:ke(t.savings,e.savings,{...e.restricciones,...n===null?{sinReutilizar:true}:{}})}}function
|
|
65
|
-
{}}}function
|
|
66
|
-
let d=
|
|
67
|
-
|
|
68
|
-
l.type==="provider-defined"}));return {req:await
|
|
69
|
-
|
|
70
|
-
{}}}return {specificationVersion:"v3",async wrapGenerate(
|
|
71
|
-
"sin-informe")return
|
|
72
|
-
let{req:s,simulado:d}=await r(
|
|
73
|
-
S=>{g={...S,stream:
|
|
74
|
-
o")return g;if(h.tipo==="sin-informe")return
|
|
75
|
-
let
|
|
76
|
-
t a finish part; nothing was measured.")),d.close();return}let u=
|
|
77
|
-
if(c!==void 0&&e.push({type:"text",delta:c}),u.type!=="finish"||e.cerrada){d.enqueue(u);return}e.push({type:"done",response:s.respuesta(u.usage,u.finishReason,
|
|
78
|
-
|
|
79
|
-
by its reader; nothing was measured.")),
|
|
80
|
-
modelId,timestamp:new Date},warnings:[]}}function Ie(t,e,n){let r=O(
|
|
81
|
-
modelId,timestamp:new Date}});return {stream:E(r)}}function
|
|
82
|
-
e)}:t.providerMetadata!==void 0?{providerMetadata:t.providerMetadata}:{}},{warnings:t.warnings,response:n?Object.fromEntries(Object.entries(n).filter(([
|
|
83
|
-
stream:E(r),...t.request!==void 0?{request:t.request}:{},...n?.headers!==void 0?{response:{headers:n.headers}}:{}}}function
|
|
84
|
-
object"||typeof n.requestId!="string"))return n}export{
|
|
64
|
+
{seed:e.seed}:{},context:{...e.context??{},authorizationScope:r},savings:ke(t.savings,e.savings,{...e.restricciones,...n===null?{sinReutilizar:true}:{}})}}function ne(t,e){if(!(!t&&!e))return {...t??{},...e??
|
|
65
|
+
{}}}function re(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 Pe="[bvsala] a streamed call finished but its savings report could not be produced; the model answer was delivered unchanged.";function Xe(t){let e=W("ai-sdk",t),n=t.reportInMetadata!==false;async function r(o,s){
|
|
66
|
+
let d=re(o.providerOptions?.bivelio),p;t.context&&(p=t.context({provider:s.provider,modelId:s.modelId,params:o}));let u=t.modelId?t.modelId({provider:s.provider,modelId:s.modelId}):Q(s),c=(Array.isArray(
|
|
67
|
+
o.tools)?o.tools:[]).map(l=>ee(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"||
|
|
68
|
+
l.type==="provider-defined"}));return {req:await te(t,{model:u,messages:H(o.prompt),tools:c,temperature:typeof o.temperature=="number"?o.temperature:void 0,seed:typeof o.seed=="number"?o.seed:void 0,context:ne(
|
|
69
|
+
p,d.context),savings:d.savings,proyeccion:{modelo:u,parametros:K(o)},restricciones:{sinResolvers:Z(o)}}),simulado:X(s)}}function a(o){return {model:o.model,messages:o.messages,...o.tools?{tools:o.tools}:
|
|
70
|
+
{}}}return {specificationVersion:"v3",async wrapGenerate(o){let{req:s,simulado:d}=await r(o.params,o.model),p,u=C(a(s),async()=>(p=await x(u,()=>o.doGenerate()),P(p,d))),c=await e.generar(s,u);if(c.tipo===
|
|
71
|
+
"sin-informe")return p;let g=e.informe(c.result.report);if(c.tipo==="vivo"){let l=p;return n?{...l,providerMetadata:y(l.providerMetadata,g)}:l}return Oe(c.result,n?g:void 0,o.model)},async wrapStream(o){
|
|
72
|
+
let{req:s,simulado:d}=await r(o.params,o.model),{abierta:p,abrir:u}=B(),c,g,l=Object.assign(C(a(s),async()=>(c=await x(l,()=>o.doGenerate()),P(c,d)),()=>{let M=new b;return x(l,()=>o.doStream()).then(
|
|
73
|
+
S=>{g={...S,stream:Le(S.stream,M,e,l,d,n)},u();},S=>M.fail(S)),M}),{abierta:p}),k=o.params.abortSignal instanceof AbortSignal?o.params.abortSignal:void 0,h=await e.transmitir(s,l,k);if(h.tipo==="abiert\
|
|
74
|
+
o")return g;if(h.tipo==="sin-informe")return oe(c,void 0);let q=e.informe(h.result.report);return h.tipo==="entero"?oe(c,n?q:void 0):Ie(h.result,n?q:void 0,o.model)},close(){e.close();}}}function Le(t,e,n,r,a,i){
|
|
75
|
+
let o=t.getReader(),s=new R;return new ReadableStream({async pull(d){let p;try{p=await o.read();}catch(l){e.fail(l),d.error(l);return}if(p.done){e.fail(new Error("[bvsala] the model stream ended withou\
|
|
76
|
+
t a finish part; nothing was measured.")),d.close();return}let u=p.value,c=s.anadir(u);if(u.type==="error"){e.fail(u.error??new Error("[bvsala] the model stream reported an error")),d.enqueue(u);return}
|
|
77
|
+
if(c!==void 0&&e.push({type:"text",delta:c}),u.type!=="finish"||e.cerrada){d.enqueue(u);return}e.push({type:"done",response:s.respuesta(u.usage,u.finishReason,a)}),e.end();let g=u;try{let l=await r.resultado,
|
|
78
|
+
k=n.informe(l.report);i&&(g={...u,providerMetadata:y(u.providerMetadata,k)});}catch{n.avisar("informe-del-stream",Pe);}d.enqueue(g);},cancel(d){return e.fail(new Error("[bvsala] the stream was cancelled \
|
|
79
|
+
by its reader; nothing was measured.")),o.cancel(d)}})}function Oe(t,e,n){return {content:O(t),finishReason:I(t),usage:L,...e?{providerMetadata:y(void 0,e)}:{},response:{id:`bvsala-${t.requestId}`,modelId:n.
|
|
80
|
+
modelId,timestamp:new Date},warnings:[]}}function Ie(t,e,n){let r=T(O(t),{usage:L,finishReason:I(t),...e?{providerMetadata:y(void 0,e)}:{}},{warnings:[],response:{id:`bvsala-${t.requestId}`,modelId:n.
|
|
81
|
+
modelId,timestamp:new Date}});return {stream:E(r)}}function oe(t,e){let n=t.response,r=T(Array.isArray(t.content)?t.content:[],{usage:t.usage,finishReason:t.finishReason,...e?{providerMetadata:y(t.providerMetadata,
|
|
82
|
+
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 {
|
|
83
|
+
stream:E(r),...t.request!==void 0?{request:t.request}:{},...n?.headers!==void 0?{response:{headers:n.headers}}:{}}}function Ye(t){let n=t?.providerMetadata?.bivelio?.savingsReport;if(!(!n||typeof n!="\
|
|
84
|
+
object"||typeof n.requestId!="string"))return n}export{Ye as getSavingsReport,Xe as savingsMiddleware};
|
|
@@ -1,76 +1,78 @@
|
|
|
1
|
-
import {createSavingsLayer,LicenseError,sha256,stableStringify}from'@bivelio/savings-layer';import {AsyncLocalStorage}from'async_hooks';var
|
|
2
|
-
null||typeof n!="object")continue;let r=n;if(r.type!=="compaction")continue;e.iteraciones++,e.input+=
|
|
3
|
-
s=
|
|
4
|
-
return e.iteraciones>0?e:null}function
|
|
5
|
-
(o?.
|
|
6
|
-
{
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
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
|
+
number"||(o?.cacheWrite1h??0)>0?Math.min(Math.max(0,(typeof i=="number"?i:0)+(o?.cacheWrite1h??0)),a??0):void 0,d=(r.input_tokens??0)+(o?.input??0)+(a??0)+(s??0),g=(e??0)+(o?.output??0),m=typeof r.input_tokens!=
|
|
6
|
+
"number",h=typeof e!="number";return {usage:{inputTokens:d,outputTokens:g,...s!=null?{cachedInputTokens:s}:{},...a!=null?{cacheWriteInputTokens:a}:{},...u!==void 0?{cacheWrite1hInputTokens:u}:{},...n||
|
|
7
|
+
h||o?{}:{reasoningTokens:0},...m||h?{complete:false}:{}},entradaAusente:m,salidaAusente:h}}function W(t,e){return e?(t??0)+e:t}function 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(
|
|
10
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,
|
|
11
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(
|
|
12
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.
|
|
13
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),
|
|
14
16
|
s=e.slice(r+1),s.charCodeAt(0)===32&&(s=s.slice(1))),o){case "data":this.datos+=s+`
|
|
15
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":
|
|
16
|
-
this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};var
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
model&&
|
|
20
|
-
return
|
|
21
|
-
|
|
22
|
-
ultCostModel","exactCache","exactCacheTtlMs","resolvers","exactTokenizer","silenceWarnings","failOpen"];function
|
|
23
|
-
t.completada}var
|
|
24
|
-
let n=
|
|
25
|
-
try{let u=await n.run(i,()=>o.generate(a));return i.invocada?{tipo:"vivo",result:u}:{tipo:"atajo",result:u}}catch(u){if(
|
|
26
|
-
let
|
|
27
|
-
"sin-informe",
|
|
28
|
-
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
|
|
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(){
|
|
29
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.
|
|
30
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||
|
|
31
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](){
|
|
32
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(
|
|
33
|
-
(e,n)=>{this.esperando={resolver:e,rechazar:n};}),return:()=>(this.terminada=true,this.pendientes.length=0,Promise.resolve({value:void 0,done:true}))}}};var
|
|
34
|
-
function
|
|
35
|
-
erministicResolvers")&&n.sinResolvers!==true}}function
|
|
36
|
-
let n=e.delProveedor!==true&&
|
|
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}:{},
|
|
37
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)?
|
|
38
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)
|
|
39
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};
|
|
40
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:
|
|
41
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);
|
|
42
|
-
a!==void 0&&(o[s]=a);}return o}finally{n.delete(r);}}async function
|
|
43
|
-
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
|
|
44
|
-
all(e.map(
|
|
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"}\
|
|
45
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"?
|
|
46
|
-
{seed:e.seed}:{},context:{...e.context??{},authorizationScope:r},savings:
|
|
47
|
-
{}}}function
|
|
48
|
-
try{return new URL(t.url).pathname.replace(/\/+$/,"").endsWith("/v1/messages")}catch{return false}}function
|
|
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){
|
|
49
51
|
return t.filter(e=>e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(`
|
|
50
|
-
`)}function
|
|
51
|
-
m",content:typeof n=="string"?n:
|
|
52
|
-
i=>({...typeof i.id=="string"?{id:i.id}:{},name:String(i.name??""),arguments:
|
|
53
|
-
l_result"&&e.push({role:"tool",content:typeof a.content=="string"?a.content:
|
|
54
|
-
ool_result"))&&e.push({role:"user",content:s});}return e}function
|
|
55
|
-
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":
|
|
56
|
-
t.messages)?t.messages:[]).filter(p).map(r=>({role:r.role,content:
|
|
57
|
-
p(t.output_config)&&t.output_config.format!==void 0?true:t.output_format!==void 0}var
|
|
58
|
-
|
|
59
|
-
id=="string"?e.id:void 0;for(let n of
|
|
60
|
-
{id:n.id}:{},name:String(n.name??""),arguments:
|
|
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.
|
|
61
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.
|
|
62
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"&&
|
|
63
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===
|
|
64
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.
|
|
65
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.
|
|
66
|
-
parada=o.stop_reason),p(n.usage)&&(this.usoDelta=
|
|
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")}\
|
|
67
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?{
|
|
68
|
-
id:e.id}:{},name:e.name,arguments:
|
|
69
|
-
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:
|
|
70
|
-
this.parada)}:{},...s?{servedServiceTier:s}:{},usage:n,...this.reproducible&&this.parada==="end_turn"?{}:{replayable:false}}}};function
|
|
71
|
-
function
|
|
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??
|
|
72
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",
|
|
73
|
-
stop_sequence:null,usage:{input_tokens:0,output_tokens:0}}}function
|
|
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,
|
|
74
76
|
"content-type":"application/json"}});let s=(i,u)=>`event: ${i}
|
|
75
77
|
data: ${JSON.stringify(u)}
|
|
76
78
|
|
|
@@ -79,21 +81,21 @@ block_start",index:u,content_block:{type:"text",text:""}}),a+=s("content_block_d
|
|
|
79
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.
|
|
80
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}}),
|
|
81
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.
|
|
82
|
-
status}`);this.respuesta=n;}respuesta};function
|
|
83
|
-
r.keys().next().value);};return {middleware:async(a,i,u)=>{if(!
|
|
84
|
-
I)}let
|
|
85
|
-
tring"?c.description:void 0,parametros:c.input_schema,delProveedor:c.input_schema===void 0&&typeof c.type=="string"&&c.type!=="custom"})),l=await
|
|
86
|
-
d),tools:
|
|
87
|
-
v={model:l.model,messages:l.messages,...l.tools?{tools:l.tools}:{}},
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
false)):(o(
|
|
91
|
-
bvsala] the model stream ended before completion; nothing was measured.")},()=>{let c=new C;return
|
|
92
|
-
void 0);}catch(c){return
|
|
93
|
-
reportFor(a){let i=typeof a=="string"?a:a?.id;return typeof i=="string"?r.get(i):void 0},close(){e.close();}}}function
|
|
94
|
-
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()}),
|
|
95
|
-
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().
|
|
96
|
-
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
|
|
97
|
-
|
|
98
|
-
l.error(
|
|
99
|
-
|
|
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};
|