@bkm016/basalt 0.1.3 → 0.1.4
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/{chunk-x1xss1d7.js → chunk-1vd0f74z.js} +2 -2
- package/{chunk-v9fea96h.js → chunk-2hbfk5xd.js} +2 -2
- package/{chunk-5j1krv9v.js → chunk-2zp1mv3q.js} +1 -1
- package/{chunk-d2j735sd.js → chunk-3ct2tkr8.js} +2 -2
- package/{chunk-c7x1zq39.js → chunk-3x94302m.js} +1 -1
- package/{chunk-gzxnene8.js → chunk-4w17tzp5.js} +2 -2
- package/{chunk-1zdwrgd4.js → chunk-5dfbezv9.js} +1 -1
- package/{chunk-bxn5kmpz.js → chunk-5x1sankd.js} +24 -24
- package/{chunk-pmqtkqsf.js → chunk-71h08f4g.js} +1 -1
- package/{chunk-fm0k0qtz.js → chunk-7afmgncg.js} +2 -2
- package/{chunk-v258nxcz.js → chunk-7nzhdrv9.js} +1 -1
- package/{chunk-zmsgwr3s.js → chunk-7q51n619.js} +1 -1
- package/{chunk-y0m980k3.js → chunk-7tbya5b5.js} +3 -3
- package/{chunk-8tjad3r0.js → chunk-8wc8qdx8.js} +5 -5
- package/{chunk-gp7y0fja.js → chunk-9rmqgc3c.js} +9 -9
- package/{chunk-nbb9trwz.js → chunk-akr0a8nc.js} +2 -2
- package/{chunk-k506w58v.js → chunk-aky4tztg.js} +2 -2
- package/{chunk-8296hw9m.js → chunk-em187cy3.js} +2 -2
- package/{chunk-2esbgxps.js → chunk-ev6yvy5y.js} +5 -5
- package/{chunk-75m78j7x.js → chunk-f3xadvab.js} +2 -2
- package/{chunk-5c9j8qe4.js → chunk-fvn32nzj.js} +26 -26
- package/{chunk-bannb9xm.js → chunk-jk25nt60.js} +1 -1
- package/{chunk-27gntzs5.js → chunk-kp22kaez.js} +1 -1
- package/{chunk-6hssbcgj.js → chunk-nmca5h6m.js} +1 -1
- package/{chunk-d8gtbw9g.js → chunk-pjyn2s97.js} +1 -1
- package/{chunk-rtzqqngy.js → chunk-q7t30zz2.js} +2 -2
- package/{chunk-aefadsy6.js → chunk-r0scgfwx.js} +1 -1
- package/{chunk-hwr56pfj.js → chunk-rmj5b73e.js} +1 -1
- package/{chunk-1qpces5a.js → chunk-vexrrw1b.js} +2 -2
- package/chunk-vkpvcxjr.js +2 -0
- package/{chunk-3cjsd292.js → chunk-whvj83b7.js} +2 -2
- package/{chunk-z55bmysw.js → chunk-xh3vr5vz.js} +1 -1
- package/{chunk-10xzzn07.js → chunk-zggzfa7j.js} +2 -2
- package/compiled.js +3 -3
- package/package.json +1 -1
- package/ui-test-worker.js +13 -13
- package/web/{chunk-7520nrbb.js → chunk-0b47eyrf.js} +1 -1
- package/web/{chunk-g46f421r.js → chunk-0h0vb6gt.js} +1 -1
- package/web/{chunk-h18tnrf2.js → chunk-0rmkpsgp.js} +1 -1
- package/web/{chunk-t7bwsdbr.js → chunk-0xkyryrq.js} +1 -1
- package/web/{chunk-h288yd5w.js → chunk-0z0y25zf.js} +1 -1
- package/web/{chunk-7ba8vrfc.js → chunk-1eg9sbbt.js} +1 -1
- package/web/{chunk-p9hsd3rn.js → chunk-1gbd61z0.js} +1 -1
- package/web/{chunk-vd6y2pcm.js → chunk-2s0bmrkv.js} +1 -1
- package/web/{chunk-33qwz9bc.js → chunk-2z1rwr28.js} +1 -1
- package/web/{chunk-tse9gvyq.js → chunk-344bq59c.js} +1 -1
- package/web/{chunk-0z0jycs8.js → chunk-3re8y26v.js} +1 -1
- package/web/chunk-3t0211rw.js +1 -0
- package/web/{chunk-5hmfk69r.js → chunk-42e3b9hv.js} +1 -1
- package/web/chunk-44rmrmcn.js +1 -0
- package/web/{chunk-fhnypcrm.js → chunk-4bzqrwr0.js} +81 -81
- package/web/{chunk-j0bwwc1g.js → chunk-4d3a7xs2.js} +1 -1
- package/web/{chunk-y3ajqthy.js → chunk-4jmazh6x.js} +1 -1
- package/web/{chunk-z4x331rx.js → chunk-4re74xwm.js} +1 -1
- package/web/{chunk-61jahh35.js → chunk-5qtyq3ce.js} +1 -1
- package/web/{chunk-wmvd6j0b.js → chunk-5z4jcqct.js} +1 -1
- package/web/{chunk-fv60p68p.js → chunk-5z6x2n5h.js} +1 -1
- package/web/{chunk-sn9ecfvy.js → chunk-6cnek1xh.js} +1 -1
- package/web/chunk-6f5ke0x9.js +1 -0
- package/web/{chunk-3qjnwsph.js → chunk-6xaqxcq8.js} +1 -1
- package/web/chunk-7q6wvv2x.js +1 -0
- package/web/{chunk-cwtdnacf.js → chunk-7qsa4p8h.js} +1 -1
- package/web/chunk-8nja0ygy.js +1 -0
- package/web/{chunk-z6bpamwq.js → chunk-8y64fkpz.js} +1 -1
- package/web/{chunk-90xqeczk.js → chunk-92ssjk2y.js} +1 -1
- package/web/chunk-9ad7v7bm.js +8 -0
- package/web/{chunk-7yc083xj.js → chunk-9cx1be43.js} +1 -1
- package/web/{chunk-wdtnhpd6.js → chunk-9dzxv335.js} +1 -1
- package/web/{chunk-w7snhcyg.js → chunk-9t5dnjaz.js} +2 -2
- package/web/{chunk-7v5rxabp.js → chunk-a408enpy.js} +1 -1
- package/web/{chunk-hszjc2ny.js → chunk-a497tykb.js} +1 -1
- package/web/{chunk-n8gfjj9a.js → chunk-aqfpnhmt.js} +2 -2
- package/web/{chunk-axkyft9f.js → chunk-b1bgzz66.js} +1 -1
- package/web/{chunk-sb1cjpq8.js → chunk-b53bfkys.js} +1 -1
- package/web/{chunk-6parf7sy.js → chunk-b6k9w215.js} +1 -1
- package/web/{chunk-es28k2t7.js → chunk-bhsaj6qq.js} +1 -1
- package/web/chunk-cjfssg3m.js +2 -0
- package/web/{chunk-5qqw2e0t.js → chunk-d11v5s7w.js} +1 -1
- package/web/{chunk-acybsx44.js → chunk-df5zx17h.js} +1 -1
- package/web/chunk-e0zre35a.js +1 -0
- package/web/{chunk-a5sg33w2.js → chunk-e9twvs9n.js} +1 -1
- package/web/chunk-f2kgtyfp.js +1 -0
- package/web/{chunk-23c1df7e.js → chunk-f4tacm06.js} +1 -1
- package/web/chunk-f8bn5tzf.js +1 -0
- package/web/chunk-fdp9bsj7.js +1 -0
- package/web/{chunk-7xk0ntav.js → chunk-fh2vj0wv.js} +1 -1
- package/web/{chunk-sgvp8vge.js → chunk-gmzqdm7v.js} +1 -1
- package/web/{chunk-tx8240k4.js → chunk-hvw3gn2a.js} +1 -1
- package/web/{chunk-rks7ksv3.js → chunk-khxcn8tt.js} +1 -1
- package/web/{chunk-eqsd8zta.js → chunk-kmr7r9xj.js} +1 -1
- package/web/chunk-kqqmp1am.js +1 -0
- package/web/{chunk-mb4qx9hy.js → chunk-kwccs9f6.js} +1 -1
- package/web/chunk-nbgqbxcy.js +1 -0
- package/web/{chunk-rcx1aee5.js → chunk-ncpnpe9w.js} +1 -1
- package/web/{chunk-jzfd7cyh.js → chunk-ne0v8mfb.js} +1 -1
- package/web/{chunk-yd1ez3wd.js → chunk-ngx2cp8x.js} +1 -1
- package/web/{chunk-4fzj0azw.js → chunk-nvhmq4z5.js} +1 -1
- package/web/chunk-nxcgf7ec.js +1 -0
- package/web/{chunk-zmdnxn6m.js → chunk-p0kvmf28.js} +1 -1
- package/web/chunk-p3k7m5nr.js +1 -0
- package/web/{chunk-9bgey148.js → chunk-pggaffrh.js} +1 -1
- package/web/{chunk-5b2nw6j1.js → chunk-pjkdrgm0.js} +1 -1
- package/web/{chunk-97b62pvb.js → chunk-pws2seas.js} +1 -1
- package/web/{chunk-mwj9tpkz.js → chunk-pz9ps2jm.js} +1 -1
- package/web/chunk-qpmbxhh6.js +1 -0
- package/web/chunk-r0rctnxz.js +1 -0
- package/web/chunk-rn3dnqm8.js +1 -0
- package/web/{chunk-47q4hmfp.js → chunk-rvrf0f3h.js} +1 -1
- package/web/{chunk-7qxhk1kz.js → chunk-sfg2wkhe.js} +1 -1
- package/web/{chunk-ep37qp12.js → chunk-sspfxp5e.js} +1 -1
- package/web/{chunk-2hd1pe9w.js → chunk-t4c8xavd.js} +1 -1
- package/web/{chunk-8qgpfxkz.js → chunk-tdr6x2xc.js} +1 -1
- package/web/chunk-tncvg1nn.js +1 -0
- package/web/{chunk-9xh96b33.js → chunk-vyp0ns1f.js} +1 -1
- package/web/{chunk-b0a8nbj0.js → chunk-wnskxerq.js} +1 -1
- package/web/{chunk-vymqrpm3.js → chunk-wvdehm9y.js} +66 -66
- package/web/chunk-x7ahcpj7.js +1 -0
- package/web/chunk-y38bf0wm.js +1 -0
- package/web/{chunk-89fkdgbp.js → chunk-y56aaba5.js} +1 -1
- package/web/{chunk-24h1rfje.js → chunk-ybrf9mhz.js} +1 -1
- package/web/{chunk-vpa55vje.js → chunk-ye58t45p.js} +3 -3
- package/web/{chunk-xnq41dgs.js → chunk-yqbnps3a.js} +1 -1
- package/web/{chunk-jqa39f8t.js → chunk-z1h20s8c.js} +1 -1
- package/web/{chunk-9a3q0jsh.js → chunk-zj4q9jth.js} +1 -1
- package/web/{chunk-ywp4s71k.js → chunk-zj5k94dk.js} +1 -1
- package/web/{chunk-xvsmtetz.js → chunk-zqch0sc8.js} +1 -1
- package/web/{chunk-0xc2c540.js → chunk-zx8zec24.js} +1 -1
- package/web/index.html +1 -1
- package/chunk-09rj27b2.js +0 -2
- package/web/chunk-166qe5j6.js +0 -2
- package/web/chunk-1c95wfvq.js +0 -1
- package/web/chunk-329rtxa9.js +0 -1
- package/web/chunk-6gxf3vsg.js +0 -1
- package/web/chunk-a91vxtx4.js +0 -1
- package/web/chunk-agec7jj4.js +0 -1
- package/web/chunk-c516cghj.js +0 -1
- package/web/chunk-dg1vas6z.js +0 -8
- package/web/chunk-fc0nx23g.js +0 -1
- package/web/chunk-jvbbrnpa.js +0 -1
- package/web/chunk-ka9ak8wr.js +0 -1
- package/web/chunk-mnjd59jk.js +0 -1
- package/web/chunk-ng0nbfhh.js +0 -1
- package/web/chunk-nz9nxk48.js +0 -1
- package/web/chunk-phw908hn.js +0 -1
- package/web/chunk-pjmmma1k.js +0 -1
- package/web/chunk-q7yn4m3t.js +0 -1
- package/web/chunk-qnhqexe0.js +0 -1
- package/web/chunk-rjqj6ffe.js +0 -1
- package/web/chunk-sjjwte12.js +0 -1
- package/web/chunk-yfbxtg5p.js +0 -1
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{f}from"./chunk-mvfsxdx6.js";import{_}from"./chunk-pxsrqrd0.js";import"./chunk-m8vkwdgr.js";import{At,Et}from"./chunk-r9aatvwm.js";import{at,Je,lt}from"./chunk-
|
|
2
|
+
import{f}from"./chunk-mvfsxdx6.js";import{_}from"./chunk-pxsrqrd0.js";import"./chunk-m8vkwdgr.js";import{At,Et}from"./chunk-r9aatvwm.js";import{at,Je,lt}from"./chunk-1vd0f74z.js";import{Ge}from"./chunk-bpw6q7g0.js";import{ee}from"./chunk-tvm4zmgj.js";import{ie}from"./chunk-d48bfd2e.js";import{q,j}from"./chunk-y69ewdn2.js";import{Ee,ct,V}from"./chunk-whvj83b7.js";import{z}from"./chunk-x4874m8e.js";import{re,ge,ye,H}from"./chunk-8wc8qdx8.js";import{M}from"./chunk-shadcb9z.js";var P=new Set(["openai","openai-codex","opencode"]),O=16,E="https://chatgpt.com/settings/usage";function I(e,s){return e.provider==="openai"&&e.baseUrl==="https://api.openai.com/v1"&&s!==void 0&&!s.startsWith("sk-")}function T(e,s){if(!e)return!1;let r=s.toLowerCase();for(let[t,i]of Object.entries(e))if(t.toLowerCase()===r&&i!==null&&i.trim().length>0)return!0;return!1}function v(e,s,r){if(s)return s;if(T(r,"authorization")||T(r,"cf-aig-authorization"))return"unused";throw Error(`No API key for provider: ${e}`)}function w(e){return e.provider==="openrouter"||e.baseUrl.includes("openrouter.ai")?"openrouter":"openai"}function R(e,s){if(e)return e;if(_("PI_CACHE_RETENTION",s)==="long")return"long";return"short"}function m(e){return{supportsDeveloperRole:e.compat?.supportsDeveloperRole??!0,supportsMidConvoSystemMessages:e.compat?.supportsMidConvoSystemMessages??!1,sessionAffinityFormat:e.compat?.sessionAffinityFormat??w(e),supportsLongCacheRetention:e.compat?.supportsLongCacheRetention??!0,supportsStrictMode:e.compat?.supportsStrictMode??!1,supportsOpenAIGrammarTools:e.compat?.supportsOpenAIGrammarTools??!1,supportsAdditionalTools:e.compat?.supportsAdditionalTools??!1,supportsToolSearch:e.compat?.supportsToolSearch??!1,supportsExplicitPromptCacheMode:e.compat?.supportsExplicitPromptCacheMode??!1,supportsMaxOutputTokens:e.compat?.supportsMaxOutputTokens??!0}}function x(e,s){return s==="long"&&e.supportsLongCacheRetention&&!e.supportsExplicitPromptCacheMode?"24h":void 0}function b(e,s){if(!e.supportsExplicitPromptCacheMode)return;if(s==="none")return{mode:"explicit"};if(s==="long"&&e.supportsLongCacheRetention)return{ttl:"30m"};return}var k=(e,s,r)=>{let t=new M,i=re(s,m(e).supportsMidConvoSystemMessages);return(async()=>{let o={role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{let c=v(e.provider,r?.apiKey,r?.headers),p=R(r?.cacheRetention,r?.env)==="none"?void 0:r?.sessionId,n=m(e),u=Ee(ge(i.messages),n.supportsOpenAIGrammarTools),d=L(e,i,c,r?.headers,r?.fetch,p),l=G(e,i,r,n,u),g=await r?.onPayload?.(l,e);if(g!==void 0)l=g;let y={...r?.signal?{signal:r.signal}:{},...r?.timeoutMs!==void 0?{timeout:r.timeoutMs}:{},maxRetries:0},{data:S,response:h}=await ie(()=>d.responses.create(l,y).withResponse(),{maxRetries:r?.maxRetries,maxRetryDelayMs:r?.maxRetryDelayMs,signal:r?.signal});if(await r?.onResponse?.({status:h.status,headers:z(h.headers)},e),t.push({type:"start",partial:o}),await lt(S,o,t,e,{onProviderStreamEvent:r?.onProviderStreamEvent,serviceTier:r?.serviceTier,grammarToolInputProperties:u,applyServiceTierPricing:(C,A)=>D(C,A,e)}),r?.signal?.aborted)throw Error("Request was aborted");if(o.stopReason==="pending")throw Error("OpenAI Responses stream ended without a stop reason");if(o.stopReason==="aborted"||o.stopReason==="error")throw Error(o.errorMessage||"An unknown error occurred");t.push({type:"done",reason:o.stopReason,message:o}),t.end()}catch(c){for(let p of o.content)delete p.index,delete p.partialJson,delete p.customInput;o.stopReason=r?.signal?.aborted?"aborted":"error";let a=j(q(c),`${e.provider==="openai"?"OpenAI":e.provider} API error`);o.errorMessage=a.includes("subscription_sharing_usage_limit_exceeded")?`${a}
|
|
3
3
|
Check your ChatGPT usage: ${E}`:a,t.push({type:"error",reason:o.stopReason,error:o}),t.end()}})(),t},ae=(e,s,r)=>{v(e.provider,r?.apiKey,r?.headers);let t={...V(e,s,r,r?.apiKey),toolChoice:r?.toolChoice},i=r?.reasoning?H(e,r.reasoning):void 0;return k(e,s,{...t,reasoningEffort:i==="off"?void 0:i})};function L(e,s,r,t,i,o){let c=m(e),a={"User-Agent":ee(),...e.headers};if(e.provider==="github-copilot"){let p=At(s.messages),n=Et({messages:s.messages,hasImages:p});Object.assign(a,n)}if(o)if(c.sessionAffinityFormat==="openrouter")a["x-session-id"]=o;else{if(c.sessionAffinityFormat==="openai")a.session_id=o;a["x-client-request-id"]=o}if(t)Object.assign(a,t);return new f({apiKey:r,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:i,defaultHeaders:a})}function G(e,s,r,t=m(e),i=Ee(ge(s.messages),t.supportsOpenAIGrammarTools)){let o=ye(s.messages,t.supportsAdditionalTools||t.supportsToolSearch),c=at(e,s,P,{grammarToolInputProperties:i,supportsMidConvoSystemMessages:t.supportsMidConvoSystemMessages,supportsAdditionalTools:t.supportsAdditionalTools,supportsToolSearch:t.supportsToolSearch,toolOptions:{supportsStrictMode:t.supportsStrictMode,supportsOpenAIGrammarTools:t.supportsOpenAIGrammarTools}}),a=R(r?.cacheRetention,r?.env),p=I(e,r?.apiKey),n={model:e.id,input:c,stream:!0,prompt_cache_key:a==="none"?void 0:Ge(r?.sessionId),prompt_cache_retention:p?void 0:x(t,a),prompt_cache_options:p?void 0:b(t,a),store:!1};if(r?.maxTokens&&t.supportsMaxOutputTokens&&!p)n.max_output_tokens=Math.max(r.maxTokens,O);if(r?.temperature!==void 0&&!p)n.temperature=r?.temperature;if(r?.serviceTier!==void 0)n.service_tier=r.serviceTier;if(o.requestTools.length>0)n.tools=Je(o.requestTools,{supportsStrictMode:t.supportsStrictMode,supportsOpenAIGrammarTools:t.supportsOpenAIGrammarTools});if(r?.toolChoice!==void 0)n.tool_choice=r.toolChoice;let u=r?.reasoningEffort??(r?.reasoningSummary?"medium":void 0);if(e.reasoning){if(u){let l=r?.reasoningEffort?e.thinkingLevelMap?.[r.reasoningEffort]??r.reasoningEffort:u;n.reasoning={effort:l,summary:r?.reasoningSummary||"auto"},n.include=["reasoning.encrypted_content"]}else if(e.provider!=="github-copilot"&&e.thinkingLevelMap?.off!==null)n.reasoning={effort:e.thinkingLevelMap?.off??"none"};if(e.provider==="xai")n.include=["reasoning.encrypted_content"]}let d=ct(e,u??"off",r?.samplingParams);if(d)Object.assign(n,d);return n}function U(e,s){switch(s){case"flex":return 0.5;case"priority":case"fast":return e.id==="gpt-5.5"?2.5:2;default:return 1}}function D(e,s,r){let t=U(r,s);if(t===1)return;e.cost.input*=t,e.cost.output*=t,e.cost.cacheRead*=t,e.cost.cacheWrite*=t,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite}export{k as stream,ae as streamSimple};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{F}from"./chunk-m8vkwdgr.js";import{
|
|
2
|
+
import{F}from"./chunk-m8vkwdgr.js";import{wr}from"./chunk-2hbfk5xd.js";import{Ze}from"./chunk-g2t6t8fk.js";import{ee}from"./chunk-tvm4zmgj.js";import{me,ce,V,he}from"./chunk-whvj83b7.js";import{g}from"./chunk-n6e43rvk.js";import{z}from"./chunk-x4874m8e.js";import{N,Me,ne,re,Q,H}from"./chunk-8wc8qdx8.js";import{M}from"./chunk-shadcb9z.js";var S=9,U=4000,D=(t,e,n)=>{let r=new M,o=re(e,t.compat?.supportsMidConvoSystemMessages);return(async()=>{let s=B(t);try{let l=n?.apiKey;if(!l)throw Error(`No API key for provider: ${t.provider}`);let f=J(),u=he(o.messages,t,(d)=>f(d)),a=se(t,o,u,n),i=await n?.onPayload?.(a,t);if(i!==void 0)a=i;let c=await Z(t,a,l,n);if(r.push({type:"start",partial:s}),await ie(t,s,r,c,n?.onProviderStreamEvent),n?.signal?.aborted)throw Error("Request was aborted");if(s.stopReason==="pending")throw Error("Mistral stream ended without a finish reason");if(s.stopReason==="aborted"||s.stopReason==="error")throw Error(s.errorMessage||"An unknown error occurred");r.push({type:"done",reason:s.stopReason,message:s}),r.end()}catch(l){for(let f of s.content)delete f.partialArgs;s.stopReason=n?.signal?.aborted?"aborted":"error",s.errorMessage=K(l),r.push({type:"error",reason:s.stopReason,error:s}),r.end()}})(),r},Ee=(t,e,n)=>{let r=n?.apiKey;if(!r)throw Error(`No API key for provider: ${t.provider}`);let o={...V(t,e,n,r),toolChoice:n?.toolChoice},s=n?.reasoning?H(t,n.reasoning):void 0,l=s==="off"?void 0:s,f=t.reasoning?t.thinkingLevelMap:void 0,u=f?l?f[l]??"high":f.off??void 0:void 0;return D(t,e,{...o,promptMode:t.reasoning&&!f&&l?"reasoning":void 0,reasoningEffort:u})};function B(t){return{role:"assistant",content:[],api:t.api,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()}}function J(){let t=new Map,e=new Map;return(n)=>{let r=t.get(n);if(r)return r;let o=0;while(!0){let s=P(n,o),l=e.get(s);if(!l||l===n)return t.set(n,s),e.set(s,n),s;o++}}}function P(t,e){let n=t.replace(/[^a-zA-Z0-9]/g,"");if(e===0&&n.length===S)return n;let r=n||t,o=e===0?r:`${r}:${e}`;return Ze(o).replace(/[^a-zA-Z0-9]/g,"").slice(0,S)}function K(t){if(t instanceof Error){let e=t,n=typeof e.statusCode==="number"?e.statusCode:void 0,r=typeof e.body==="string"?e.body.trim():void 0;if(n!==void 0&&r)return`Mistral API error (${n}): ${W(r,U)}`;if(n!==void 0)return`Mistral API error (${n}): ${t.message}`;return t.message}return q(t)}function W(t,e){if(t.length<=e)return t;return`${t.slice(0,e)}... [truncated ${t.length-e} chars]`}function q(t){try{let e=JSON.stringify(t);return e===void 0?String(t):e}catch{return String(t)}}async function Z(t,e,n,r){let o=new URL(t.baseUrl);o.pathname=`${o.pathname.replace(/\/+$/u,"")}/`;let s=new URL("v1/chat/completions",o),l=G(t,n,r),f=r?.timeoutMs??60000,u=AbortSignal.timeout(f),a=wr([r?.signal,u]),i;try{i=await(r?.fetch??globalThis.fetch)(s,{method:"POST",headers:l,body:JSON.stringify(X(e)),signal:a.signal})}catch(c){if(u.aborted&&!r?.signal?.aborted)throw Error(`Mistral response headers timed out after ${f}ms`);throw c}finally{a.cleanup()}if(await r?.onResponse?.({status:i.status,headers:z(i.headers)},t),!i.ok){let c=await i.text();throw new O(i.status,c,i.statusText)}if(!i.body)throw Error("Mistral response has no body");return oe(i.body,r?.signal)}class O extends Error{statusCode;body;constructor(t,e,n){super(n||`Request failed with status ${t}`);this.name="MistralHttpError",this.statusCode=t,this.body=e}}function G(t,e,n){let r=new Headers({"User-Agent":ee(),accept:"text/event-stream",authorization:`Bearer ${e}`,"content-type":"application/json"});A(r,t.headers),A(r,n?.headers);let o=I(t.headers,"x-affinity")||I(n?.headers,"x-affinity");if(L(n)&&!o)r.set("x-affinity",n.sessionId);return r}function A(t,e){if(!e)return;for(let[n,r]of Object.entries(e))if(r===null)t.delete(n);else t.set(n,r)}function I(t,e){return!!t&&Object.keys(t).some((n)=>n.toLowerCase()===e)}function X(t){let e={...t};for(let[r,o]of[["topP","top_p"],["maxTokens","max_tokens"],["randomSeed","random_seed"],["responseFormat","response_format"],["toolChoice","tool_choice"],["presencePenalty","presence_penalty"],["frequencyPenalty","frequency_penalty"],["parallelToolCalls","parallel_tool_calls"],["reasoningEffort","reasoning_effort"],["promptMode","prompt_mode"],["promptCacheKey","prompt_cache_key"],["safePrompt","safe_prompt"]])k(e,r,o);e.messages=t.messages.map((r)=>Y(r));let n=e.response_format;if(w(n)){let r={...n};k(r,"jsonSchema","json_schema");let o=r.json_schema;if(w(o)){let s={...o};k(s,"schemaDefinition","schema"),r.json_schema=s}e.response_format=r}return e}function Y(t){let e={...t};if(k(e,"toolCalls","tool_calls"),k(e,"toolCallId","tool_call_id"),Array.isArray(t.content))e.content=t.content.map((n)=>te(n));return e}function te(t){let e={...t};for(let[n,r]of[["imageUrl","image_url"],["documentUrl","document_url"],["documentName","document_name"],["fileId","file_id"],["referenceIds","reference_ids"],["inputAudio","input_audio"]])k(e,n,r);return e}function k(t,e,n){if(!(e in t))return;t[n]=t[e],delete t[e]}function w(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}var b=Symbol("mistral-stream-done");async function*oe(t,e){let n=t.getReader(),r=new TextDecoder,o="",s=()=>{n.cancel().catch(()=>{})};e?.addEventListener("abort",s,{once:!0});try{while(!0){if(e?.aborted)throw e.reason;let{done:l,value:f}=await n.read();if(e?.aborted)throw e.reason;o+=l?r.decode():r.decode(f,{stream:!0});let u=E(o);while(u){let a=v(o.slice(0,u.index));if(o=o.slice(u.index+u.length),a===b)return;if(a)yield a;u=E(o)}if(l)break}if(o.trim()){let l=v(o);if(l!==b&&l)yield l}}finally{e?.removeEventListener("abort",s);try{await n.cancel()}catch{}try{n.releaseLock()}catch{}}}function E(t){let e=/\r\n\r\n|\r\n\r|\r\n\n|\r\r\n|\n\r\n|\r\r|\n\r|\n\n/u.exec(t);return e?.index===void 0?void 0:{index:e.index,length:e[0].length}}function v(t){let e=t.split(/\r\n|\r|\n/u).filter((r)=>r.startsWith("data:")).map((r)=>r.slice(5).trimStart()).join(`
|
|
3
3
|
`).trim();if(!e)return;if(e==="[DONE]")return b;let n=JSON.parse(e);if(!w(n)||!Array.isArray(n.choices))throw Error("Invalid Mistral streaming event");return{data:n}}function se(t,e,n,r){let o={model:t.id,stream:!0,messages:fe(n,t.input.includes("image"))},s=ne(e.messages);if(s.length>0)o.tools=le(s);if(r?.temperature!==void 0)o.temperature=r.temperature;if(r?.maxTokens!==void 0)o.maxTokens=r.maxTokens;if(r?.toolChoice)o.toolChoice=ue(r.toolChoice);if(r?.promptMode)o.promptMode=r.promptMode;if(r?.reasoningEffort)o.reasoningEffort=r.reasoningEffort;if(L(r))o.promptCacheKey=r.sessionId;return o}function L(t){return t?.cacheRetention!=="none"&&!!t?.sessionId}function ae(t,e){let n=t,r=n.promptTokensDetails?.cachedTokens??n.prompt_tokens_details?.cached_tokens??n.promptTokenDetails?.cachedTokens??n.prompt_token_details?.cached_tokens??n.numCachedTokens??n.num_cached_tokens??0,o=typeof r==="number"&&Number.isFinite(r)?r:0;return Math.min(e,Math.max(0,o))}async function ie(t,e,n,r,o){let s=null,l=e.content,f=()=>l.length-1,u=new Map,a=(i)=>{if(!i)return;if(i.type==="text"){n.push({type:"text_end",contentIndex:f(),content:i.text,partial:e});return}if(i.type==="thinking")n.push({type:"thinking_end",contentIndex:f(),content:i.thinking,partial:e})};for await(let i of r){let c=i.data;if(await o?.(c,t),e.responseId||=c.id,c.usage){let p=c.usage.prompt_tokens||0,h=ae(c.usage,p);e.usage.input=Math.max(0,p-h),e.usage.output=c.usage.completion_tokens||0,e.usage.cacheRead=h,e.usage.cacheWrite=0,e.usage.totalTokens=c.usage.total_tokens||e.usage.input+e.usage.output+e.usage.cacheRead+e.usage.cacheWrite,Q(t,e.usage)}let d=c.choices[0];if(!d)continue;if(d.finish_reason){e.rawStopReason=d.finish_reason;let p=pe(d.finish_reason);if(e.stopReason=p.stopReason,p.errorMessage)e.errorMessage=p.errorMessage}let x=d.delta;if(x.content!==null&&x.content!==void 0){let p=typeof x.content==="string"?[x.content]:x.content;for(let h of p){if(typeof h==="string"){let m=g(h);if(!m)continue;if(!s||s.type!=="text")a(s),s={type:"text",text:""},e.content.push(s),n.push({type:"text_start",contentIndex:f(),partial:e});s.text+=m,n.push({type:"text_delta",contentIndex:f(),delta:m,partial:e});continue}if(h.type==="thinking"){let m=(h.thinking??[]).map((y)=>y.text??"").filter((y)=>y.length>0).join(""),_=g(m);if(!_)continue;if(!s||s.type!=="thinking")a(s),s={type:"thinking",thinking:""},e.content.push(s),n.push({type:"thinking_start",contentIndex:f(),partial:e});s.thinking+=_,n.push({type:"thinking_delta",contentIndex:f(),delta:_,partial:e});continue}if(h.type==="text"){let m=g(h.text??"");if(!m)continue;if(!s||s.type!=="text")a(s),s={type:"text",text:""},e.content.push(s),n.push({type:"text_start",contentIndex:f(),partial:e});s.text+=m,n.push({type:"text_delta",contentIndex:f(),delta:m,partial:e})}}}let j=x.tool_calls||[];for(let p of j){if(s)a(s),s=null;let h=p.id&&p.id!=="null"?p.id:P(`toolcall:${p.index??0}`,0),m=p.index??h,_=u.get(m),y;if(_!==void 0){let R=e.content[_];if(R?.type==="toolCall")y=R}if(!y)y={type:"toolCall",id:h,name:p.function.name,arguments:{},partialArgs:""},e.content.push(y),u.set(m,e.content.length-1),n.push({type:"toolcall_start",contentIndex:e.content.length-1,partial:e});let C=typeof p.function.arguments==="string"?p.function.arguments:JSON.stringify(p.function.arguments||{});y.partialArgs=(y.partialArgs||"")+C,y.arguments=F(y.partialArgs),n.push({type:"toolcall_delta",contentIndex:u.get(m),delta:C,partial:e})}}a(s);for(let i of u.values()){let c=e.content[i];if(c.type!=="toolCall")continue;let d=c;d.arguments=F(d.partialArgs),delete d.partialArgs,n.push({type:"toolcall_end",contentIndex:i,toolCall:d,partial:e})}}function le(t){return t.map((e)=>{let n=ce(e,!0);return{type:"function",function:{name:e.name,description:e.description,parameters:T(me(e,n)),strict:n??!1}}})}function T(t){if(Array.isArray(t))return t.map((e)=>T(e));if(t&&typeof t==="object"){let e={};for(let[n,r]of Object.entries(t))e[n]=T(r);return e}return t}function fe(t,e){let n=[];for(let[r,o]of t.entries()){if(o.role==="system"){let a=r===0?N(o):Me(o);if(a.length>0)n.push({role:"system",content:g(a)});continue}if(o.role==="user"){if(typeof o.content==="string"){n.push({role:"user",content:g(o.content)});continue}let a=o.content.some((c)=>c.type==="image"),i=o.content.filter((c)=>c.type==="text"||e).map((c)=>{if(c.type==="text")return{type:"text",text:g(c.text)};return{type:"image_url",imageUrl:`data:${c.mimeType};base64,${c.data}`}});if(i.length>0){n.push({role:"user",content:i});continue}if(a&&!e)n.push({role:"user",content:"(image omitted: model does not support images)"});continue}if(o.role==="assistant"){let a=[],i=[];for(let d of o.content){if(d.type==="text"){if(d.text.trim().length>0)a.push({type:"text",text:g(d.text)});continue}if(d.type==="thinking"){if(d.thinking.trim().length>0)a.push({type:"thinking",thinking:[{type:"text",text:g(d.thinking)}]});continue}i.push({id:d.id,type:"function",function:{name:d.name,arguments:JSON.stringify(d.arguments||{})},index:0})}let c={role:"assistant",prefix:!1};if(a.length>0)c.content=a;if(i.length>0)c.toolCalls=i;if(a.length>0||i.length>0)n.push(c);continue}let s=[],l=o.content.filter((a)=>a.type==="text").map((a)=>a.type==="text"?g(a.text):"").join(`
|
|
4
4
|
`),f=o.content.some((a)=>a.type==="image"),u=de(l,f,e,o.isError);s.push({type:"text",text:u});for(let a of o.content){if(!e)continue;if(a.type!=="image")continue;s.push({type:"image_url",imageUrl:`data:${a.mimeType};base64,${a.data}`})}n.push({role:"tool",toolCallId:o.toolCallId,name:o.toolName,content:s})}return n}function de(t,e,n,r){let o=t.trim(),s=r?"[tool error] ":"";if(o.length>0)return`${s}${o}${e&&!n?`
|
|
5
5
|
[tool image omitted: model does not support images]`:""}`;if(e){if(n)return r?"[tool error] (see attached image)":"(see attached image)";return r?"[tool error] (image omitted: model does not support images)":"(image omitted: model does not support images)"}return r?"[tool error] (no tool output)":"(no tool output)"}function ue(t){if(!t)return;if(t==="auto"||t==="none"||t==="any"||t==="required")return t;return{type:"function",function:{name:t.function.name}}}function pe(t){if(t===null)return{stopReason:"stop"};switch(t){case"stop":return{stopReason:"stop"};case"length":case"model_length":return{stopReason:"length"};case"tool_calls":return{stopReason:"toolUse"};case"error":return{stopReason:"error",errorMessage:"Provider stopped with: error (server error)"};default:return{stopReason:"error",errorMessage:`Provider stopped with: ${t}`}}}export{D as stream,Ee as streamSimple};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{L}from"./chunk-jwdb0ccj.js";import{b}from"./chunk-981f9dw8.js";import{i}from"./chunk-0y7ne3d0.js";var u=i(b());var B=i(b());var p=i(L()),d=i(b());var P=i(L()),f=i(b()),S=(e,t,r)=>{let o={EcsContainer:async(s)=>{let{fromHttp:a}=await import("./chunk-cjc90f84.js"),{fromContainerMetadata:n}=await import("./chunk-y7nma9rk.js");return r?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer"),async()=>f.chain(a(s??{}),n(s))().then(m)},Ec2InstanceMetadata:async(s)=>{r?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata");let{fromInstanceMetadata:a}=await import("./chunk-y7nma9rk.js");return async()=>a(s)().then(m)},Environment:async(s)=>{r?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment");let{fromEnv:a}=await import("./chunk-
|
|
2
|
+
import{L}from"./chunk-jwdb0ccj.js";import{b}from"./chunk-981f9dw8.js";import{i}from"./chunk-0y7ne3d0.js";var u=i(b());var B=i(b());var p=i(L()),d=i(b());var P=i(L()),f=i(b()),S=(e,t,r)=>{let o={EcsContainer:async(s)=>{let{fromHttp:a}=await import("./chunk-cjc90f84.js"),{fromContainerMetadata:n}=await import("./chunk-y7nma9rk.js");return r?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer"),async()=>f.chain(a(s??{}),n(s))().then(m)},Ec2InstanceMetadata:async(s)=>{r?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata");let{fromInstanceMetadata:a}=await import("./chunk-y7nma9rk.js");return async()=>a(s)().then(m)},Environment:async(s)=>{r?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment");let{fromEnv:a}=await import("./chunk-vkpvcxjr.js");return async()=>a(s)().then(m)}};if(e in o)return o[e];else throw new f.CredentialsProviderError(`Unsupported credential source in profile ${t}. Got ${e}, expected EcsContainer or Ec2InstanceMetadata or Environment.`,{logger:r})},m=(e)=>P.setCredentialFeature(e,"CREDENTIALS_PROFILE_NAMED_PROVIDER","p");var I=(e,{profile:t="default",logger:r}={})=>Boolean(e)&&typeof e==="object"&&typeof e.role_arn==="string"&&["undefined","string"].indexOf(typeof e.role_session_name)>-1&&["undefined","string"].indexOf(typeof e.external_id)>-1&&["undefined","string"].indexOf(typeof e.mfa_serial)>-1&&(q(e,{profile:t,logger:r})||H(e,{profile:t,logger:r})),q=(e,{profile:t,logger:r})=>{let o=typeof e.source_profile==="string"&&typeof e.credential_source>"u";if(o)r?.debug?.(` ${t} isAssumeRoleWithSourceProfile source_profile=${e.source_profile}`);return o},H=(e,{profile:t,logger:r})=>{let o=typeof e.credential_source==="string"&&typeof e.source_profile>"u";if(o)r?.debug?.(` ${t} isCredentialSourceProfile credential_source=${e.credential_source}`);return o},R=async(e,t,r,o,s={},a)=>{r.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)");let n=t[e],{source_profile:c,region:K}=n;if(!r.roleAssumer){let{getDefaultRoleAssumer:l}=await import("./chunk-xfvvh1s5.js");r.roleAssumer=l({...r.clientConfig,credentialProviderLogger:r.logger,parentClientConfig:{...o,...r?.parentClientConfig,region:K??r?.parentClientConfig?.region??o?.region}},r.clientPlugins)}if(c&&c in s)throw new d.CredentialsProviderError(`Detected a cycle attempting to resolve credentials for profile ${d.getProfileName(r)}. Profiles visited: `+Object.keys(s).join(", "),{logger:r.logger});r.logger?.debug(`@aws-sdk/credential-provider-ini - finding credential resolver using ${c?`source_profile=[${c}]`:`profile=[${e}]`}`);let E=c?a(c,t,r,o,{...s,[c]:!0},v(t[c]??{})):(await S(n.credential_source,e,r.logger)(r))();if(v(n))return E.then((l)=>p.setCredentialFeature(l,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"));else{let l={RoleArn:n.role_arn,RoleSessionName:n.role_session_name||`aws-sdk-js-${Date.now()}`,ExternalId:n.external_id,DurationSeconds:parseInt(n.duration_seconds||"3600",10)},{mfa_serial:_}=n;if(_){if(!r.mfaCodeProvider)throw new d.CredentialsProviderError(`Profile ${e} requires multi-factor authentication, but no MFA code callback was provided.`,{logger:r.logger,tryNextLink:!1});l.SerialNumber=_,l.TokenCode=await r.mfaCodeProvider(_)}let G=await E;return r.roleAssumer(G,l).then((U)=>p.setCredentialFeature(U,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"))}},v=(e)=>!e.role_arn&&!!e.credential_source;var A=i(L()),O=(e)=>Boolean(e&&e.login_session),x=async(e,t,r)=>{let{fromLoginCredentials:o}=await import("./chunk-97rzj7f6.js"),s=await o({...t,profile:e})({callerClientConfig:r});return A.setCredentialFeature(s,"CREDENTIALS_PROFILE_LOGIN","AC")};var k=i(L()),F=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.credential_process==="string",h=async(e,t)=>{let{fromProcess:r}=await import("./chunk-vk1gxk1t.js"),o=await r({...e,profile:t})();return k.setCredentialFeature(o,"CREDENTIALS_PROFILE_PROCESS","v")};var C=i(L()),D=async(e,t,r={},o)=>{let{fromSSO:s}=await import("./chunk-ztsjgssj.js");return s({profile:e,logger:r.logger,parentClientConfig:r.parentClientConfig,clientConfig:r.clientConfig})({callerClientConfig:o}).then((a)=>{if(t.sso_session)return C.setCredentialFeature(a,"CREDENTIALS_PROFILE_SSO","r");else return C.setCredentialFeature(a,"CREDENTIALS_PROFILE_SSO_LEGACY","t")})},T=(e)=>e&&(typeof e.sso_start_url==="string"||typeof e.sso_account_id==="string"||typeof e.sso_session==="string"||typeof e.sso_region==="string"||typeof e.sso_role_name==="string");var W=i(L()),y=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.aws_access_key_id==="string"&&typeof e.aws_secret_access_key==="string"&&["undefined","string"].indexOf(typeof e.aws_session_token)>-1&&["undefined","string"].indexOf(typeof e.aws_account_id)>-1,g=async(e,t)=>{t?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials");let r={accessKeyId:e.aws_access_key_id,secretAccessKey:e.aws_secret_access_key,sessionToken:e.aws_session_token,...e.aws_credential_scope&&{credentialScope:e.aws_credential_scope},...e.aws_account_id&&{accountId:e.aws_account_id}};return W.setCredentialFeature(r,"CREDENTIALS_PROFILE","n")};var N=i(L()),j=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.web_identity_token_file==="string"&&typeof e.role_arn==="string"&&["undefined","string"].indexOf(typeof e.role_session_name)>-1,M=async(e,t,r)=>{let{fromTokenFile:o}=await import("./chunk-pbcy6zdt.js"),s=await o({webIdentityTokenFile:e.web_identity_token_file,roleArn:e.role_arn,roleSessionName:e.role_session_name,roleAssumerWithWebIdentity:t.roleAssumerWithWebIdentity,logger:t.logger,parentClientConfig:t.parentClientConfig})({callerClientConfig:r});return N.setCredentialFeature(s,"CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN","q")};var w=async(e,t,r,o,s={},a=!1)=>{let n=t[e];if(Object.keys(s).length>0&&y(n))return g(n,r);if(a||I(n,{profile:e,logger:r.logger}))return R(e,t,r,o,s,w);if(y(n))return g(n,r);if(j(n))return M(n,r,o);if(F(n))return h(r,e);if(T(n))return await D(e,n,r,o);if(O(n))return x(e,r,o);throw new B.CredentialsProviderError(`Could not resolve credentials using profile: [${e}] in configuration/credentials file(s).`,{logger:r.logger})};var V=(e={})=>async({callerClientConfig:t}={})=>{e.logger?.debug("@aws-sdk/credential-provider-ini - fromIni");let r=await u.parseKnownFiles(e);return w(u.getProfileName({profile:e.profile??t?.profile}),r,e,t)};export{V as fromIni};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{vr}from"./chunk-em187cy3.js";import{se}from"./chunk-akr0a8nc.js";var t={api:"typesafe-system-one",label:"System One API",url:(e)=>new URL("systemone",`${e.baseUrl.replace(/\/+$/u,"")}/`),payload:(e,r)=>({model:e.id,...r}),output:(e)=>{if(!se(e))throw Error("System One API returned an unexpected response");return e}},a=(e,r,s)=>vr(t,e,r,s);export{a as classify};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{f}from"./chunk-mvfsxdx6.js";import{F}from"./chunk-m8vkwdgr.js";import{_}from"./chunk-pxsrqrd0.js";import{At,Et}from"./chunk-r9aatvwm.js";import{Ge}from"./chunk-bpw6q7g0.js";import{Ze}from"./chunk-g2t6t8fk.js";import{ee}from"./chunk-tvm4zmgj.js";import{ie}from"./chunk-d48bfd2e.js";import{q,j}from"./chunk-y69ewdn2.js";import{me,
|
|
2
|
+
import{f}from"./chunk-mvfsxdx6.js";import{F}from"./chunk-m8vkwdgr.js";import{_}from"./chunk-pxsrqrd0.js";import{At,Et}from"./chunk-r9aatvwm.js";import{Ge}from"./chunk-bpw6q7g0.js";import{Ze}from"./chunk-g2t6t8fk.js";import{ee}from"./chunk-tvm4zmgj.js";import{ie}from"./chunk-d48bfd2e.js";import{q,j}from"./chunk-y69ewdn2.js";import{me,Lr,Or,ce,Jt,Ee,ct,V,Eo,_o,he}from"./chunk-whvj83b7.js";import{g}from"./chunk-n6e43rvk.js";import{z}from"./chunk-x4874m8e.js";import{N,Me,re,ge,ye,Q,H}from"./chunk-8wc8qdx8.js";import{M}from"./chunk-shadcb9z.js";function te(e,n){if(!e)return!1;let t=n.toLowerCase();for(let[s,u]of Object.entries(e))if(s.toLowerCase()===t&&u!==null&&u.trim().length>0)return!0;return!1}function ue(e,n,t){if(n)return n;if(te(t,"authorization")||te(t,"cf-aig-authorization"))return"unused";throw Error(`No API key for provider: ${e}`)}function xe(e){for(let n of e){if(n.role==="toolResult")return!0;if(n.role==="assistant"){if(n.content.some((t)=>t.type==="toolCall"))return!0}}return!1}function ne(e){return e.type==="text"}function _e(e){return e.type==="thinking"}function ve(e){return e.type==="toolCall"}function Ae(e){return e.type==="image"}function Ce(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Ie(e){return(e.id===void 0||e.id===null||typeof e.id==="string")&&(e.format===void 0||typeof e.format==="string")&&(e.index===void 0||typeof e.index==="number")}function J(e){if(!Ce(e)||!Ie(e))return!1;switch(e.type){case"reasoning.summary":return typeof e.summary==="string";case"reasoning.encrypted":return typeof e.data==="string";case"reasoning.text":return typeof e.text==="string"&&(e.signature===void 0||e.signature===null||typeof e.signature==="string");default:return!1}}function Se(e){if(!e)return;try{let n=JSON.parse(e);return Array.isArray(n)&&n.length>0&&n.every(J)?n:void 0}catch{return}}function we(e){if(!e)return;try{let n=JSON.parse(e);return J(n)&&n.type==="reasoning.encrypted"&&typeof n.id==="string"&&n.id.length>0&&n.data.length>0?n:void 0}catch{return}}function se(e,n){e.id??=n.id,e.format||=n.format,e.index??=n.index}function Fe(e,n){let t=e[e.length-1];if(n.type==="reasoning.text"&&t?.type==="reasoning.text"){t.text+=n.text,t.signature||=n.signature,se(t,n);return}if(n.type==="reasoning.summary"&&t?.type==="reasoning.summary"){t.summary+=n.summary,se(t,n);return}e.push({...n})}var Oe=["reasoning","reasoning_content","reasoning_text"];function be(e){return Oe.includes(e)}function fe(e,n){if(e)return e;if(_("PI_CACHE_RETENTION",n)==="long")return"long";return"short"}var Be=(e,n,t)=>{let s=new M,u=re(n,U(e).supportsMidConvoSystemMessages);return(async()=>{let r={role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()},R,h=(v)=>{if(R!==void 0)v.thinkingSignature=JSON.stringify(R)};try{let v=ue(e.provider,t?.apiKey,t?.headers),a=U(e),x=Ee(ge(u.messages),a.supportsOpenAIGrammarTools),d=fe(t?.cacheRetention,t?.env),m=d==="none"?void 0:t?.sessionId,o=Pe(e,u,v,t?.headers,t?.fetch,m,a),l=Le(e,u,t,a,d,x),y=await t?.onPayload?.(l,e);if(y!==void 0)l=y;let E={...t?.signal?{signal:t.signal}:{},...t?.timeoutMs!==void 0?{timeout:t.timeoutMs}:{},maxRetries:0},{data:S,response:D}=await ie(()=>o.chat.completions.create(l,E).withResponse(),{maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,signal:t?.signal});await t?.onResponse?.({status:D.status,headers:z(D.headers)},e),s.push({type:"start",partial:r});let B=null,b=null,I=!1,P=new Map,G=new Map,c=r.content,w=(i)=>c.indexOf(i),Z=(i)=>{let p=i.customInput?.property;if(p===void 0)return"";let A=i.arguments[p];return typeof A==="string"?A:""},X=(i,p,A)=>{let k=i.customInput;if(!k)return;let O=Or(k.jsonBuffer,k.property,p,A);return i.arguments={[k.property]:p},O},de=(i)=>{let p=w(i);if(p===-1)return;if(i.type==="text")s.push({type:"text_end",contentIndex:p,content:i.text,partial:r});else if(i.type==="thinking")h(i),s.push({type:"thinking_end",contentIndex:p,content:i.thinking,partial:r});else if(i.type==="toolCall"){if(i.customInput){let A=X(i,Z(i),!0);if(A!==void 0)s.push({type:"toolcall_delta",contentIndex:p,delta:A,partial:r})}else i.arguments=F(i.partialArgs);delete i.partialArgs,delete i.customInput,delete i.streamIndex,s.push({type:"toolcall_end",contentIndex:p,toolCall:i,partial:r})}},ke=()=>{if(!B)B={type:"text",text:""},c.push(B),s.push({type:"text_start",contentIndex:w(B),partial:r});return B},Y=(i)=>{if(!b)b={type:"thinking",thinking:"",thinkingSignature:i},c.push(b),s.push({type:"thinking_start",contentIndex:w(b),partial:r});return b},Te=(i)=>{let p=typeof i.index==="number"?i.index:void 0,A=i.function?.name??i.custom?.name??"",k=p!==void 0?P.get(p):void 0;if(!k&&i.id)k=G.get(i.id);if(!k){let O=i.custom&&!i.function?x.get(A)??"input":void 0,L=O!==void 0;if(k={type:"toolCall",id:i.id||"",name:A,arguments:L?{[O]:""}:{},partialArgs:L?void 0:"",customInput:L?{property:O,jsonBuffer:{input:"",started:!1,closed:!1}}:void 0,streamIndex:p},p!==void 0)P.set(p,k);if(i.id)G.set(i.id,k);c.push(k),s.push({type:"toolcall_start",contentIndex:w(k),partial:r})}if(p!==void 0&&k.streamIndex===void 0)k.streamIndex=p,P.set(p,k);if(i.id)G.set(i.id,k);if(!k.name&&A)k.name=A;if(i.custom&&!i.function&&!k.customInput){let O=x.get(k.name)??"input";k.arguments={[O]:""},k.customInput={property:O,jsonBuffer:{input:"",started:!1,closed:!1}},delete k.partialArgs}return k};for await(let i of S){if(await t?.onProviderStreamEvent?.(i,e),!i||typeof i!=="object")continue;if(r.responseId||=i.id,typeof i.model==="string"&&i.model.length>0&&i.model!==e.id)r.responseModel||=i.model;if(i.usage)r.usage=ae(i.usage,e);let p=Array.isArray(i.choices)?i.choices[0]:void 0;if(!p)continue;if(!i.usage&&p.usage)r.usage=ae(p.usage,e);if(p.finish_reason){r.rawStopReason=p.finish_reason;let A=Ve(p.finish_reason);if(r.stopReason=A.stopReason,A.errorMessage)r.errorMessage=A.errorMessage;I=!0}if(p.delta){if(p.delta.content!==null&&p.delta.content!==void 0&&p.delta.content.length>0){let T=ke();T.text+=p.delta.content,s.push({type:"text_delta",contentIndex:w(T),delta:p.delta.content,partial:r})}let A=["reasoning_content","reasoning","reasoning_text"],k=p.delta,O=null;for(let T of A){let C=k[T];if(typeof C==="string"&&C.length>0){O=T;break}}if(O){let T=k[O];if(typeof T==="string"&&T.length>0){let C=e.provider==="opencode-go"&&O==="reasoning"?"reasoning_content":O,K=Y(C);K.thinking+=T,s.push({type:"thinking_delta",contentIndex:w(K),delta:T,partial:r})}}if(p?.delta?.tool_calls)for(let T of p.delta.tool_calls){let C=Te(T);if(!C.id&&T.id)C.id=T.id,G.set(T.id,C);let K=T.function?.name??T.custom?.name;if(!C.name&&K)C.name=K;let W="";if(T.function?.arguments)W=T.function.arguments,C.partialArgs=(C.partialArgs??"")+T.function.arguments,C.arguments=F(C.partialArgs);else if(T.custom?.input){let Re=Z(C)+T.custom.input;W=X(C,Re,!1)??""}s.push({type:"toolcall_delta",contentIndex:w(C),delta:W,partial:r})}let L=p.delta.reasoning_details;if(Array.isArray(L))for(let T of L){if(!J(T))continue;Y(""),R??=[],Fe(R,T)}}}for(let i of c)de(i);if(t?.signal?.aborted)throw Error("Request was aborted");if(r.stopReason==="aborted")throw Error("Request was aborted");if(!I&&!a.supportsFinishReason)r.stopReason=r.content.some((i)=>i.type==="toolCall")?"toolUse":"stop";if(r.stopReason==="error")throw Error(r.errorMessage||"Provider returned an error stop reason");if(a.supportsFinishReason&&!I||r.stopReason==="pending")throw Error("Stream ended without finish_reason");s.push({type:"done",reason:r.stopReason,message:r}),s.end()}catch(v){for(let x of r.content){if(x.type==="thinking")h(x);delete x.index,delete x.partialArgs,delete x.customInput,delete x.streamIndex}r.stopReason=t?.signal?.aborted?"aborted":"error",r.errorMessage=j(q(v));let a=v?.error?.metadata?.raw;if(a&&!r.errorMessage.includes(String(a)))r.errorMessage+=`
|
|
3
3
|
${a}`;s.push({type:"error",reason:r.stopReason,error:r}),s.end()}})(),s},yt=(e,n,t)=>{ue(e.provider,t?.apiKey,t?.headers);let s={...V(e,n,t,t?.apiKey),toolChoice:t?.toolChoice},u=t?.reasoning?H(e,t.reasoning):void 0;return Be(e,n,{...s,reasoningEffort:u==="off"?void 0:u,thinkingBudgets:t?.thinkingBudgets})};function Pe(e,n,t,s,u,r,R=U(e)){let h={"User-Agent":ee(),...e.headers};if(e.provider==="github-copilot"){let v=At(n.messages),a=Et({messages:n.messages,hasImages:v});Object.assign(h,a)}if(r&&R.sendSessionAffinityHeaders)if(R.sessionAffinityFormat==="openrouter")h["x-session-id"]=r;else{if(R.sessionAffinityFormat==="openai")h.session_id=r;h["x-client-request-id"]=r,h["x-session-affinity"]=r}if(s)Object.assign(h,s);return new f({apiKey:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:u,defaultHeaders:h})}function Le(e,n,t,s=U(e),u=fe(t?.cacheRetention,t?.env),r=Ee(ge(n.messages),s.supportsOpenAIGrammarTools)){let R=ye(n.messages,s.supportsMidConvoSystemMessages===!0&&s.supportsMidConvoToolAdditions===!0),h=Je(e,n,s,{grammarToolInputProperties:r}),v=Ne(s,u),a={model:e.id,messages:h,stream:!0,prompt_cache_key:e.baseUrl.includes("api.openai.com")&&u!=="none"||u==="long"&&s.supportsLongCacheRetention?Ge(t?.sessionId):void 0,prompt_cache_retention:u==="long"&&s.supportsLongCacheRetention?"24h":void 0};if(s.supportsUsageInStreaming!==!1)a.stream_options={include_usage:!0};if(s.supportsStore)a.store=!1;if(t?.maxTokens)if(s.maxTokensField==="max_tokens")a.max_tokens=t.maxTokens;else a.max_completion_tokens=t.maxTokens;if(t?.temperature!==void 0)a.temperature=t.temperature;if(R.requestTools.length>0){if(a.tools=pe(R.requestTools,s),s.zaiToolStream)a.tool_stream=!0}else if(xe(n.messages))a.tools=[];if(v)je(h,a.tools,v);if(t?.toolChoice)a.tool_choice=t.toolChoice;if(s.vllmPriority!==void 0)a.priority=s.vllmPriority;let x=qe(s),d=De(e,t,a);if(s.thinkingFormat==="zai"&&e.reasoning){let o=a;if(o.thinking=t?.reasoningEffort?{type:"enabled",clear_thinking:!1}:{type:"disabled"},t?.reasoningEffort&&s.supportsReasoningEffort){let l=e.thinkingLevelMap?.[t.reasoningEffort],y=l===void 0?t.reasoningEffort:l;if(typeof y==="string")o.reasoning_effort=y}}else if(s.thinkingFormat==="qwen"&&e.reasoning){if(a.enable_thinking=!!t?.reasoningEffort,t?.reasoningEffort&&s.supportsReasoningEffort){let o=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort;if(typeof o==="string")a.reasoning_effort=o}}else if(s.thinkingFormat==="qwen-chat-template"&&e.reasoning)a.chat_template_kwargs={enable_thinking:!!t?.reasoningEffort,preserve_thinking:!0};else if(s.thinkingFormat==="chat-template"&&e.reasoning){let o=oe(e,t,s.chatTemplateKwargs,d);if(o)a.chat_template_kwargs=o}else if(s.thinkingFormat==="baseten"&&e.reasoning){let o=a,l=oe(e,t,s.chatTemplateArgs,d);if(l)o.chat_template_args=l;if(s.supportsReasoningEffort){let y=t?.reasoningEffort,E=y?e.thinkingLevelMap?.[y]:e.thinkingLevelMap?.off,S=E===void 0?y:E;if(typeof S==="string")o.reasoning_effort=S}}else if(s.thinkingFormat==="deepseek"&&e.reasoning){if(t?.reasoningEffort)a.thinking={type:"enabled"};else if(e.thinkingLevelMap?.off!==null)a.thinking={type:"disabled"};if(t?.reasoningEffort&&s.supportsReasoningEffort)a.reasoning_effort=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort}else if(s.thinkingFormat==="openrouter"&&e.reasoning){let o=a;if(t?.reasoningEffort)o.reasoning={effort:e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort};else if(e.thinkingLevelMap?.off!==null)o.reasoning={effort:e.thinkingLevelMap?.off??"none"}}else if(s.thinkingFormat==="ant-ling"&&e.reasoning&&t?.reasoningEffort){let o=e.thinkingLevelMap?.[t.reasoningEffort];if(typeof o==="string")a.reasoning={effort:o}}else if(s.thinkingFormat==="together"&&e.reasoning){let o=a;if(o.reasoning={enabled:!!t?.reasoningEffort},t?.reasoningEffort&&s.supportsReasoningEffort)o.reasoning_effort=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort}else if(s.thinkingFormat==="string-thinking"&&e.reasoning){let o=a;if(t?.reasoningEffort)o.thinking=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort;else if(e.thinkingLevelMap?.off!==null)o.thinking=e.thinkingLevelMap?.off??"none"}else if(t?.reasoningEffort&&e.reasoning&&s.supportsReasoningEffort)a.reasoning_effort=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort;else if(!t?.reasoningEffort&&e.reasoning&&s.supportsReasoningEffort){let o=e.thinkingLevelMap?.off;if(typeof o==="string")a.reasoning_effort=o}if(x&&d!==void 0)Object.assign(a,{[x]:d});if(e.compat?.openRouterRouting)a.provider=e.compat.openRouterRouting;if(e.compat?.vercelGatewayRouting){let o=e.compat.vercelGatewayRouting;if(o.only||o.order){let l={};if(o.only)l.only=o.only;if(o.order)l.order=o.order;a.providerOptions={gateway:l}}}let m=ct(e,t?.reasoningEffort??"off",t?.samplingParams);if(m)Object.assign(a,m);return a}function qe(e){if(e.thinkingTokenBudgetField)return e.thinkingTokenBudgetField;if(e.supportsThinkingTokenBudget)return"thinking_token_budget";return}function De(e,n,t){if(!n?.reasoningEffort||!e.reasoning)return;let s=t.max_tokens??t.max_completion_tokens??e.maxTokens,u=_o(Eo(n.reasoningEffort,n.thinkingBudgets),s);return u>0?u:void 0}function oe(e,n,t,s){let u={};for(let[r,R]of Object.entries(t)){let h=ze(e,n,R,s);if(h!==void 0)u[r]=h}return Object.keys(u).length>0?u:void 0}function ze(e,n,t,s){if(typeof t!=="object"||t===null)return t;let u=n?.reasoningEffort;if(!u&&t.omitWhenOff)return;if(t.$var==="thinking.enabled")return!!u;if(t.$var==="thinking.budget")return s;let r=u?e.thinkingLevelMap?.[u]:e.thinkingLevelMap?.off;return r===void 0?u:typeof r==="string"?r:void 0}function Ne(e,n){if(e.cacheControlFormat!=="anthropic"||n==="none")return;let t=n==="long"&&e.supportsLongCacheRetention?"1h":void 0;return{type:"ephemeral",...t?{ttl:t}:{}}}function je(e,n,t){$e(e,t),He(n,t),Ke(e,t)}function $e(e,n){for(let t of e)if(t.role==="system"||t.role==="developer"){Ue(t,n);return}}function Ke(e,n){for(let t=e.length-1;t>=0;t--){let s=e[t];if(s.role==="user"||s.role==="assistant"||s.role==="tool"){if(We(s,n))return}}}function He(e,n){if(!e||e.length===0)return;let t=e[e.length-1];t.cache_control=n}function Ue(e,n){return le(e,n)}function We(e,n){if(e.role==="user"||e.role==="assistant"||e.role==="tool")return le(e,n);return!1}function le(e,n){let t=e.content;if(typeof t==="string"){if(t.length===0)return!1;return e.content=[{type:"text",text:t,cache_control:n}],!0}if(!Array.isArray(t))return!1;for(let s=t.length-1;s>=0;s--){let u=t[s];if(u?.type==="text"){let r=u;return r.cache_control=n,!0}}return!1}function Je(e,n,t,s){let u=re(n,t.supportsMidConvoSystemMessages),r=[],R=(d)=>{if(d.includes("|")){let m=d.indexOf("|"),o=d.slice(0,m).replace(/[^a-zA-Z0-9_-]/g,"_"),l=d.slice(m+1).replace(/[^a-zA-Z0-9_-]/g,"_"),y=l.length>0?`${o}_${l}`:o;if(y.length<=40)return y;let E=Ze(d).slice(0,8);return`${o.slice(0,Math.max(1,40-E.length-1))}_${E}`}if(e.provider==="openai")return d.length>40?d.slice(0,40):d;return d},h=he(u.messages,e,(d)=>R(d)),v=ye(u.messages,t.supportsMidConvoSystemMessages===!0&&t.supportsMidConvoToolAdditions===!0),a=e.reasoning&&t.supportsDeveloperRole?"developer":"system",x=null;for(let d=0;d<h.length;d++){let m=h[d];if(t.requiresAssistantAfterToolResult&&x==="toolResult"&&m.role==="user")r.push({role:"assistant",content:"I have processed the tool results."});if(m.role==="system"){let o=d>0&&v.anchorsAdditions?m.toolsAdded??[]:[];if(o.length>0){let y={role:"system",tools:pe(o,t)};r.push(y)}let l=d===0?N(m):Me(m);if(l.length>0)r.push({role:a,content:g(l)})}else if(m.role==="user")if(typeof m.content==="string")r.push({role:"user",content:g(m.content)});else{let o=m.content.filter((l)=>l.type!=="text"||l.text.length>0).map((l)=>{if(l.type==="text")return{type:"text",text:g(l.text)};else return{type:"image_url",image_url:{url:`data:${l.mimeType};base64,${l.data}`}}});if(o.length===0)continue;r.push({role:"user",content:o})}else if(m.role==="assistant"){let o={role:"assistant",content:t.requiresAssistantAfterToolResult?"":null},l=m.content.filter(ne).filter((c)=>c.text.trim().length>0).map((c)=>({type:"text",text:g(c.text)})),y=l.map((c)=>c.text).join(""),E=m.content.filter(_e),S=m.content.filter(ve),D=E.map((c)=>Se(c.thinkingSignature)).find((c)=>c!==void 0),B=S.map((c)=>we(c.thoughtSignature)).filter((c)=>c!==void 0),b=D??(B.length>0?B:void 0),I=E.filter((c)=>c.thinking.trim().length>0);if(I.length>0)if(t.requiresThinkingAsText){let c=I.map((w)=>g(w.thinking)).join(`
|
|
4
4
|
|
|
5
5
|
`);o.content=[{type:"text",text:c},...l]}else{if(y.length>0)o.content=y;if(!b){let c=I[0].thinkingSignature;if(e.provider==="opencode-go"&&c==="reasoning")c="reasoning_content";if(c&&be(c))o[c]=I.map((w)=>w.thinking).join(`
|
|
6
|
-
`)}}else if(y.length>0)o.content=y;if(S.length>0)o.tool_calls=S.map((c)=>{let w=s?.grammarToolInputProperties?.get(c.name);if(w!==void 0)return{id:c.id,type:"custom",custom:{name:c.name,input:g(
|
|
6
|
+
`)}}else if(y.length>0)o.content=y;if(S.length>0)o.tool_calls=S.map((c)=>{let w=s?.grammarToolInputProperties?.get(c.name);if(w!==void 0)return{id:c.id,type:"custom",custom:{name:c.name,input:g(Lr(c.name,c.arguments,w))}};return{id:c.id,type:"function",function:{name:c.name,arguments:JSON.stringify(c.arguments)}}});if(b)o.reasoning_details=b;if(t.requiresReasoningContentOnAssistantMessages&&e.reasoning&&o.reasoning_content===void 0)o.reasoning_content="";let P=o.content;if(!(P!==null&&P!==void 0&&(typeof P==="string"?P.length>0:P.length>0))&&!o.tool_calls)continue;r.push(o)}else if(m.role==="toolResult"){let o=[],l=d;for(;l<h.length&&h[l].role==="toolResult";l++){let y=h[l],E=y.content.filter(ne).map((I)=>I.text).join(`
|
|
7
7
|
`),S=y.content.some((I)=>I.type==="image"),B=E.length>0?E:S?"(see attached image)":"(no tool output)",b={role:"tool",content:g(B),tool_call_id:y.toolCallId};if(t.requiresToolResultName&&y.toolName)b.name=y.toolName;if(r.push(b),S&&e.input.includes("image")){for(let I of y.content)if(Ae(I))o.push({type:"image_url",image_url:{url:`data:${I.mimeType};base64,${I.data}`}})}}if(d=l-1,o.length>0){if(t.requiresAssistantAfterToolResult)r.push({role:"assistant",content:"I have processed the tool results."});r.push({role:"user",content:[{type:"text",text:"Attached image(s) from tool result:"},...o]}),x="user"}else x="toolResult";continue}x=m.role}return r}function pe(e,n){return e.map((t)=>{let s=Jt(t,n.supportsOpenAIGrammarTools);if(s)return{type:"custom",custom:{name:t.name,description:t.description,format:{type:"grammar",grammar:{syntax:s.format,definition:s.definition}}}};let u=ce(t,n.supportsStrictMode!==!1);return{type:"function",function:{name:t.name,description:t.description,parameters:me(t,u),...n.supportsStrictMode!==!1&&{strict:u??!1}}}})}function ae(e,n){let t=e.prompt_tokens||0,s=e.prompt_tokens_details?.cached_tokens??e.prompt_cache_hit_tokens??e.cached_tokens??0,u=e.prompt_tokens_details?.cache_write_tokens||0,r=Math.max(0,t-s-u),R=e.completion_tokens||0,h={input:r,output:R,cacheRead:s,cacheWrite:u,reasoning:e.completion_tokens_details?.reasoning_tokens||0,totalTokens:r+R+s+u,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return Q(n,h),h}function Ve(e){if(e===null)return{stopReason:"stop"};switch(e){case"stop":case"end":return{stopReason:"stop"};case"length":return{stopReason:"length"};case"function_call":case"tool_calls":return{stopReason:"toolUse"};case"content_filter":return{stopReason:"error",errorMessage:"Provider finish_reason: content_filter"};case"network_error":return{stopReason:"error",errorMessage:"Provider finish_reason: network_error"};default:return{stopReason:"error",errorMessage:`Provider finish_reason: ${e}`}}}function Qe(e){let{provider:n,baseUrl:t}=e,s=n==="zai"||n==="zai-coding-cn"||t.includes("api.z.ai")||t.includes("open.bigmodel.cn"),u=n==="together"||t.includes("api.together.ai")||t.includes("api.together.xyz"),r=n==="moonshotai"||n==="moonshotai-cn"||t.includes("api.moonshot."),R=n==="openrouter"||t.includes("openrouter.ai"),h=n==="cloudflare-workers-ai"||t.includes("api.cloudflare.com"),v=n==="cloudflare-ai-gateway"||t.includes("gateway.ai.cloudflare.com"),a=n==="nvidia"||t.includes("integrate.api.nvidia.com"),x=n==="ant-ling"||t.includes("api.ant-ling.com"),d=n==="cerebras"||t.includes("cerebras.ai"),m=n==="deepseek"||t.toLowerCase().includes("deepseek.com"),o=a||d||n==="xai"||t.includes("api.x.ai")||u||t.includes("chutes.ai")||m||s||r||n==="opencode"||t.includes("opencode.ai")||h||v||x,l=t.includes("chutes.ai")||m||r||v||u||a||x||s,y=n==="xai"||t.includes("api.x.ai"),E=R&&(e.id.startsWith("anthropic/")||e.id.startsWith("openai/")),S=n==="openrouter"&&e.id.startsWith("anthropic/")?"anthropic":void 0;return{supportsStore:!o,supportsDeveloperRole:E||!o&&!R,supportsReasoningEffort:!y&&!s&&!r&&!u&&!v&&!a&&!x,supportsUsageInStreaming:!0,supportsFinishReason:!0,maxTokensField:l?"max_tokens":"max_completion_tokens",requiresToolResultName:!1,requiresAssistantAfterToolResult:!1,requiresThinkingAsText:!1,requiresReasoningContentOnAssistantMessages:m,thinkingFormat:m?"deepseek":s?"zai":u?"together":x?"ant-ling":R?"openrouter":"openai",openRouterRouting:{},vercelGatewayRouting:{},chatTemplateKwargs:{},chatTemplateArgs:{},zaiToolStream:!1,supportsThinkingTokenBudget:!1,thinkingTokenBudgetField:void 0,supportsStrictMode:!1,supportsOpenAIGrammarTools:!1,supportsMidConvoSystemMessages:!1,supportsMidConvoToolAdditions:!1,cacheControlFormat:S,sendSessionAffinityHeaders:R,sessionAffinityFormat:R?"openrouter":"openai",supportsLongCacheRetention:!(u||h||v||a||x)}}function U(e){let n=Qe(e);if(!e.compat)return n;return{supportsStore:e.compat.supportsStore??n.supportsStore,supportsDeveloperRole:e.compat.supportsDeveloperRole??n.supportsDeveloperRole,supportsReasoningEffort:e.compat.supportsReasoningEffort??n.supportsReasoningEffort,supportsUsageInStreaming:e.compat.supportsUsageInStreaming??n.supportsUsageInStreaming,supportsFinishReason:e.compat.supportsFinishReason??n.supportsFinishReason,maxTokensField:e.compat.maxTokensField??n.maxTokensField,requiresToolResultName:e.compat.requiresToolResultName??n.requiresToolResultName,requiresAssistantAfterToolResult:e.compat.requiresAssistantAfterToolResult??n.requiresAssistantAfterToolResult,requiresThinkingAsText:e.compat.requiresThinkingAsText??n.requiresThinkingAsText,requiresReasoningContentOnAssistantMessages:e.compat.requiresReasoningContentOnAssistantMessages??n.requiresReasoningContentOnAssistantMessages,thinkingFormat:e.compat.thinkingFormat??n.thinkingFormat,openRouterRouting:e.compat.openRouterRouting??{},vercelGatewayRouting:e.compat.vercelGatewayRouting??n.vercelGatewayRouting,chatTemplateKwargs:e.compat.chatTemplateKwargs??n.chatTemplateKwargs,chatTemplateArgs:e.compat.chatTemplateArgs??n.chatTemplateArgs,zaiToolStream:e.compat.zaiToolStream??n.zaiToolStream,supportsThinkingTokenBudget:e.compat.supportsThinkingTokenBudget??n.supportsThinkingTokenBudget,thinkingTokenBudgetField:e.compat.thinkingTokenBudgetField??n.thinkingTokenBudgetField,supportsStrictMode:e.compat.supportsStrictMode??n.supportsStrictMode,supportsOpenAIGrammarTools:e.compat.supportsOpenAIGrammarTools??n.supportsOpenAIGrammarTools,supportsMidConvoSystemMessages:e.compat.supportsMidConvoSystemMessages??n.supportsMidConvoSystemMessages,supportsMidConvoToolAdditions:e.compat.supportsMidConvoToolAdditions??n.supportsMidConvoToolAdditions,cacheControlFormat:e.compat.cacheControlFormat??n.cacheControlFormat,sendSessionAffinityHeaders:e.compat.sendSessionAffinityHeaders??n.sendSessionAffinityHeaders,sessionAffinityFormat:e.compat.sessionAffinityFormat??n.sessionAffinityFormat,supportsLongCacheRetention:e.compat.supportsLongCacheRetention??n.supportsLongCacheRetention,vllmPriority:e.compat.vllmPriority}}export{Je as convertMessages,Be as stream,yt as streamSimple};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{te}from"./chunk-
|
|
2
|
+
import{te}from"./chunk-8wc8qdx8.js";var m=function(e,r){if(typeof e==="string"&&/^\.\.?\//.test(e))return e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(s,c,t,o,i){return c?r?".jsx":".js":t&&(!o||!i)?s:t+o+"."+i.toLowerCase()+"js"});return e},p=(e)=>{let r=import.meta.url.endsWith(".js")?e.replace(/\.ts$/,".js"):e;return import(m(r))},n;function ai(e){n=e}var li=()=>te(async()=>n??await p("./bedrock-converse-stream.ts"));
|
|
3
3
|
export{ai,li};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{vr}from"./chunk-em187cy3.js";import{se}from"./chunk-akr0a8nc.js";var s="Cloudflare Workers AI";function n(r){if(Array.isArray(r)){let e=r.map((t)=>se(t)&&typeof t.message==="string"?t.message:void 0).filter((t)=>t!==void 0);if(e.length>0)return`${s} error: ${e.join("; ")}`}return`${s} request failed`}var o={api:"cloudflare-workers-ai-system-one",label:s,url:(r)=>new URL("run",`${r.baseUrl.replace(/\/+$/u,"")}/`),payload:(r,e)=>({model:r.id,input:e}),output:(r)=>{if(!se(r))throw Error(`${s} returned an unexpected response`);if(r.success===!1)throw Error(n(r.errors));let e=r.result;if(!se(e))throw Error(`${s} returned an unexpected response`);if("answers"in e)return e;if(e.state!=="Completed")throw Error(`${s} run did not complete (state: ${String(e.state)})`);if(!se(e.result))throw Error(`${s} returned an unexpected response`);return e.result}},i=(r,e,t)=>vr(o,r,e,t);export{i as classify};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{_}from"./chunk-pxsrqrd0.js";var a={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function p(e,r){let o=e.toLowerCase(),t=e.toUpperCase();return r?.[o]||r?.[t]||_(o)||_(t)||""}function f(e){if(e instanceof URL)return e;try{return new URL(e)}catch{return}}function u(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function l(e){let r=e.trim().toLowerCase();if(!r)return;if(r.startsWith("[")){let t=r.indexOf("]");if(t!==-1){let n=r.slice(1,t),c=r.slice(t+1);if(c.startsWith(":")){let s=Number.parseInt(c.slice(1),10);return{host:n,port:Number.isNaN(s)?0:s}}return{host:n,port:0}}}if(r.includes(":")&&r.split(":").length>2)return{host:r,port:0};let o=r.lastIndexOf(":");if(o!==-1&&o===r.indexOf(":")){let t=r.slice(0,o),n=Number.parseInt(r.slice(o+1),10);if(!Number.isNaN(n))return{host:t,port:n}}return{host:r,port:0}}function d(e,r,o){let t=p("no_proxy",o).toLowerCase();if(!t)return!0;if(t==="*")return!1;let n=u(e.toLowerCase());return t.split(/[,\s]/).every((c)=>{let s=l(c);if(!s)return!0;if(s.port&&s.port!==r)return!0;let i=u(s.host);if(i.startsWith("*."))i=i.slice(2);else if(i.startsWith(".")||i.startsWith("*"))i=i.slice(1);if(!i)return!0;if(n===i)return!1;if(n.endsWith(`.${i}`))return!1;return!0})}function h(e,r){let o=f(e);if(!o?.protocol||!o.host)return"";let t=o.protocol.split(":",1)[0],n=u(o.hostname||o.host.replace(/:\d*$/,"")),c=Number.parseInt(o.port,10)||a[t]||0;if(!d(n,c,r))return"";let s=p(`${t}_proxy`,r)||p("all_proxy",r);if(s&&!s.includes("://"))s=`${t}://${s}`;return s}var x="Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL.";function
|
|
3
|
-
export{
|
|
2
|
+
import{_}from"./chunk-pxsrqrd0.js";var a={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function p(e,r){let o=e.toLowerCase(),t=e.toUpperCase();return r?.[o]||r?.[t]||_(o)||_(t)||""}function f(e){if(e instanceof URL)return e;try{return new URL(e)}catch{return}}function u(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function l(e){let r=e.trim().toLowerCase();if(!r)return;if(r.startsWith("[")){let t=r.indexOf("]");if(t!==-1){let n=r.slice(1,t),c=r.slice(t+1);if(c.startsWith(":")){let s=Number.parseInt(c.slice(1),10);return{host:n,port:Number.isNaN(s)?0:s}}return{host:n,port:0}}}if(r.includes(":")&&r.split(":").length>2)return{host:r,port:0};let o=r.lastIndexOf(":");if(o!==-1&&o===r.indexOf(":")){let t=r.slice(0,o),n=Number.parseInt(r.slice(o+1),10);if(!Number.isNaN(n))return{host:t,port:n}}return{host:r,port:0}}function d(e,r,o){let t=p("no_proxy",o).toLowerCase();if(!t)return!0;if(t==="*")return!1;let n=u(e.toLowerCase());return t.split(/[,\s]/).every((c)=>{let s=l(c);if(!s)return!0;if(s.port&&s.port!==r)return!0;let i=u(s.host);if(i.startsWith("*."))i=i.slice(2);else if(i.startsWith(".")||i.startsWith("*"))i=i.slice(1);if(!i)return!0;if(n===i)return!1;if(n.endsWith(`.${i}`))return!1;return!0})}function h(e,r){let o=f(e);if(!o?.protocol||!o.host)return"";let t=o.protocol.split(":",1)[0],n=u(o.hostname||o.host.replace(/:\d*$/,"")),c=Number.parseInt(o.port,10)||a[t]||0;if(!d(n,c,r))return"";let s=p(`${t}_proxy`,r)||p("all_proxy",r);if(s&&!s.includes("://"))s=`${t}://${s}`;return s}var x="Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL.";function Mr(e,r){let o=h(e,r);if(!o)return;let t;try{t=new URL(o)}catch(n){throw Error(`Invalid proxy URL ${JSON.stringify(o)}: ${n instanceof Error?n.message:String(n)}`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw Error(`${x} Got ${t.protocol}`);return t}
|
|
3
|
+
export{Mr};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{N,H}from"./chunk-
|
|
3
|
-
export{me,
|
|
2
|
+
import{N,H}from"./chunk-8wc8qdx8.js";class p extends Error{}var L=["$ref","$defs","definitions","allOf","oneOf","patternProperties","dependentSchemas","dependencies","unevaluatedProperties","propertyNames","contains","prefixItems","not","if","then","else"];function y(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function D(e){if(!y(e))return!1;let n=typeof e.type==="string"?[e.type]:Array.isArray(e.type)?e.type:[];return n.includes("object")||n.includes("array")||e.properties!==void 0||e.items!==void 0}function M(e){if(!y(e))return!1;if(e.type==="null"||Array.isArray(e.type)&&e.type.includes("null"))return!0;if(e.const===null||Array.isArray(e.enum)&&e.enum.includes(null))return!0;return Array.isArray(e.anyOf)&&e.anyOf.some((n)=>M(n))}function w(e,n){if(!y(e))throw new p("boolean schemas are unsupported");for(let a of L)if(e[a]!==void 0)throw new p(`${a} schemas are unsupported`);if(n){for(let[a,l]of Object.entries(e))if(n(a,l))throw new p(`${a}: ${JSON.stringify(l)} is unsupported`)}if(e.anyOf!==void 0){if(!Array.isArray(e.anyOf)||e.anyOf.length===0)throw new p("anyOf must contain at least one schema");for(let a of e.anyOf){if(D(a))throw new p("object and array unions are unsupported");w(a,n)}}if(e.items!==void 0){if(Array.isArray(e.items))throw new p("tuple schemas are unsupported");w(e.items,n)}let t=e.type==="object";if(e.properties!==void 0&&!t)throw new p("properties require type object");if(!t)return;if(e.additionalProperties!==void 0&&e.additionalProperties!==!1)throw new p("schema-valued or true additionalProperties is unsupported");if(e.properties!==void 0&&!y(e.properties))throw new p("object properties must be a schema map");if(e.required!==void 0&&(!Array.isArray(e.required)||e.required.some((a)=>typeof a!=="string")))throw new p("object required must be a string array");let r=e.properties??{},i=Object.keys(r),o=new Set(Array.isArray(e.required)?e.required:[]);if([...o].some((a)=>!i.includes(a)))throw new p("required contains an unknown property");for(let[a,l]of Object.entries(r))if(w(l,n),!o.has(a)&&!M(l))r[a]={anyOf:[l,{type:"null"}]};e.required=i,e.additionalProperties=!1}function k(e,n){let t=structuredClone(e);if(!y(t))throw new p("root schema must have type object");if(w(t,n),t.type!=="object")throw new p("root schema must have type object");return t}function me(e,n){return n===!0?k(e.parameters):e.parameters}function Lr(e,n,t){let r=n[t];if(typeof r!=="string")throw Error(`Grammar tool call "${e}" requires argument "${t}" to be a string.`);return r}function Or(e,n,t,r){if(e.closed){if(r&&t===e.input)return;throw Error(`grammar tool input for property "${n}" changed after it was closed`)}if(!t.startsWith(e.input))throw Error(`grammar tool input for property "${n}" changed non-monotonically`);let i=t.slice(e.input.length);if(!r&&i.length===0)return;let o="";if(!e.started)o+=`{${JSON.stringify(n)}:"`,e.started=!0;if(o+=JSON.stringify(i).slice(1,-1),e.input=t,r)o+='"}',e.closed=!0;return o}function G(e){let n=e.parameters;if(n.type!=="object")throw Error("grammar constrained sampling requires an object parameter schema");if(!Array.isArray(n.required)||n.required.length!==1||typeof n.required[0]!=="string")throw Error("grammar constrained sampling requires exactly one required string property");let t=n.required[0];if(!n.properties?.[t])throw Error(`grammar constrained sampling requires a properties entry for ${t}`);if(n.properties[t]?.type!=="string")throw Error(`grammar constrained sampling property ${t} must have type string`);return t}function ce(e,n,t){let r=e.constrainedSampling;if(!r||r.type!=="json_schema")return;if(n)try{return k(e.parameters,t),!0}catch(i){if(!(i instanceof p))throw i;if(r.strict!=="require")return;throw Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but ${i.message}.`)}if(r.strict==="require")throw Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`);return}function Jt(e,n){let t=e.constrainedSampling;if(!t||t.type!=="grammar")return;if(!n)return;let r=t.variants.openai_lark,i=t.variants.openai_regex,o=typeof r==="string"&&r.trim().length>0,a=typeof i==="string"&&i.trim().length>0;if(!o&&!a)throw Error(`Tool "${e.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);try{return{format:o?"lark":"regex",definition:o?r:i,inputProperty:G(e)}}catch(l){let d=l instanceof Error?l.message:String(l);throw Error(`Tool "${e.name}" cannot use grammar constrained sampling: ${d}.`)}}function Ee(e,n){let t=new Map;for(let r of e??[]){let i=Jt(r,n);if(i)t.set(r.name,i.inputProperty)}return t}var O=3.5,b=4800;function _(e){return e.totalTokens||e.input+e.output+e.cacheRead+e.cacheWrite}function P(e){try{return JSON.stringify(e)??"undefined"}catch{return"[unserializable]"}}function W(e){if(typeof e==="string")return e.length;let n=0;for(let t of e)n+=t.type==="text"?t.text.length:b;return n}function v(e){return Math.ceil(e.length/O)}function C(e){return Math.ceil(W(e)/O)}function E(e){let n=0;if(e.role==="system")return v(N(e))+R(e.toolsAdded)+R(e.toolsRemoved);if(e.role==="user")return C(e.content);if(e.role==="toolResult")return C(e.content);for(let t of e.content)if(t.type==="text")n+=t.text.length;else if(t.type==="thinking")n+=t.thinking.length;else n+=t.name.length+P(t.arguments).length;return Math.ceil(n/O)}function B(e){let n=Number.NEGATIVE_INFINITY,t;for(let r=0;r<e.length;r++){let i=e[r];if(i.role==="assistant"){let o=i;if(o.timestamp>=n&&o.stopReason!=="aborted"&&o.stopReason!=="error"&&_(o.usage)>0)t={usage:o.usage,index:r}}n=Math.max(n,i.timestamp)}return t}function S(e){let n="messages"in e?e.messages:e,t=B(n);if(t){let i=_(t.usage),o=0;for(let a=t.index+1;a<n.length;a++)o+=E(n[a]);return{tokens:i+o,usageTokens:i,trailingTokens:o,lastUsageIndex:t.index}}let r=0;for(let i of n)r+=E(i);return{tokens:r,usageTokens:0,trailingTokens:r,lastUsageIndex:null}}function R(e){if(!e||e.length===0)return 0;return v(P(e))}var F=4096,q=1;function Zt(e,n,t){if(e.contextWindow<=0)return Math.max(q,t);let r=e.contextWindow-S(n).tokens-F;return Math.min(t,Math.max(q,r))}function ct(e,n,t){let r=H(e,n),i=e.samplingParamsByThinkingLevel?.[r];return e.samplingParams||i||t?{...e.samplingParams,...i,...t}:void 0}function V(e,n,t,r){let i=ct(e,t?.reasoning??"off",t?.samplingParams);return{temperature:t?.temperature,samplingParams:i,maxTokens:Zt(e,n,t?.maxTokens??e.maxTokens),signal:t?.signal,telemetryContext:t?.telemetryContext,apiKey:r||t?.apiKey,fetch:t?.fetch,transport:t?.transport,cacheRetention:t?.cacheRetention,sessionId:t?.sessionId,headers:t?.headers,onPayload:t?.onPayload,onResponse:t?.onResponse,onProviderStreamEvent:t?.onProviderStreamEvent,timeoutMs:t?.timeoutMs,websocketConnectTimeoutMs:t?.websocketConnectTimeoutMs,maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,metadata:t?.metadata,env:t?.env}}var z=1024,K={minimal:1024,low:2048,medium:8192,high:16384};function Ao(e){return e==="xhigh"||e==="max"?"high":e}function Eo(e,n){let t={...K,...n},r=Ao(e);return t[r]}function _o(e,n){return Math.min(e,Math.max(0,n-z))}function Nr(e,n,t,r){let i=Eo(t,r),o=e===void 0?n:Math.min(e+i,n);if(o<=i)i=_o(i,o);return{maxTokens:o,thinkingBudget:i}}function j(e,n){let t=[],r=!1;for(let i of e){if(i.type==="image"){if(!r)t.push({type:"text",text:n});r=!0;continue}t.push(i),r=i.text===n}return t}function Y(e,n){if(n.input.includes("image"))return e;return e.map((t)=>{if(t.role==="user"&&Array.isArray(t.content))return{...t,content:j(t.content,"(image omitted: model does not support images)")};if(t.role==="toolResult")return{...t,content:j(t.content,"(tool image omitted: model does not support images)")};return t})}function he(e,n,t){let r=new Map,i=e.map((s)=>s.content==null?{...s,content:[]}:s),a=Y(i,n).map((s)=>{if(s.role==="system"||s.role==="user")return s;if(s.role==="toolResult"){let u=r.get(s.toolCallId);if(u&&u!==s.toolCallId)return{...s,toolCallId:u};return s}if(s.role==="assistant"){let u=s,c=u.provider===n.provider&&u.api===n.api&&u.model===n.id,x=u.content.flatMap((f)=>{if(f.type==="thinking"){if(f.redacted)return c?f:[];if(c&&f.thinkingSignature)return f;if(!f.thinking||f.thinking.trim()==="")return[];if(c)return f;return{type:"text",text:f.thinking}}if(f.type==="text"){if(c)return f;return{type:"text",text:f.text}}if(f.type==="toolCall"){let m=f,g=m;if(!c&&m.thoughtSignature)g={...m},delete g.thoughtSignature;if(!c&&t){let I=t(m.id,n,u);if(I!==m.id)r.set(m.id,I),g={...g,id:I}}return g}return f});return{...u,content:x}}return s}),l=[],d=[],h=new Set,T=[],A=()=>{if(d.length>0){for(let s of d)if(!h.has(s.id))l.push({role:"toolResult",toolCallId:s.id,toolName:s.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});d=[],h=new Set}l.push(...T),T.length=0};for(let s=0;s<a.length;s++){let u=a[s];if(u.role==="assistant"){A();let c=u;if(c.stopReason==="error"||c.stopReason==="aborted")continue;let x=c.content.filter((f)=>f.type==="toolCall");if(x.length>0)d=x,h=new Set;l.push(u)}else if(u.role==="toolResult")h.add(u.toolCallId),l.push(u);else if(u.role==="system")if(d.length>0)T.push(u);else l.push(u);else if(u.role==="user")A(),l.push(u);else l.push(u)}return A(),l}
|
|
3
|
+
export{me,Lr,Or,ce,Jt,Ee,Zt,ct,V,Ao,Eo,_o,Nr,he};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{dr,kt,zt,jt,Vt,Kt,mr,hr,Rt,fr,gr,yr,br,Sr,xr}from"./chunk-9rmqgc3c.js";import{_}from"./chunk-pxsrqrd0.js";import{ee}from"./chunk-tvm4zmgj.js";import{q,j}from"./chunk-y69ewdn2.js";import{V}from"./chunk-whvj83b7.js";import{g}from"./chunk-n6e43rvk.js";import{fe}from"./chunk-x4874m8e.js";import{N,pe,ne,Le,Q,H}from"./chunk-8wc8qdx8.js";import{M}from"./chunk-shadcb9z.js";var b="v1",O="gcp-vertex-credentials",R=0,y=(e,o,t)=>{let i=new M,u=Le(o);return(async()=>{let n={role:"assistant",content:[],api:"google-vertex",provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(t?.fetch&&t.fetch!==globalThis.fetch)throw Error("Custom fetch is not supported by the Google Vertex adapter");let c=L(t),d=c?S(e,c,t?.headers):I(e,P(t),U(t),t?.headers,t?.env),p=D(e,u,t),k=await t?.onPayload?.(p,e);if(k!==void 0)p=k;let f=await xr(()=>d.models.generateContentStream(p),t);i.push({type:"start",partial:n});let r=null,m=n.content,l=()=>m.length-1;for await(let s of f){await t?.onProviderStreamEvent?.(s,e),n.responseId||=s.responseId;let C=s.candidates?.[0];if(C?.content?.parts)for(let a of C.content.parts){if(a.text!==void 0){let h=hr(a);if(!r||h&&r.type!=="thinking"||!h&&r.type!=="text"){if(r)if(r.type==="text")i.push({type:"text_end",contentIndex:m.length-1,content:r.text,partial:n});else i.push({type:"thinking_end",contentIndex:l(),content:r.thinking,partial:n});if(h)r={type:"thinking",thinking:"",thinkingSignature:void 0},n.content.push(r),i.push({type:"thinking_start",contentIndex:l(),partial:n});else r={type:"text",text:""},n.content.push(r),i.push({type:"text_start",contentIndex:l(),partial:n})}if(r.type==="thinking")r.thinking+=a.text,r.thinkingSignature=Rt(r.thinkingSignature,a.thoughtSignature),i.push({type:"thinking_delta",contentIndex:l(),delta:a.text,partial:n});else r.text+=a.text,r.textSignature=Rt(r.textSignature,a.thoughtSignature),i.push({type:"text_delta",contentIndex:l(),delta:a.text,partial:n})}if(a.functionCall){if(r){if(r.type==="text")i.push({type:"text_end",contentIndex:l(),content:r.text,partial:n});else i.push({type:"thinking_end",contentIndex:l(),content:r.thinking,partial:n});r=null}let h=a.functionCall.id,x={type:"toolCall",id:!h||n.content.some((T)=>T.type==="toolCall"&&T.id===h)?`${a.functionCall.name}_${Date.now()}_${++R}`:h,name:a.functionCall.name||"",arguments:a.functionCall.args??{},...a.thoughtSignature&&{thoughtSignature:a.thoughtSignature}};n.content.push(x),i.push({type:"toolcall_start",contentIndex:l(),partial:n}),i.push({type:"toolcall_delta",contentIndex:l(),delta:JSON.stringify(x.arguments),partial:n}),i.push({type:"toolcall_end",contentIndex:l(),toolCall:x,partial:n})}}if(C?.finishReason){if(n.rawStopReason=C.finishReason,n.stopReason=Sr(C.finishReason),n.content.some((a)=>a.type==="toolCall")&&n.stopReason==="stop")n.stopReason="toolUse"}if(s.usageMetadata)n.usage={input:(s.usageMetadata.promptTokenCount||0)-(s.usageMetadata.cachedContentTokenCount||0),output:(s.usageMetadata.candidatesTokenCount||0)+(s.usageMetadata.thoughtsTokenCount||0),cacheRead:s.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:s.usageMetadata.thoughtsTokenCount||0,totalTokens:s.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},Q(e,n.usage)}if(r)if(r.type==="text")i.push({type:"text_end",contentIndex:l(),content:r.text,partial:n});else i.push({type:"thinking_end",contentIndex:l(),content:r.thinking,partial:n});if(t?.signal?.aborted)throw Error("Request was aborted");if(n.stopReason==="pending")throw Error("Google Vertex stream ended without a finish reason");if(n.stopReason==="aborted"||n.stopReason==="error"){let s=n.rawStopReason?`Provider stopped with: ${n.rawStopReason}`:"An unknown error occurred";throw Error(s)}i.push({type:"done",reason:n.stopReason,message:n}),i.end()}catch(c){for(let d of n.content)if("index"in d)delete d.index;n.stopReason=t?.signal?.aborted?"aborted":"error",n.errorMessage=j(q(c)),i.push({type:"error",reason:n.stopReason,error:n}),i.end()}})(),i},ue=(e,o,t)=>{let i={...V(e,o,t,void 0),toolChoice:t?.toolChoice};if(!t?.reasoning)return y(e,o,{...i,thinking:{enabled:!1}});let u=H(e,t.reasoning);if(u==="off")return y(e,o,{...i,thinking:{enabled:!1}});let n=zt(e,u);if(jt(e))return y(e,o,{...i,thinking:{enabled:!0,level:Vt(n)}});return y(e,o,{...i,thinking:{enabled:!0,budgetTokens:K(e,n,t.thinkingBudgets)}})};function I(e,o,t,i,u){let n=G(u);return new kt({vertexai:!0,project:o,location:t,apiVersion:b,...n?{googleAuthOptions:n}:{},httpOptions:v(e,i)})}function S(e,o,t){return new kt({vertexai:!0,apiKey:o,apiVersion:b,httpOptions:v(e,t)})}function v(e,o){let t={},i=w(e.baseUrl);if(i){if(t.baseUrl=i,t.baseUrlResourceScope=dr.COLLECTION,E(i))t.apiVersion=""}let u=fe({"User-Agent":ee(),...e.headers,...o});if(u)t.headers=u;return Object.keys(t).length>0?t:void 0}function w(e){let o=e.trim();if(!o||o.includes("{location}"))return;return o}function E(e){try{return new URL(e).pathname.split("/").some((t)=>/^v\d+(?:beta\d*)?$/.test(t))}catch{return/(?:^|\/)v\d+(?:beta\d*)?(?:\/|$)/.test(e)}}function G(e){let o=_("GOOGLE_APPLICATION_CREDENTIALS",e);return o?{keyFilename:o}:void 0}function L(e){let o=e?.apiKey?.trim();if(!o||o===O||A(o))return;return o}function A(e){return/^<[^>]+>$/.test(e)}function P(e){let o=e?.project||_("GOOGLE_CLOUD_PROJECT",e?.env)||_("GCLOUD_PROJECT",e?.env);if(!o)throw Error("Vertex AI requires a project ID. Set GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT or pass project in options.");return o}function U(e){let o=e?.location||_("GOOGLE_CLOUD_LOCATION",e?.env);if(!o)throw Error("Vertex AI requires a location. Set GOOGLE_CLOUD_LOCATION or pass location in options.");return o}function D(e,o,t={}){let i=fr(e,o),u=pe(o.messages),n=ne(o.messages),c={};if(t.temperature!==void 0)c.temperature=t.temperature;if(t.maxTokens!==void 0)c.maxOutputTokens=t.maxTokens;let d=yr(e.id),p=n.length>0?br(n,t.toolChoice,d):void 0,k=u?N(u):"",f={...Object.keys(c).length>0&&c,...k&&{systemInstruction:g(k)},...n.length>0&&{tools:gr(n,!1,d)},...p!==void 0&&{toolConfig:{functionCallingConfig:{mode:p}}}};if(t.thinking?.enabled&&e.reasoning){let m={includeThoughts:!0};if(t.thinking.level!==void 0)m.thinkingLevel=Kt(t.thinking.level);else if(t.thinking.budgetTokens!==void 0)m.thinkingBudget=t.thinking.budgetTokens;f.thinkingConfig=m}else if(e.reasoning&&t.thinking&&!t.thinking.enabled)f.thinkingConfig=mr(e);if(t.signal){if(t.signal.aborted)throw Error("Request aborted");f.abortSignal=t.signal}return{model:e.id,contents:i,config:f}}function K(e,o,t){if(t?.[o]!==void 0)return t[o];if(e.id.includes("2.5-pro"))return{minimal:128,low:2048,medium:8192,high:32768}[o];if(e.id.includes("2.5-flash"))return{minimal:128,low:2048,medium:8192,high:24576}[o];return-1}export{y as stream,ue as streamSimple};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
function n(t,r,o,i,s){if(i==="m")throw TypeError("Private method is not writable");if(i==="a"&&!s)throw TypeError("Private accessor was defined without a setter");if(typeof r==="function"?t!==r||!s:!r.has(t))throw TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?s.call(t,o):s?s.value=o:r.set(t,o),o}function e(t,r,o,i){if(o==="a"&&!i)throw TypeError("Private accessor was defined without a getter");if(typeof r==="function"?t!==r||!i:!r.has(t))throw TypeError("Cannot read private member from an object whose class did not declare it");return o==="m"?i:o==="a"?i.call(t):i?i.value:r.get(t)}function He(t){return typeof t==="object"&&t!==null&&(("name"in t)&&t.name==="AbortError"||("message"in t)&&String(t.message).includes("FetchRequestCanceledException"))}var Ot=(t)=>{if(t instanceof Error)return t;if(typeof t==="object"&&t!==null){try{let r=Object.prototype.toString.call(t);if(r==="[object Error]"||r==="[object DOMException]"){let o=Error(t.message,t.cause?{cause:t.cause}:{});if(t.stack)o.stack=t.stack;if(t.cause&&!o.cause)o.cause=t.cause;if(t.name)o.name=t.name;return o}}catch{}try{return Error(JSON.stringify(t))}catch{}}return Error(t)};var c=(()=>{class t extends Error{}return t})();class Z extends c{constructor(t,r,o,i,s){super(`${Z.makeMessage(t,r,o)}`);this.status=t,this.headers=i,this.requestID=i?.get("request-id"),this.workspaceID=i?.get("anthropic-workspace-id"),this.error=r,this.type=s??null}static makeMessage(t,r,o){let i=r?.message?typeof r.message==="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):o;if(t&&i)return`${t} ${i}`;if(t)return`${t} status code (no body)`;if(i)return i;return"(no status code or body)"}static generate(t,r,o,i){if(!t||!i)return new xt({message:o,cause:Ot(r)});let s=r,u=s?.error?.type;if(t===400)return new hn(t,s,o,i,u);if(t===401)return new fn(t,s,o,i,u);if(t===403)return new gn(t,s,o,i,u);if(t===404)return new yn(t,s,o,i,u);if(t===409)return new bn(t,s,o,i,u);if(t===422)return new Sn(t,s,o,i,u);if(t===429)return new xn(t,s,o,i,u);if(t>=500)return new wn(t,s,o,i,u);return new Z(t,s,o,i,u)}}class Ae extends Z{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}}class xt extends Z{constructor({message:t,cause:r}){super(void 0,void 0,t||"Connection error.",void 0);if(r)this.cause=r}}class mn extends xt{constructor({message:t}={}){super({message:t??"Request timed out."})}}class yo extends c{constructor(t,{cause:r}={}){super(t??"Retryable error.");if(r!==void 0)this.cause=r}}class hn extends Z{}class fn extends Z{}class gn extends Z{}class yn extends Z{}class bn extends Z{}class Sn extends Z{}class xn extends Z{}class wn extends Z{}var b=/^[a-z][a-z0-9+.-]*:/i,ri=(t)=>b.test(t),xe=(t)=>(xe=Array.isArray,xe(t)),bo=xe;function
|
|
3
|
-
export{n,e,He,Ot,c,Z,Ae,xt,mn,yo,hn,fn,gn,yn,bn,Sn,xn,wn,ri,xe,bo,
|
|
2
|
+
function n(t,r,o,i,s){if(i==="m")throw TypeError("Private method is not writable");if(i==="a"&&!s)throw TypeError("Private accessor was defined without a setter");if(typeof r==="function"?t!==r||!s:!r.has(t))throw TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?s.call(t,o):s?s.value=o:r.set(t,o),o}function e(t,r,o,i){if(o==="a"&&!i)throw TypeError("Private accessor was defined without a getter");if(typeof r==="function"?t!==r||!i:!r.has(t))throw TypeError("Cannot read private member from an object whose class did not declare it");return o==="m"?i:o==="a"?i.call(t):i?i.value:r.get(t)}function He(t){return typeof t==="object"&&t!==null&&(("name"in t)&&t.name==="AbortError"||("message"in t)&&String(t.message).includes("FetchRequestCanceledException"))}var Ot=(t)=>{if(t instanceof Error)return t;if(typeof t==="object"&&t!==null){try{let r=Object.prototype.toString.call(t);if(r==="[object Error]"||r==="[object DOMException]"){let o=Error(t.message,t.cause?{cause:t.cause}:{});if(t.stack)o.stack=t.stack;if(t.cause&&!o.cause)o.cause=t.cause;if(t.name)o.name=t.name;return o}}catch{}try{return Error(JSON.stringify(t))}catch{}}return Error(t)};var c=(()=>{class t extends Error{}return t})();class Z extends c{constructor(t,r,o,i,s){super(`${Z.makeMessage(t,r,o)}`);this.status=t,this.headers=i,this.requestID=i?.get("request-id"),this.workspaceID=i?.get("anthropic-workspace-id"),this.error=r,this.type=s??null}static makeMessage(t,r,o){let i=r?.message?typeof r.message==="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):o;if(t&&i)return`${t} ${i}`;if(t)return`${t} status code (no body)`;if(i)return i;return"(no status code or body)"}static generate(t,r,o,i){if(!t||!i)return new xt({message:o,cause:Ot(r)});let s=r,u=s?.error?.type;if(t===400)return new hn(t,s,o,i,u);if(t===401)return new fn(t,s,o,i,u);if(t===403)return new gn(t,s,o,i,u);if(t===404)return new yn(t,s,o,i,u);if(t===409)return new bn(t,s,o,i,u);if(t===422)return new Sn(t,s,o,i,u);if(t===429)return new xn(t,s,o,i,u);if(t>=500)return new wn(t,s,o,i,u);return new Z(t,s,o,i,u)}}class Ae extends Z{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}}class xt extends Z{constructor({message:t,cause:r}){super(void 0,void 0,t||"Connection error.",void 0);if(r)this.cause=r}}class mn extends xt{constructor({message:t}={}){super({message:t??"Request timed out."})}}class yo extends c{constructor(t,{cause:r}={}){super(t??"Retryable error.");if(r!==void 0)this.cause=r}}class hn extends Z{}class fn extends Z{}class gn extends Z{}class yn extends Z{}class bn extends Z{}class Sn extends Z{}class xn extends Z{}class wn extends Z{}var b=/^[a-z][a-z0-9+.-]*:/i,ri=(t)=>b.test(t),xe=(t)=>(xe=Array.isArray,xe(t)),bo=xe;function kr(t){if(typeof t!=="object")return{};return t??{}}function So(t){if(!t)return!0;for(let r in t)return!1;return!0}function l(t,r){return Object.prototype.hasOwnProperty.call(t,r)}function xo(t){return t!=null&&typeof t==="object"&&!Array.isArray(t)}var vn=(t,r)=>{if(typeof r!=="number"||!Number.isInteger(r))throw new c(`${t} must be an integer`);if(r<0)throw new c(`${t} must be a positive integer`);return r};var An=(t)=>{try{return JSON.parse(t)}catch(r){return}};function wt(t){}var k=(t)=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()||void 0;return};function ni(t){let r=0;for(let s of t)r+=s.length;let o=new Uint8Array(r),i=0;for(let s of t)o.set(s,i),i+=s.length;return o}var y;function Nt(t){let r;return(y??(r=new globalThis.TextEncoder,y=r.encode.bind(r)))(t)}var w;function vt(t){let r;return(w??(r=new globalThis.TextDecoder,w=r.decode.bind(r)))(t)}var Rr="warn",a={off:0,error:200,warn:300,info:400,debug:500},En=(t,r,o)=>{if(!t)return;if(l(a,t))return t;o.warn(`${r} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(a))}`);return};function f(){}function p(t,r,o){if(!r||a[t]>a[o])return f;else return r[t].bind(r)}var O={error:f,warn:f,info:f,debug:f},h=new WeakMap;function x(t,r){let o=h.get(t);if(o&&o[0]===r)return o[1];let i={error:p("error",t,r),warn:p("warn",t,r),info:p("info",t,r),debug:p("debug",t,r)};return h.set(t,[r,i]),i}function T(t){let r=t.logger,o=t.logLevel??"off";if(!r)return O;return x(r,o)}var m,d;function oi(){let t=k("ANTHROPIC_LOG");if(!d||t!==m)m=t,d=x(console,En(t,"process.env['ANTHROPIC_LOG']",x(console,Rr))??Rr);return d}function Xe(t,r,o){if(t.debug===f)return;t.debug(r,L(o))}var L=(t)=>{if(t.options)t.options={...t.options},delete t.options.headers;if(t.headers)t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([r,o])=>[r,r.toLowerCase()==="authorization"||r.toLowerCase()==="api-key"||r.toLowerCase()==="x-api-key"||r.toLowerCase()==="cookie"||r.toLowerCase()==="set-cookie"?"***":o]));if("retryOfRequestLogID"in t){if(t.retryOfRequestLogID)t.retryOf=t.retryOfRequestLogID;delete t.retryOfRequestLogID}return t};function le(t,r){return t instanceof Z&&t.status===r}function R(t){return t instanceof Z&&typeof t.status==="number"&&t.status>=400&&t.status<500}function Dt(t){return R(t)&&!le(t,408)&&!le(t,409)&&!le(t,429)}function _n(t,r,o){return Math.min(r*2**t,o)}function ii(t,r){return t+Math.random()*(r-t)}function Pn(t){return t*(1-Math.random()*0.25)}var E=(()=>{class t extends Error{constructor(r){let o=typeof r==="string"?r:r.map((i)=>{if(i.type==="text")return i.text;return`[${i.type}]`}).join(" ");super(o);this.name="ToolError",this.content=r}}return t})();var wo=15000,g=5000;function Ir(t,r){if(!(t>=g))throw new c(`${r} must be at least ${g}ms (got ${t}); to run without memory sync, pass \`memorySyncIntervalMs: null\` to the worker instead`)}function Ut(){let t,r;return{promise:new Promise((i,s)=>{t=i,r=s}),resolve:t,reject:r}}
|
|
3
|
+
export{n,e,He,Ot,c,Z,Ae,xt,mn,yo,hn,fn,gn,yn,bn,Sn,xn,wn,ri,xe,bo,kr,So,xo,vn,An,wt,k,ni,Nt,vt,Rr,En,T,oi,Xe,le,Dt,_n,ii,Pn,E,wo,Ir,Ut};
|