@bivelio/savings-layer 0.5.1 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +115 -0
- package/LICENSE +183 -163
- package/LICENSE-CLOUD.md +174 -0
- package/NOTICE +11 -0
- package/README.md +228 -126
- package/dist/adapters/ai-sdk.js +78 -78
- package/dist/adapters/anthropic-sdk.js +88 -88
- package/dist/adapters/langchain.js +58 -58
- package/dist/adapters/mastra.js +70 -70
- package/dist/gateway/bin.js +1291 -1082
- package/dist/index.d.ts +367 -197
- package/dist/index.js +1717 -1641
- package/docs/terminales/README.md +39 -33
- package/docs/terminales/aider.md +1 -1
- package/docs/terminales/claude-code.md +2 -2
- package/docs/terminales/cline.md +1 -1
- package/docs/terminales/codex.md +3 -3
- package/docs/terminales/copilot.md +1 -1
- package/docs/terminales/crush.md +1 -1
- package/docs/terminales/cursor.md +32 -0
- package/docs/terminales/deepseek.md +28 -0
- package/docs/terminales/droid.md +1 -1
- package/docs/terminales/gemini.md +38 -0
- package/docs/terminales/goose.md +2 -2
- package/docs/terminales/kilo.md +2 -2
- package/docs/terminales/no-soportados.md +16 -27
- package/docs/terminales/ollama.md +19 -0
- package/docs/terminales/opencode.md +2 -2
- package/docs/terminales/qwen-code.md +2 -2
- package/package.json +48 -20
package/dist/adapters/ai-sdk.js
CHANGED
|
@@ -1,93 +1,93 @@
|
|
|
1
|
-
import {createSavingsLayer,LicenseError}from'@bivelio/savings-layer';import {AsyncLocalStorage}from'async_hooks';var
|
|
2
|
-
nothing more was sent.",
|
|
3
|
-
completada:false,...{}}}async function
|
|
4
|
-
t)===
|
|
5
|
-
function
|
|
6
|
-
async generate(a
|
|
7
|
-
text",delta:
|
|
8
|
-
if(Array.isArray(t))return t.map(
|
|
9
|
-
ultCostModel","exactCache","exactCacheTtlMs","resolvers","exactTokenizer","silenceWarnings","failOpen"];function
|
|
10
|
-
t.completada}var
|
|
11
|
-
let n=
|
|
12
|
-
try{let
|
|
13
|
-
let
|
|
14
|
-
"sin-informe",
|
|
15
|
-
stringify(o));if(e.onReport)try{e.onReport(
|
|
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
|
|
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
|
|
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
|
|
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
|
|
26
|
-
map(
|
|
27
|
-
tool":for(let
|
|
28
|
-
{}});break}}return e}var
|
|
29
|
-
entries(t))if(!(n==="toolCallId"||n==="id")&&!(n==="text"&&t.type==="text")){if(n==="providerOptions"||n==="providerMetadata"){e[n]=
|
|
30
|
-
t:[]).map(e=>m(e)?{role:e.role,content:typeof e.content=="string"?"$text":
|
|
31
|
-
if(!m(t))return;let e={};for(let[n,r]of Object.entries(t))
|
|
32
|
-
entries(t))n==="prompt"||n==="abortSignal"||n==="headers"||n==="providerOptions"||(e[n]=r);return e.prompt=
|
|
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
|
|
34
|
-
t)?t:void 0}function
|
|
35
|
-
0,outputTokens:g??0,complete:false}}let
|
|
36
|
-
void 0?{cacheWriteInputTokens:
|
|
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
|
|
38
|
-
|
|
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":
|
|
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
|
|
43
|
-
text:this.texto,...this.toolCalls.length>0?{toolCalls:this.toolCalls}:{},...
|
|
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
|
|
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
|
|
46
|
-
return {unified:(t.toolCalls?.length??0)>0?"tool-calls":"stop",raw:void 0}}function
|
|
47
|
-
response-metadata",...n.response}),t.forEach((a
|
|
48
|
-
xt-start",id:o,...
|
|
49
|
-
{providerMetadata:
|
|
50
|
-
id:o,...
|
|
51
|
-
{pull(n){e<t.length?n.enqueue(t[e++]):n.close();}})}function
|
|
52
|
-
return typeof t.provider=="string"&&t.provider.toLowerCase().startsWith("mock")}function S(t,e){return {...m(t)?t:{},bivelio:{savingsReport:e}}}var
|
|
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]),
|
|
56
|
-
8,
|
|
57
|
-
[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),
|
|
58
|
-
64;p++){let
|
|
59
|
-
h(
|
|
60
|
-
|
|
61
|
-
false&&e?.[
|
|
62
|
-
true}}function
|
|
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
|
|
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(
|
|
68
|
-
|
|
69
|
-
let e=globalThis.crypto?.subtle;if(e){let r=new Uint8Array(await e.digest("SHA-256",t));return Array.from(r,
|
|
70
|
-
fromCharCode(...t.subarray(r,r+32768));return
|
|
71
|
-
",")}`);return await
|
|
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:
|
|
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=
|
|
75
|
-
let
|
|
76
|
-
o.tools)?o.tools:[]).map(
|
|
77
|
-
|
|
78
|
-
c,
|
|
79
|
-
{}}}return {specificationVersion:"v3",async wrapGenerate(o){let{req:
|
|
80
|
-
"sin-informe")return c;let g=e.informe(f.result.report);if(f.tipo==="vivo"){let
|
|
81
|
-
let{req:
|
|
82
|
-
|
|
83
|
-
o")return g;if(
|
|
84
|
-
let o=t.getReader(),
|
|
85
|
-
t a finish part; nothing was measured.")),
|
|
86
|
-
if(f!==void 0&&e.push({type:"text",delta:f}),
|
|
87
|
-
|
|
88
|
-
by its reader; nothing was measured.")),o.cancel(
|
|
89
|
-
modelId,timestamp:new Date},warnings:[]}}function _e(t,e,n){let r
|
|
90
|
-
modelId,timestamp:new Date}});return {stream:
|
|
91
|
-
e)}:t.providerMetadata!==void 0?{providerMetadata:t.providerMetadata}:{}},{warnings:t.warnings,response:n?Object.fromEntries(Object.entries(n).filter(([
|
|
92
|
-
stream:
|
|
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
|
|
5
|
-
{}};let o=ke.exec(t);if(o!==null){let
|
|
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
|
-
|
|
9
|
-
return e.iteraciones>0?e:null}function H(t,e,n){let r=t??{},o=V(r.iterations),
|
|
10
|
-
number"||(o?.cacheWrite1h??0)>0?Math.min(Math.max(0,(typeof i=="number"?i:0)+(o?.cacheWrite1h??0)),
|
|
11
|
-
"number",m=typeof e!="number";return {usage:{inputTokens:
|
|
12
|
-
m||o?{}:{reasoningTokens:0},...h||m?{complete:false}:{}},entradaAusente:h,salidaAusente:m}}function G(t,e){return e?(t??0)+e:t}function
|
|
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
|
|
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"],
|
|
18
|
-
return
|
|
19
|
-
"https:"||e.port!==""?null:
|
|
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
|
|
23
|
-
crPendiente=true),o++,
|
|
24
|
-
|
|
25
|
-
`;break;case "event":this.evento=
|
|
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
|
|
27
|
-
nothing more was sent.",
|
|
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,
|
|
29
|
-
e.model&&ae(t.messages,e.messages)&&ae(t.tools,e.tools)}function ce(t,e){let n=o=>{let
|
|
30
|
-
|
|
31
|
-
let i=await
|
|
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
|
|
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
|
|
36
|
-
try{let
|
|
37
|
-
let
|
|
38
|
-
"sin-informe",de),{tipo:"sin-informe"};throw
|
|
39
|
-
stringify(
|
|
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
|
|
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]),
|
|
48
|
-
8,
|
|
49
|
-
[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),
|
|
50
|
-
64;
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
false&&e?.[o]!==false;return {...
|
|
54
|
-
true}}function
|
|
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
|
|
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(
|
|
60
|
-
|
|
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
|
|
63
|
-
",")}`);return await he(o)}catch{return null}}async function ye(t,e){let n=await
|
|
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:
|
|
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
|
|
67
|
-
try{return new URL(t.url).pathname.replace(/\/+$/,"").endsWith("/v1/messages")}catch{return false}}function
|
|
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:
|
|
71
|
-
i=>({...typeof i.id=="string"?{id:i.id}:{},name:String(i.name??""),arguments:Re(i.input)}));e.push({role:"assistant",content:
|
|
72
|
-
l_result"&&e.push({role:"tool",content:typeof
|
|
73
|
-
ool_result"))&&e.push({role:"user",content:
|
|
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":
|
|
75
|
-
t.messages)?t.messages:[]).filter(g).map(r=>({role:r.role,content:
|
|
76
|
-
g(t.output_config)&&t.output_config.format!==void 0?true:t.output_format!==void 0}function
|
|
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(
|
|
80
|
-
n.push({clave:`muestreo:${e}`,mensaje:`[bvsala] Model "${e}" rejects a non-default ${o.map(
|
|
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,
|
|
83
|
-
this.id=typeof e.id=="string"?e.id:void 0;for(let n of
|
|
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
|
|
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:
|
|
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,
|
|
94
|
-
return {text:this.texto,...o.length>0?{toolCalls:o}:{},...
|
|
95
|
-
usoDelta?.output_tokens,iterations:r})?{unbilledRefusal:true}:{},...
|
|
96
|
-
stringify(JSON.parse(t===""?"{}":t))}catch{return t}}function
|
|
97
|
-
"{}");}catch{
|
|
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=
|
|
99
|
-
JSON.stringify(r),{status:200,headers:{...o,"content-type":"application/json"}});let
|
|
100
|
-
data: ${JSON.stringify(
|
|
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
|
|
103
|
-
block_start",index:
|
|
104
|
-
ntent_block_start",index:
|
|
105
|
-
stringify(i.input)}})),s
|
|
106
|
-
s
|
|
107
|
-
status}`);this.respuesta=n;}respuesta};function
|
|
108
|
-
r.keys().next().value);};return {middleware:async(
|
|
109
|
-
|
|
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"})),
|
|
111
|
-
anthropic/${String(
|
|
112
|
-
pic-beta")),restricciones:{sinResolvers:
|
|
113
|
-
|
|
114
|
-
return
|
|
115
|
-
"atajo"?(o(`msg_bvsala_${
|
|
116
|
-
if(
|
|
117
|
-
c},
|
|
118
|
-
result.requestId}`,c),_e(
|
|
119
|
-
|
|
120
|
-
{type:"done",response:
|
|
121
|
-
plication/json"))return t.clone().json().then(
|
|
122
|
-
l stream had no body; nothing was measured.")),t;let
|
|
123
|
-
{async pull(
|
|
124
|
-
"[bvsala] the stream was cancelled by its reader; nothing was measured.")),
|
|
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};
|