gemi 0.232.0 → 0.233.1
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/dist/ai/Agent.d.ts +41 -11
- package/dist/ai/Agent.d.ts.map +1 -1
- package/dist/ai/AgentController.d.ts +29 -0
- package/dist/ai/AgentController.d.ts.map +1 -1
- package/dist/ai/AgentProvider.d.ts +32 -2
- package/dist/ai/AgentProvider.d.ts.map +1 -1
- package/dist/ai/FallbackProvider.d.ts.map +1 -1
- package/dist/ai/index.js +28 -28
- package/dist/ai/index.js.map +4 -4
- package/dist/ai/providers/anthropicRequest.d.ts.map +1 -1
- package/dist/ai/providers/capabilities.d.ts +17 -0
- package/dist/ai/providers/capabilities.d.ts.map +1 -1
- package/dist/ai/providers/request.d.ts +7 -0
- package/dist/ai/providers/request.d.ts.map +1 -1
- package/dist/ai/testing/index.js +3 -3
- package/dist/ai/testing/index.js.map +3 -3
- package/dist/ai/testing/scriptedProvider.d.ts +2 -0
- package/dist/ai/testing/scriptedProvider.d.ts.map +1 -1
- package/dist/auth/AuthController.d.ts.map +1 -1
- package/dist/auth/UserProvider.d.ts +19 -0
- package/dist/auth/UserProvider.d.ts.map +1 -1
- package/dist/{chunk-vwnrha3f.js → chunk-1eha67ey.js} +1 -1
- package/dist/{chunk-957arkj0.js → chunk-607nk925.js} +23 -23
- package/dist/{chunk-957arkj0.js.map → chunk-607nk925.js.map} +3 -3
- package/dist/{chunk-pbdk8w5m.js → chunk-6j439skq.js} +1 -1
- package/dist/chunk-hd9yny4q.js +88 -0
- package/dist/{chunk-vsh9jck0.js.map → chunk-hd9yny4q.js.map} +4 -4
- package/dist/{chunk-8640e2g9.js → chunk-rgcdf5pb.js} +2 -2
- package/dist/{chunk-8640e2g9.js.map → chunk-rgcdf5pb.js.map} +1 -1
- package/dist/chunk-t17vf1ep.js +12 -0
- package/dist/{chunk-8x8pbn1z.js.map → chunk-t17vf1ep.js.map} +6 -6
- package/dist/{chunk-x35w5kjh.js → chunk-vsr08sbe.js} +1 -1
- package/dist/facades/index.js +1 -1
- package/dist/http/index.js +1 -1
- package/dist/i18n/index.js +1 -1
- package/dist/kernel/index.js +1 -1
- package/dist/server/index.js +1 -1
- package/dist/services/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-8x8pbn1z.js +0 -12
- package/dist/chunk-vsh9jck0.js +0 -88
- /package/dist/{chunk-vwnrha3f.js.map → chunk-1eha67ey.js.map} +0 -0
- /package/dist/{chunk-pbdk8w5m.js.map → chunk-6j439skq.js.map} +0 -0
- /package/dist/{chunk-x35w5kjh.js.map → chunk-vsr08sbe.js.map} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$ as SJ,_ as n,aa as bJ,ba as qJ}from"./chunk-8640e2g9.js";import{Da as E,Ha as T,Ia as TJ}from"./chunk-v2fd69at.js";import"./chunk-ba1h9pm6.js";import{Ye as GJ,gh as IJ,hh as g,ph as AJ,qh as BJ,rh as RJ}from"./chunk-vsh9jck0.js";import"./chunk-jkhtybga.js";import"./chunk-mgvrfhy8.js";import{Ai as WJ,wi as jJ,xi as YJ}from"./chunk-vjqpcet2.js";import{Dj as DJ}from"./chunk-jqqyj6cr.js";import"./chunk-30zs008n.js";import"./chunk-m4wagwhr.js";import"./chunk-6xt7w9bb.js";import"./chunk-c5kd7eac.js";import"./chunk-9bjggtdt.js";import"./chunk-efnerp0c.js";import"./chunk-0zakpsep.js";import"./chunk-djhr379j.js";import"./chunk-qgka1mvf.js";import"./chunk-znh1mbqs.js";import"./chunk-g0mxdh2x.js";import"./chunk-7ka1abkd.js";import"./chunk-6fpjc2eg.js";import"./chunk-dqb257xv.js";import{um as KJ}from"./chunk-1v1ek1ey.js";import"./chunk-0dp6jvrg.js";import{Mm as PJ}from"./chunk-x8by5j7p.js";import{Om as f}from"./chunk-kfcz4qa8.js";import"./chunk-30jcs49q.js";import{createHash as _2}from"crypto";import{join as i,resolve as EJ,sep as vJ}from"path";import{Duplex as cJ}from"stream";import{constants as k,createBrotliCompress as pJ,createGzip as dJ}from"zlib";var lJ=["br","gzip"],oJ=1024,nJ=5,iJ=19,aJ=6;function rJ(J){if(J===void 0)return 1;if(!/^\d+(\.\d{0,3})?$/.test(J.trim()))return 1;let $=Number(J.trim());return Number.isFinite($)?Math.min($,1):1}function tJ(J){if(J===null||J===void 0)return null;let $=new Map;for(let Z of J.split(",")){let[Q,...H]=Z.split(";"),j=Q.trim().toLowerCase();if(j==="")continue;let Y=1;for(let W of H){let V=W.indexOf("=");if(V===-1)continue;if(W.slice(0,V).trim().toLowerCase()==="q"){Y=rJ(W.slice(V+1));break}}$.set(j,Y)}return $}function p(J,$=lJ){let Z=tJ(J);if(!Z)return null;let Q=Z.get("*"),H=null,j=0;for(let Y of $){let W=Z.get(Y)??Q??0;if(W>j)H=Y,j=W}return H}function sJ(J,$){if(!J)return!1;return J.split(",").some((Z)=>Z.trim().toLowerCase().split("=")[0].trim()===$)}function eJ(J,$){if(J==="HEAD")return!1;if($.status<200||$.status===204||$.status===206||$.status===304)return!1;if($.headers.has("Content-Range"))return!1;let Z=$.headers.get("Content-Type");if(!Z||!/^\s*text\/html\s*(;|$)/i.test(Z))return!1;if(!$.body)return!1;let Q=$.headers.get("Content-Encoding");if(Q&&Q.trim().toLowerCase()!=="identity")return!1;if(sJ($.headers.get("Cache-Control"),"no-transform"))return!1;let H=$.headers.get("Content-Length");if(H!==null&&Number(H)<oJ)return!1;return!0}function J2(J){let $=J==="br"?pJ({params:{[k.BROTLI_PARAM_QUALITY]:nJ,[k.BROTLI_PARAM_LGWIN]:iJ},flush:k.BROTLI_OPERATION_FLUSH}):dJ({level:aJ,flush:k.Z_SYNC_FLUSH});return cJ.toWeb($)}function $2(J){let $=J.get("Vary");if(!$){J.set("Vary","Accept-Encoding");return}let Z=$.split(",").map((Q)=>Q.trim().toLowerCase());if(Z.includes("*")||Z.includes("accept-encoding"))return;J.append("Vary","Accept-Encoding")}function ZJ(J,$){if(!eJ(J.method,$))return $;let Z=new Headers($.headers);$2(Z);let Q=p(J.headers.get("Accept-Encoding"));if(!Q)return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z});let H;try{H=J2(Q)}catch{return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z})}return Z.set("Content-Encoding",Q),Z.delete("Content-Length"),new Response($.body.pipeThrough(H),{status:$.status,statusText:$.statusText,headers:Z})}import{readdir as W2,stat as VJ}from"fs/promises";import{join as G2}from"path";import{mkdir as R2,readFile as Z2,stat as T2,writeFile as S2}from"fs/promises";import{dirname as q2,join as Q2}from"path";import{promisify as QJ}from"util";import{brotliCompress as X2,constants as w2,gzip as H2}from"zlib";var j2=".vite/static-assets.json";var XJ={br:".br",gzip:".gz"},Y2=["br","gzip"],k2=QJ(X2),y2=QJ(H2);async function HJ(J){let $;try{$=await Z2(Q2(J,j2),"utf8")}catch{return null}let Z;try{Z=JSON.parse($)?.files}catch{return null}if(!Z||typeof Z!=="object")return null;let Q={files:{}};for(let[H,j]of Object.entries(Z)){if(!Array.isArray(j))continue;Q.files[H]=Y2.filter((Y)=>j.includes(Y))}return Q}function d(J){let $=J.toString(),Z=new Bun.CryptoHasher("sha1");return Z.update($),Z.digest("hex")}async function zJ(J){let $=new Set;async function Z(Q,H){let j;try{j=await W2(Q,{withFileTypes:!0})}catch{return}for(let Y of j){if(Y.name.startsWith("."))continue;if(H&&Y.name==="assets")continue;let W=G2(Q,Y.name),V=Y.isDirectory(),z=Y.isFile();if(Y.isSymbolicLink())try{let C=await VJ(W);V=C.isDirectory(),z=C.isFile()}catch{continue}if(z)$.add(W);else if(V&&!Y.isSymbolicLink())await Z(W,!1)}}return await Z(J,!0),$}var V2="public, max-age=31536000, must-revalidate",z2="public, max-age=31536000, immutable";async function U2(J,$,Z){if(Z.length===0||J.headers.has("Range"))return null;let Q=p(J.headers.get("Accept-Encoding"),Z);if(!Q)return null;let H=$+XJ[Q];try{let j=await VJ(H);return j.isFile()?{encoding:Q,path:H,size:j.size}:null}catch{return null}}async function UJ(J,$,Z={}){let Q=Bun.file($),H=Z.encodings??[],j={"Content-Type":Q.type||"application/octet-stream","Cache-Control":Z.immutable?z2:V2,"Accept-Ranges":"bytes"};if(H.length>0)j.Vary="Accept-Encoding";let Y=await U2(J,$,H);if(Y){let z=Bun.file(Y.path);return new Response(z.stream(),{headers:{...j,"Content-Encoding":Y.encoding,"Content-Length":String(Y.size),ETag:`${d(z.lastModified)}-${Y.encoding}`}})}let W=Q.size;j.ETag=d(Q.lastModified);let V=jJ(J.headers.get("Range"));if(V){let z=YJ(V,W);if(!z)return GJ(W);return new Response(Q.slice(z.start,z.end+1).stream(),{status:206,headers:{...j,"Content-Range":WJ(z.start,z.end,W),"Content-Length":String(z.length)}})}return new Response(Q.stream(),{headers:{...j,"Content-Length":String(W)}})}import{stat as I2}from"fs/promises";var y="app/client.tsx";function OJ(J,$=E){let Z=J[y]?.file;if(!Z)return;return{module:T(Z,$),preload:R(J,y,$)}}function R(J,$,Z=E){let Q=[],H=new Set,j=(Y)=>{if(H.has(Y))return;H.add(Y);let W=J[Y];if(!W?.file)return;Q.push(T(W.file,Z));for(let V of W.imports??[])j(V)};return j($),Q}function K2(J,$,Z=E){let Q=new Set(R(J,$,Z)),H=[],j=new Set,Y=(V)=>{if(j.has(V))return;j.add(V);let z=J[V];if(!z)return;for(let C of z.dynamicImports??[])if(!/(^|\/)node_modules\//.test(C)&&!H.includes(C))H.push(C);for(let C of z.imports??[])Y(C)};Y($);let W=[];for(let V of H)for(let z of R(J,V,Z))if(!Q.has(z))Q.add(z),W.push(z);return W}function xJ(J,$){let Z=[],Q=new Set,H=new Set,j=(Y)=>{if(H.has(Y))return;H.add(Y);let W=J[Y];if(!W)return;for(let V of W.imports??[])j(V);for(let V of W.css??[])if(!Q.has(V))Q.add(V),Z.push(V)};return j($),Z}function CJ(J,$=E){let Z=new Map;return(Q)=>{if(!Z.has(Q)){let H=`${Q}${KJ}`,j=J[H]?.file;Z.set(Q,j?{src:T(j,$),preload:R(J,H,$),dynamicPreload:K2(J,H,$)}:void 0)}return Z.get(Q)}}var LJ="x-gemi-build";var O2="__gemiReload";function x2(J,$,Z,Q){let H=Date.now(),j=function(U){return typeof U==="number"&&H-U>=0&&H-U<Z},Y=function(U){try{let K=U?JSON.parse(U):null;return K&&typeof K==="object"&&!Array.isArray(K)?K:{}}catch{return{}}},W=function(U){let K={};for(let M in U)if(j(U[M]))K[M]=U[M];return K},V=function(U){let K=2166136261;for(let M=0;M<U.length;M++)K=Math.imul(K^U.charCodeAt(M),16777619);return(K>>>0).toString(36)},z=null,C={};try{z=window.sessionStorage,C=Y(z.getItem(J))}catch{z=null}let N=J+":",F="",I="";try{let U=new URL($,window.location.href);F=V(new URL(window.location.href).origin),I=V(U.origin+U.pathname)}catch{}let L=null;try{let U=window.name;if(!I)L=null;else if(U==="")L={};else if(U.indexOf(N)===0){let K=Y(U.slice(N.length)),M=K.m;L=K.o===F&&M&&typeof M==="object"&&!Array.isArray(M)?M:{}}}catch{L=null}if(Q==="tidy"){try{let U=window.name;if(L===null||U.indexOf(N)!==0)return"ok";for(let K in L)if(j(L[K]))return"cooldown";window.name=""}catch{}return"ok"}if(j(C[$])||L&&j(L[I]))return"cooldown";if(!z&&!L)return"storage";if(!Q)return"ok";if(z)try{let U=W(C);U[$]=H;let K=JSON.stringify(U);if(z.setItem(J,K),z.getItem(J)===K)return"ok"}catch{}if(L)try{let U=W(L);U[I]=H;let K=N+JSON.stringify({o:F,m:U});if(window.name=K,window.name===K)return"ok"}catch{}return"storage"}function _J(J,$=30000){let Z=JSON.stringify("gemi:chunk-reload"),Q=JSON.stringify(`Failed to fetch dynamically imported module: ${J}`);return`var g=${x2.toString()};var r=!1;try{r=navigator.onLine!==!1&&g(${Z},window.location.href,${Number($)},!0)==="ok"}catch(e){}if(r)window.location.reload();else throw new Error(${Q});export {r as ${O2}}`}var C2=new RegExp(`^${IJ}/.+\\.m?js$`);function l(J){return C2.test(J)}function MJ(J){if(l(J))return new Response(_J(J),{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store"}});if(g(J))return new Response("Not found",{status:404});return}function NJ(J){let $=J?.trim();if(!$)return;try{let Z=new URL($);if(Z.protocol!=="https:"&&Z.protocol!=="http:")throw Error("not http(s)");return Z.search="",Z.hash="",Z.href.endsWith("/")?Z.href:`${Z.href}/`}catch{console.error(`GEMI_ASSET_FALLBACK_URL is not an absolute http(s) URL (${JSON.stringify($)}); missing assets are not looked up anywhere else.`);return}}function FJ({base:J,timeoutMs:$=3000,missTtlMs:Z=30000,fetch:Q=fetch,now:H=Date.now}){let j=new Map,Y=(W)=>{if(j.delete(W),j.set(W,H()+Z),j.size>1000)j.delete(j.keys().next().value)};return async(W,V)=>{if(W.method!=="GET"&&W.method!=="HEAD")return;let z=j.get(V);if(z!==void 0){if(z>H())return;j.delete(V)}let C;try{C=new URL(V.replace(/^\/+/,""),J)}catch{return}if(!C.href.startsWith(J))return;let N=new AbortController,F=setTimeout(()=>N.abort(),$),I;try{I=await Q(C.href,{method:W.method,signal:N.signal,redirect:"error"})}catch{Y(V);return}finally{clearTimeout(F)}if(I.status!==200){I.body?.cancel().catch(()=>{}),Y(V);return}let L=Bun.file(V).type,U=new Headers({"Content-Type":L!=="application/octet-stream"&&L||I.headers.get("content-type")||"application/octet-stream","Cache-Control":"public, max-age=31536000, immutable",["x-gemi-asset-fallback"]:"1"}),K=I.headers.get("content-length");if(K&&!I.headers.get("content-encoding"))U.set("Content-Length",K);return new Response(W.method==="HEAD"?null:I.body,{status:200,headers:U})}}var L2=`<!DOCTYPE html>
|
|
2
|
+
import{$ as SJ,_ as n,aa as bJ,ba as qJ}from"./chunk-rgcdf5pb.js";import{Da as E,Ha as T,Ia as TJ}from"./chunk-v2fd69at.js";import"./chunk-ba1h9pm6.js";import{Ye as GJ,gh as IJ,hh as g,ph as AJ,qh as BJ,rh as RJ}from"./chunk-hd9yny4q.js";import"./chunk-jkhtybga.js";import"./chunk-mgvrfhy8.js";import{Ai as WJ,wi as jJ,xi as YJ}from"./chunk-vjqpcet2.js";import{Dj as DJ}from"./chunk-jqqyj6cr.js";import"./chunk-30zs008n.js";import"./chunk-m4wagwhr.js";import"./chunk-6xt7w9bb.js";import"./chunk-c5kd7eac.js";import"./chunk-9bjggtdt.js";import"./chunk-efnerp0c.js";import"./chunk-0zakpsep.js";import"./chunk-djhr379j.js";import"./chunk-qgka1mvf.js";import"./chunk-znh1mbqs.js";import"./chunk-g0mxdh2x.js";import"./chunk-7ka1abkd.js";import"./chunk-6fpjc2eg.js";import"./chunk-dqb257xv.js";import{um as KJ}from"./chunk-1v1ek1ey.js";import"./chunk-0dp6jvrg.js";import{Mm as PJ}from"./chunk-x8by5j7p.js";import{Om as f}from"./chunk-kfcz4qa8.js";import"./chunk-30jcs49q.js";import{createHash as _2}from"crypto";import{join as i,resolve as EJ,sep as vJ}from"path";import{Duplex as cJ}from"stream";import{constants as k,createBrotliCompress as pJ,createGzip as dJ}from"zlib";var lJ=["br","gzip"],oJ=1024,nJ=5,iJ=19,aJ=6;function rJ(J){if(J===void 0)return 1;if(!/^\d+(\.\d{0,3})?$/.test(J.trim()))return 1;let $=Number(J.trim());return Number.isFinite($)?Math.min($,1):1}function tJ(J){if(J===null||J===void 0)return null;let $=new Map;for(let Z of J.split(",")){let[Q,...H]=Z.split(";"),j=Q.trim().toLowerCase();if(j==="")continue;let Y=1;for(let W of H){let V=W.indexOf("=");if(V===-1)continue;if(W.slice(0,V).trim().toLowerCase()==="q"){Y=rJ(W.slice(V+1));break}}$.set(j,Y)}return $}function p(J,$=lJ){let Z=tJ(J);if(!Z)return null;let Q=Z.get("*"),H=null,j=0;for(let Y of $){let W=Z.get(Y)??Q??0;if(W>j)H=Y,j=W}return H}function sJ(J,$){if(!J)return!1;return J.split(",").some((Z)=>Z.trim().toLowerCase().split("=")[0].trim()===$)}function eJ(J,$){if(J==="HEAD")return!1;if($.status<200||$.status===204||$.status===206||$.status===304)return!1;if($.headers.has("Content-Range"))return!1;let Z=$.headers.get("Content-Type");if(!Z||!/^\s*text\/html\s*(;|$)/i.test(Z))return!1;if(!$.body)return!1;let Q=$.headers.get("Content-Encoding");if(Q&&Q.trim().toLowerCase()!=="identity")return!1;if(sJ($.headers.get("Cache-Control"),"no-transform"))return!1;let H=$.headers.get("Content-Length");if(H!==null&&Number(H)<oJ)return!1;return!0}function J2(J){let $=J==="br"?pJ({params:{[k.BROTLI_PARAM_QUALITY]:nJ,[k.BROTLI_PARAM_LGWIN]:iJ},flush:k.BROTLI_OPERATION_FLUSH}):dJ({level:aJ,flush:k.Z_SYNC_FLUSH});return cJ.toWeb($)}function $2(J){let $=J.get("Vary");if(!$){J.set("Vary","Accept-Encoding");return}let Z=$.split(",").map((Q)=>Q.trim().toLowerCase());if(Z.includes("*")||Z.includes("accept-encoding"))return;J.append("Vary","Accept-Encoding")}function ZJ(J,$){if(!eJ(J.method,$))return $;let Z=new Headers($.headers);$2(Z);let Q=p(J.headers.get("Accept-Encoding"));if(!Q)return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z});let H;try{H=J2(Q)}catch{return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z})}return Z.set("Content-Encoding",Q),Z.delete("Content-Length"),new Response($.body.pipeThrough(H),{status:$.status,statusText:$.statusText,headers:Z})}import{readdir as W2,stat as VJ}from"fs/promises";import{join as G2}from"path";import{mkdir as R2,readFile as Z2,stat as T2,writeFile as S2}from"fs/promises";import{dirname as q2,join as Q2}from"path";import{promisify as QJ}from"util";import{brotliCompress as X2,constants as w2,gzip as H2}from"zlib";var j2=".vite/static-assets.json";var XJ={br:".br",gzip:".gz"},Y2=["br","gzip"],k2=QJ(X2),y2=QJ(H2);async function HJ(J){let $;try{$=await Z2(Q2(J,j2),"utf8")}catch{return null}let Z;try{Z=JSON.parse($)?.files}catch{return null}if(!Z||typeof Z!=="object")return null;let Q={files:{}};for(let[H,j]of Object.entries(Z)){if(!Array.isArray(j))continue;Q.files[H]=Y2.filter((Y)=>j.includes(Y))}return Q}function d(J){let $=J.toString(),Z=new Bun.CryptoHasher("sha1");return Z.update($),Z.digest("hex")}async function zJ(J){let $=new Set;async function Z(Q,H){let j;try{j=await W2(Q,{withFileTypes:!0})}catch{return}for(let Y of j){if(Y.name.startsWith("."))continue;if(H&&Y.name==="assets")continue;let W=G2(Q,Y.name),V=Y.isDirectory(),z=Y.isFile();if(Y.isSymbolicLink())try{let C=await VJ(W);V=C.isDirectory(),z=C.isFile()}catch{continue}if(z)$.add(W);else if(V&&!Y.isSymbolicLink())await Z(W,!1)}}return await Z(J,!0),$}var V2="public, max-age=31536000, must-revalidate",z2="public, max-age=31536000, immutable";async function U2(J,$,Z){if(Z.length===0||J.headers.has("Range"))return null;let Q=p(J.headers.get("Accept-Encoding"),Z);if(!Q)return null;let H=$+XJ[Q];try{let j=await VJ(H);return j.isFile()?{encoding:Q,path:H,size:j.size}:null}catch{return null}}async function UJ(J,$,Z={}){let Q=Bun.file($),H=Z.encodings??[],j={"Content-Type":Q.type||"application/octet-stream","Cache-Control":Z.immutable?z2:V2,"Accept-Ranges":"bytes"};if(H.length>0)j.Vary="Accept-Encoding";let Y=await U2(J,$,H);if(Y){let z=Bun.file(Y.path);return new Response(z.stream(),{headers:{...j,"Content-Encoding":Y.encoding,"Content-Length":String(Y.size),ETag:`${d(z.lastModified)}-${Y.encoding}`}})}let W=Q.size;j.ETag=d(Q.lastModified);let V=jJ(J.headers.get("Range"));if(V){let z=YJ(V,W);if(!z)return GJ(W);return new Response(Q.slice(z.start,z.end+1).stream(),{status:206,headers:{...j,"Content-Range":WJ(z.start,z.end,W),"Content-Length":String(z.length)}})}return new Response(Q.stream(),{headers:{...j,"Content-Length":String(W)}})}import{stat as I2}from"fs/promises";var y="app/client.tsx";function OJ(J,$=E){let Z=J[y]?.file;if(!Z)return;return{module:T(Z,$),preload:R(J,y,$)}}function R(J,$,Z=E){let Q=[],H=new Set,j=(Y)=>{if(H.has(Y))return;H.add(Y);let W=J[Y];if(!W?.file)return;Q.push(T(W.file,Z));for(let V of W.imports??[])j(V)};return j($),Q}function K2(J,$,Z=E){let Q=new Set(R(J,$,Z)),H=[],j=new Set,Y=(V)=>{if(j.has(V))return;j.add(V);let z=J[V];if(!z)return;for(let C of z.dynamicImports??[])if(!/(^|\/)node_modules\//.test(C)&&!H.includes(C))H.push(C);for(let C of z.imports??[])Y(C)};Y($);let W=[];for(let V of H)for(let z of R(J,V,Z))if(!Q.has(z))Q.add(z),W.push(z);return W}function xJ(J,$){let Z=[],Q=new Set,H=new Set,j=(Y)=>{if(H.has(Y))return;H.add(Y);let W=J[Y];if(!W)return;for(let V of W.imports??[])j(V);for(let V of W.css??[])if(!Q.has(V))Q.add(V),Z.push(V)};return j($),Z}function CJ(J,$=E){let Z=new Map;return(Q)=>{if(!Z.has(Q)){let H=`${Q}${KJ}`,j=J[H]?.file;Z.set(Q,j?{src:T(j,$),preload:R(J,H,$),dynamicPreload:K2(J,H,$)}:void 0)}return Z.get(Q)}}var LJ="x-gemi-build";var O2="__gemiReload";function x2(J,$,Z,Q){let H=Date.now(),j=function(U){return typeof U==="number"&&H-U>=0&&H-U<Z},Y=function(U){try{let K=U?JSON.parse(U):null;return K&&typeof K==="object"&&!Array.isArray(K)?K:{}}catch{return{}}},W=function(U){let K={};for(let M in U)if(j(U[M]))K[M]=U[M];return K},V=function(U){let K=2166136261;for(let M=0;M<U.length;M++)K=Math.imul(K^U.charCodeAt(M),16777619);return(K>>>0).toString(36)},z=null,C={};try{z=window.sessionStorage,C=Y(z.getItem(J))}catch{z=null}let N=J+":",F="",I="";try{let U=new URL($,window.location.href);F=V(new URL(window.location.href).origin),I=V(U.origin+U.pathname)}catch{}let L=null;try{let U=window.name;if(!I)L=null;else if(U==="")L={};else if(U.indexOf(N)===0){let K=Y(U.slice(N.length)),M=K.m;L=K.o===F&&M&&typeof M==="object"&&!Array.isArray(M)?M:{}}}catch{L=null}if(Q==="tidy"){try{let U=window.name;if(L===null||U.indexOf(N)!==0)return"ok";for(let K in L)if(j(L[K]))return"cooldown";window.name=""}catch{}return"ok"}if(j(C[$])||L&&j(L[I]))return"cooldown";if(!z&&!L)return"storage";if(!Q)return"ok";if(z)try{let U=W(C);U[$]=H;let K=JSON.stringify(U);if(z.setItem(J,K),z.getItem(J)===K)return"ok"}catch{}if(L)try{let U=W(L);U[I]=H;let K=N+JSON.stringify({o:F,m:U});if(window.name=K,window.name===K)return"ok"}catch{}return"storage"}function _J(J,$=30000){let Z=JSON.stringify("gemi:chunk-reload"),Q=JSON.stringify(`Failed to fetch dynamically imported module: ${J}`);return`var g=${x2.toString()};var r=!1;try{r=navigator.onLine!==!1&&g(${Z},window.location.href,${Number($)},!0)==="ok"}catch(e){}if(r)window.location.reload();else throw new Error(${Q});export {r as ${O2}}`}var C2=new RegExp(`^${IJ}/.+\\.m?js$`);function l(J){return C2.test(J)}function MJ(J){if(l(J))return new Response(_J(J),{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store"}});if(g(J))return new Response("Not found",{status:404});return}function NJ(J){let $=J?.trim();if(!$)return;try{let Z=new URL($);if(Z.protocol!=="https:"&&Z.protocol!=="http:")throw Error("not http(s)");return Z.search="",Z.hash="",Z.href.endsWith("/")?Z.href:`${Z.href}/`}catch{console.error(`GEMI_ASSET_FALLBACK_URL is not an absolute http(s) URL (${JSON.stringify($)}); missing assets are not looked up anywhere else.`);return}}function FJ({base:J,timeoutMs:$=3000,missTtlMs:Z=30000,fetch:Q=fetch,now:H=Date.now}){let j=new Map,Y=(W)=>{if(j.delete(W),j.set(W,H()+Z),j.size>1000)j.delete(j.keys().next().value)};return async(W,V)=>{if(W.method!=="GET"&&W.method!=="HEAD")return;let z=j.get(V);if(z!==void 0){if(z>H())return;j.delete(V)}let C;try{C=new URL(V.replace(/^\/+/,""),J)}catch{return}if(!C.href.startsWith(J))return;let N=new AbortController,F=setTimeout(()=>N.abort(),$),I;try{I=await Q(C.href,{method:W.method,signal:N.signal,redirect:"error"})}catch{Y(V);return}finally{clearTimeout(F)}if(I.status!==200){I.body?.cancel().catch(()=>{}),Y(V);return}let L=Bun.file(V).type,U=new Headers({"Content-Type":L!=="application/octet-stream"&&L||I.headers.get("content-type")||"application/octet-stream","Cache-Control":"public, max-age=31536000, immutable",["x-gemi-asset-fallback"]:"1"}),K=I.headers.get("content-length");if(K&&!I.headers.get("content-encoding"))U.set("Content-Length",K);return new Response(W.method==="HEAD"?null:I.body,{status:200,headers:U})}}var L2=`<!DOCTYPE html>
|
|
3
3
|
<html lang="en">
|
|
4
4
|
<head>
|
|
5
5
|
<meta charset="UTF-8" />
|
package/dist/facades/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ig as r,Jg as s,Kg as t,Lg as u,Pf as a,Sf as c,Tf as e,Uf as f,Vf as h,Wf as i,Xf as j,cg as k,dg as l,eg as m,fg as n,gg as o,hg as p,uh as v,xg as q}from"../chunk-
|
|
2
|
+
import{Ig as r,Jg as s,Kg as t,Lg as u,Pf as a,Sf as c,Tf as e,Uf as f,Vf as h,Wf as i,Xf as j,cg as k,dg as l,eg as m,fg as n,gg as o,hg as p,uh as v,xg as q}from"../chunk-hd9yny4q.js";import"../chunk-jkhtybga.js";import"../chunk-mgvrfhy8.js";import{xj as d}from"../chunk-vjqpcet2.js";import"../chunk-jqqyj6cr.js";import{Ij as b,Mj as g}from"../chunk-30zs008n.js";import"../chunk-m4wagwhr.js";import"../chunk-6xt7w9bb.js";import"../chunk-c5kd7eac.js";import"../chunk-9bjggtdt.js";import"../chunk-efnerp0c.js";import"../chunk-0zakpsep.js";import"../chunk-djhr379j.js";import"../chunk-qgka1mvf.js";import"../chunk-znh1mbqs.js";import"../chunk-g0mxdh2x.js";import"../chunk-7ka1abkd.js";import"../chunk-6fpjc2eg.js";import"../chunk-dqb257xv.js";import"../chunk-1v1ek1ey.js";import"../chunk-0dp6jvrg.js";import"../chunk-x8by5j7p.js";import"../chunk-kfcz4qa8.js";import"../chunk-30jcs49q.js";export{f as Url,d as Storage,r as Runs,j as Redis,a as Redirect,l as RateLimiter,e as Query,h as Meta,g as Log,m as Lock,c as Lang,s as Features,b as Facade,u as DB,n as Crypt,i as Cookie,o as Connections,t as ConnectionQueries,p as ChangeFeed,k as Cache,q as Broadcast,v as Auth};
|
|
3
3
|
|
|
4
4
|
//# debugId=5390D81B4718E18C64756E2164756E21
|
package/dist/http/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ah as ea,Bh as fa,Ch as ga,Dh as ha,Eh as ia,Fh as ja,Gh as ka,Hh as la,Ih as ma,Jh as na,Kh as oa,Lh as pa,Mh as qa,Nf as K,Nh as ra,Of as L,Oh as sa,Ph as ta,Qf as M,Qh as ua,Rf as N,Rh as va,Tg as aa,Ve as t,We as u,Xe as v,Ye as w,Ze as x,_e as E,df as F,hf as G,if as H,jf as I,kf as J,vh as ba,wh as ca,xh as da}from"../chunk-
|
|
2
|
+
import{Ah as ea,Bh as fa,Ch as ga,Dh as ha,Eh as ia,Fh as ja,Gh as ka,Hh as la,Ih as ma,Jh as na,Kh as oa,Lh as pa,Mh as qa,Nf as K,Nh as ra,Of as L,Oh as sa,Ph as ta,Qf as M,Qh as ua,Rf as N,Rh as va,Tg as aa,Ve as t,We as u,Xe as v,Ye as w,Ze as x,_e as E,df as F,hf as G,if as H,jf as I,kf as J,vh as ba,wh as ca,xh as da}from"../chunk-hd9yny4q.js";import"../chunk-jkhtybga.js";import"../chunk-mgvrfhy8.js";import{Ai as i,Bi as j,Ei as n,Ji as o,Ki as p,Li as q,Mi as r,Ri as s,Ti as y,Ui as z,Vi as A,Wi as B,Xi as C,Yi as D,gj as O,hj as P,ij as Q,jj as R,kj as S,lj as T,mj as U,nj as V,oj as W,pi as a,pj as X,qi as b,qj as Y,ri as d,sj as Z,tj as _,uj as $,wi as e,xi as f,yi as g,zi as h}from"../chunk-vjqpcet2.js";import{Bj as c}from"../chunk-jqqyj6cr.js";import"../chunk-30zs008n.js";import{Pj as k,Qj as l,Rj as m}from"../chunk-m4wagwhr.js";import"../chunk-6xt7w9bb.js";import"../chunk-c5kd7eac.js";import"../chunk-9bjggtdt.js";import"../chunk-efnerp0c.js";import"../chunk-0zakpsep.js";import"../chunk-djhr379j.js";import"../chunk-qgka1mvf.js";import"../chunk-znh1mbqs.js";import"../chunk-g0mxdh2x.js";import"../chunk-7ka1abkd.js";import"../chunk-6fpjc2eg.js";import"../chunk-dqb257xv.js";import"../chunk-1v1ek1ey.js";import"../chunk-0dp6jvrg.js";import"../chunk-x8by5j7p.js";import"../chunk-kfcz4qa8.js";import"../chunk-30jcs49q.js";export{g as toRangeHeaderValue,v as toMiddlewareList,k as stateKey,$ as safeFetch,f as resolveRange,e as parseRangeHeader,h as parseContentRange,r as parseByteSize,ja as middlewareConfigDefaults,u as httpError,d as getCookies,j as formatUnsatisfiedContentRange,i as formatContentRange,ra as defineResourcePolicy,ia as defineMiddlewareConfig,n as cspNonce,w as createUnsatisfiableResponse,x as createStreamResponse,M as createFileResponse,I as clientIp,J as clientAddress,Z as classifyAddress,da as authorizeChannel,N as ViewRouter,o as ValidationError,W as TooManyRedirectsError,U as TooLargeError,T as TimeoutError,sa as SitemapError,ta as Sitemap,L as SameSiteBounceMiddleware,_ as SafeResponse,O as SafeFetchError,K as SAME_SITE_BOUNCE_PARAM,ua as RobotsTxt,va as Robots,qa as ResourcePolicy,b as ResourceController,m as RequestState,c as RequestBreakerError,H as RateLimitMiddleware,F as RateLimitExceededError,A as RangeNotSatisfiableError,oa as PoliciesServiceProvider,pa as Policies,q as PayloadTooLargeError,B as NotFoundError,X as NetworkError,l as MissingRequestStateError,G as Middleware,ga as McpToolDeclaration,ha as McpRouter,fa as McpRouteDeclaration,ea as McpModelParam,p as InvalidValidationRuleError,P as InvalidUrlError,z as InsufficientPermissionsError,Y as HttpStatusError,t as HttpResponse,s as HttpRequest,C as FileNotFoundError,S as DnsError,ma as CorsMiddleware,a as Controller,V as ContentTypeError,ca as ChannelRouter,ba as ChannelDeclaration,la as CacheMiddleware,na as CSRFMiddleware,aa as BodyLimitMiddleware,Q as BlockedHostError,R as BlockedAddressError,y as AuthorizationError,ka as AuthenticationMiddleware,D as AuthenticationError,E as ApiRouter};
|
|
3
3
|
|
|
4
4
|
//# debugId=1D843BB4F9206B5E64756E2164756E21
|
package/dist/i18n/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ra as T}from"../chunk-b9gwjs4r.js";import"../chunk-hke4hzfm.js";import{pb as D}from"../chunk-rqzpxeb5.js";import{Se as b,Te as w}from"../chunk-xkrfxcm7.js";import"../chunk-7g3r55sj.js";import{Sf as j}from"../chunk-
|
|
2
|
+
import{ra as T}from"../chunk-b9gwjs4r.js";import"../chunk-hke4hzfm.js";import{pb as D}from"../chunk-rqzpxeb5.js";import{Se as b,Te as w}from"../chunk-xkrfxcm7.js";import"../chunk-7g3r55sj.js";import{Sf as j}from"../chunk-hd9yny4q.js";import"../chunk-jkhtybga.js";import"../chunk-mgvrfhy8.js";import"../chunk-vjqpcet2.js";import"../chunk-jqqyj6cr.js";import"../chunk-30zs008n.js";import"../chunk-m4wagwhr.js";import"../chunk-6xt7w9bb.js";import"../chunk-c5kd7eac.js";import"../chunk-9bjggtdt.js";import"../chunk-efnerp0c.js";import"../chunk-0zakpsep.js";import"../chunk-djhr379j.js";import"../chunk-qgka1mvf.js";import"../chunk-znh1mbqs.js";import"../chunk-g0mxdh2x.js";import{gm as V,hm as X,im as E,jm as L,km as R,lm as S}from"../chunk-7ka1abkd.js";import"../chunk-6fpjc2eg.js";import"../chunk-dqb257xv.js";import"../chunk-1v1ek1ey.js";import"../chunk-0dp6jvrg.js";import"../chunk-x8by5j7p.js";import"../chunk-kfcz4qa8.js";import"../chunk-30jcs49q.js";import{createElement as J,Fragment as M,isValidElement as U}from"react";function $(q,B){let G=Object.values(B).some((z)=>typeof z==="function"&&U(z(""))),Q=/{{([^{}]+?)(?::([^{}\[\]]+?))?(?:\[(.*?)\])?}}/g;if(!G)return q.replace(Q,(W,O,_,Z)=>{let C=O.includes(":")?O.split(":")[0]:O,H=B[C];if(H===void 0)return W;if(typeof H==="function"){let K=H(Z!==void 0?Z:"");if(U(K))throw Error("JSX returned in string context");return String(K)}if(_)switch(_.toLowerCase()){case"number":return Number(H).toString();case"string":return String(H);case"boolean":return Boolean(H).toString();default:return String(H)}return String(H)});else{let z=[],W=0,O=null;while((O=Q.exec(q))!==null){let[_,Z,C,H]=O,F=O.index,K=Z.includes(":")?Z.split(":")[0]:Z;if(F>W)z.push(q.substring(W,F));let Y=B[K];if(Y===void 0)z.push(_);else if(typeof Y==="function"){let A=Y(H!==void 0?H:"");z.push(A)}else if(C)switch(C.toLowerCase()){case"number":z.push(Number(Y).toString());break;case"string":z.push(String(Y));break;case"boolean":z.push(Boolean(Y).toString());break;default:z.push(String(Y))}else z.push(String(Y));W=F+_.length}if(W<q.length)z.push(q.substring(W));return J(M,{},...z)}}class P{name;dictionary;constructor(q,B){this.name=q;this.dictionary=B}reference(q){if(typeof window<"u")throw Error("Cannot use reference in the browser");if(!this.dictionary?.[q])throw Error(`Translation not found for ${String(q)}`);return this.dictionary[q]}render(q,...B){let{locale:G=j.locale(),params:Q}={params:{},...B[0]};if(typeof window<"u")throw Error("Cannot use render in the browser");if(!this.dictionary?.[q]?.[G])throw Error(`Translation not found for ${String(q)} in ${String(G)}`);return $(this.dictionary[q][G],Q??{})}static create(q,B){return new P(q,B)}static text(q,...B){let{locale:G=j.locale(),params:Q}={params:{},...B?.[0]};if(!q?.[G])throw Error(`Translation not found for ${String(G)}`);return $(q[G],Q??{})}}async function N(q,B,...G){let{locale:Q=j.locale(),params:z}={params:{},...G[0]},O=(await q.load(String(Q)))[B];if(typeof O!=="string")throw Error(`Translation not found for "${B}" in "${String(Q)}" (dictionary ${q.id})`);return $(O,z??{})}export{w as translationConfigDefaults,N as translate,V as resolveLocale,X as negotiateLocale,L as isValidTimeZone,b as defineTranslationConfig,T as defineDictionary,R as createFormatter,S as Translator,D as TranslationServiceProvider,P as Dictionary,E as DEFAULT_TIME_ZONE};
|
|
3
3
|
|
|
4
4
|
//# debugId=7747E1C7C4FBB69464756E2164756E21
|
package/dist/kernel/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ta as E}from"../chunk-kspqqyv1.js";import{ob as l}from"../chunk-11yrxwkt.js";import{pb as H}from"../chunk-rqzpxeb5.js";import{$b as I,Cb as g,Db as W,Eb as _,Fb as p,Gb as P,Hb as u,Ib as $,Jb as V,Kb as q,Lb as B,Mb as K,Qb as L,Rb as Q,Sb as T,Wb as U,Xb as y,Yb as F,Zb as C,_b as D,cc as b,fc as f,gc as k,hc as m}from"../chunk-
|
|
2
|
+
import{Ta as E}from"../chunk-kspqqyv1.js";import{ob as l}from"../chunk-11yrxwkt.js";import{pb as H}from"../chunk-rqzpxeb5.js";import{$b as I,Cb as g,Db as W,Eb as _,Fb as p,Gb as P,Hb as u,Ib as $,Jb as V,Kb as q,Lb as B,Mb as K,Qb as L,Rb as Q,Sb as T,Wb as U,Xb as y,Yb as F,Zb as C,_b as D,cc as b,fc as f,gc as k,hc as m}from"../chunk-1eha67ey.js";import"../chunk-607nk925.js";import"../chunk-x6fa13e1.js";import"../chunk-kpmp5hmc.js";import"../chunk-a2y481gh.js";import{Me as h}from"../chunk-c71dr883.js";import"../chunk-xkrfxcm7.js";import"../chunk-7g3r55sj.js";import{Lf as n,Mf as v,kh as w,oh as A,pf as d,qf as s,sh as R}from"../chunk-hd9yny4q.js";import"../chunk-jkhtybga.js";import"../chunk-mgvrfhy8.js";import"../chunk-vjqpcet2.js";import"../chunk-jqqyj6cr.js";import"../chunk-30zs008n.js";import"../chunk-m4wagwhr.js";import"../chunk-6xt7w9bb.js";import{dk as M}from"../chunk-c5kd7eac.js";import"../chunk-9bjggtdt.js";import"../chunk-efnerp0c.js";import"../chunk-0zakpsep.js";import"../chunk-djhr379j.js";import"../chunk-qgka1mvf.js";import"../chunk-znh1mbqs.js";import"../chunk-g0mxdh2x.js";import"../chunk-qqe19gtm.js";import"../chunk-7ka1abkd.js";import{mm as O,om as J}from"../chunk-6fpjc2eg.js";import"../chunk-dqb257xv.js";import"../chunk-1v1ek1ey.js";import"../chunk-0dp6jvrg.js";import"../chunk-x8by5j7p.js";import"../chunk-kfcz4qa8.js";import"../chunk-30jcs49q.js";var N=[C,I,E,T,L,k,B,Q,D,y,_,U,f,V,F,H,b,K,q,m,$];class S{config={};providers=[];services=[];serviceInstances=[];serviceTokens=new Set;servicesBooted=!1;models=[];app=new J;boot(){if(this.models.length>0)l(...this.models);else a();this.app.config.merge(this.config),J.setInstance(this.app),this.app.registerMany([...N,...this.providers]),this.registerServices()}registerServices(){let j=this.serviceTokens;this.serviceInstances=[],this.serviceTokens=new Set,this.servicesBooted=!1;let X=new Map;for(let z of this.services){let G=typeof z==="function"?new z:z,x=G.constructor;if(!x.token)throw Error(`Service [${x.name}] is listed in \`services\` but does not declare a \`static token\`.`);let Y=X.get(x.token);if(Y)throw Error(`Services [${Y}] and [${x.name}] both declare the token "${x.token}". Tokens are the container's keys, so they must be unique.`);X.set(x.token,x.name);let Z=x;if(!j.has(x.token)&&this.app.bound(Z))throw Error(`Service [${x.name}] declares the token "${x.token}", which is already bound in the container by the framework or a provider. Binding it would replace that service everywhere, so pick a token nothing else owns.`);this.app.instance(Z,G),this.serviceInstances.push(G),this.serviceTokens.add(x.token)}this.app.setShutdownHooks(this.serviceInstances.map((z)=>({name:`${z.constructor.name}.onShutdown`,shutdown:(G)=>z.onShutdown(G)})))}async waitForBoot(){await this.app.boot(),await this.bootServices(),p(this.app)}async bootServices(){if(this.servicesBooted)return;for(let j of this.serviceInstances)await j.boot();this.servicesBooted=!0}shutdown(j){return this.run(()=>this.app.shutdown(j))}run(j){return O.run(this.app,j)}resolve(j){return this.app.make(j)}apiRoutes(){return this.app.make(A)}viewRoutes(){return this.app.make(w)}domains(){return this.app.make(R)}queue(){return this.app.make(h)}mcpHttp(){return this.app.config.get("route.mcp.remote.enabled")===!0?this.app.make(g):null}sockets(){return this.app.config.get("route.channels")?this.app.make(u):null}globalMiddleware(j){return P(j)}destroy(){if(this.app.resolved(W))this.app.make(W).stop();if(this.app.flush(),J.getInstance()===this.app)J.setInstance(void 0);O.disable()}}function a(){if(Bun.env.NODE_ENV==="production")return;let j=M();if(j.length===0)return;console.warn(`[gemi] ${j.length} model${j.length===1?" is":"s are"} registered, but Kernel.models is empty.
|
|
3
3
|
Nested relation reads resolve a model by name, so a policy on a subclass that does not own its
|
|
4
4
|
`+" name is skipped inside every include \u2014 scoped at the root, "+`unscoped in an include, with nothing
|
|
5
5
|
to notice it. Declaring the modules registers each class under its own name and audits the set:
|
package/dist/server/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ra as f}from"../chunk-ba1h9pm6.js";import{Sa as A}from"../chunk-jrvqya5h.js";import{Am as q,Bm as w,Em as Z,Fm as P,Gm as y,Hm as S,Im as U,ym as Q}from"../chunk-0dp6jvrg.js";import{Mm as H}from"../chunk-x8by5j7p.js";import"../chunk-kfcz4qa8.js";import{Um as F}from"../chunk-30jcs49q.js";var x="/__gemi__/health",$=Symbol.for("gemi.server.health");function V(){let z=globalThis;return z[$]??={lagMs:0,consecutiveBreaches:0,degraded:!1,timer:void 0},z[$]}function W(){let z=V(),B=Q();return{healthy:!B&&!z.degraded,shuttingDown:B,lagMs:z.lagMs,consecutiveBreaches:z.consecutiveBreaches}}function E(z,B){let I=V();I.lagMs=z,I.consecutiveBreaches=z>B.maxLagMs?I.consecutiveBreaches+1:0;let J=I.consecutiveBreaches>=B.breaches;if(J&&!I.degraded)console.warn(`[gemi] Health: degraded (event-loop lag ${Math.round(z)}ms, ${I.consecutiveBreaches} samples in a row over ${B.maxLagMs}ms).`);else if(!J&&I.degraded)console.log(`[gemi] Health: recovered (event-loop lag ${Math.round(z)}ms).`);I.degraded=J}function G(z){let B=V();if(B.timer)return;let I=performance.now()+z.intervalMs;B.timer=setInterval(()=>{let J=performance.now();E(Math.max(0,J-I),z),I=J+z.intervalMs},z.intervalMs),B.timer.unref?.()}function _(z=process.env){return{paths:D(z.GEMI_HEALTH_PATH),intervalMs:O("GEMI_HEALTH_INTERVAL_MS",z.GEMI_HEALTH_INTERVAL_MS,500),maxLagMs:O("GEMI_HEALTH_MAX_LAG_MS",z.GEMI_HEALTH_MAX_LAG_MS,1000),breaches:Math.ceil(O("GEMI_HEALTH_BREACHES",z.GEMI_HEALTH_BREACHES,3))}}function D(z){if(z===void 0||z.trim()==="")return[x];if(z.trim().toLowerCase()==="off")return[];let B=z.split(",").map((J)=>J.trim()).filter(Boolean);if(B.filter((J)=>!J.startsWith("/")).length>0)throw Error(`GEMI_HEALTH_PATH: expected comma-separated paths starting with "/", or "off"; got ${JSON.stringify(z)}.`);return B}function O(z,B,I){if(B===void 0||B.trim()==="")return I;let J=Number(B);if(Number.isFinite(J)&&J>0)return J;return console.warn(`[gemi] Ignoring ${z}="${B}": expected a positive number.`),I}function j(z,B){if(B.length===0)return z;let I=new Set(B);return async(J,K)=>{if(!B.some((b)=>J.url.includes(b))||!I.has(new URL(J.url).pathname))return z(J,K);return y(R(J.method))}}function R(z){let B={"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"};if(z!=="GET"&&z!=="HEAD")return new Response("Method Not Allowed",{status:405,headers:{...B,Allow:"GET, HEAD"}});let{healthy:I,shuttingDown:J}=W();return new Response(z==="HEAD"?null:I?"ok":J?"shutting down":"degraded",{status:I?200:503,headers:B})}var L=Symbol.for("gemi.server.devGeneration"),X={graceMs:1e4,providerTimeoutMs:5000};class Y{app;inFlight=0;waiters=new Set;constructor(z){this.app=z}track(z){return async(B,I)=>{this.inFlight++;try{return await z(B,I)}finally{if(this.inFlight--,this.inFlight===0)this.wake()}}}get pending(){return this.inFlight}async retire({graceMs:z,providerTimeoutMs:B}){try{await this.idle(z),await Promise.resolve().then(()=>this.app.shutdown({timeoutMs:B}))}catch(I){C(I)}}idle(z){if(this.inFlight===0)return Promise.resolve();return new Promise((B)=>{let I=()=>{clearTimeout(J),this.waiters.delete(I),B()},J=setTimeout(I,z);this.waiters.add(I)})}wake(){for(let z of this.waiters)z()}}function N(z,B=X){let I=globalThis,J=I[L];if(I[L]=z,!J||J===z||typeof J.retire!=="function")return Promise.resolve();let K=J.retire.bind(J);return Promise.resolve().then(()=>K(B)).catch(C)}function C(z){console.error("[gemi] Shutting down the application a reload replaced failed:",z)}class k{app;instrumentation;handleSignals;server;stopping;settings;constructor(z){this.app=new A({kernel:z.kernel}),this.handleSignals=z.handleSignals??!0,this.instrumentation=S(z.instrumentation??((B,I)=>I(B)))}async start(){process.env.ROOT_DIR=H();let z=Bun.env.NODE_ENV==="production",B=_();if(z)G(B);let I=j(this.instrumentation,B.paths);if(z){if(this.handleSignals)U(()=>this.stop());this.settings=Z()}try{await this.app.waitForBoot()}catch(J){if(!z)this.app.shutdown({timeoutMs:X.providerTimeoutMs});throw J}if(z){let{httpProd:J}=await import("../chunk-
|
|
2
|
+
import{Ra as f}from"../chunk-ba1h9pm6.js";import{Sa as A}from"../chunk-jrvqya5h.js";import{Am as q,Bm as w,Em as Z,Fm as P,Gm as y,Hm as S,Im as U,ym as Q}from"../chunk-0dp6jvrg.js";import{Mm as H}from"../chunk-x8by5j7p.js";import"../chunk-kfcz4qa8.js";import{Um as F}from"../chunk-30jcs49q.js";var x="/__gemi__/health",$=Symbol.for("gemi.server.health");function V(){let z=globalThis;return z[$]??={lagMs:0,consecutiveBreaches:0,degraded:!1,timer:void 0},z[$]}function W(){let z=V(),B=Q();return{healthy:!B&&!z.degraded,shuttingDown:B,lagMs:z.lagMs,consecutiveBreaches:z.consecutiveBreaches}}function E(z,B){let I=V();I.lagMs=z,I.consecutiveBreaches=z>B.maxLagMs?I.consecutiveBreaches+1:0;let J=I.consecutiveBreaches>=B.breaches;if(J&&!I.degraded)console.warn(`[gemi] Health: degraded (event-loop lag ${Math.round(z)}ms, ${I.consecutiveBreaches} samples in a row over ${B.maxLagMs}ms).`);else if(!J&&I.degraded)console.log(`[gemi] Health: recovered (event-loop lag ${Math.round(z)}ms).`);I.degraded=J}function G(z){let B=V();if(B.timer)return;let I=performance.now()+z.intervalMs;B.timer=setInterval(()=>{let J=performance.now();E(Math.max(0,J-I),z),I=J+z.intervalMs},z.intervalMs),B.timer.unref?.()}function _(z=process.env){return{paths:D(z.GEMI_HEALTH_PATH),intervalMs:O("GEMI_HEALTH_INTERVAL_MS",z.GEMI_HEALTH_INTERVAL_MS,500),maxLagMs:O("GEMI_HEALTH_MAX_LAG_MS",z.GEMI_HEALTH_MAX_LAG_MS,1000),breaches:Math.ceil(O("GEMI_HEALTH_BREACHES",z.GEMI_HEALTH_BREACHES,3))}}function D(z){if(z===void 0||z.trim()==="")return[x];if(z.trim().toLowerCase()==="off")return[];let B=z.split(",").map((J)=>J.trim()).filter(Boolean);if(B.filter((J)=>!J.startsWith("/")).length>0)throw Error(`GEMI_HEALTH_PATH: expected comma-separated paths starting with "/", or "off"; got ${JSON.stringify(z)}.`);return B}function O(z,B,I){if(B===void 0||B.trim()==="")return I;let J=Number(B);if(Number.isFinite(J)&&J>0)return J;return console.warn(`[gemi] Ignoring ${z}="${B}": expected a positive number.`),I}function j(z,B){if(B.length===0)return z;let I=new Set(B);return async(J,K)=>{if(!B.some((b)=>J.url.includes(b))||!I.has(new URL(J.url).pathname))return z(J,K);return y(R(J.method))}}function R(z){let B={"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"};if(z!=="GET"&&z!=="HEAD")return new Response("Method Not Allowed",{status:405,headers:{...B,Allow:"GET, HEAD"}});let{healthy:I,shuttingDown:J}=W();return new Response(z==="HEAD"?null:I?"ok":J?"shutting down":"degraded",{status:I?200:503,headers:B})}var L=Symbol.for("gemi.server.devGeneration"),X={graceMs:1e4,providerTimeoutMs:5000};class Y{app;inFlight=0;waiters=new Set;constructor(z){this.app=z}track(z){return async(B,I)=>{this.inFlight++;try{return await z(B,I)}finally{if(this.inFlight--,this.inFlight===0)this.wake()}}}get pending(){return this.inFlight}async retire({graceMs:z,providerTimeoutMs:B}){try{await this.idle(z),await Promise.resolve().then(()=>this.app.shutdown({timeoutMs:B}))}catch(I){C(I)}}idle(z){if(this.inFlight===0)return Promise.resolve();return new Promise((B)=>{let I=()=>{clearTimeout(J),this.waiters.delete(I),B()},J=setTimeout(I,z);this.waiters.add(I)})}wake(){for(let z of this.waiters)z()}}function N(z,B=X){let I=globalThis,J=I[L];if(I[L]=z,!J||J===z||typeof J.retire!=="function")return Promise.resolve();let K=J.retire.bind(J);return Promise.resolve().then(()=>K(B)).catch(C)}function C(z){console.error("[gemi] Shutting down the application a reload replaced failed:",z)}class k{app;instrumentation;handleSignals;server;stopping;settings;constructor(z){this.app=new A({kernel:z.kernel}),this.handleSignals=z.handleSignals??!0,this.instrumentation=S(z.instrumentation??((B,I)=>I(B)))}async start(){process.env.ROOT_DIR=H();let z=Bun.env.NODE_ENV==="production",B=_();if(z)G(B);let I=j(this.instrumentation,B.paths);if(z){if(this.handleSignals)U(()=>this.stop());this.settings=Z()}try{await this.app.waitForBoot()}catch(J){if(!z)this.app.shutdown({timeoutMs:X.providerTimeoutMs});throw J}if(z){let{httpProd:J}=await import("../chunk-vsr08sbe.js");this.server=await J(this.app,I)}else{f();let{httpDev:J}=await import("../chunk-6j439skq.js"),K=new Y(this.app);this.server=await J(this.app,K.track(I)),N(K)}return this.server}stop(z={}){let B=this.app.sockets();return this.stopping??=P({server:this.server,closeSockets:B?()=>B.shutdown():void 0,shutdownProviders:(I)=>this.app.shutdown(I),settings:{...this.settings??Z(),...z}}),this.stopping}}export{q as shutdownSignal,W as liveness,Q as isShuttingDown,w as holdShutdown,k as Server};
|
|
3
3
|
|
|
4
4
|
//# debugId=B8D428333312557264756E2164756E21
|
package/dist/services/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{rb as j$}from"../chunk-g6tqje74.js";import{$b as $$,Ab as m4,Bb as o1,Cb as U9,Db as x9,Eb as h9,Ib as E9,Jb as g9,Kb as m9,Lb as c9,Mb as d9,Nb as l9,Ob as n9,Pb as i9,Qb as s9,Rb as o9,Sb as a9,Tb as i4,Ub as A6,Vb as h,Wb as t9,Xb as r9,Yb as e9,Zb as W$,_b as Z$,ac as Q$,bc as Y$,cc as K$,dc as J$,ec as z$,fc as G$,gc as X$,hc as B$,sb as F9,tb as M9,ub as L9,vb as D9,wb as H9,xb as p4,yb as N9,zb as g4}from"../chunk-vwnrha3f.js";import{kc as l4}from"../chunk-957arkj0.js";import"../chunk-x6fa13e1.js";import{de as S9,ee as R9,fe as O9,ge as _9,he as V9,ie as C9,je as T9,ke as P9,le as b9,me as q9,ne as w9,oe as v9,pe as I9,qe as f9,re as y9,se as A9}from"../chunk-kpmp5hmc.js";import{te as k9}from"../chunk-a2y481gh.js";import{Ae as rZ,Be as eZ,Ce as W9,De as Z9,Ee as $9,Fe as Q9,Ge as Y9,He as K9,Ie as J9,Je as z9,Ke as G9,Le as X9,Me as B9,Re as j9,ue as q4,ve as iZ,we as sZ,xe as oZ,ye as aZ,ze as tZ}from"../chunk-c71dr883.js";import{Se as u9,Te as p9}from"../chunk-xkrfxcm7.js";import"../chunk-7g3r55sj.js";import{$e as P6,$f as A8,Af as L8,Ag as NZ,Bf as D8,Bg as UZ,Cf as H8,Cg as xZ,Df as N8,Dg as SZ,Ef as K6,Eg as RZ,Eh as cZ,Ff as U8,Fg as OZ,Fh as uZ,Gf as x8,Gg as _Z,Hf as S8,Hg as VZ,If as R8,Jf as O8,Mg as R,Ng as i,Og as kZ,Pg as CZ,Qg as TZ,Rg as PZ,Sg as bZ,Ug as qZ,Vg as wZ,Wg as vZ,Xg as IZ,Yf as I8,Zf as f8,Zg as fZ,_f as y8,af as K8,ag as h8,ah as yZ,bf as J8,bg as E8,bh as AZ,cf as z8,ch as hZ,ef as G8,fh as EZ,ig as KZ,jg as y6,kf as b6,kg as JZ,kh as gZ,lf as T4,mf as j6,nf as T1,of as P4,og as zZ,oh as mZ,pg as GZ,qg as BZ,sf as E6,sh as s4,tf as g6,tg as jZ,th as z1,ug as FZ,vf as X8,vg as MZ,wf as B8,wg as LZ,xf as j8,yf as F8,yg as DZ,zf as M8,zg as HZ}from"../chunk-vsh9jck0.js";import"../chunk-jkhtybga.js";import"../chunk-mgvrfhy8.js";import{$i as C1,Ri as E4,Vi as j1,Xi as Y1,_i as V4,aj as d1,bj as _8,cj as V8,dj as k8,ej as C8,fj as T8,rj as dW,sj as lW,vj as P8,wj as b8,xi as C4,yi as _4,yj as l1,zi as k1}from"../chunk-vjqpcet2.js";import"../chunk-jqqyj6cr.js";import{Jj as q8,Kj as w8,Lj as v8,Mj as L6}from"../chunk-30zs008n.js";import{Nj as w}from"../chunk-m4wagwhr.js";import{$j as o8,Vj as l8,Wj as n8,Xj as U,Yj as i8,Zj as b,_j as s8}from"../chunk-6xt7w9bb.js";import{fk as u8,gk as p8,hk as d8}from"../chunk-c5kd7eac.js";import"../chunk-9bjggtdt.js";import{Qk as XZ}from"../chunk-efnerp0c.js";import{Sk as g8,Tk as m8,Uk as c8,Vk as a8,Wk as t8,Xk as r8,Yk as e8,Zk as WZ,_k as ZZ,dl as $Z,el as QZ,fl as YZ}from"../chunk-0zakpsep.js";import"../chunk-djhr379j.js";import"../chunk-qgka1mvf.js";import{Rl as M6}from"../chunk-znh1mbqs.js";import"../chunk-g0mxdh2x.js";import{am as w4,bm as pZ,cm as dZ,dm as lZ,fm as nZ}from"../chunk-qqe19gtm.js";import"../chunk-7ka1abkd.js";import{pm as C}from"../chunk-6fpjc2eg.js";import"../chunk-dqb257xv.js";import"../chunk-1v1ek1ey.js";import"../chunk-0dp6jvrg.js";import"../chunk-x8by5j7p.js";import"../chunk-kfcz4qa8.js";import{Um as p1}from"../chunk-30jcs49q.js";import{Buffer as J6}from"buffer";class z6 extends C1{client;config;constructor(...W){super();this.config=W}async connect(){let W=await import("../chunk-65wnm25z.js");return this.client??=new W.S3Client(...this.config),{sdk:W,client:this.client}}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,Q,Y,K=process.env.BUCKET_NAME;if(W instanceof Blob)$=W,Y=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,Q=W.type;else $=W.body,Y=W.name,K=W.bucket??K,Q=W.contentType||($ instanceof Blob||$ instanceof File?$.type:void 0);Q=Q||void 0;let J=$ instanceof J6?$:$ instanceof Blob||$ instanceof File?J6.from(await $.arrayBuffer()):"",{sdk:z,client:G}=await this.connect();return Z?.throwIfAborted(),await G.send(new z.PutObjectCommand({Bucket:K,Key:Y,Body:J,ContentType:Q}),{abortSignal:Z}),Y}async delete(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME;if(!Z)throw Error("Object name has to be specified");let{sdk:Q,client:Y}=await this.connect();try{await Y.send(new Q.DeleteObjectCommand({Bucket:$,Key:Z}))}catch(K){if(K?.name==="NoSuchKey"||K?.$metadata?.httpStatusCode===404)return;throw K}}async*pages(W,{bucket:Z,signal:$}){let{sdk:Q,client:Y}=await this.connect(),K;do{$?.throwIfAborted();let J=await Y.send(new Q.ListObjectsV2Command({Bucket:Z??process.env.BUCKET_NAME,Prefix:W,ContinuationToken:K}),{abortSignal:$});yield(J.Contents??[]).map((z)=>({name:z.Key,size:z.Size??0,lastModified:z.LastModified??new Date(0)})),K=J.IsTruncated?J.NextContinuationToken:void 0}while(K)}async*objects(W,Z={}){for await(let $ of this.pages(W,Z))yield*$}async deletePrefix(W,Z={}){V4(W);let $=Z.bucket??process.env.BUCKET_NAME,{sdk:Q,client:Y}=await this.connect(),K=0;for await(let J of this.pages(W,{...Z,bucket:$})){if(J.length===0)continue;Z.signal?.throwIfAborted();let G=(await Y.send(new Q.DeleteObjectsCommand({Bucket:$,Delete:{Objects:J.map((X)=>({Key:X.name})),Quiet:!0}}),{abortSignal:Z.signal}))?.Errors??[];if(G.length>0){let X=G[0];throw Error(`S3 could not delete ${G.length} object(s) under "${W}", e.g. "${X.Key}": ${X.Code??"unknown"} ${X.Message??""}`.trim())}K+=J.length}return K}async list(W){let{sdk:Z,client:$}=await this.connect();return await $.send(new Z.ListObjectsV2Command({Bucket:process.env.BUCKET_NAME,Prefix:W}))}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=process.env.BUCKET_NAME,Q;if(typeof W==="string")Q=W;else $=W.bucket??$,Q=W.name;if(!Q)throw Error("Object name has to be specified");let{sdk:Y,client:K}=await this.connect();Z?.throwIfAborted();let J=await K.send(new Y.GetObjectCommand({Bucket:$,Key:Q}),{abortSignal:Z}),z=d1(J.Body.transformToWebStream(),Z);return Z?.throwIfAborted(),new Response(z,{headers:{"Content-Type":J.ContentType,"Content-Length":J.ContentLength.toString(),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":J.LastModified?.toUTCString()||"",ETag:J.ETag||""}})}async read(W){let Z=typeof W==="string"?{name:W}:W,$=Z.bucket??process.env.BUCKET_NAME,{name:Q,range:Y=null}=Z;if(!Q)throw Error("Object name has to be specified");let{sdk:K,client:J}=await this.connect(),z;try{z=await J.send(new K.GetObjectCommand({Bucket:$,Key:Q,Range:Y?_4(Y):void 0}))}catch(j){if(j?.name==="InvalidRange"||j?.$metadata?.httpStatusCode===416)throw new j1(await this.size({name:Q,bucket:$}));if(j?.name==="NoSuchKey"||j?.$metadata?.httpStatusCode===404)throw new Y1(Q);throw j}let G=k1(z.ContentRange),X=Boolean(G)&&z.$metadata?.httpStatusCode===206,B=G?.total??z.ContentLength??0;return{body:z.Body.transformToWebStream(),start:G?.start??0,end:G?.end??B-1,total:B,partial:X,type:z.ContentType??"application/octet-stream",etag:z.ETag||void 0,lastModified:z.LastModified,name:Q}}async size(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME,{sdk:Q,client:Y}=await this.connect();try{return(await Y.send(new Q.HeadObjectCommand({Bucket:$,Key:Z}))).ContentLength??0}catch(K){if(K?.name==="NotFound"||K?.$metadata?.httpStatusCode===404)throw new Y1(Z);throw K}}}import{Buffer as G6}from"buffer";import{Readable as sW}from"stream";function k4(W){return W?.statusCode===404||W?.details?.errorCode==="BlobNotFound"||W?.code==="BlobNotFound"}function oW(W){return W?.statusCode===416||W?.details?.errorCode==="InvalidRange"||W?.code==="InvalidRange"}class X6 extends C1{config;serviceClientPromise=null;constructor(W={}){super();this.config=W}async serviceClient(){if(this.config.serviceClient)return this.config.serviceClient;return this.serviceClientPromise??=(async()=>{let W;try{W=await import("@azure/storage-blob")}catch{throw Error("AzureBlobDriver requires the '@azure/storage-blob' package. Install it with `bun add @azure/storage-blob`, or pass a pre-built `serviceClient`.")}let Z=this.config.connectionString??process.env.AZURE_STORAGE_CONNECTION_STRING;if(this.config.url)return new W.BlobServiceClient(this.config.url,this.config.credential);if(Z)return W.BlobServiceClient.fromConnectionString(Z);throw Error("AzureBlobDriver needs a connection string (AZURE_STORAGE_CONNECTION_STRING), a `url`, or a `serviceClient`.")})(),this.serviceClientPromise}async blob(W,Z){if(!W)throw Error("Object name has to be specified");let $=Z??this.config.container??process.env.BUCKET_NAME;if(!$)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");return(await this.serviceClient()).getContainerClient($).getBlockBlobClient(W)}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,Q,Y,K;if(W instanceof Blob)$=W,Y=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,Q=W.type;else $=W.body,Y=W.name,K=W.bucket,Q=W.contentType??($ instanceof Blob||$ instanceof File?$.type:void 0);let J=$ instanceof G6?$:G6.from(await $.arrayBuffer()),z=await this.blob(Y,K);return Z?.throwIfAborted(),await z.uploadData(J,{blobHTTPHeaders:Q?{blobContentType:Q}:void 0,abortSignal:Z}),Y}async*objects(W,{bucket:Z,signal:$}={}){$?.throwIfAborted();let Q=Z??this.config.container??process.env.BUCKET_NAME;if(!Q)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");let K=(await this.serviceClient()).getContainerClient(Q);for await(let J of K.listBlobsFlat({prefix:W}))$?.throwIfAborted(),yield{name:J.name,size:J.properties?.contentLength??0,lastModified:J.properties?.lastModified??new Date(0)}}async list(W){let Z=this.config.container??process.env.BUCKET_NAME,Q=(await this.serviceClient()).getContainerClient(Z),Y=[];for await(let K of Q.listBlobsFlat({prefix:W}))Y.push(K.name);return Y}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=await this.download(typeof W==="string"?{name:W}:{name:W.name,bucket:W.bucket},Z);return new Response($.body,{headers:{"Content-Type":$.type,"Content-Length":String($.total),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":$.lastModified?.toUTCString()??"",ETag:$.etag??""}})}async read(W){return this.download(typeof W==="string"?{name:W}:W)}async download(W,Z){let{name:$,bucket:Q,range:Y=null}=W,K=await this.blob($,Q);Z?.throwIfAborted();let J,z,G=Y?.kind==="suffix"||Y?.kind==="offset"&&Y.end===null&&Y.start===0;if(Y&&G){let V=await this.size({name:$,bucket:Q}),Q1=C4(Y,V);if(!Q1)throw new j1(V);J=Q1.start,z=Q1.length}else if(Y?.kind==="offset")J=Y.start,z=Y.end===null?void 0:Y.end-Y.start+1;let X;try{X=await K.download(J,z,Z?{abortSignal:Z}:void 0)}catch(V){if(oW(V))throw new j1(await this.size({name:$,bucket:Q}));if(k4(V))throw new Y1($);throw V}let B=k1(X.contentRange),j=Boolean(B),D=B?.total??X.contentLength??0,x=await aW(X);if(x instanceof ReadableStream)x=d1(x,Z);return Z?.throwIfAborted(),{body:x,start:B?.start??0,end:B?.end??D-1,total:D,partial:j,type:X.contentType??"application/octet-stream",etag:X.etag||void 0,lastModified:X.lastModified,name:$}}async size(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,Q=await this.blob(Z,$);try{return(await Q.getProperties()).contentLength??0}catch(Y){if(k4(Y))throw new Y1(Z);throw Y}}async delete(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,Q=await this.blob(Z,$);try{await Q.delete()}catch(Y){if(k4(Y))return;throw Y}}}async function aW(W){if(W.blobBody)return await W.blobBody;if(W.readableStreamBody)return sW.toWeb(W.readableStreamBody);return null}function tW(W){return W}class b4 extends Error{code="ERR_RATE_LIMITER_TIMEOUT";constructor(W){super(`RedisRateLimiter: Redis did not answer within ${W}ms.`);this.name="RedisRateLimiterTimeoutError"}}class n1 extends Error{code="ERR_RATE_LIMITER_DISCONNECTED";constructor(){super("RedisRateLimiter: the Redis client is not connected.");this.name="RedisRateLimiterDisconnectedError"}}var B6=1000,rW=60000,eW=`
|
|
2
|
+
import{rb as j$}from"../chunk-g6tqje74.js";import{$b as $$,Ab as m4,Bb as o1,Cb as U9,Db as x9,Eb as h9,Ib as E9,Jb as g9,Kb as m9,Lb as c9,Mb as d9,Nb as l9,Ob as n9,Pb as i9,Qb as s9,Rb as o9,Sb as a9,Tb as i4,Ub as A6,Vb as h,Wb as t9,Xb as r9,Yb as e9,Zb as W$,_b as Z$,ac as Q$,bc as Y$,cc as K$,dc as J$,ec as z$,fc as G$,gc as X$,hc as B$,sb as F9,tb as M9,ub as L9,vb as D9,wb as H9,xb as p4,yb as N9,zb as g4}from"../chunk-1eha67ey.js";import{kc as l4}from"../chunk-607nk925.js";import"../chunk-x6fa13e1.js";import{de as S9,ee as R9,fe as O9,ge as _9,he as V9,ie as C9,je as T9,ke as P9,le as b9,me as q9,ne as w9,oe as v9,pe as I9,qe as f9,re as y9,se as A9}from"../chunk-kpmp5hmc.js";import{te as k9}from"../chunk-a2y481gh.js";import{Ae as rZ,Be as eZ,Ce as W9,De as Z9,Ee as $9,Fe as Q9,Ge as Y9,He as K9,Ie as J9,Je as z9,Ke as G9,Le as X9,Me as B9,Re as j9,ue as q4,ve as iZ,we as sZ,xe as oZ,ye as aZ,ze as tZ}from"../chunk-c71dr883.js";import{Se as u9,Te as p9}from"../chunk-xkrfxcm7.js";import"../chunk-7g3r55sj.js";import{$e as P6,$f as A8,Af as L8,Ag as NZ,Bf as D8,Bg as UZ,Cf as H8,Cg as xZ,Df as N8,Dg as SZ,Ef as K6,Eg as RZ,Eh as cZ,Ff as U8,Fg as OZ,Fh as uZ,Gf as x8,Gg as _Z,Hf as S8,Hg as VZ,If as R8,Jf as O8,Mg as R,Ng as i,Og as kZ,Pg as CZ,Qg as TZ,Rg as PZ,Sg as bZ,Ug as qZ,Vg as wZ,Wg as vZ,Xg as IZ,Yf as I8,Zf as f8,Zg as fZ,_f as y8,af as K8,ag as h8,ah as yZ,bf as J8,bg as E8,bh as AZ,cf as z8,ch as hZ,ef as G8,fh as EZ,ig as KZ,jg as y6,kf as b6,kg as JZ,kh as gZ,lf as T4,mf as j6,nf as T1,of as P4,og as zZ,oh as mZ,pg as GZ,qg as BZ,sf as E6,sh as s4,tf as g6,tg as jZ,th as z1,ug as FZ,vf as X8,vg as MZ,wf as B8,wg as LZ,xf as j8,yf as F8,yg as DZ,zf as M8,zg as HZ}from"../chunk-hd9yny4q.js";import"../chunk-jkhtybga.js";import"../chunk-mgvrfhy8.js";import{$i as C1,Ri as E4,Vi as j1,Xi as Y1,_i as V4,aj as d1,bj as _8,cj as V8,dj as k8,ej as C8,fj as T8,rj as dW,sj as lW,vj as P8,wj as b8,xi as C4,yi as _4,yj as l1,zi as k1}from"../chunk-vjqpcet2.js";import"../chunk-jqqyj6cr.js";import{Jj as q8,Kj as w8,Lj as v8,Mj as L6}from"../chunk-30zs008n.js";import{Nj as w}from"../chunk-m4wagwhr.js";import{$j as o8,Vj as l8,Wj as n8,Xj as U,Yj as i8,Zj as b,_j as s8}from"../chunk-6xt7w9bb.js";import{fk as u8,gk as p8,hk as d8}from"../chunk-c5kd7eac.js";import"../chunk-9bjggtdt.js";import{Qk as XZ}from"../chunk-efnerp0c.js";import{Sk as g8,Tk as m8,Uk as c8,Vk as a8,Wk as t8,Xk as r8,Yk as e8,Zk as WZ,_k as ZZ,dl as $Z,el as QZ,fl as YZ}from"../chunk-0zakpsep.js";import"../chunk-djhr379j.js";import"../chunk-qgka1mvf.js";import{Rl as M6}from"../chunk-znh1mbqs.js";import"../chunk-g0mxdh2x.js";import{am as w4,bm as pZ,cm as dZ,dm as lZ,fm as nZ}from"../chunk-qqe19gtm.js";import"../chunk-7ka1abkd.js";import{pm as C}from"../chunk-6fpjc2eg.js";import"../chunk-dqb257xv.js";import"../chunk-1v1ek1ey.js";import"../chunk-0dp6jvrg.js";import"../chunk-x8by5j7p.js";import"../chunk-kfcz4qa8.js";import{Um as p1}from"../chunk-30jcs49q.js";import{Buffer as J6}from"buffer";class z6 extends C1{client;config;constructor(...W){super();this.config=W}async connect(){let W=await import("../chunk-65wnm25z.js");return this.client??=new W.S3Client(...this.config),{sdk:W,client:this.client}}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,Q,Y,K=process.env.BUCKET_NAME;if(W instanceof Blob)$=W,Y=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,Q=W.type;else $=W.body,Y=W.name,K=W.bucket??K,Q=W.contentType||($ instanceof Blob||$ instanceof File?$.type:void 0);Q=Q||void 0;let J=$ instanceof J6?$:$ instanceof Blob||$ instanceof File?J6.from(await $.arrayBuffer()):"",{sdk:z,client:G}=await this.connect();return Z?.throwIfAborted(),await G.send(new z.PutObjectCommand({Bucket:K,Key:Y,Body:J,ContentType:Q}),{abortSignal:Z}),Y}async delete(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME;if(!Z)throw Error("Object name has to be specified");let{sdk:Q,client:Y}=await this.connect();try{await Y.send(new Q.DeleteObjectCommand({Bucket:$,Key:Z}))}catch(K){if(K?.name==="NoSuchKey"||K?.$metadata?.httpStatusCode===404)return;throw K}}async*pages(W,{bucket:Z,signal:$}){let{sdk:Q,client:Y}=await this.connect(),K;do{$?.throwIfAborted();let J=await Y.send(new Q.ListObjectsV2Command({Bucket:Z??process.env.BUCKET_NAME,Prefix:W,ContinuationToken:K}),{abortSignal:$});yield(J.Contents??[]).map((z)=>({name:z.Key,size:z.Size??0,lastModified:z.LastModified??new Date(0)})),K=J.IsTruncated?J.NextContinuationToken:void 0}while(K)}async*objects(W,Z={}){for await(let $ of this.pages(W,Z))yield*$}async deletePrefix(W,Z={}){V4(W);let $=Z.bucket??process.env.BUCKET_NAME,{sdk:Q,client:Y}=await this.connect(),K=0;for await(let J of this.pages(W,{...Z,bucket:$})){if(J.length===0)continue;Z.signal?.throwIfAborted();let G=(await Y.send(new Q.DeleteObjectsCommand({Bucket:$,Delete:{Objects:J.map((X)=>({Key:X.name})),Quiet:!0}}),{abortSignal:Z.signal}))?.Errors??[];if(G.length>0){let X=G[0];throw Error(`S3 could not delete ${G.length} object(s) under "${W}", e.g. "${X.Key}": ${X.Code??"unknown"} ${X.Message??""}`.trim())}K+=J.length}return K}async list(W){let{sdk:Z,client:$}=await this.connect();return await $.send(new Z.ListObjectsV2Command({Bucket:process.env.BUCKET_NAME,Prefix:W}))}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=process.env.BUCKET_NAME,Q;if(typeof W==="string")Q=W;else $=W.bucket??$,Q=W.name;if(!Q)throw Error("Object name has to be specified");let{sdk:Y,client:K}=await this.connect();Z?.throwIfAborted();let J=await K.send(new Y.GetObjectCommand({Bucket:$,Key:Q}),{abortSignal:Z}),z=d1(J.Body.transformToWebStream(),Z);return Z?.throwIfAborted(),new Response(z,{headers:{"Content-Type":J.ContentType,"Content-Length":J.ContentLength.toString(),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":J.LastModified?.toUTCString()||"",ETag:J.ETag||""}})}async read(W){let Z=typeof W==="string"?{name:W}:W,$=Z.bucket??process.env.BUCKET_NAME,{name:Q,range:Y=null}=Z;if(!Q)throw Error("Object name has to be specified");let{sdk:K,client:J}=await this.connect(),z;try{z=await J.send(new K.GetObjectCommand({Bucket:$,Key:Q,Range:Y?_4(Y):void 0}))}catch(j){if(j?.name==="InvalidRange"||j?.$metadata?.httpStatusCode===416)throw new j1(await this.size({name:Q,bucket:$}));if(j?.name==="NoSuchKey"||j?.$metadata?.httpStatusCode===404)throw new Y1(Q);throw j}let G=k1(z.ContentRange),X=Boolean(G)&&z.$metadata?.httpStatusCode===206,B=G?.total??z.ContentLength??0;return{body:z.Body.transformToWebStream(),start:G?.start??0,end:G?.end??B-1,total:B,partial:X,type:z.ContentType??"application/octet-stream",etag:z.ETag||void 0,lastModified:z.LastModified,name:Q}}async size(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME,{sdk:Q,client:Y}=await this.connect();try{return(await Y.send(new Q.HeadObjectCommand({Bucket:$,Key:Z}))).ContentLength??0}catch(K){if(K?.name==="NotFound"||K?.$metadata?.httpStatusCode===404)throw new Y1(Z);throw K}}}import{Buffer as G6}from"buffer";import{Readable as sW}from"stream";function k4(W){return W?.statusCode===404||W?.details?.errorCode==="BlobNotFound"||W?.code==="BlobNotFound"}function oW(W){return W?.statusCode===416||W?.details?.errorCode==="InvalidRange"||W?.code==="InvalidRange"}class X6 extends C1{config;serviceClientPromise=null;constructor(W={}){super();this.config=W}async serviceClient(){if(this.config.serviceClient)return this.config.serviceClient;return this.serviceClientPromise??=(async()=>{let W;try{W=await import("@azure/storage-blob")}catch{throw Error("AzureBlobDriver requires the '@azure/storage-blob' package. Install it with `bun add @azure/storage-blob`, or pass a pre-built `serviceClient`.")}let Z=this.config.connectionString??process.env.AZURE_STORAGE_CONNECTION_STRING;if(this.config.url)return new W.BlobServiceClient(this.config.url,this.config.credential);if(Z)return W.BlobServiceClient.fromConnectionString(Z);throw Error("AzureBlobDriver needs a connection string (AZURE_STORAGE_CONNECTION_STRING), a `url`, or a `serviceClient`.")})(),this.serviceClientPromise}async blob(W,Z){if(!W)throw Error("Object name has to be specified");let $=Z??this.config.container??process.env.BUCKET_NAME;if(!$)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");return(await this.serviceClient()).getContainerClient($).getBlockBlobClient(W)}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,Q,Y,K;if(W instanceof Blob)$=W,Y=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,Q=W.type;else $=W.body,Y=W.name,K=W.bucket,Q=W.contentType??($ instanceof Blob||$ instanceof File?$.type:void 0);let J=$ instanceof G6?$:G6.from(await $.arrayBuffer()),z=await this.blob(Y,K);return Z?.throwIfAborted(),await z.uploadData(J,{blobHTTPHeaders:Q?{blobContentType:Q}:void 0,abortSignal:Z}),Y}async*objects(W,{bucket:Z,signal:$}={}){$?.throwIfAborted();let Q=Z??this.config.container??process.env.BUCKET_NAME;if(!Q)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");let K=(await this.serviceClient()).getContainerClient(Q);for await(let J of K.listBlobsFlat({prefix:W}))$?.throwIfAborted(),yield{name:J.name,size:J.properties?.contentLength??0,lastModified:J.properties?.lastModified??new Date(0)}}async list(W){let Z=this.config.container??process.env.BUCKET_NAME,Q=(await this.serviceClient()).getContainerClient(Z),Y=[];for await(let K of Q.listBlobsFlat({prefix:W}))Y.push(K.name);return Y}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=await this.download(typeof W==="string"?{name:W}:{name:W.name,bucket:W.bucket},Z);return new Response($.body,{headers:{"Content-Type":$.type,"Content-Length":String($.total),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":$.lastModified?.toUTCString()??"",ETag:$.etag??""}})}async read(W){return this.download(typeof W==="string"?{name:W}:W)}async download(W,Z){let{name:$,bucket:Q,range:Y=null}=W,K=await this.blob($,Q);Z?.throwIfAborted();let J,z,G=Y?.kind==="suffix"||Y?.kind==="offset"&&Y.end===null&&Y.start===0;if(Y&&G){let V=await this.size({name:$,bucket:Q}),Q1=C4(Y,V);if(!Q1)throw new j1(V);J=Q1.start,z=Q1.length}else if(Y?.kind==="offset")J=Y.start,z=Y.end===null?void 0:Y.end-Y.start+1;let X;try{X=await K.download(J,z,Z?{abortSignal:Z}:void 0)}catch(V){if(oW(V))throw new j1(await this.size({name:$,bucket:Q}));if(k4(V))throw new Y1($);throw V}let B=k1(X.contentRange),j=Boolean(B),D=B?.total??X.contentLength??0,x=await aW(X);if(x instanceof ReadableStream)x=d1(x,Z);return Z?.throwIfAborted(),{body:x,start:B?.start??0,end:B?.end??D-1,total:D,partial:j,type:X.contentType??"application/octet-stream",etag:X.etag||void 0,lastModified:X.lastModified,name:$}}async size(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,Q=await this.blob(Z,$);try{return(await Q.getProperties()).contentLength??0}catch(Y){if(k4(Y))throw new Y1(Z);throw Y}}async delete(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,Q=await this.blob(Z,$);try{await Q.delete()}catch(Y){if(k4(Y))return;throw Y}}}async function aW(W){if(W.blobBody)return await W.blobBody;if(W.readableStreamBody)return sW.toWeb(W.readableStreamBody);return null}function tW(W){return W}class b4 extends Error{code="ERR_RATE_LIMITER_TIMEOUT";constructor(W){super(`RedisRateLimiter: Redis did not answer within ${W}ms.`);this.name="RedisRateLimiterTimeoutError"}}class n1 extends Error{code="ERR_RATE_LIMITER_DISCONNECTED";constructor(){super("RedisRateLimiter: the Redis client is not connected.");this.name="RedisRateLimiterDisconnectedError"}}var B6=1000,rW=60000,eW=`
|
|
3
3
|
local currentKey = KEYS[1]
|
|
4
4
|
local previousKey = KEYS[2]
|
|
5
5
|
local limit = tonumber(ARGV[1])
|
package/package.json
CHANGED
package/dist/chunk-8x8pbn1z.js
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Hd as MQ,Pd as I,Qd as o,Rd as U5,Sd as C5,Td as OQ,Ud as N5,Vd as h,Wd as QQ,Xd as M,rd as JQ,td as $Q}from"./chunk-x6fa13e1.js";import{Ej as Z5,Mj as F5}from"./chunk-30zs008n.js";var{fetch:u5,WebSocket:m5}=globalThis;function lQ(Q,$){if(typeof Bun>"u")return Q!==$;return typeof Q!=="function"||!/\{\s*\[native code\]\s*\}\s*$/.test(Function.prototype.toString.call(Q))}class XQ extends Error{constructor(Q){super(`A model provider tried to call ${c5(Q)} from a test. Tests under vitest do not reach real model providers: give the agent a scripted or fake provider, or set GEMI_AI_LIVE=1 to make real (billed) calls.`);this.name="LiveModelCallRefusedError"}}function iQ(Q=process.env){return!Q.VITEST||Q.GEMI_AI_LIVE==="1"}function nQ(Q){if(iQ()||lQ(globalThis.fetch,u5)||sQ(Q))return;throw new XQ(Q)}function rQ(Q){let $=globalThis.WebSocket;if(iQ()||lQ($,m5)||sQ(Q))return;throw new XQ(Q)}function sQ(Q){let $;try{$=new URL(Q).hostname}catch{return!1}return $==="localhost"||$.endsWith(".localhost")||$==="[::1]"||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test($)}function c5(Q){try{return new URL(Q).origin}catch{return"a provider"}}function HQ(Q,$,J){let Z=Q.on;if(Z===void 0)return!0;if(typeof Z!=="function")return Z.includes($.code);try{return Z($,J)===!0}catch{return!1}}var d5=4000,p5=60000;function aQ(Q){if(Q===void 0)return;let $=(J,Z)=>typeof J==="number"&&Number.isFinite(J)&&J>=Z;if(!Q||!$(Q.patienceMs,0)||Q.initialWaitMs!==void 0&&!$(Q.initialWaitMs,1)||Q.maxWaitMs!==void 0&&!$(Q.maxWaitMs,1)||Q.on!==void 0&&typeof Q.on!=="function"&&!(Array.isArray(Q.on)&&Q.on.every((J)=>typeof J==="string")))throw Error(`The provider's retry policy ${JSON.stringify(Q)} is not usable: patienceMs has to be a number of milliseconds (0 or more), initialWaitMs and maxWaitMs above 0, and on a list of error codes or a function.`)}function jQ(Q,$,J,Z,Y){let G=Q.patienceMs-Z;if(G<=0)return;let B=Q.maxWaitMs??p5,z=Q.initialWaitMs??d5,X=J!==void 0?Math.min(J,B):Math.round(Math.min(B,z*2**$)*(0.5+Y()*0.5));return Math.min(X,G)}var l5=500,oQ=20000;function i5(Q,$){if(!Q)return;let J=Q.trim();if(/^\d+(\.\d+)?$/.test(J))return Math.max(0,Number(J)*1000);let Z=Date.parse(J);if(Number.isNaN(Z))return;return Math.max(0,Z-$)}function a(Q,$){let J=Math.min(oQ,l5*2**Q);return Math.round(J*(0.5+$()*0.5))}function n5(Q){return Q===429||Q===408||Q===409||Q>=500}function r5(Q,$){return n5(Q)&&M($).retryable}function tQ(Q){return Q.reason??new DOMException("The operation was aborted.","AbortError")}function eQ(Q,$){return new Promise((J,Z)=>{let Y=setTimeout(J,Q);$?.addEventListener("abort",()=>{clearTimeout(Y),Z(tQ($))},{once:!0})})}async function zQ(Q,$,J=eQ){if(!$)return await J(Q);$.throwIfAborted();let Z;try{await Promise.race([J(Q,$),new Promise((Y,G)=>{Z=()=>G(tQ($)),$.addEventListener("abort",Z,{once:!0})})])}finally{if(Z)$.removeEventListener("abort",Z)}}async function g(Q,$,J){if(!J.fetchImpl)nQ(Q);let Z=J.fetchImpl??((V,W)=>fetch(V,W)),Y=J.sleep??eQ,G=J.random??Math.random,B=J.now??Date.now,z=Math.max(0,J.maxRetries),X=J.startedAt??B(),K=J.retry,j=(V,W,q,U)=>{let P=B()-X;try{J.onRetry?.({attempt:W+1,maxRetries:z,error:M(q),...h(q),timedOut:U,delayMs:V,elapsedMs:P,...K?{remainingMs:Math.max(0,K.patienceMs-P-V)}:{}})}catch{}return zQ(V,J.signal,Y)},H=(V,W,q,U)=>{if(!K)return;let{status:P}=h(q);if(!HQ(K,M(q),{...P?{status:P}:{},timedOut:U}))return;return jQ(K,V-z,W,B()-X,G)};for(let V=0;;V++){J.signal?.throwIfAborted();let W=new AbortController,q=()=>W.abort(J.signal?.reason);J.signal?.addEventListener("abort",q,{once:!0});let U=!1,P=J.timeoutMs>0?setTimeout(()=>{U=!0,W.abort()},J.timeoutMs):void 0,D;try{D=await Z(Q,{...$,signal:W.signal})}catch(y){if(P!==void 0)clearTimeout(P);if(J.signal?.removeEventListener("abort",q),J.signal?.aborted)throw y;let S=U?new o(J.timeoutMs):y;if(U&&J.retryTimeouts===!1)throw S;let E=V<z?a(V,G):H(V,void 0,S,U);if(E===void 0)throw S;await j(E,V,S,U);continue}if(P!==void 0)clearTimeout(P);if(D.ok)return D;J.signal?.removeEventListener("abort",q);let c=await s5(D),N=new I(D.status,c,D.headers.get("x-request-id")??D.headers.get("request-id")??void 0,i5(D.headers.get("retry-after"),B()));if(!r5(D.status,N))throw N;let O=N.retryAfter??(D.status===429?M(N).retryAfter:void 0),i=V>=z?H(V,O,N,!1):O===void 0?a(V,G):Math.min(O,oQ);if(i===void 0)throw N;await j(i,V,N,!1)}}async function s5(Q){let $;try{$=await Q.text()}catch{return null}try{return JSON.parse($)}catch{return $}}function Q5(Q,$,J){let Z=$.idleMs>0?$.idleMs:0,Y=$.maxMs>0?$.maxMs:0;if(!Q||!Z&&!Y)return Q;let G=Y?performance.now()+Y:1/0,B=Q.getReader();return new ReadableStream({async pull(z){let X,K,j=Math.max(0,G-performance.now()),H=!Z||j<=Z,V=H?j:Z,W=new Promise((q,U)=>{X=setTimeout(()=>{K=H?J.max():J.idle(),U(K)},V)});try{let q=await Promise.race([B.read(),W]);if(q.done)z.close();else z.enqueue(q.value)}catch(q){let U=K??q;z.error(U),B.cancel(U).catch(()=>{})}finally{clearTimeout(X)}},cancel(z){return B.cancel(z)}},{highWaterMark:0})}var FQ=30000,$5=10,J5=7200,a5=600,o5="gpt-live-transcribe";function t5(Q){return Q.type==="transcription"}function e5(Q){if(Q.language!==void 0&&Q.languages!==void 0)throw TypeError("A transcription session takes `languages` or `language`, not both (gpt-live-transcribe reads `languages`).");for(let Y of Q.keywords??[])if(/[<>\r\n]/.test(Y))throw TypeError(`Transcription keywords must be one line without "<" or ">", got ${JSON.stringify(Y)}.`);let $={model:Q.model??o5};if(Q.prompt!==void 0)$.prompt=Q.prompt;if(Q.keywords?.length)$.keywords=Q.keywords;if(Q.languages?.length)$.languages=Q.languages;if(Q.language!==void 0)$.language=Q.language;if(Q.delay!==void 0)$.delay=Q.delay;let J={transcription:$,turn_detection:Q.turnDetection?Y5(Q.turnDetection):null};if(Q.noiseReduction!==void 0)J.noise_reduction=Q.noiseReduction&&{type:Q.noiseReduction};let Z={type:"transcription",audio:{input:J}};if(Q.logprobs)Z.include=["item.input_audio_transcription.logprobs"];return{...Z,...Q.vendor}}function Q6(Q){if(!Q)return{type:"object",properties:{}};return Z5(Q)?Q.toJSONSchema():Q}function t(Q,$){if(t5(Q))return e5(Q);let J={type:"realtime"},Z=Q.model??$;if(Z)J.model=Z;if(Q.instructions!==void 0)J.instructions=Q.instructions;if(Q.outputModalities)J.output_modalities=Q.outputModalities;if(Q.maxOutputTokens!==void 0)J.max_output_tokens=Q.maxOutputTokens;if(Q.truncation!==void 0)J.truncation=Q.truncation;if(Q.tools)J.tools=Q.tools.map((B)=>({type:"function",name:B.name,...B.description?{description:B.description}:{},parameters:Q6(B.parameters)}));if(Q.toolChoice!==void 0)J.tool_choice=typeof Q.toolChoice==="string"?Q.toolChoice:{type:"function",name:Q.toolChoice.name};let Y={};if(Q.turnDetection!==void 0)Y.turn_detection=Q.turnDetection&&Y5(Q.turnDetection);if(Q.transcription!==void 0)Y.transcription=Q.transcription;if(Q.noiseReduction!==void 0)Y.noise_reduction=Q.noiseReduction&&{type:Q.noiseReduction};let G={};if(Q.voice!==void 0)G.voice=Q.voice;if(Q.speed!==void 0)G.speed=Q.speed;if(Object.keys(Y).length||Object.keys(G).length)J.audio={...Object.keys(Y).length?{input:Y}:{},...Object.keys(G).length?{output:G}:{}};return{...J,...Q.vendor}}function Y5(Q){let $={type:Q.type};if(Q.createResponse!==void 0)$.create_response=Q.createResponse;if(Q.interruptResponse!==void 0)$.interrupt_response=Q.interruptResponse;if(Q.type==="semantic_vad"){if(Q.eagerness!==void 0)$.eagerness=Q.eagerness}else{if(Q.threshold!==void 0)$.threshold=Q.threshold;if(Q.prefixPaddingMs!==void 0)$.prefix_padding_ms=Q.prefixPaddingMs;if(Q.silenceDurationMs!==void 0)$.silence_duration_ms=Q.silenceDurationMs;if(Q.idleTimeoutMs!==void 0)$.idle_timeout_ms=Q.idleTimeoutMs}return $}function UQ(Q){let $=Number(Q?.input_tokens??0),J=Number(Q?.output_tokens??0),Z={inputTokens:$,outputTokens:J,totalTokens:Number(Q?.total_tokens??$+J)},Y=Q?.input_token_details??Q?.input_tokens_details,G=Q?.output_token_details??Q?.output_tokens_details;if(typeof Y?.cached_tokens==="number")Z.cachedInputTokens=Y.cached_tokens;if(typeof Y?.audio_tokens==="number")Z.audioInputTokens=Y.audio_tokens;let B=Y?.cached_tokens_details?.audio_tokens;if(typeof B==="number")Z.cachedAudioInputTokens=B;if(typeof Y?.image_tokens==="number"&&Y.image_tokens>0)Z.imageInputTokens=Y.image_tokens;if(typeof G?.audio_tokens==="number")Z.audioOutputTokens=G.audio_tokens;return Z}class d extends Error{code;retryable;status;constructor(Q,$={}){super(Q.message,{cause:$.cause});if(this.name="RealtimeRequestError",this.code=Q.code,this.retryable=Q.retryable,$.status!==void 0)this.status=$.status}}var $6=60;class e{model;target;options;constructor(Q,$){this.target=Q,this.options=$,this.model=$.model}url(Q){return`${this.target.base}/realtime${Q}${this.target.query}`}sidebandUrl(Q){let $=this.target.base.replace(/^http(s?):/i,(Z,Y)=>`ws${Y}:`),J=this.target.query?`${this.target.query}&`:"?";return`${$}/realtime${J}call_id=${encodeURIComponent(Q)}`}async createCall(Q){let $=Q.flow??this.options.callFlow??"unified",J,Z;if($==="ephemeral")J={authorization:`Bearer ${(await this.clientSecret({session:Q.session,ttlSeconds:$6,signal:Q.signal})).value}`,"content-type":"application/sdp"},Z=Q.sdp;else{let X=new FormData;X.set("sdp",Q.sdp),X.set("session",JSON.stringify(t(Q.session??{},this.model))),J=await this.target.headers(),Z=X}if(Q.safetyIdentifier)J["OpenAI-Safety-Identifier"]=Q.safetyIdentifier;let Y=this.url("/calls"),G=await this.request(Q.webrtcFilter?`${Y}${Y.includes("?")?"&":"?"}webrtcfilter=on`:Y,{method:"POST",headers:J,body:Z},Q.signal),B=await G.text(),z=Z6(G);if(!z)throw new d({code:"provider_error",message:"The provider started a realtime call but did not say which one (no Location).",retryable:!1});return{sdpAnswer:B,callId:z}}async clientSecret(Q={}){let $=Q.ttlSeconds??a5;if(!Number.isInteger($)||$<$5||$>J5)throw RangeError(`ttlSeconds must be a whole number from ${$5} to ${J5}, got ${$}.`);let J={...await this.target.headers(),"content-type":"application/json"};if(Q.safetyIdentifier)J["OpenAI-Safety-Identifier"]=Q.safetyIdentifier;let Y=await(await this.request(this.url("/client_secrets"),{method:"POST",headers:J,body:JSON.stringify({expires_after:{anchor:"created_at",seconds:$},session:t(Q.session??{},this.model)})},Q.signal)).json();if(typeof Y?.value!=="string")throw new d({code:"provider_error",message:"The provider answered a client secret request with no secret.",retryable:!1});return{value:Y.value,expiresAt:Number(Y.expires_at??0),session:Y.session,callsUrl:this.url("/calls")}}async hangup(Q,$={}){try{await this.request(this.url(`/calls/${encodeURIComponent(Q)}/hangup`),{method:"POST",headers:await this.target.headers()},$.signal)}catch(J){if(J6(J,Q))return;throw J}}sideband(Q,$={}){return new qQ({...$,callId:Q,url:this.sidebandUrl(Q),headers:this.target.headers,webSocket:$.webSocket??this.options.webSocket,hangup:()=>this.hangup(Q)})}async request(Q,$,J){try{return await g(Q,$,{maxRetries:this.target.maxRetries,timeoutMs:this.target.timeoutMs,retryTimeouts:!1,signal:J,fetchImpl:this.options.fetchImpl})}catch(Z){if(J?.aborted)throw Z;throw new d(M(Z),{cause:Z,...Z instanceof I?{status:Z.status}:{}})}}}function J6(Q,$){if(!(Q instanceof d)||Q.status!==404)return!1;let J=Q.cause instanceof I?Q.cause.body:void 0,Z=J?.error??J,Y=String(Z?.code??"").toLowerCase(),G=String(Z?.message??"").toLowerCase();if(Y.includes("call"))return!0;if(G.includes($.toLowerCase()))return!0;return/\bcall\b/.test(G)&&/not (be )?found|does not exist|no longer|ended/.test(G)}function Z6(Q){let $=Q.headers.get("location");if(!$)return;let J=$.split("?")[0].replace(/\/+$/,""),Z=J.slice(J.lastIndexOf("/")+1);return Z?decodeURIComponent(Z):void 0}var Y6={"response.audio_transcript.delta":"response.output_audio_transcript.delta","response.audio_transcript.done":"response.output_audio_transcript.done","response.text.delta":"response.output_text.delta","response.text.done":"response.output_text.done","response.audio.delta":"response.output_audio.delta","response.audio.done":"response.output_audio.done"};function G6(Q){if(typeof Q!=="string")return;let $;try{$=JSON.parse(Q)}catch{return}if(!$||typeof $!=="object"||typeof $.type!=="string")return;let J=Y6[$.type];if(J)$.type=J;if($.type==="response.done"&&$.response?.usage)$.usage=UQ($.response.usage);if($.type==="conversation.item.input_audio_transcription.completed"&&$.usage)if($.usage.type==="duration"){let Z=Number($.usage.seconds);if(Number.isFinite(Z))$.transcriptionSeconds=Z}else $.transcriptionUsage=UQ($.usage);return $}var G5=1,V6=500;function B6(Q,$){let J=globalThis.WebSocket;if(!J)throw Error("No global WebSocket: the realtime sideband needs Bun or Node 22+.");return rQ(Q),new J(Q,{headers:$.headers})}class qQ{callId;ready;closed;init;socket;finalEvent;outbox=[];subscribers=new Set;listeners=new Set;backlog=[];closing=!1;finished=!1;everOpened=!1;failures=0;resolveReady;rejectReady;resolveClosed;constructor(Q){this.init=Q,this.callId=Q.callId,this.ready=new Promise(($,J)=>{this.resolveReady=$,this.rejectReady=J}),this.ready.catch(()=>{}),this.closed=new Promise(($)=>this.resolveClosed=$),this.open()}send(Q){if(this.finished||this.closing)return;let $=JSON.stringify(Q);if(this.socket?.readyState===G5)this.socket.send($);else this.outbox.push($)}updateSession(Q){this.send({type:"session.update",session:t(Q)})}addItem(Q){this.send({type:"conversation.item.create",item:Q})}addNote(Q){this.addItem({type:"message",role:"system",content:[{type:"input_text",text:Q}]})}functionOutput(Q,$){this.addItem({type:"function_call_output",call_id:Q,output:typeof $==="string"?$:JSON.stringify($)})}createResponse(Q={}){let $={};if(Q.instructions!==void 0)$.instructions=Q.instructions;if(Q.toolChoice!==void 0)$.tool_choice=typeof Q.toolChoice==="string"?Q.toolChoice:{type:"function",name:Q.toolChoice.name};if(Q.outputModalities)$.output_modalities=Q.outputModalities;if(Q.conversation)$.conversation=Q.conversation;if(Q.metadata)$.metadata=Q.metadata;Object.assign($,Q.vendor),this.send(Object.keys($).length?{type:"response.create",response:$}:{type:"response.create"})}cancelResponse(Q){this.send(Q?{type:"response.cancel",response_id:Q}:{type:"response.cancel"})}on(Q){return this.listeners.add(Q),()=>this.listeners.delete(Q)}[Symbol.asyncIterator](){let Q={queue:this.backlog??[],done:this.finished};return this.backlog=void 0,this.subscribers.add(Q),{next:async()=>{for(;;){let J=Q.queue.shift();if(J)return{value:J,done:!1};if(Q.done)return this.subscribers.delete(Q),{value:void 0,done:!0};await new Promise((Z)=>Q.wake=Z),Q.wake=void 0}},return:async()=>{return Q.done=!0,Q.queue.length=0,this.subscribers.delete(Q),{value:void 0,done:!0}}}}close(Q=1000,$="closed"){if(this.finished||this.closing)return;if(this.closing=!0,this.socket&&this.socket.readyState<=G5)this.socket.close(Q,$);else this.finish(Q,$,!0)}async hangup(){try{await this.init.hangup()}catch(Q){if(this.finalEvent&&!this.finalEvent.byClient&&this.finalEvent.code===1000)return;throw Q}this.close(1000,"hangup")}async open(){let Q;try{let J=await this.init.headers();if(this.closing)return this.finish(1000,"closed",!0);Q=(this.init.webSocket??B6)(this.init.url,{headers:J})}catch(J){return this.dropped(1006,J instanceof Error?J.message:String(J),!1)}this.socket=Q;let $=!1;Q.addEventListener("open",()=>{$=!0;let J=this.everOpened;this.everOpened=!0;let Z=this.failures;this.failures=0;for(let Y of this.outbox.splice(0))Q.send(Y);if(this.resolveReady(),J)this.emit({type:"sideband.reconnected",attempt:Z})}),Q.addEventListener("message",(J)=>{let Z=G6(J.data);if(Z)this.emit(Z)}),Q.addEventListener("close",(J)=>{if(this.socket!==Q)return;this.dropped(J.code??1006,J.reason??"",$)}),Q.addEventListener("error",()=>{})}dropped(Q,$,J){if(this.socket=void 0,this.closing)return this.finish(Q,$,!0);let Z=this.init.reconnect?.attempts??3;if(!((Q!==1000||!J)&&this.failures<Z))return this.finish(Q,$,!1);this.failures+=1;let G=(this.init.reconnect?.delayMs??500)*2**(this.failures-1);setTimeout(()=>void this.open(),G)}finish(Q,$,J){if(this.finished)return;this.finished=!0,this.outbox.length=0;let Z={type:"sideband.closed",code:Q,reason:$,byClient:J};this.finalEvent=Z,this.emit(Z);for(let Y of this.subscribers)Y.done=!0,Y.wake?.();if(!this.everOpened)this.rejectReady(Error(`Realtime sideband did not open (${Q} ${$}).`));this.resolveClosed(Z)}emit(Q){if(this.backlog){if(this.backlog.push(Q),this.backlog.length>V6)this.backlog.shift()}for(let $ of this.subscribers){if($.done)continue;$.queue.push(Q),$.wake?.()}for(let $ of this.listeners)try{$(Q)}catch{}}}var K5=3;function CQ(Q){let $=new Map;for(let J of Q)for(let Z of J.content??[]){if(Z.type!=="file"||!Z.fileId||$.has(Z.fileId))continue;$.set(Z.fileId,{name:Z.name,mimeType:Z.mimeType})}return $}function W5(Q,$,J=new Map){if(!($ instanceof I))return[];if($.status!==400&&$.status!==404)return[];let Z=LQ($.body);if(!Z)return[];let Y=K6(Q.input);if(Y.length===0)return[];let G=/^input\[(\d+)\]\.content\[(\d+)\]\.file_id$/.exec(Z.param??"");if(G){let K=Q.input[Number(G[1])],j=NQ(K)[Number(G[2])],H=j&&typeof j.file_id==="string"?j.file_id:void 0;if(H)return[H]}let B=Z.message??"",z=B5(Y.map((K)=>K.fileId).filter((K)=>W6(B,K)));if(z.length>0)return z;let X=/Expected (image type|context stuffing file type) to be a supported format:.*but got \.([a-z0-9]+)\.?\s*$/is.exec(B);if(X){let K=X[1].toLowerCase()==="image type"?"input_image":"input_file",j=X[2].toLowerCase(),H=B5(Y.filter((W)=>W.type===K).map((W)=>W.fileId)),V=H.filter((W)=>(J.get(W)?.name??"").trim().toLowerCase().endsWith(`.${j}`));if(V.length===1)return V;if(V.length===0&&H.length===1)return H}return[]}function X5(Q,$,J=new Map){return{...Q,input:Q.input.map((Z)=>{let Y=NQ(Z);if(!Y.some((G)=>V5(G,$)))return Z;return{...Z,content:Y.map((G)=>V5(G,$)?{type:"input_text",text:p(J.get(String(G.file_id))?.name)}:G)}})}}function p(Q){return`[${Q?`attachment ${JSON.stringify(Q)}`:"an attachment"} could not be read by the provider and is not shown to you. Tell the user if it matters to the answer; uploading it again may help.]`}function V5(Q,$){return typeof Q.file_id==="string"&&$.has(Q.file_id)}function NQ(Q){let $=Q?.content;return Array.isArray($)?$:[]}function K6(Q){let $=[];for(let J of Q)for(let Z of NQ(J))if(typeof Z.file_id==="string"&&Z.file_id)$.push({type:String(Z.type),fileId:Z.file_id});return $}function LQ(Q){if(!Q||typeof Q!=="object")return null;let $=Q,J=$.error&&typeof $.error==="object"?$.error:Q;return{message:typeof J.message==="string"?J.message:void 0,param:typeof J.param==="string"?J.param:void 0}}function W6(Q,$){let J=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${J}($|[^A-Za-z0-9_-])`).test(Q)}function B5(Q){return[...new Set(Q)]}function H5(Q,$){if(!($ instanceof I))return null;if($.status!==400&&$.status!==404)return null;let J=Q?.input;if(!Array.isArray(J))return null;let Z=LQ($.body)?.message??"",Y=/Item with id '([^']+)' not found/i.exec(Z)?.[1];if(!Y)return null;let G=(B)=>B?.type==="reasoning";if(!J.some((B)=>G(B)&&B.id===Y))return null;return{...Q,input:J.filter((B)=>!G(B))}}async function*xQ(Q){let $="",J="",Z=[],Y,G=()=>{if(Z.length===0&&!J)return null;let X={event:J,data:Z.join(`
|
|
3
|
-
`),id:Y};return J="",Z=[],Y=void 0,X.data?X:null},B=(X)=>{let K=X.endsWith("\r")?X.slice(0,-1):X;if(K==="")return G();if(K.startsWith(":"))return null;let j=K.indexOf(":"),H=j===-1?K:K.slice(0,j),V=j===-1?"":K.slice(j+1);if(V.startsWith(" "))V=V.slice(1);if(H==="event")J=V;else if(H==="data")Z.push(V);else if(H==="id")Y=V;return null};for await(let X of Q){$+=X;let K=$.indexOf(`
|
|
4
|
-
`);while(K!==-1){let j=$.slice(0,K);$=$.slice(K+1);let H=B(j);if(H)yield H;K=$.indexOf(`
|
|
5
|
-
`)}}if($.length>0){let X=B($);if(X)yield X}let z=G();if(z)yield z}async function*j5(Q,$={}){let J=new Map,Z=new Set,Y,G=!1,B,z=(X,K)=>({type:"finish",reason:X,usage:K,...B?{model:B}:{}});for await(let X of xQ(Q)){if(X.data==="[DONE]")break;let K;try{K=JSON.parse(X.data)}catch{continue}let j=typeof K.type==="string"?K.type:X.event,H=K.response?.model;if(typeof H==="string"&&H)B=H;switch(j){case"response.output_text.delta":{let V=String(K.delta??"");if(!V)break;yield $.structuredOutput?{type:"output-delta",delta:V}:{type:"text-delta",delta:V};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let V=String(K.delta??"");if(!V)break;yield{type:"reasoning-delta",delta:V,id:K.item_id};break}case"response.output_item.added":{let V=K.item;if(!V)break;if(V.type==="function_call"){let W=String(V.id??K.item_id??V.call_id??"");J.set(W,{callId:String(V.call_id??W),name:String(V.name??""),namespace:typeof V.namespace==="string"&&V.namespace?V.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let V=J.get(String(K.item_id??""));if(!V)break;let W=String(K.delta??"");if(!W)break;yield{type:"tool-call-delta",toolCallId:V.callId,name:V.name,argsDelta:W,...V.namespace?{namespace:V.namespace}:{}};break}case"response.function_call_arguments.done":{let V=String(K.item_id??""),W=J.get(V);if(!W)break;W.done=!0,yield{type:"tool-call",toolCallId:W.callId,name:W.name,args:String(K.arguments??""),...W.namespace?{namespace:W.namespace}:{}};break}case"response.output_item.done":{let V=K.item;if(!V)break;if(V.type==="function_call"){let W=String(V.id??K.item_id??V.call_id??""),q=J.get(W);if(q?.done)break;let U=(typeof V.namespace==="string"?V.namespace:"")||q?.namespace;if(yield{type:"tool-call",toolCallId:String(V.call_id??W),name:String(V.name??q?.name??""),args:String(V.arguments??""),...U?{namespace:U}:{}},q)q.done=!0;break}if(V.type==="tool_search_call"||V.type==="tool_search_output"){if(V.type==="tool_search_call"&&V.arguments!==void 0)Y=V.arguments;let W=X6(V);if(W.loaded.length===0&&W.namespaces.length===0)break;let q=String(V.tool_search_call_id??V.id??"");if(Z.has(q))break;Z.add(q);let U=Y;Y=void 0,yield{type:"tool-search",...W,...U!==void 0&&U!==null?{arguments:U}:{}}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(K.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{G=!0,yield z("stop",PQ(K.response?.usage));break}case"response.incomplete":{G=!0;let V=PQ(K.response?.usage),W=K.response?.incomplete_details?.reason;if(W==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:H6(K.response?.content_filters),retryable:!1}},yield z("error",V);break}yield z(W==="max_output_tokens"?"length":"stop",V);break}case"response.failed":case"error":{G=!0;let V=K.response?.error??K.error??K;yield{type:"error",error:j6(V),...QQ(V)},yield z("error",PQ(K.response?.usage));break}}if(G)return}if(!G)yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield z("error",R())}function X6(Q){let $=[],J=[];return z5(Q.results??Q.tools??Q.loaded??Q.output,$,J,0),{loaded:DQ($),namespaces:DQ(J)}}function z5(Q,$,J,Z){if(!Array.isArray(Q)||Z>4)return;for(let Y of Q){if(typeof Y==="string"){$.push(Y);continue}if(!Y||typeof Y!=="object")continue;let G=Y,B=typeof G.name==="string"?G.name:typeof G.tool_name==="string"?G.tool_name:"",z=G.tools??G.functions;if(Array.isArray(z)){if(B)J.push(B);z5(z,$,J,Z+1);continue}if(B)$.push(B)}}function DQ(Q){return Q.filter(($,J)=>Q.indexOf($)===J)}function H6(Q){if(!Array.isArray(Q))return"The provider's content filter blocked this request.";let J=[];for(let Z of Q){if(!Z||typeof Z!=="object")continue;let Y=Z,G=Y.content_filter_results;if(!G||typeof G!=="object")continue;for(let[B,z]of Object.entries(G))if(z&&typeof z==="object"&&z.filtered===!0)J.push(`${B} (${String(Y.source_type??"unknown")})`)}return J.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${DQ(J).join(", ")}.`}function j6(Q){let $=typeof Q?.message==="string"?Q.message:"The provider stream failed.",J=String(Q?.code??"").toLowerCase();if(J==="rate_limit_exceeded")return{code:"rate_limited",message:$,retryable:!0};if(J==="context_length_exceeded")return{code:"context_length_exceeded",message:$,retryable:!1};if(J.includes("content_filter"))return{code:"content_filtered",message:$,retryable:!1};return{code:"provider_error",message:$,retryable:!0}}function R(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function PQ(Q){if(!Q)return R();let $=Number(Q.input_tokens??0),J=Number(Q.output_tokens??0),Z={inputTokens:$,outputTokens:J,totalTokens:Number(Q.total_tokens??$+J)},Y=Q.output_tokens_details?.reasoning_tokens;if(typeof Y==="number")Z.reasoningTokens=Y;let G=Q.input_tokens_details?.cached_tokens;if(typeof G==="number")Z.cachedInputTokens=G;return Z}async function*q5(Q){if(!Q)return;let $=Q.getReader(),J=new TextDecoder;try{while(!0){let{done:Y,value:G}=await $.read();if(Y)break;if(G)yield J.decode(G,{stream:!0})}let Z=J.decode();if(Z)yield Z}finally{$.releaseLock()}}function ZQ(Q){return{responsesUrl:`${Q.base}/responses${Q.query}`,filesUrl:`${Q.base}/files${Q.query}`,headers:Q.headers,timeoutMs:Q.timeoutMs,streamIdleTimeoutMs:Q.streamIdleTimeoutMs,streamMaxDurationMs:Q.streamMaxDurationMs,maxToolArgumentChars:Q.maxToolArgumentChars,maxToolArgumentWhitespace:Q.maxToolArgumentWhitespace,maxRetries:Q.maxRetries,...Q.retry?{retry:Q.retry}:{}}}async function*YQ(Q,$,J){let Z=J.parse??j5,Y=$,G=new Set,B=0,z=!1,X=Math.max(0,Q.maxRetries),K=Q.random??Math.random,j,H=(N)=>{if(!j)return N;let O=$Q($Q(R(),j),N.usage);return j=void 0,{...N,usage:O}},V=()=>H({type:"finish",reason:"aborted",usage:R()}),W=Q.streamIdleTimeoutMs??0,q=Q.streamMaxDurationMs??0,U=Q.maxToolArgumentChars??0,P=Q.maxToolArgumentWhitespace??0,D=Q.now??Date.now,c=D();for(let N=0;;N++){let O=new AbortController,i=J.signal?AbortSignal.any([J.signal,O.signal]):O.signal,y;while(y===void 0)try{let C=[],F=()=>{},L=g(Q.responsesUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify(Y)},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,signal:i,fetchImpl:Q.fetchImpl,sleep:Q.sleep,random:Q.random,now:Q.now,startedAt:c,...Q.retry?{retry:Q.retry}:{},onRetry:(_)=>{C.push({type:"retry",..._,phase:"request"}),F()}}),T=L.then(()=>!0,()=>!0);for(;;){let _=new Promise((b)=>F=()=>b(!1)),k=await Promise.race([T,_]);if(yield*C.splice(0),k)break}y=await L}catch(C){let F=Y,L=J.files&&B<K5?W5(F,C,J.files).filter((k)=>!G.has(k)):[];if(L.length>0){B++;let k=M(C).message;for(let b of L)G.add(b),yield{type:"file-rejected",fileId:b,message:k,...h(C)};Y=X5(F,new Set(L),J.files);continue}let T=z?null:H5(Y,C);if(T){z=!0,Y=T;continue}let _=M(C);if(_.code==="aborted"){yield V();return}yield{type:"error",error:_,...h(C)},yield H({type:"finish",reason:"error",usage:R()});return}let S=[],E=!1,f,WQ=!1,A,w=new Map,pQ,n;try{let C=Q5(y.body,{idleMs:W,maxMs:q},{idle:()=>{let F=new U5(W);return O.abort(F),F},max:()=>{let F=new C5(q);return O.abort(F),F}});for await(let F of Z(q5(C),{structuredOutput:J.structuredOutput,onUsage:(L)=>pQ=L})){if(F.type==="tool-call-delta"){let L=w.get(F.toolCallId);if(!L)w.set(F.toolCallId,L=z6());q6(L,F.argsDelta,P>0);let T=L.chars;if(P>0&&L.space>P){let _=L.text.trimEnd(),k=F6(_);if(U6(F.name,F.toolCallId,T,L.space,P,k),!k){let b=new N5(P,F.name,F.toolCallId,T,L.space);throw O.abort(b),b}w.delete(F.toolCallId),n={type:"tool-call",toolCallId:F.toolCallId,name:F.name,args:_,...F.namespace?{namespace:F.namespace}:{}};break}if(U>0&&T>U){let _=new OQ(U,F.name,F.toolCallId,T);throw O.abort(_),_}yield F;continue}if(F.type==="tool-call")w.delete(F.toolCallId);if(E){yield F.type==="finish"?H(F):F;continue}if(JQ(F)){E=!0,yield*S.splice(0),yield F;continue}if(F.type==="error")f=F.error;S.push(F)}if(n)await C?.cancel().catch(()=>{})}catch(C){WQ=C instanceof o;let F=M(C);if(F.code==="aborted"||J.signal?.aborted){yield V();return}if(C instanceof OQ)A=C.detail;if(E){yield{type:"error",error:F,...A?{toolArgumentsTooLong:A}:{}},yield H({type:"finish",reason:"error",usage:R()});return}f=F,S.push({type:"error",error:F,...A?{toolArgumentsTooLong:A}:{}},{type:"finish",reason:"error",usage:R()})}if(n){if(O.abort(),!E)yield*S.splice(0);if(yield n,w.size>0)yield{type:"tool-call-discard",toolCallIds:[...w.keys()]};yield H({type:"finish",reason:"stop",usage:pQ??R()});return}if(E)return;let r={};for(let C of S)if(C.type==="error")r=h(C);let s=!f?.retryable||J.signal?.aborted||A&&J.retryToolArgumentsTooLong===!1?void 0:N<X?a(N,K):Q.retry&&HQ(Q.retry,f,{...r.status!==void 0?{status:r.status}:{},timedOut:WQ,...A?{toolArgumentsTooLong:A}:{}})?jQ(Q.retry,N-X,f.retryAfter,D()-c,K):void 0;if(s!==void 0){for(let F of S)if(F.type==="finish")j=$Q(j??R(),F.usage);if(w.size>0)yield{type:"tool-call-discard",toolCallIds:[...w.keys()]};let C=D()-c;yield{type:"retry",attempt:N+1,maxRetries:X,error:f,...r,phase:"stream",timedOut:WQ,...A?{toolArgumentsTooLong:A}:{},delayMs:s,elapsedMs:C,...Q.retry?{remainingMs:Math.max(0,Q.retry.patienceMs-C-s)}:{}};try{await zQ(s,J.signal,Q.sleep)}catch{yield V();return}continue}for(let C of S)yield C.type==="finish"?H(C):C;return}}function z6(){return{chars:0,text:"",inString:!1,escaped:!1,space:0}}function q6(Q,$,J){if(Q.chars+=$.length,!J)return;Q.text+=$;for(let Z of $){if(Q.inString){if(Q.escaped)Q.escaped=!1;else if(Z==="\\")Q.escaped=!0;else if(Z==='"')Q.inString=!1}else if(Z===" "||Z===`
|
|
6
|
-
`||Z==="\r"||Z==="\t"){Q.space++;continue}else if(Z==='"')Q.inString=!0;Q.space=0}}function F6(Q){try{return JSON.parse(Q),!0}catch{return!1}}function U6(Q,$,J,Z,Y,G){let B=`[gemi/ai] tool call "${Q}" ran away in white space (more than ${Y} characters, maxToolArgumentWhitespace); ${G?"its arguments were whole JSON, so it was finished as written":"its arguments were not whole JSON, so it was cut"}`,z={tool:Q,toolCallId:$,chars:J,whitespace:Z,limit:Y,whole:G},X=!1;try{F5.warning(B,z),X=!0}catch{}if(!X||Bun.env.NODE_ENV==="development")console.warn(B,z)}async function GQ(Q,$,J="user_data"){let Z=new FormData;if(J)Z.set("purpose",J);Z.set("file",$);let G=await(await g(Q.filesUrl,{method:"POST",headers:await Q.headers(),body:Z},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,fetchImpl:Q.fetchImpl})).json();if(!G?.id)throw Error("The provider accepted the upload but returned no file id.");return G.id}async function VQ(Q,$){let J=Q.filesUrl.indexOf("?"),Z=J===-1?Q.filesUrl:Q.filesUrl.slice(0,J),Y=J===-1?"":Q.filesUrl.slice(J);try{await(await g(`${Z}/${encodeURIComponent($)}${Y}`,{method:"DELETE",headers:await Q.headers()},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,fetchImpl:Q.fetchImpl,...Q.sleep?{sleep:Q.sleep}:{},...Q.random?{random:Q.random}:{}})).body?.cancel()}catch(G){if(G instanceof I&&G.status===404)return;throw G}}function SQ(Q,$){let{capabilities:J}=$,Z={model:$.model,input:C6(Q.messages,J,Q.tools),stream:!0};if(Q.systemPrompt)Z.instructions=Q.systemPrompt;let Y=_6(Q.tools,J);if(Y.length>0){if(Z.tools=Y,!J.parallelToolCalls)Z.parallel_tool_calls=!1;if(Q.toolChoice!==void 0)Z.tool_choice=typeof Q.toolChoice==="string"?Q.toolChoice:{type:"function",name:Q.toolChoice.name}}if(Q.output)Z.text={format:{type:"json_schema",name:Q.output.name,schema:Q.output.schema,strict:Q.output.strict}};if(Q.reasoning&&J.reasoning)Z.reasoning=Q.reasoning==="none"?{effort:"none"}:{effort:Q.reasoning,summary:"auto"};if(typeof Q.temperature==="number")Z.temperature=Q.temperature;if(typeof Q.maxOutputTokens==="number")Z.max_output_tokens=Q.maxOutputTokens;if(Q.promptCacheKey)Z.prompt_cache_key=Q.promptCacheKey;return Z}function C6(Q,$,J){let Z=[],Y=new Map;if($.toolSearch){for(let G of J??[])if(BQ(G))Y.set(G.name,G)}for(let G of Q){let B=G.role,z=!O6.has(G.finishReason),X=[],K=()=>{if(X.length===0)return;Z.push({type:"message",role:B,content:X}),X=[]};for(let j of G.content??[])switch(j.type){case"text":{if(!j.text)break;X.push(u(B,j.text));break}case"output":{if(j.partial)break;X.push(u(B,JSON.stringify(j.value)));break}case"file":{if(B==="assistant")break;let H=_Q(j);if(!$.fileInput){if(H)X.push(u(B,l(j,!1)));break}if(IQ(j,H),j.providerRejected){if(H)X.push(u(B,l(j,!1)));X.push(u(B,p(j.name)));break}if(H)X.push(u(B,l(j,!!j.fileId)));if(j.fileId)X.push(P6(j));break}case"reasoning":{if(K(),!z)break;let H=M6(j);if(H)Z.push(H);break}case"tool-call":{if(j.partial)break;if(K(),$.toolSearch&&Array.isArray(j.toolSearches))for(let V of j.toolSearches)Z.push(...S6(V,J??[]));let H={type:"function_call",call_id:j.toolCallId,name:String(j.name),arguments:JSON.stringify(j.input??{})};if(j.namespace&&Y.has(j.namespace))H.namespace=j.namespace;Z.push(H);break}case"tool-result":{K(),Z.push({type:"function_call_output",call_id:j.toolCallId,output:AQ(j)});break}}K()}return L6(Z)}var N6="No result was recorded for this tool call. Assume it did not complete.";function L6(Q){let $=new Set,J=new Set,Z=[];for(let G of Q){if(G.type==="function_call"){let B=String(G.call_id);if($.has(B))continue;$.add(B)}else if(G.type==="function_call_output"){let B=String(G.call_id);if(!$.has(B)||J.has(B))continue;J.add(B)}Z.push(G)}if(J.size===$.size)return Z;let Y=[];for(let G of Z){if(Y.push(G),G.type!=="function_call")continue;let B=String(G.call_id);if(J.has(B))continue;J.add(B),Y.push({type:"function_call_output",call_id:B,output:N6})}return Y}function u(Q,$){return{type:Q==="assistant"?"output_text":"input_text",text:$}}function _Q(Q){let $=Q.attachmentId;return typeof $==="string"&&$.startsWith(MQ)?$:void 0}function l(Q,$){let J=[`id=${JSON.stringify(Q.attachmentId)}`];if(Q.name)J.push(`name=${JSON.stringify(Q.name)}`);if(Q.mimeType)J.push(`mimeType=${JSON.stringify(Q.mimeType)}`);let Z=`attachment ${J.join(" ")}`;return $?`[${Z}]`:`[${Z} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function P6(Q){return{type:RQ(Q)?"input_image":"input_file",file_id:Q.fileId}}function RQ(Q){let $=Q.mimeType?.trim().toLowerCase()??"";return $?$.startsWith("image/")&&$!=="image/svg+xml":D6(Q.name)}function IQ(Q,$){if(Q.fileId?.startsWith(MQ))throw Error(`FilePart.fileId holds a gemi attachment id (${Q.fileId}). That field is the *provider's* file id, from \`fileId\` on the upload response; the \`attachmentId\` goes in \`FilePart.attachmentId\`, is shown to the model as text, and is resolved by a tool through \`ctx.attachments\`.`);if(!Q.fileId&&!$)throw Error("FilePart.fileId is empty and there is no `attachmentId` either. `fileId` is the *provider's* file id and `attachmentId` is gemi's (`gemi_att_\u2026`), both from the upload response; an upload always answers at least one, so a part with neither was built from something other than that answer.")}function D6(Q){let $=/\.([a-z0-9]+)$/.exec(Q?.trim().toLowerCase()??"");return $?.[1]!==void 0&&x6.has($[1])}var x6=new Set(["jpeg","jpg","png","gif","webp"]),O6=new Set(["error","aborted","interrupted"]);function M6(Q){if(!Q.id)return null;let $={type:"reasoning",id:Q.id};return $.summary=Q.text?[{type:"summary_text",text:Q.text}]:[],$}function AQ(Q){if(Q.status==="ok"){let $=Q.modelOutput!==void 0?Q.modelOutput:Q.output;return typeof $==="string"?$:JSON.stringify($??null)}if(Q.status==="running"){let $=Q.job?.summary===void 0?"":` Started with: ${JSON.stringify(Q.job.summary)}.`;return`Started background job ${Q.job?.id??"(unknown)"}. It is still running, so there is no result yet: this message will be replaced by the result when it finishes. Do not start it again.${$}`}if(Q.status==="denied"){let $=Q.reason?` Reason given: ${Q.reason}`:"";if(Q.cause==="stopped")return`The run was stopped before this tool call could complete, so it did not run.${$}`;if(Q.cause==="interrupted")return`The run was interrupted (the server stopped) while this tool call was in progress, so its result was lost. It may have run in part or in full: check its effects before repeating it.${$}`;if(Q.cause==="denied-earlier")return`The user already declined this tool call earlier in this conversation, so it did not run and they were not asked again. Do not ask for it again; carry on without it.${$}`;return`The user declined this tool call, so it did not run.${$}`}return`The tool call failed and produced no result. Error (${Q.error?.code??"unknown"}): ${Q.error?.message??"no message"}`}function S6(Q,$){let J=new Set(L5(Q?.loaded)),Z=L5(Q?.namespaces),Y=new Set(Z),G=[];for(let z of $)if(BQ(z)){if(!Y.has(z.name))continue;let X=z.tools.filter((K)=>J.size===0||J.has(K.name));if(X.length===0)continue;G.push({type:"namespace",name:z.name,description:z.description,tools:X.map((K)=>m(K,!0))})}else if(z.deferred&&J.has(z.name))G.push(m(z,!0));if(G.length===0)return[];return[{type:"tool_search_call",call_id:null,execution:"server",status:"completed",arguments:Q.arguments&&typeof Q.arguments==="object"?Q.arguments:{paths:Z.length>0?Z:[...J]}},{type:"tool_search_output",call_id:null,execution:"server",status:"completed",tools:G}]}function L5(Q){return Array.isArray(Q)?Q.filter(($)=>typeof $==="string"):[]}function BQ(Q){return Array.isArray(Q.tools)}function _6(Q,$){if(!Q||Q.length===0)return[];if(!$.toolSearch){let Y=[];for(let G of Q)if(BQ(G))for(let B of G.tools)Y.push(m(B,!1));else Y.push(m(G,!1));return Y}let J=[],Z=!1;for(let Y of Q)if(BQ(Y)){let G=Y.tools.map((B)=>{if(B.deferred)Z=!0;return m(B,!0)});J.push({type:"namespace",name:Y.name,description:Y.description,tools:G})}else{if(Y.deferred)Z=!0;J.push(m(Y,!0))}if(Z)J.push({type:"tool_search"});return J}function m(Q,$){let J={type:"function",name:Q.name,description:Q.description,parameters:Q.parameters,strict:Q.strict};if($&&Q.deferred)J.defer_loading=!0;return J}var R6=64000;function P5(Q,$){let J={model:$.model,max_tokens:Q.maxOutputTokens??R6,messages:f6(Q.messages,$.capabilities),stream:!0},Z=Q.output,Y=!!Z?.strict&&!b6(Z.schema),G=Z&&!Y?h6(Z.schema):void 0,B=[Q.systemPrompt,G].filter(Boolean);if(B.length>0)J.system=[{type:"text",text:B.join(`
|
|
7
|
-
|
|
8
|
-
`)}];let z=$.capabilities.reasoning?Q.reasoning:void 0;if(z==="none"){if(/^claude-sonnet-5-5(?:-\d{8})?$/.test($.modelId))J.thinking={type:"between_tools"};J.output_config={effort:"low"}}else if(z)J.thinking={type:"adaptive",display:"summarized"},J.output_config={effort:A6(z,$.modelId)};else if($.capabilities.reasoning&&I6(J.messages))J.thinking={type:"adaptive"};if(J.thinking?.type==="adaptive"&&$.blockBinding)J.thinking.block_binding={prefix_mismatch_behavior:"drop_block"};if(Z&&Y)J.output_config={...J.output_config,format:{type:"json_schema",schema:v6(Z.schema)}};let X=r6(Q.tools);if(X.length>0){J.tools=X;let K=y6(Q.toolChoice,$.forcedToolChoice);if(!$.capabilities.parallelToolCalls)K.disable_parallel_tool_use=!0;if(Q.toolChoice!==void 0||K.disable_parallel_tool_use)J.tool_choice=K}return T6(J)}function I6(Q){return Q.some(($)=>$.content.some((J)=>J.type==="thinking"||J.type==="redacted_thinking"))}var TQ="thinking-binding-controls-2026-08-01";function D5(Q){if(/bound to a different conversation|Invalid `signature` in `thinking` block/i.test(Q))return"thinking";if(/schema is too complex/i.test(Q))return"schema";return}function x5(Q){let $=[];for(let J of Q.messages){let Z=J.content.filter((G)=>G.type!=="thinking"&&G.type!=="redacted_thinking");if(Z.length===0)continue;let Y=$.at(-1);if(Y?.role===J.role)Y.content.push(...Z);else $.push({role:J.role,content:Z})}return{...Q,messages:$}}function A6(Q,$){if(Q==="none"||Q==="minimal")return"low";if(Q==="xhigh"&&/^claude-(?:opus|sonnet)-4-6(?:-|$)/.test($))return"high";return Q}function T6(Q){let $=(Z)=>{if(Z)Z.cache_control={type:"ephemeral"}};$(Q.tools?.at(-1)),$(Q.system?.at(-1));let J=Q.messages.at(-1)?.content??[];return $([...J].reverse().find((Z)=>Z.type!=="thinking"&&Z.type!=="redacted_thinking")),Q}var E6=new Set(["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","maxItems","uniqueItems"]),w6=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]),k6=/\\[1-9]|\(\?<?[=!]|\\[bB]/,O5=new Set(["properties","patternProperties","$defs","definitions"]);function v6(Q){let $=(J)=>{if(Array.isArray(J))return J.map($);if(!v(J))return J;let Z={},Y=[];for(let[G,B]of Object.entries(J)){if(E6.has(G)||G==="minItems"&&typeof B==="number"&&B>1||G==="format"&&typeof B==="string"&&!w6.has(B)||G==="pattern"&&typeof B==="string"&&k6.test(B)){Y.push(`${G}: ${JSON.stringify(B)}`);continue}Z[G]=O5.has(G)&&v(B)?Object.fromEntries(Object.entries(B).map(([X,K])=>[X,$(K)])):$(B)}if(Y.length>0){let G=`{${Y.join(", ")}}`;Z.description=typeof Z.description==="string"?`${Z.description} ${G}`:G}if(Z.type==="object"||v(Z.properties))Z.additionalProperties=!1;return Z};return $(Q)}function b6(Q){let $=0,J=0,Z=(Y)=>{if(Array.isArray(Y))return Y.forEach(Z);if(!v(Y))return;if(Array.isArray(Y.anyOf)||Array.isArray(Y.type))J++;if(v(Y.properties)){let G=new Set(Array.isArray(Y.required)?Y.required:[]);$+=Object.keys(Y.properties).filter((B)=>!G.has(B)).length}for(let[G,B]of Object.entries(Y))if(O5.has(G)&&v(B))Object.values(B).forEach(Z);else Z(B)};return Z(Q),$>24||J>16}function h6(Q){return`Answer with only a JSON value (no prose, no code fence) that matches this JSON schema:
|
|
9
|
-
${JSON.stringify(Q)}`}function y6(Q,$){if(Q==="none")return{type:"none"};if(Q==="required")return $?{type:"any"}:{type:"auto"};if(Q&&typeof Q==="object")return $?{type:"tool",name:Q.name}:{type:"auto"};return{type:"auto"}}function f6(Q,$){let J=[],Z=new Map;for(let j of Q){let H=j.role==="assistant"?"assistant":"user";J.push("step-end");for(let V of j.content??[])switch(V.type){case"text":{if(H==="assistant"?!!V.text:!!V.text?.trim())J.push({role:H,block:{type:"text",text:V.text}});break}case"output":{if(V.partial)break;let W=V.text??JSON.stringify(V.value);J.push({role:H,block:{type:"text",text:W}});break}case"file":{if(H==="assistant")break;for(let W of p6(V,$))J.push({role:H,block:W});break}case"reasoning":{let W=H==="assistant"?d6(V):void 0;if(W)J.push({role:H,block:W});break}case"tool-call":{if(V.partial)break;J.push({role:"assistant",block:{type:"tool_use",id:V.toolCallId,name:String(V.name),input:v(V.input)?V.input:{}}});break}case"tool-result":{if(J.push("step-end"),Z.has(V.toolCallId))break;Z.set(V.toolCallId,{type:"tool_result",tool_use_id:V.toolCallId,content:AQ(V),...V.status==="error"?{is_error:!0}:{}});break}}}let Y=[],G=(j,H)=>{let V=Y[Y.length-1];if(V&&V.role===j)V.content.push(H);else Y.push({role:j,content:[H]})},B=new Set,z=[],X=!1,K=()=>{for(let j of z)G("user",Z.get(j)??c6(j));z=[],X=!1};for(let j of J){if(j==="step-end"){X=!0;continue}let{role:H,block:V}=j;if(X||H==="user")K();if(V.type==="tool_use"){let W=String(V.id);if(B.has(W))continue;B.add(W),z.push(W)}G(H,V)}if(K(),Y[0]?.role==="assistant")Y.unshift({role:"user",content:[{type:"text",text:g6}]});if(Y.at(-1)?.role==="assistant")Y.push({role:"user",content:[{type:"text",text:u6}]});return Y}var g6="(The conversation continues from an earlier point.)",u6="Continue.",m6="No result was recorded for this tool call. Assume it did not complete.";function c6(Q){return{type:"tool_result",tool_use_id:Q,content:m6}}function d6(Q){let $=Q.providerMetadata?.anthropic;if(!v($))return;if($.type==="thinking"&&typeof $.signature==="string")return{type:"thinking",thinking:Q.text??"",signature:$.signature};if($.type==="redacted_thinking"&&typeof $.data==="string")return{type:"redacted_thinking",data:$.data};return}function p6(Q,$){let J=_Q(Q),Z=(G)=>J?[{type:"text",text:l(Q,G)}]:[];if(!$.fileInput)return Z(!1);if(IQ(Q,J),!Q.fileId)return Z(!1);let Y=Q.providerRejected?void 0:i6(Q);if(!Y)return[...Z(!1),{type:"text",text:p(Q.name)}];return[...Z(!0),{type:Y,source:{type:"file",file_id:Q.fileId}}]}var l6=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function i6(Q){let $=Q.mimeType?.trim().toLowerCase()??"";if(RQ(Q))return!$||l6.has($)?"image":void 0;if($)return $==="application/pdf"||$==="text/plain"?"document":void 0;return/\.(pdf|txt)$/i.test(Q.name??"")?"document":void 0}function v(Q){return!!Q&&typeof Q==="object"&&!Array.isArray(Q)}function n6(Q){return Array.isArray(Q.tools)}function r6(Q){let $=[];for(let J of Q??[])for(let Z of n6(J)?J.tools:[J])$.push({name:Z.name,description:Z.description,input_schema:Z.parameters,eager_input_streaming:!0});return $}async function*R5(Q,$={}){let J=new Map,Z=[],Y,G={},B,z,X=!1,K=(j)=>({type:"finish",reason:j,usage:EQ(G),...Y?{model:Y}:{}});for await(let j of xQ(Q)){let H;try{H=JSON.parse(j.data)}catch{continue}switch(typeof H.type==="string"?H.type:j.event){case"message_start":{let W=H.message??{};if(typeof W.model==="string"&&W.model)Y=W.model;G=_5(G,W.usage),$.onUsage?.(EQ(G));break}case"content_block_start":{let W=Number(H.index),q=H.content_block??{},U={type:String(q.type??""),id:typeof q.id==="string"?q.id:void 0,name:typeof q.name==="string"?q.name:void 0,args:"",signature:typeof q.signature==="string"?q.signature:""};if(J.set(W,U),U.type==="redacted_thinking")yield{type:"reasoning-delta",delta:"",providerMetadata:{anthropic:{type:"redacted_thinking",data:String(q.data??"")}}};if(U.type==="text"&&typeof q.text==="string"&&q.text)yield S5(q.text,$);break}case"content_block_delta":{let W=J.get(Number(H.index)),q=H.delta??{};if(!W)break;if(q.type==="text_delta"){let U=String(q.text??"");if(U)yield S5(U,$)}else if(q.type==="thinking_delta"){let U=String(q.thinking??"");if(U)yield{type:"reasoning-delta",delta:U}}else if(q.type==="signature_delta")W.signature+=String(q.signature??"");else if(q.type==="input_json_delta"&&W.type==="tool_use"){let U=String(q.partial_json??"");if(!U)break;W.args+=U,yield{type:"tool-call-delta",toolCallId:W.id??"",name:W.name??"",argsDelta:U}}break}case"content_block_stop":{let W=Number(H.index),q=J.get(W);if(J.delete(W),q?.type==="thinking")yield{type:"reasoning-delta",delta:"",providerMetadata:{anthropic:{type:"thinking",signature:q.signature}}};if(q?.type==="tool_use")if(q.args||="{}",s6(q.args))yield M5(q);else Z.push(q);break}case"message_delta":{if(typeof H.delta?.stop_reason==="string")B=H.delta.stop_reason;if(H.delta?.stop_details)z=H.delta.stop_details;G=_5(G,H.usage),$.onUsage?.(EQ(G));break}case"message_stop":{if(X=!0,B==="refusal"){yield{type:"error",error:o6(z)},yield K("error");break}let W=a6(B);if(Z.length>0&&W==="length")yield{type:"tool-call-discard",toolCallIds:Z.map((q)=>q.id??"")};else for(let q of Z)yield M5(q);yield K(W);break}case"error":{X=!0;let W=H.error??H;yield{type:"error",error:t6(W),...QQ(W)},yield K("error");break}}if(X)return}yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield K("error")}function M5(Q){return{type:"tool-call",toolCallId:Q.id??"",name:Q.name??"",args:Q.args}}function s6(Q){try{return JSON.parse(Q),!0}catch{return!1}}function S5(Q,$){return $.structuredOutput?{type:"output-delta",delta:Q}:{type:"text-delta",delta:Q}}function a6(Q){if(Q==="max_tokens"||Q==="model_context_window_exceeded")return"length";return"stop"}function o6(Q){let $=typeof Q?.explanation==="string"?Q.explanation:"",J=typeof Q?.category==="string"?` (${Q.category})`:"";return{code:"content_filtered",message:$||`The model declined to answer${J}.`,retryable:!1}}function t6(Q){let $=String(Q?.type??"").toLowerCase(),J=typeof Q?.message==="string"?Q.message:"The provider stream failed.";if($==="rate_limit_error")return{code:"rate_limited",message:J,retryable:!0};if($==="invalid_request_error"||$==="request_too_large")return{code:/prompt is too long|request_too_large/i.test(`${$} ${J}`)?"context_length_exceeded":"provider_error",message:J,retryable:!1};if($==="authentication_error"||$==="permission_error"||$==="billing_error"||$==="not_found_error")return{code:"provider_error",message:J,retryable:!1};return{code:"provider_error",message:J,retryable:!0}}function _5(Q,$){if(!$||typeof $!=="object")return Q;let J={...Q};for(let Y of["input_tokens","output_tokens","cache_creation_input_tokens","cache_read_input_tokens"])if(typeof $[Y]==="number")J[Y]=$[Y];let Z=$.output_tokens_details?.thinking_tokens;if(typeof Z==="number")J.thinking_tokens=Z;return J}function EQ(Q){if(!Q)return R();let{cache_read_input_tokens:$,cache_creation_input_tokens:J}=Q,Z=(Q.input_tokens??0)+($??0)+(J??0),Y=Q.output_tokens??0,G={inputTokens:Z,outputTokens:Y,totalTokens:Z+Y};if(typeof $==="number")G.cachedInputTokens=$;if(typeof J==="number")G.cacheWriteInputTokens=J;if(typeof Q.thinking_tokens==="number")G.reasoningTokens=Q.thinking_tokens;return G}function wQ(Q){let $=vQ(Q);if($.startsWith("gpt-3.5")||$.startsWith("text-")||$.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1,supportsForcedToolChoice:!0};let J=Q7($);if(J?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:J.major>1,toolSearch:I5(J),supportsForcedToolChoice:!0};if(J?.kind==="gpt")return{reasoning:J.major>=5,structuredOutput:J.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),fileInput:J.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:I5(J),supportsForcedToolChoice:!0};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0,supportsForcedToolChoice:!0}}function I5(Q){if(Q.kind==="o")return Q.major>=5;return Q.major>5||Q.major===5&&Q.minor>=2}function kQ(Q){let $=vQ(Q),J=/^claude-(?:opus|sonnet|haiku)-4(?:-(\d{1,2}))?(?:-\d{8})?$/.exec($);return{reasoning:!(/^claude-(?:3|2|instant)/.test($)||!!J&&Number(J[1]??0)<=5),structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!1,supportsForcedToolChoice:e6(Q)}}function e6(Q){let $=vQ(Q);return/^claude-(?:3|2|instant)/.test($)||/^claude-(?:opus|sonnet|haiku)-4(?:-|$)/.test($)||/^claude-(?:opus|sonnet|fable|mythos)-5(?:-\d{8})?$/.test($)||/^claude-haiku-5-5(?:-\d{8})?$/.test($)}function vQ(Q){return Q.trim().toLowerCase()}function Q7(Q){let $=/^gpt-(\d+)(?:\.(\d+))?/.exec(Q);if($?.[1])return{kind:"gpt",major:Number($[1]),minor:Number($[2]??0)};let J=/^o(\d+)(?:[-.]|$)/.exec(Q);if(J?.[1])return{kind:"o",major:Number(J[1]),minor:0};return null}var bQ=120000,hQ=2,yQ=120000,fQ=300000,gQ=1000;function x(Q){return typeof process>"u"?void 0:process.env?.[Q]}var $7="preview";function A5(Q){let $=Q.trim().replace(/\/+$/,"");if(!$)return"";return`${$.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function J7(Q){return/^\d{4}-\d{2}-\d{2}/.test(Q)?"":"/v1"}function uQ(Q,$={}){return{base:(Q.baseURL??x("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let Z=Q.apiKey??x("OPENAI_API_KEY");return{...Z?{authorization:`Bearer ${Z}`}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??bQ,streamIdleTimeoutMs:Q.streamIdleTimeoutMs??yQ,streamMaxDurationMs:Q.streamMaxDurationMs??fQ,maxToolArgumentChars:Q.maxToolArgumentChars??0,maxToolArgumentWhitespace:Q.maxToolArgumentWhitespace??gQ,maxRetries:Q.maxRetries??hQ,...cQ(Q)}}function T5(Q){let $=Q.baseURL??Q.endpoint??x("AZURE_OPENAI_ENDPOINT");if($)return A5($);let J=Q.resourceName??x("AZURE_OPENAI_RESOURCE_NAME")??x("AZURE_RESOURCE_NAME");return J?A5(`https://${J.trim()}.cognitiveservices.azure.com`):""}function mQ(Q,$={}){let J=Q.apiVersion??x("AZURE_OPENAI_API_VERSION")??$7;return{base:`${T5(Q)}${J7(J)}`,query:`?api-version=${encodeURIComponent(J)}`,headers:async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`,...Q.headers};let Z=Q.apiKey??x("AZURE_OPENAI_API_KEY");return{...Z?{"api-key":Z}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??bQ,streamIdleTimeoutMs:Q.streamIdleTimeoutMs??yQ,streamMaxDurationMs:Q.streamMaxDurationMs??fQ,maxToolArgumentChars:Q.maxToolArgumentChars??0,maxToolArgumentWhitespace:Q.maxToolArgumentWhitespace??gQ,maxRetries:Q.maxRetries??hQ,...cQ(Q)}}var Z7="2026-10-21";function E5(Q,$={}){let J=Q.baseURL??x("ANTHROPIC_BASE_URL")??"https://api.anthropic.com";return k5(J,Q,$,async()=>{let Z=Q.workspaceId??x("ANTHROPIC_WORKSPACE_ID"),Y=Z?{"anthropic-workspace-id":Z}:{},G=Q.apiKey??x("ANTHROPIC_API_KEY");if(G)return{"x-api-key":G,...Y};let B=x("ANTHROPIC_AUTH_TOKEN");return B?{authorization:`Bearer ${B}`,...Y}:Y})}function w5(Q,$={}){let J=Q.resourceName??x("ANTHROPIC_FOUNDRY_RESOURCE"),Z=Q.baseURL??Q.endpoint??x("ANTHROPIC_FOUNDRY_BASE_URL")??(J?`https://${J.trim()}.services.ai.azure.com/anthropic`:"");if(!Z.trim())throw Error("AzureAnthropicProvider has no Foundry endpoint. Set `endpoint` (the deployment's Target URI without `/v1/messages`, e.g. `https://<resource>.services.ai.azure.com/anthropic`) or `resourceName`, or the ANTHROPIC_FOUNDRY_BASE_URL or ANTHROPIC_FOUNDRY_RESOURCE environment variable.");return k5(Z,Q,$,async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`};let Y=Q.apiKey??x("ANTHROPIC_FOUNDRY_API_KEY");return Y?{"api-key":Y}:{}})}function k5(Q,$,J,Z){return{base:`${Q.trim().replace(/\/+$/,"").replace(/\/v1$/,"")}/v1`,query:"",headers:async()=>({...await Z(),"anthropic-version":Z7,...$.headers}),timeoutMs:$.timeoutMs??J.timeoutMs??bQ,streamIdleTimeoutMs:$.streamIdleTimeoutMs??yQ,streamMaxDurationMs:$.streamMaxDurationMs??fQ,maxToolArgumentChars:$.maxToolArgumentChars??0,maxToolArgumentWhitespace:$.maxToolArgumentWhitespace??gQ,maxRetries:$.maxRetries??hQ,...cQ($)}}function v5(Q,$={}){return{...mQ(Q,$),base:`${T5(Q)}/v1`,query:""}}function cQ(Q){return aQ(Q.retry),Q.retry?{retry:Q.retry}:{}}class KQ{static models(){return[]}normalizeError(Q){return M(Q)}}var b5=["gpt-5.5","gpt-5.4","gpt-5.4-mini","gpt-5.4-nano","gpt-5.2","gpt-5.1","gpt-5","gpt-5-mini","gpt-5-nano","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4o","gpt-4o-mini","o4-mini","o3","o3-mini"];class h5 extends KQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=wQ(Q),this.config=$}static model(Q,$){return new h5(Q,$)}static models(){return b5}stream(Q){let $=SQ(Q,{model:this.model,capabilities:this.capabilities});return YQ(this.endpoint(),$,{signal:Q.signal,retryToolArgumentsTooLong:Q.retryToolArgumentsTooLong,structuredOutput:Boolean(Q.output),files:CQ(Q.messages)})}upload(Q){return GQ(this.endpoint(),Q)}deleteFile(Q){return VQ(this.endpoint(),Q)}endpoint(){return ZQ(uQ(this.config))}get realtime(){return new e(uQ(this.config,{timeoutMs:FQ}),{model:this.model})}}var Y7=["claude-opus-5-5","claude-sonnet-5-5","claude-haiku-5-5","claude-fable-5-2","claude-fable-5-1","claude-opus-5","claude-sonnet-5","claude-fable-5","claude-opus-4-8","claude-sonnet-4-6","claude-haiku-4-5"];class dQ extends KQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=kQ(Q),this.config=$}static model(Q,$){return new dQ(Q,$)}static models(){return Y7}stream(Q){return this.send(Q)}async*send(Q){let $=Q,J=!1,Z=new Set;for(;;){let Y=this.request($);if(J)Y=x5(Y);let G,B=!1;for await(let z of YQ(this.endpointFor(Y),Y,{signal:Q.signal,retryToolArgumentsTooLong:Q.retryToolArgumentsTooLong,structuredOutput:Boolean(Q.output),parse:R5})){if(G)continue;if(!B&&z.type==="error"&&z.status===400){let X=D5(z.error.message);if(X&&!Z.has(X)){Z.add(X),G=X;continue}}if(JQ(z))B=!0;yield z}if(!G)return;if(G==="thinking")J=!0;else if($.output)$={...$,output:{...$.output,strict:!1}}}}request(Q){return P5(Q,{model:this.deployment(),modelId:this.model,capabilities:this.capabilities,forcedToolChoice:this.capabilities.supportsForcedToolChoice!==!1,blockBinding:this.bindsThinking()})}endpointFor(Q){let $=this.endpoint();if(!(Q.thinking?.type==="adaptive"&&Q.thinking.block_binding))return $;return{...$,headers:async()=>{let Z=await $.headers(),Y=Z["anthropic-beta"];return{...Z,"anthropic-beta":Y?`${Y},${TQ}`:TQ}}}}bindsThinking(){return!0}deployment(){return this.model}upload(Q){return GQ(this.endpoint(),Q,null)}deleteFile(Q){return VQ(this.endpoint(),Q)}endpoint(){return y5(E5(this.config))}}function y5(Q){return{...ZQ(Q),responsesUrl:`${Q.base}/messages`}}class f5 extends dQ{constructor(Q,$={}){super(Q,$);this.capabilities={...kQ(Q),fileInput:!1}}static model(Q,$){return new f5(Q,$)}upload(Q){return Promise.reject(Error("AzureAnthropicProvider does not upload files: the Files API is not available on Azure-hosted Foundry deployments. The file is still stored by gemi and named to the model by its attachment id."))}deleteFile(Q){return Promise.reject(Error("AzureAnthropicProvider does not delete files: the Files API is not available on Azure-hosted Foundry deployments."))}deployment(){return this.config.deployment??this.model}bindsThinking(){return!1}endpoint(){return y5(w5(this.config))}}class g5 extends KQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=wQ(Q),this.config=$}static model(Q,$){return new g5(Q,$)}static models(){return b5}stream(Q){let $=SQ(Q,{model:this.deployment(),capabilities:this.capabilities});return YQ(this.endpoint(),$,{signal:Q.signal,retryToolArgumentsTooLong:Q.retryToolArgumentsTooLong,structuredOutput:Boolean(Q.output),files:CQ(Q.messages)})}upload(Q){return GQ(this.endpoint(),Q,"assistants")}deleteFile(Q){return VQ(this.endpoint(),Q)}deployment(){return this.config.deployment??this.model}endpoint(){return ZQ(mQ(this.config))}get realtime(){return new e(v5(this.config,{timeoutMs:FQ}),{model:this.deployment(),callFlow:"ephemeral"})}}
|
|
10
|
-
export{g as ca,uQ as da,mQ as ea,qQ as fa,o5 as ga,UQ as ha,d as ia,e as ja,J6 as ka,KQ as la,h5 as ma,dQ as na,f5 as oa,g5 as pa};
|
|
11
|
-
|
|
12
|
-
//# debugId=00E261704EDAB59F64756E2164756E21
|