gemi 0.205.2 → 0.205.3
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/index.js +1 -1
- package/dist/ai/providers/call.d.ts.map +1 -1
- package/dist/ai/providers/fileRejection.d.ts +4 -0
- package/dist/ai/providers/fileRejection.d.ts.map +1 -1
- package/dist/ai/providers/request.d.ts.map +1 -1
- package/dist/ai/providers/staleReasoning.d.ts +25 -0
- package/dist/ai/providers/staleReasoning.d.ts.map +1 -0
- package/dist/ai/testing/index.js +1 -1
- package/dist/chunk-2e40rx0p.js +11 -0
- package/dist/{chunk-bb74k64k.js.map → chunk-2e40rx0p.js.map} +7 -6
- package/dist/{chunk-mepaafn3.js → chunk-bdrce9s8.js} +1 -1
- package/dist/{chunk-zfrwh9qm.js → chunk-bz84hrc3.js} +2 -2
- package/dist/{chunk-zfrwh9qm.js.map → chunk-bz84hrc3.js.map} +1 -1
- package/dist/{chunk-kj7z3kav.js → chunk-rbndzqg7.js} +1 -1
- package/dist/server/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-bb74k64k.js +0 -11
- /package/dist/{chunk-mepaafn3.js.map → chunk-bdrce9s8.js.map} +0 -0
- /package/dist/{chunk-kj7z3kav.js.map → chunk-rbndzqg7.js.map} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$ as AJ,_ as p,aa as DJ,ba as PJ}from"./chunk-
|
|
2
|
+
import{$ as AJ,_ as p,aa as DJ,ba as PJ}from"./chunk-bz84hrc3.js";import{Da as b,Ha as T,Ia as NJ}from"./chunk-v2fd69at.js";import"./chunk-ba1h9pm6.js";import{Pe as jJ,dh as xJ,eh as k,mh as IJ,nh as MJ,oh as FJ}from"./chunk-zwznp46g.js";import"./chunk-hthyn5pj.js";import"./chunk-1em8t2x1.js";import{ti as ZJ,ui as XJ,xi as QJ}from"./chunk-7wzhdq1x.js";import{Kj as LJ}from"./chunk-aed0vv5g.js";import"./chunk-jy26hy7z.js";import"./chunk-8ar7180x.js";import"./chunk-yj1h4rzn.js";import"./chunk-3z8d8v8q.js";import"./chunk-wdrmzjtq.js";import"./chunk-6cx6kh04.js";import"./chunk-06w8hhnk.js";import"./chunk-24tj4dzx.js";import"./chunk-xgc5tj8k.js";import"./chunk-etcds9w3.js";import"./chunk-nfher0gz.js";import"./chunk-65btke6p.js";import"./chunk-vyaedzr8.js";import"./chunk-djnn8vvp.js";import{im as GJ}from"./chunk-tx5zrdmb.js";import"./chunk-0eq7am78.js";import{Am as _J}from"./chunk-77dt2tap.js";import{Cm as y}from"./chunk-ne51fxg2.js";import"./chunk-zf1eqgzt.js";import{createHash as U2}from"crypto";import{join as d,resolve as TJ,sep as BJ}from"path";import{Duplex as gJ}from"stream";import{constants as E,createBrotliCompress as fJ,createGzip as mJ}from"zlib";var uJ=["br","gzip"],hJ=1024,cJ=5,pJ=19,dJ=6;function lJ(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 oJ(J){if(J===null||J===void 0)return null;let $=new Map;for(let Z of J.split(",")){let[X,...j]=Z.split(";"),H=X.trim().toLowerCase();if(H==="")continue;let W=1;for(let G of j){let U=G.indexOf("=");if(U===-1)continue;if(G.slice(0,U).trim().toLowerCase()==="q"){W=lJ(G.slice(U+1));break}}$.set(H,W)}return $}function m(J,$=uJ){let Z=oJ(J);if(!Z)return null;let X=Z.get("*"),j=null,H=0;for(let W of $){let G=Z.get(W)??X??0;if(G>H)j=W,H=G}return j}function nJ(J,$){if(!J)return!1;return J.split(",").some((Z)=>Z.trim().toLowerCase().split("=")[0].trim()===$)}function iJ(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 X=$.headers.get("Content-Encoding");if(X&&X.trim().toLowerCase()!=="identity")return!1;if(nJ($.headers.get("Cache-Control"),"no-transform"))return!1;let j=$.headers.get("Content-Length");if(j!==null&&Number(j)<hJ)return!1;return!0}function aJ(J){let $=J==="br"?fJ({params:{[E.BROTLI_PARAM_QUALITY]:cJ,[E.BROTLI_PARAM_LGWIN]:pJ},flush:E.BROTLI_OPERATION_FLUSH}):mJ({level:dJ,flush:E.Z_SYNC_FLUSH});return gJ.toWeb($)}function rJ(J){let $=J.get("Vary");if(!$){J.set("Vary","Accept-Encoding");return}let Z=$.split(",").map((X)=>X.trim().toLowerCase());if(Z.includes("*")||Z.includes("accept-encoding"))return;J.append("Vary","Accept-Encoding")}function s(J,$){if(!iJ(J.method,$))return $;let Z=new Headers($.headers);rJ(Z);let X=m(J.headers.get("Accept-Encoding"));if(!X)return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z});let j;try{j=aJ(X)}catch{return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z})}return Z.set("Content-Encoding",X),Z.delete("Content-Length"),new Response($.body.pipeThrough(j),{status:$.status,statusText:$.statusText,headers:Z})}import{readdir as X2,stat as HJ}from"fs/promises";import{join as Q2}from"path";import{mkdir as F2,readFile as tJ,stat as N2,writeFile as A2}from"fs/promises";import{dirname as P2,join as sJ}from"path";import{promisify as e}from"util";import{brotliCompress as eJ,constants as R2,gzip as J2}from"zlib";var $2=".vite/static-assets.json";var JJ={br:".br",gzip:".gz"},Z2=["br","gzip"],S2=e(eJ),b2=e(J2);async function $J(J){let $;try{$=await tJ(sJ(J,$2),"utf8")}catch{return null}let Z;try{Z=JSON.parse($)?.files}catch{return null}if(!Z||typeof Z!=="object")return null;let X={files:{}};for(let[j,H]of Object.entries(Z)){if(!Array.isArray(H))continue;X.files[j]=Z2.filter((W)=>H.includes(W))}return X}function u(J){let $=J.toString(),Z=new Bun.CryptoHasher("sha1");return Z.update($),Z.digest("hex")}async function WJ(J){let $=new Set;async function Z(X,j){let H;try{H=await X2(X,{withFileTypes:!0})}catch{return}for(let W of H){if(W.name.startsWith("."))continue;if(j&&W.name==="assets")continue;let G=Q2(X,W.name),U=W.isDirectory(),O=W.isFile();if(W.isSymbolicLink())try{let _=await HJ(G);U=_.isDirectory(),O=_.isFile()}catch{continue}if(O)$.add(G);else if(U&&!W.isSymbolicLink())await Z(G,!1)}}return await Z(J,!0),$}var j2="public, max-age=31536000, must-revalidate",H2="public, max-age=31536000, immutable";async function W2(J,$,Z){if(Z.length===0||J.headers.has("Range"))return null;let X=m(J.headers.get("Accept-Encoding"),Z);if(!X)return null;let j=$+JJ[X];try{let H=await HJ(j);return H.isFile()?{encoding:X,path:j,size:H.size}:null}catch{return null}}async function YJ(J,$,Z={}){let X=Bun.file($),j=Z.encodings??[],H={"Content-Type":X.type||"application/octet-stream","Cache-Control":Z.immutable?H2:j2,"Accept-Ranges":"bytes"};if(j.length>0)H.Vary="Accept-Encoding";let W=await W2(J,$,j);if(W){let O=Bun.file(W.path);return new Response(O.stream(),{headers:{...H,"Content-Encoding":W.encoding,"Content-Length":String(W.size),ETag:`${u(O.lastModified)}-${W.encoding}`}})}let G=X.size;H.ETag=u(X.lastModified);let U=ZJ(J.headers.get("Range"));if(U){let O=XJ(U,G);if(!O)return jJ(G);return new Response(X.slice(O.start,O.end+1).stream(),{status:206,headers:{...H,"Content-Range":QJ(O.start,O.end,G),"Content-Length":String(O.length)}})}return new Response(X.stream(),{headers:{...H,"Content-Length":String(G)}})}import{stat as z2}from"fs/promises";var v="app/client.tsx";function OJ(J,$=b){let Z=J[v]?.file;if(!Z)return;return{module:T(Z,$),preload:P(J,v,$)}}function P(J,$,Z=b){let X=[],j=new Set,H=(W)=>{if(j.has(W))return;j.add(W);let G=J[W];if(!G?.file)return;X.push(T(G.file,Z));for(let U of G.imports??[])H(U)};return H($),X}function Y2(J,$,Z=b){let X=new Set(P(J,$,Z)),j=[],H=new Set,W=(U)=>{if(H.has(U))return;H.add(U);let O=J[U];if(!O)return;for(let _ of O.dynamicImports??[])if(!/(^|\/)node_modules\//.test(_)&&!j.includes(_))j.push(_);for(let _ of O.imports??[])W(_)};W($);let G=[];for(let U of j)for(let O of P(J,U,Z))if(!X.has(O))X.add(O),G.push(O);return G}function VJ(J,$){let Z=[],X=new Set,j=new Set,H=(W)=>{if(j.has(W))return;j.add(W);let G=J[W];if(!G)return;for(let U of G.imports??[])H(U);for(let U of G.css??[])if(!X.has(U))X.add(U),Z.push(U)};return H($),Z}function UJ(J,$=b){let Z=new Map;return(X)=>{if(!Z.has(X)){let j=`${X}${GJ}`,H=J[j]?.file;Z.set(X,H?{src:T(H,$),preload:P(J,j,$),dynamicPreload:Y2(J,j,$)}:void 0)}return Z.get(X)}}var zJ="x-gemi-build";function G2(J,$,Z,X){let j=Date.now(),H=function(V){return typeof V==="number"&&j-V>=0&&j-V<Z},W=function(V){try{let z=V?JSON.parse(V):null;return z&&typeof z==="object"&&!Array.isArray(z)?z:{}}catch{return{}}},G=function(V){let z={};for(let I in V)if(H(V[I]))z[I]=V[I];return z},U=function(V){let z=2166136261;for(let I=0;I<V.length;I++)z=Math.imul(z^V.charCodeAt(I),16777619);return(z>>>0).toString(36)},O=null,_={};try{O=window.sessionStorage,_=W(O.getItem(J))}catch{O=null}let F=J+":",N="",A="";try{let V=new URL($,window.location.href);N=U(new URL(window.location.href).origin),A=U(V.origin+V.pathname)}catch{}let C=null;try{let V=window.name;if(!A)C=null;else if(V==="")C={};else if(V.indexOf(F)===0){let z=W(V.slice(F.length)),I=z.m;C=z.o===N&&I&&typeof I==="object"&&!Array.isArray(I)?I:{}}}catch{C=null}if(X==="tidy"){try{let V=window.name;if(C===null||V.indexOf(F)!==0)return"ok";for(let z in C)if(H(C[z]))return"cooldown";window.name=""}catch{}return"ok"}if(H(_[$])||C&&H(C[A]))return"cooldown";if(!O&&!C)return"storage";if(!X)return"ok";if(O)try{let V=G(_);V[$]=j;let z=JSON.stringify(V);if(O.setItem(J,z),O.getItem(J)===z)return"ok"}catch{}if(C)try{let V=G(C);V[A]=j;let z=F+JSON.stringify({o:N,m:V});if(window.name=z,window.name===z)return"ok"}catch{}return"storage"}function KJ(J,$=30000){let Z=JSON.stringify("gemi:chunk-reload"),X=JSON.stringify(`Failed to fetch dynamically imported module: ${J}`);return`var g=${G2.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(${X});export {}`}var O2=new RegExp(`^${xJ}/.+\\.m?js$`);function h(J){return O2.test(J)}function CJ(J){if(h(J))return new Response(KJ(J),{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store"}});if(k(J))return new Response("Not found",{status:404});return}var V2=`<!DOCTYPE html>
|
|
3
3
|
<html lang="en">
|
|
4
4
|
<head>
|
|
5
5
|
<meta charset="UTF-8" />
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Qa as m}from"./chunk-ba1h9pm6.js";import{createElement as j}from"react";function z(i,t){let u=Object.keys(t).sort((s,p)=>p.length-s.length).map((s)=>s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),r=new RegExp(u.join("|"),"g");return i.replace(r,(s)=>t[s])}async function X(i,t,u=[],r){let s=[...u.map((n)=>`${i}/views/${n}.tsx`),r?`${i}/views/${r}.tsx`:`${i}/views/RootLayout.tsx`],p=new Set;for(let n of s){let e=t.moduleGraph.getModulesByFile(n);if(e)for(let d of e)p.add(d)}let b=[],l=[],g={};for(let n of p)if(n)for(let e of n.importedModules){if(e.file.includes("module.css"))g[e.file]=e.ssrTransformResult.map.sourcesContent.join("");if(e.file.includes(".css"))l.push(e.file)}for(let n of l){let e=await t.transformRequest(n+"?direct"),d=n.includes("module.css"),a="";if(d)a=z(g[n],e.default);b.push({isDev:!0,id:n,content:d?a:e.code})}return b.map((n,e)=>{return j("style",{key:e,type:"text/css","data-vite-dev-id":n.id,dangerouslySetInnerHTML:{__html:n.content}})})}async function Y(i=[]){return i.map((t,u)=>{return j("style",{key:u,id:t?.id,type:"text/css",dangerouslySetInnerHTML:{__html:t.content}})})}import{existsSync as f}from"fs";import{basename as q}from"path";import{networkInterfaces as k}from"os";var v={name:"gemi",version:"0.205.
|
|
2
|
+
import{Qa as m}from"./chunk-ba1h9pm6.js";import{createElement as j}from"react";function z(i,t){let u=Object.keys(t).sort((s,p)=>p.length-s.length).map((s)=>s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),r=new RegExp(u.join("|"),"g");return i.replace(r,(s)=>t[s])}async function X(i,t,u=[],r){let s=[...u.map((n)=>`${i}/views/${n}.tsx`),r?`${i}/views/${r}.tsx`:`${i}/views/RootLayout.tsx`],p=new Set;for(let n of s){let e=t.moduleGraph.getModulesByFile(n);if(e)for(let d of e)p.add(d)}let b=[],l=[],g={};for(let n of p)if(n)for(let e of n.importedModules){if(e.file.includes("module.css"))g[e.file]=e.ssrTransformResult.map.sourcesContent.join("");if(e.file.includes(".css"))l.push(e.file)}for(let n of l){let e=await t.transformRequest(n+"?direct"),d=n.includes("module.css"),a="";if(d)a=z(g[n],e.default);b.push({isDev:!0,id:n,content:d?a:e.code})}return b.map((n,e)=>{return j("style",{key:e,type:"text/css","data-vite-dev-id":n.id,dangerouslySetInnerHTML:{__html:n.content}})})}async function Y(i=[]){return i.map((t,u)=>{return j("style",{key:u,id:t?.id,type:"text/css",dangerouslySetInnerHTML:{__html:t.content}})})}import{existsSync as f}from"fs";import{basename as q}from"path";import{networkInterfaces as k}from"os";var v={name:"gemi",version:"0.205.3",private:!1,license:"MIT",author:"Enes Tufekci <enes@gemijs.dev>",repository:{type:"git",url:"git+https://github.com/nstfkc/gemi.git",directory:"packages/gemi"},bin:{gemi:"./dist/bin/gemi.js","gemi-orm-generator":"./dist/bin/orm-generator.js"},files:["dist/**/*","ide/typescript-plugin/package.json","skills/**/*"],module:!0,exports:{"./http":"./http/index.ts","./client":"./client/index.ts","./ai":"./ai/index.ts","./ai/client":"./ai/client/index.ts","./ai/voice":"./ai/voice/index.ts","./ai/testing":"./ai/testing/index.ts","./testing":"./testing/index.ts","./app":"./app/index.ts","./facades":"./facades/index.ts","./email":"./email/index.ts","./vite":"./dist/vite/index.mjs","./kernel":"./kernel/index.ts","./services":"./services/index.ts","./i18n":"./i18n/index.ts","./dictionary":"./i18n/dictionaryRuntime.ts","./server":"./server/index.ts","./config":"./config/index.ts","./container":"./container/index.ts","./foundation":"./foundation/index.ts","./database":"./database/index.ts","./orm":"./orm/index.ts","./support":"./support/index.ts","./probe":"./probe/index.ts","./console/run":"./console/run.ts","./queue/work":"./services/queue/work.ts","./stats/route-table":"./stats/route-table.ts","./ide/typescript-plugin":"./ide/typescript-plugin/index.ts","./bun/preload":"./bun/preload.ts","./bun/plugin":"./bun/plugin.ts","./vitest":"./vitest/index.ts"},scripts:{lint:"oxlint",typecheck:"tsc --noEmit -p tsconfig.json && tsc --noEmit -p tsconfig.browser.json && tsc --noEmit -p ide/typescript-plugin/tsconfig.json",build:"NODE_ENV=production bun run build:core && bun run build:bin && bun run build:types && bun run build:client && bun run build:plugin && bun run build:ts-plugin && bun run build:client-types && bun run build:augmentation","build:core":"bun ./scripts/build.ts","build:bin":"bun build --outdir=./dist/bin --target=bun --external=vite --external=react-dom --external=react/jsx-runtime --external=bun --external=sharp --external=@azure/storage-blob --external=@azure/communication-email --external=@azure/identity --external=typescript --sourcemap ./bin/gemi.ts ./bin/orm-generator.ts && bun ./scripts/prepare-bin.ts","build:client":"rm -rf dist/client dist/testing dist/ai/client dist/ai/voice dist/chunks && vite build -c vite.client.config.mts","build:plugin":"vite build -c vite.plugin.config.mts","build:ts-plugin":"bun ./scripts/build-ts-plugin.ts","build:types":"tsc -p tsconfig.build.json","build:client-types":"tsc -p tsconfig.browser.json",test:"bun --bun x vitest","test:types":"vitest run --typecheck.only","test:live":"bun --bun x vitest run ai/live","test:packaging":"bun --bun x vitest run --config vitest.packaging.config.ts","build:publish":"bun scripts/build-publish.ts",prepublishOnly:"echo 'Do not publish from this directory \u2014 its exports point at TS source. Run: bun run build:publish, then publish from .publish/' && exit 1","build:augmentation":"bun ./scripts/wire-augmentation.ts"},dependencies:{"@aws-sdk/client-s3":"^3.629.0","@aws-sdk/s3-request-presigner":"^3.629.0","ast-types":"^0.14.2",commander:"^12.1.0",history:"^5.3.0","jsx-email":"2.0.0-rc2.1","magic-string":"^0.30.17",open:"^10.1.0","react-error-boundary":"^6.0.0",recast:"^0.23.9",resend:"^6.12.3",satori:"^0.12.2","temporal-polyfill":"^0.2.5","twitter-api-v2":"^1.20.2","urlpattern-polyfill":"^10.0.0",uuid:"^9.0.1"},devDependencies:{"@babel/parser":"^7.25.4","@prisma/generator-helper":"^6.5.0","@repo/typescript-config":"*","@testing-library/react":"^16.3.2","@types/bun":"^1.3.14","@types/eslint":"^8.56.5","@types/node":"^20.11.24","@types/react":"^19.0.2","@types/react-dom":"^19.0.2",eslint:"^8.57.0","happy-dom":"^21.0.4",jsdom:"^30.0.1",oxlint:"^1.39.0",postgres:"^3.4.5",react:"19.2.3","react-dom":"19.2.3",typescript:"^5.7.3",vitest:"^4.0.0"},peerDependencies:{"@azure/communication-email":"^1.1.0","@azure/identity":"^4.0.0","@azure/storage-blob":"^12.28.0",react:">=19","react-dom":">=19",sharp:"^0.34.2",typescript:">=5",vite:"^8.0.0",postgres:"^3.4.0"},peerDependenciesMeta:{"@azure/communication-email":{optional:!0},"@azure/identity":{optional:!0},"@azure/storage-blob":{optional:!0},typescript:{optional:!0},postgres:{optional:!0}}};var $=[" \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557\u2588\u2588\u2557","\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551","\u2588\u2588\u2551 \u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2554\u2588\u2588\u2588\u2588\u2554\u2588\u2588\u2551\u2588\u2588\u2551","\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2551\u255A\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2551","\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u255A\u2550\u255D \u2588\u2588\u2551\u2588\u2588\u2551"," \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D"],h=Boolean(process.stdout.isTTY)&&!process.env.NO_COLOR,c=(i,t)=>h?`\x1B[${i}m${t}\x1B[0m`:t,E=(i)=>c("1",i),x=(i)=>c("2",i),o=(i)=>c("36",i),G=(i)=>c("32",i),J=(i)=>c("35",i);function N(){return v.version??"?"}function O(i){for(let t of Object.values(k()))for(let u of t??[])if((u.family==="IPv4"||u.family===4)&&!u.internal)return`http://${u.address}:${i}`;return null}function Q(i){return m(i).filter((t)=>f(t)).map((t)=>q(t))}function F(i){let{port:t,rootDir:u}=i,r=`http://localhost:${t}`,s=O(t),p=Q(u),b=(g,n)=>` ${G("\u279C")} ${E(g.padEnd(9))}${n}`,l=["",...$.map((g)=>J(g)),"",` ${x("gemi")} ${o(`v${N()}`)}`,"",b("Local:",o(r)),b("Network:",s?o(s):x("unavailable")),b("Env:",p.length?p.join(", "):x("none")),""];console.log(l.join(`
|
|
3
3
|
`))}function V(i,t){return Error(`app/views/${i}.tsx is missing. gemi's auth routes render it because ${t} is on. Add the view, or turn that setting off in app/config/auth.ts.`)}function U(i=process.env.SERVER_IDLE_TIMEOUT){if(i===void 0||i.trim()==="")return 10;let t=Number(i.trim());if(!Number.isInteger(t)||t<0||t>255)throw Error(`SERVER_IDLE_TIMEOUT must be a whole number of seconds from 0 to 255 (0 disables the timeout), got ${JSON.stringify(i)}.`);return t}
|
|
4
4
|
export{X as Z,Y as _,F as $,V as aa,U as ba};
|
|
5
5
|
|
|
6
|
-
//# debugId=
|
|
6
|
+
//# debugId=49A0D825C71B9B3364756E2164756E21
|
|
@@ -8,6 +8,6 @@
|
|
|
8
8
|
"/**\n * Bun's default, and what both servers use when `SERVER_IDLE_TIMEOUT` is unset.\n */\nexport const DEFAULT_SERVER_IDLE_TIMEOUT = 10;\n\n/**\n * The `idleTimeout` (seconds) both `gemi dev` and `gemi start` pass to\n * `Bun.serve`, from `SERVER_IDLE_TIMEOUT` (#787).\n *\n * One reader for both servers, so a long-poll that works under `gemi start`\n * also works under `gemi dev`. Before this, only `httpProd` read the variable\n * and the dev server always ran at Bun's 10 seconds.\n *\n * It is the time a connection may stay silent, a response that has not started\n * included, before Bun closes it; `0` disables it. It does not apply to an\n * upgraded websocket (the HMR relay included), which has its own\n * `websocket.idleTimeout`.\n *\n * Unset or blank means the default. Anything that is not a whole number from 0\n * to 255 (Bun's own limits) fails the boot with the variable's name, instead\n * of Bun's \"expects idleTimeout to be an integer\", which does not say where the\n * value came from.\n */\nexport function serverIdleTimeout(raw: string | undefined = process.env.SERVER_IDLE_TIMEOUT): number {\n if (raw === undefined || raw.trim() === \"\") return DEFAULT_SERVER_IDLE_TIMEOUT;\n\n const seconds = Number(raw.trim());\n if (!Number.isInteger(seconds) || seconds < 0 || seconds > 255) {\n throw new Error(\n `SERVER_IDLE_TIMEOUT must be a whole number of seconds from 0 to 255 ` +\n `(0 disables the timeout), got ${JSON.stringify(raw)}.`,\n );\n }\n return seconds;\n}\n"
|
|
9
9
|
],
|
|
10
10
|
"mappings": ";yCAAA,wBAAS,cAGT,SAAS,CAAc,CAAC,EAAc,EAAwC,CAC5E,IAAM,EAAc,OAAO,KAAK,CAAM,EACnC,KAAK,CAAC,EAAG,IAAM,EAAE,OAAS,EAAE,MAAM,EAClC,IAAI,CAAC,IAAQ,EAAI,QAAQ,sBAAuB,MAAM,CAAC,EAGpD,EAAQ,IAAI,OAAO,EAAY,KAAK,GAAG,EAAG,GAAG,EAEnD,OAAO,EAAK,QAAQ,EAAO,CAAC,IAAU,EAAO,EAAM,EAGrD,eAAsB,CAAe,CACnC,EACA,EACA,EAAyB,CAAC,EAE1B,EACA,CACA,IAAM,EAAQ,CACZ,GAAG,EAAa,IAAI,CAAC,IAAS,GAAG,WAAgB,OAAU,EAC3D,EAAS,GAAG,WAAgB,QAAe,GAAG,wBAChD,EAEM,EAAU,IAAI,IACpB,QAAW,KAAQ,EAAO,CACxB,IAAM,EAAM,EAAK,YAAY,iBAAiB,CAAI,EAClD,GAAI,EACF,QAAW,KAAK,EAAK,EAAQ,IAAI,CAAC,EAItC,IAAM,EAAS,CAAC,EACV,EAAa,CAAC,EACd,EAA2C,CAAC,EAClD,QAAW,KAAO,EAChB,GAAI,EACF,QAAW,KAAY,EAAI,gBAAiB,CAC1C,GAAI,EAAS,KAAK,SAAS,YAAY,EACrC,EAAiB,EAAS,MAAQ,EAAS,mBAAmB,IAAI,eAAe,KAAK,EAAE,EAE1F,GAAI,EAAS,KAAK,SAAS,MAAM,EAC/B,EAAW,KAAK,EAAS,IAAI,EAMrC,QAAW,KAAiB,EAAY,CACtC,IAAM,EAAY,MAAM,EAAK,iBAAiB,EAAgB,SAAS,EAEjE,EAAc,EAAc,SAAS,YAAY,EAEnD,EAAuB,GAE3B,GAAI,EACF,EAAuB,EACrB,EAAiB,GAGhB,EAA6D,OAChE,EAGF,EAAO,KAAK,CACV,MAAO,GACP,GAAI,EACJ,QAAS,EAAc,EAAuB,EAAU,IAC1D,CAAC,EAGH,OAAO,EAAO,IAAI,CAAC,EAAO,IAAM,CAC9B,OAAO,EAAc,QAAS,CAC5B,IAAK,EACL,KAAM,WACN,mBAAoB,EAAM,GAC1B,wBAAyB,CAAE,OAAQ,EAAM,OAAQ,CACnD,CAAC,EACF,EAGH,eAAsB,CAAY,CAAC,EAAS,CAAC,EAAG,CAC9C,OAAO,EAAO,IAAI,CAAC,EAAO,IAAM,CAC9B,OAAO,EAAc,QAAS,CAC5B,IAAK,EACL,GAAI,GAAO,GACX,KAAM,WACN,wBAAyB,CAAE,OAAQ,EAAM,OAAQ,CACnD,CAAC,EACF,EC3FH,qBAAS,WACT,mBAAS,aACT,4BAAS,wnIAKT,IAAM,EAAM,CACV,oKACA,mLACA,yKACA,oKACA,mLACA,yJACF,EAEM,EAAW,QAAQ,QAAQ,OAAO,KAAK,GAAK,CAAC,QAAQ,IAAI,SACzD,EAAQ,CAAC,EAAc,IAC3B,EAAW,QAAQ,KAAQ,WAAgB,EACvC,EAAO,CAAC,IAAc,EAAM,IAAK,CAAC,EAClC,EAAM,CAAC,IAAc,EAAM,IAAK,CAAC,EACjC,EAAO,CAAC,IAAc,EAAM,KAAM,CAAC,EACnC,EAAQ,CAAC,IAAc,EAAM,KAAM,CAAC,EACpC,EAAU,CAAC,IAAc,EAAM,KAAM,CAAC,EAE5C,SAAS,CAAW,EAAW,CAC7B,OAAQ,EAA6B,SAAW,IAGlD,SAAS,CAAU,CAAC,EAAsC,CACxD,QAAW,KAAU,OAAO,OAAO,EAAkB,CAAC,EACpD,QAAW,KAAS,GAAU,CAAC,EAG7B,IADa,EAAM,SAAW,QAAW,EAAM,SAAuB,IAC1D,CAAC,EAAM,SAAU,MAAO,UAAU,EAAM,WAAW,IAGnE,OAAO,KAGT,SAAS,CAAc,CAAC,EAA2B,CACjD,OAAO,EAAS,CAAO,EACpB,OAAO,CAAC,IAAS,EAAW,CAAI,CAAC,EACjC,IAAI,CAAC,IAAS,EAAS,CAAI,CAAC,EAG1B,SAAS,CAAkB,CAAC,EAGhC,CACD,IAAQ,OAAM,WAAY,EACpB,EAAQ,oBAAoB,IAC5B,EAAU,EAAW,CAAI,EACzB,EAAM,EAAe,CAAO,EAE5B,EAAM,CAAC,EAAe,IAC1B,KAAK,EAAM,QAAE,MAAM,EAAK,EAAM,OAAO,CAAC,CAAC,IAAI,IAEvC,EAAM,CACV,GACA,GAAG,EAAI,IAAI,CAAC,IAAS,EAAQ,CAAI,CAAC,EAClC,GACA,KAAK,EAAI,MAAM,KAAK,EAAK,IAAI,EAAY,GAAG,IAC5C,GACA,EAAI,SAAU,EAAK,CAAK,CAAC,EACzB,EAAI,WAAY,EAAU,EAAK,CAAO,EAAI,EAAI,aAAa,CAAC,EAC5D,EAAI,OAAQ,EAAI,OAAS,EAAI,KAAK,IAAI,EAAI,EAAI,MAAM,CAAC,EACrD,EACF,EAEA,QAAQ,IAAI,EAAI,KAAK;AAAA,CAAI,CAAC,ECjErB,SAAS,CAAwB,CAAC,EAAc,EAAoB,CACzE,OAAW,MACT,aAAa,0DAA6D,wEAE5E,ECcK,SAAS,CAAiB,CAAC,EAA0B,QAAQ,IAAI,oBAA6B,CACnG,GAAI,IAAQ,QAAa,EAAI,KAAK,IAAM,GAAI,MArBH,IAuBzC,IAAM,EAAU,OAAO,EAAI,KAAK,CAAC,EACjC,GAAI,CAAC,OAAO,UAAU,CAAO,GAAK,EAAU,GAAK,EAAU,IACzD,MAAU,MACR,qGACmC,KAAK,UAAU,CAAG,IACvD,EAEF,OAAO",
|
|
11
|
-
"debugId": "
|
|
11
|
+
"debugId": "49A0D825C71B9B3364756E2164756E21",
|
|
12
12
|
"names": []
|
|
13
13
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$ as c,Z as P,aa as f,ba as l}from"./chunk-
|
|
2
|
+
import{$ as c,Z as P,aa as f,ba as l}from"./chunk-bz84hrc3.js";import{Ba as u,Ca as m}from"./chunk-q751b0jx.js";import"./chunk-v2fd69at.js";import"./chunk-hke4hzfm.js";import"./chunk-0cckwd91.js";import"./chunk-1tc6j8bn.js";import"./chunk-ba1h9pm6.js";import"./chunk-jy61580r.js";import{Kj as S}from"./chunk-aed0vv5g.js";import{im as T}from"./chunk-tx5zrdmb.js";import{Cm as y}from"./chunk-ne51fxg2.js";import"./chunk-zf1eqgzt.js";import{join as YJ}from"path";import{createServer as AJ}from"vite";import{join as R,sep as o}from"path";import{existsSync as a,statSync as s}from"fs";import{IncomingMessage as t,ServerResponse as r}from"http";import{Socket as e}from"net";function i(J){return J.replace(/\x1b\[[0-9;]*m/g,"").replace(/\[[0-9;]*m/g,"").replace(/\n\s*\n/g,`
|
|
3
3
|
`).split(`
|
|
4
4
|
`).map((W)=>W.trim()).filter((W)=>W.length>0).join(`
|
|
5
5
|
`).trim()}function N(J){return`
|
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-jy61580r.js";import{mm as Q,om as q,pm as w,sm as Z,tm as P,um as y,vm as S,wm as U}from"../chunk-0eq7am78.js";import{Am as H}from"../chunk-77dt2tap.js";import"../chunk-ne51fxg2.js";import{Im as F}from"../chunk-zf1eqgzt.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-jy61580r.js";import{mm as Q,om as q,pm as w,sm as Z,tm as P,um as y,vm as S,wm as U}from"../chunk-0eq7am78.js";import{Am as H}from"../chunk-77dt2tap.js";import"../chunk-ne51fxg2.js";import{Im as F}from"../chunk-zf1eqgzt.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-bdrce9s8.js");this.server=await J(this.app,I)}else{f();let{httpDev:J}=await import("../chunk-rbndzqg7.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=FE20FBD008CD065864756E2164756E21
|
package/package.json
CHANGED
package/dist/chunk-bb74k64k.js
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Md as KQ,Sd as A,Td as p,Ud as uQ,Vd as cQ,Wd as mQ,Xd as T,Yd as M,wd as r,yd as n}from"./chunk-e0scxs81.js";import{Tj as IQ}from"./chunk-8ar7180x.js";var j5=500,xQ=20000;function F5(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 d(Q,$){let J=Math.min(xQ,j5*2**Q);return Math.round(J*(0.5+$()*0.5))}function U5(Q){return Q===429||Q===408||Q===409||Q>=500}function q5(Q,$){return U5(Q)&&M($).retryable}function _Q(Q){return Q.reason??new DOMException("The operation was aborted.","AbortError")}function SQ(Q,$){return new Promise((J,Z)=>{let X=setTimeout(J,Q);$?.addEventListener("abort",()=>{clearTimeout(X),Z(_Q($))},{once:!0})})}async function QQ(Q,$,J=SQ){if(!$)return await J(Q);$.throwIfAborted();let Z;try{await Promise.race([J(Q,$),new Promise((X,Y)=>{Z=()=>Y(_Q($)),$.addEventListener("abort",Z,{once:!0})})])}finally{if(Z)$.removeEventListener("abort",Z)}}async function h(Q,$,J){let Z=J.fetchImpl??((B,G)=>fetch(B,G)),X=J.sleep??SQ,Y=J.random??Math.random,V=J.now??Date.now,K=Math.max(0,J.maxRetries),j=J.startedAt??V(),W=(B,G,H,U)=>{try{J.onRetry?.({attempt:G+1,maxRetries:K,error:M(H),...T(H),timedOut:U,delayMs:B,elapsedMs:V()-j})}catch{}return QQ(B,J.signal,X)},F;for(let B=0;B<=K;B++){J.signal?.throwIfAborted();let G=new AbortController,H=()=>G.abort(J.signal?.reason);J.signal?.addEventListener("abort",H,{once:!0});let U=!1,z=J.timeoutMs>0?setTimeout(()=>{U=!0,G.abort()},J.timeoutMs):void 0,N;try{N=await Z(Q,{...$,signal:G.signal})}catch(I){if(z!==void 0)clearTimeout(z);if(J.signal?.removeEventListener("abort",H),J.signal?.aborted)throw I;if(F=U?new p(J.timeoutMs):I,U&&J.retryTimeouts===!1)throw F;if(B===K)throw F;await W(d(B,Y),B,F,U);continue}if(z!==void 0)clearTimeout(z);if(N.ok)return N;J.signal?.removeEventListener("abort",H);let _=await z5(N),D=new A(N.status,_,N.headers.get("x-request-id")??N.headers.get("request-id")??void 0,F5(N.headers.get("retry-after"),V()));if(B===K||!q5(N.status,D))throw D;let g=D.retryAfter??(N.status===429?M(D).retryAfter:void 0);await W(g===void 0?d(B,Y):Math.min(g,xQ),B,D,!1),F=D}throw F??Error("Provider request failed with no response.")}async function z5(Q){let $;try{$=await Q.text()}catch{return null}try{return JSON.parse($)}catch{return $}}function OQ(Q,$,J){let Z=$.idleMs>0?$.idleMs:0,X=$.maxMs>0?$.maxMs:0;if(!Q||!Z&&!X)return Q;let Y=X?performance.now()+X:1/0,V=Q.getReader();return new ReadableStream({async pull(K){let j,W,F=Math.max(0,Y-performance.now()),B=!Z||F<=Z,G=B?F:Z,H=new Promise((U,z)=>{j=setTimeout(()=>{W=B?J.max():J.idle(),z(W)},G)});try{let U=await Promise.race([V.read(),H]);if(U.done)K.close();else K.enqueue(U.value)}catch(U){let z=W??U;K.error(z),V.cancel(z).catch(()=>{})}finally{clearTimeout(j)}},cancel(K){return V.cancel(K)}},{highWaterMark:0})}var JQ=30000,RQ=10,AQ=7200,L5=600,D5="gpt-live-transcribe";function P5(Q){return Q.type==="transcription"}function C5(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 X of Q.keywords??[])if(/[<>\r\n]/.test(X))throw TypeError(`Transcription keywords must be one line without "<" or ">", got ${JSON.stringify(X)}.`);let $={model:Q.model??D5};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?TQ(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 N5(Q){if(!Q)return{type:"object",properties:{}};return IQ(Q)?Q.toJSONSchema():Q}function l(Q,$){if(P5(Q))return C5(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((V)=>({type:"function",name:V.name,...V.description?{description:V.description}:{},parameters:N5(V.parameters)}));if(Q.toolChoice!==void 0)J.tool_choice=typeof Q.toolChoice==="string"?Q.toolChoice:{type:"function",name:Q.toolChoice.name};let X={};if(Q.turnDetection!==void 0)X.turn_detection=Q.turnDetection&&TQ(Q.turnDetection);if(Q.transcription!==void 0)X.transcription=Q.transcription;if(Q.noiseReduction!==void 0)X.noise_reduction=Q.noiseReduction&&{type:Q.noiseReduction};let Y={};if(Q.voice!==void 0)Y.voice=Q.voice;if(Q.speed!==void 0)Y.speed=Q.speed;if(Object.keys(X).length||Object.keys(Y).length)J.audio={...Object.keys(X).length?{input:X}:{},...Object.keys(Y).length?{output:Y}:{}};return{...J,...Q.vendor}}function TQ(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 ZQ(Q){let $=Number(Q?.input_tokens??0),J=Number(Q?.output_tokens??0),Z={inputTokens:$,outputTokens:J,totalTokens:Number(Q?.total_tokens??$+J)},X=Q?.input_token_details??Q?.input_tokens_details,Y=Q?.output_token_details??Q?.output_tokens_details;if(typeof X?.cached_tokens==="number")Z.cachedInputTokens=X.cached_tokens;if(typeof X?.audio_tokens==="number")Z.audioInputTokens=X.audio_tokens;let V=X?.cached_tokens_details?.audio_tokens;if(typeof V==="number")Z.cachedAudioInputTokens=V;if(typeof X?.image_tokens==="number"&&X.image_tokens>0)Z.imageInputTokens=X.image_tokens;if(typeof Y?.audio_tokens==="number")Z.audioOutputTokens=Y.audio_tokens;return Z}class y 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 M5=60;class i{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,X)=>`ws${X}:`),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:M5,signal:Q.signal})).value}`,"content-type":"application/sdp"},Z=Q.sdp;else{let j=new FormData;j.set("sdp",Q.sdp),j.set("session",JSON.stringify(l(Q.session??{},this.model))),J=await this.target.headers(),Z=j}if(Q.safetyIdentifier)J["OpenAI-Safety-Identifier"]=Q.safetyIdentifier;let X=this.url("/calls"),Y=await this.request(Q.webrtcFilter?`${X}${X.includes("?")?"&":"?"}webrtcfilter=on`:X,{method:"POST",headers:J,body:Z},Q.signal),V=await Y.text(),K=_5(Y);if(!K)throw new y({code:"provider_error",message:"The provider started a realtime call but did not say which one (no Location).",retryable:!1});return{sdpAnswer:V,callId:K}}async clientSecret(Q={}){let $=Q.ttlSeconds??L5;if(!Number.isInteger($)||$<RQ||$>AQ)throw RangeError(`ttlSeconds must be a whole number from ${RQ} to ${AQ}, got ${$}.`);let J={...await this.target.headers(),"content-type":"application/json"};if(Q.safetyIdentifier)J["OpenAI-Safety-Identifier"]=Q.safetyIdentifier;let X=await(await this.request(this.url("/client_secrets"),{method:"POST",headers:J,body:JSON.stringify({expires_after:{anchor:"created_at",seconds:$},session:l(Q.session??{},this.model)})},Q.signal)).json();if(typeof X?.value!=="string")throw new y({code:"provider_error",message:"The provider answered a client secret request with no secret.",retryable:!1});return{value:X.value,expiresAt:Number(X.expires_at??0),session:X.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(x5(J,Q))return;throw J}}sideband(Q,$={}){return new $Q({...$,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 h(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 y(M(Z),{cause:Z,...Z instanceof A?{status:Z.status}:{}})}}}function x5(Q,$){if(!(Q instanceof y)||Q.status!==404)return!1;let J=Q.cause instanceof A?Q.cause.body:void 0,Z=J?.error??J,X=String(Z?.code??"").toLowerCase(),Y=String(Z?.message??"").toLowerCase();if(X.includes("call"))return!0;if(Y.includes($.toLowerCase()))return!0;return/\bcall\b/.test(Y)&&/not (be )?found|does not exist|no longer|ended/.test(Y)}function _5(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 S5={"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 O5(Q){if(typeof Q!=="string")return;let $;try{$=JSON.parse(Q)}catch{return}if(!$||typeof $!=="object"||typeof $.type!=="string")return;let J=S5[$.type];if(J)$.type=J;if($.type==="response.done"&&$.response?.usage)$.usage=ZQ($.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=ZQ($.usage);return $}var EQ=1,R5=500;function A5(Q,$){let J=globalThis.WebSocket;if(!J)throw Error("No global WebSocket: the realtime sideband needs Bun or Node 22+.");return new J(Q,{headers:$.headers})}class $Q{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===EQ)this.socket.send($);else this.outbox.push($)}updateSession(Q){this.send({type:"session.update",session:l(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<=EQ)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??A5)(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 X of this.outbox.splice(0))Q.send(X);if(this.resolveReady(),J)this.emit({type:"sideband.reconnected",attempt:Z})}),Q.addEventListener("message",(J)=>{let Z=O5(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 Y=(this.init.reconnect?.delayMs??500)*2**(this.failures-1);setTimeout(()=>void this.open(),Y)}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 X of this.subscribers)X.done=!0,X.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>R5)this.backlog.shift()}for(let $ of this.subscribers){if($.done)continue;$.queue.push(Q),$.wake?.()}for(let $ of this.listeners)try{$(Q)}catch{}}}var vQ=3;function XQ(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 hQ(Q,$,J=new Map){if(!($ instanceof A))return[];if($.status!==400&&$.status!==404)return[];let Z=T5($.body);if(!Z)return[];let X=I5(Q.input);if(X.length===0)return[];let Y=/^input\[(\d+)\]\.content\[(\d+)\]\.file_id$/.exec(Z.param??"");if(Y){let W=Q.input[Number(Y[1])],F=YQ(W)[Number(Y[2])],B=F&&typeof F.file_id==="string"?F.file_id:void 0;if(B)return[B]}let V=Z.message??"",K=kQ(X.map((W)=>W.fileId).filter((W)=>E5(V,W)));if(K.length>0)return K;let j=/Expected (image type|context stuffing file type) to be a supported format:.*but got \.([a-z0-9]+)\.?\s*$/is.exec(V);if(j){let W=j[1].toLowerCase()==="image type"?"input_image":"input_file",F=j[2].toLowerCase(),B=kQ(X.filter((H)=>H.type===W).map((H)=>H.fileId)),G=B.filter((H)=>(J.get(H)?.name??"").trim().toLowerCase().endsWith(`.${F}`));if(G.length===1)return G;if(G.length===0&&B.length===1)return B}return[]}function yQ(Q,$,J=new Map){return{...Q,input:Q.input.map((Z)=>{let X=YQ(Z);if(!X.some((Y)=>wQ(Y,$)))return Z;return{...Z,content:X.map((Y)=>wQ(Y,$)?{type:"input_text",text:b(J.get(String(Y.file_id))?.name)}:Y)}})}}function b(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 wQ(Q,$){return typeof Q.file_id==="string"&&$.has(Q.file_id)}function YQ(Q){let $=Q?.content;return Array.isArray($)?$:[]}function I5(Q){let $=[];for(let J of Q)for(let Z of YQ(J))if(typeof Z.file_id==="string"&&Z.file_id)$.push({type:String(Z.type),fileId:Z.file_id});return $}function T5(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 E5(Q,$){let J=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${J}($|[^A-Za-z0-9_-])`).test(Q)}function kQ(Q){return[...new Set(Q)]}async function*VQ(Q){let $="",J="",Z=[],X,Y=()=>{if(Z.length===0&&!J)return null;let j={event:J,data:Z.join(`
|
|
3
|
-
`),id:X};return J="",Z=[],X=void 0,j.data?j:null},V=(j)=>{let W=j.endsWith("\r")?j.slice(0,-1):j;if(W==="")return Y();if(W.startsWith(":"))return null;let F=W.indexOf(":"),B=F===-1?W:W.slice(0,F),G=F===-1?"":W.slice(F+1);if(G.startsWith(" "))G=G.slice(1);if(B==="event")J=G;else if(B==="data")Z.push(G);else if(B==="id")X=G;return null};for await(let j of Q){$+=j;let W=$.indexOf(`
|
|
4
|
-
`);while(W!==-1){let F=$.slice(0,W);$=$.slice(W+1);let B=V(F);if(B)yield B;W=$.indexOf(`
|
|
5
|
-
`)}}if($.length>0){let j=V($);if(j)yield j}let K=Y();if(K)yield K}async function*bQ(Q,$={}){let J=new Map,Z=new Set,X,Y=!1,V,K=(j,W)=>({type:"finish",reason:j,usage:W,...V?{model:V}:{}});for await(let j of VQ(Q)){if(j.data==="[DONE]")break;let W;try{W=JSON.parse(j.data)}catch{continue}let F=typeof W.type==="string"?W.type:j.event,B=W.response?.model;if(typeof B==="string"&&B)V=B;switch(F){case"response.output_text.delta":{let G=String(W.delta??"");if(!G)break;yield $.structuredOutput?{type:"output-delta",delta:G}:{type:"text-delta",delta:G};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let G=String(W.delta??"");if(!G)break;yield{type:"reasoning-delta",delta:G,id:W.item_id};break}case"response.output_item.added":{let G=W.item;if(!G)break;if(G.type==="function_call"){let H=String(G.id??W.item_id??G.call_id??"");J.set(H,{callId:String(G.call_id??H),name:String(G.name??""),namespace:typeof G.namespace==="string"&&G.namespace?G.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let G=J.get(String(W.item_id??""));if(!G)break;let H=String(W.delta??"");if(!H)break;yield{type:"tool-call-delta",toolCallId:G.callId,name:G.name,argsDelta:H,...G.namespace?{namespace:G.namespace}:{}};break}case"response.function_call_arguments.done":{let G=String(W.item_id??""),H=J.get(G);if(!H)break;H.done=!0,yield{type:"tool-call",toolCallId:H.callId,name:H.name,args:String(W.arguments??""),...H.namespace?{namespace:H.namespace}:{}};break}case"response.output_item.done":{let G=W.item;if(!G)break;if(G.type==="function_call"){let H=String(G.id??W.item_id??G.call_id??""),U=J.get(H);if(U?.done)break;let z=(typeof G.namespace==="string"?G.namespace:"")||U?.namespace;if(yield{type:"tool-call",toolCallId:String(G.call_id??H),name:String(G.name??U?.name??""),args:String(G.arguments??""),...z?{namespace:z}:{}},U)U.done=!0;break}if(G.type==="tool_search_call"||G.type==="tool_search_output"){if(G.type==="tool_search_call"&&G.arguments!==void 0)X=G.arguments;let H=w5(G);if(H.loaded.length===0&&H.namespaces.length===0)break;let U=String(G.tool_search_call_id??G.id??"");if(Z.has(U))break;Z.add(U);let z=X;X=void 0,yield{type:"tool-search",...H,...z!==void 0&&z!==null?{arguments:z}:{}}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(W.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{Y=!0,yield K("stop",WQ(W.response?.usage));break}case"response.incomplete":{Y=!0;let G=WQ(W.response?.usage),H=W.response?.incomplete_details?.reason;if(H==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:k5(W.response?.content_filters),retryable:!1}},yield K("error",G);break}yield K(H==="max_output_tokens"?"length":"stop",G);break}case"response.failed":case"error":{Y=!0;let G=W.response?.error??W.error??W;yield{type:"error",error:v5(G)},yield K("error",WQ(W.response?.usage));break}}if(Y)return}if(!Y)yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield K("error",x())}function w5(Q){let $=[],J=[];return fQ(Q.results??Q.tools??Q.loaded??Q.output,$,J,0),{loaded:GQ($),namespaces:GQ(J)}}function fQ(Q,$,J,Z){if(!Array.isArray(Q)||Z>4)return;for(let X of Q){if(typeof X==="string"){$.push(X);continue}if(!X||typeof X!=="object")continue;let Y=X,V=typeof Y.name==="string"?Y.name:typeof Y.tool_name==="string"?Y.tool_name:"",K=Y.tools??Y.functions;if(Array.isArray(K)){if(V)J.push(V);fQ(K,$,J,Z+1);continue}if(V)$.push(V)}}function GQ(Q){return Q.filter(($,J)=>Q.indexOf($)===J)}function k5(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 X=Z,Y=X.content_filter_results;if(!Y||typeof Y!=="object")continue;for(let[V,K]of Object.entries(Y))if(K&&typeof K==="object"&&K.filtered===!0)J.push(`${V} (${String(X.source_type??"unknown")})`)}return J.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${GQ(J).join(", ")}.`}function v5(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 x(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function WQ(Q){if(!Q)return x();let $=Number(Q.input_tokens??0),J=Number(Q.output_tokens??0),Z={inputTokens:$,outputTokens:J,totalTokens:Number(Q.total_tokens??$+J)},X=Q.output_tokens_details?.reasoning_tokens;if(typeof X==="number")Z.reasoningTokens=X;let Y=Q.input_tokens_details?.cached_tokens;if(typeof Y==="number")Z.cachedInputTokens=Y;return Z}async function*gQ(Q){if(!Q)return;let $=Q.getReader(),J=new TextDecoder;try{while(!0){let{done:X,value:Y}=await $.read();if(X)break;if(Y)yield J.decode(Y,{stream:!0})}let Z=J.decode();if(Z)yield Z}finally{$.releaseLock()}}function a(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,maxRetries:Q.maxRetries}}async function*s(Q,$,J){let Z=J.parse??bQ,X=$,Y=new Set,V=0,K=Math.max(0,Q.maxRetries),j=Q.random??Math.random,W,F=(_)=>{if(!W)return _;let D=n(n(x(),W),_.usage);return W=void 0,{..._,usage:D}},B=()=>F({type:"finish",reason:"aborted",usage:x()}),G=Q.streamIdleTimeoutMs??0,H=Q.streamMaxDurationMs??0,U=Q.maxToolArgumentChars??0,z=Q.now??Date.now,N=z();for(let _=0;;_++){let D=new AbortController,g=J.signal?AbortSignal.any([J.signal,D.signal]):D.signal,I;while(I===void 0)try{let L=[],q=()=>{},P=h(Q.responsesUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify(X)},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,signal:g,fetchImpl:Q.fetchImpl,sleep:Q.sleep,random:Q.random,now:Q.now,startedAt:N,onRetry:(R)=>{L.push({type:"retry",...R,phase:"request"}),q()}}),O=P.then(()=>!0,()=>!0);for(;;){let R=new Promise((B5)=>q=()=>B5(!1)),m=await Promise.race([O,R]);if(yield*L.splice(0),m)break}I=await P}catch(L){let q=X,P=J.files&&V<vQ?hQ(q,L,J.files).filter((R)=>!Y.has(R)):[];if(P.length>0){V++;let R=M(L).message;for(let m of P)Y.add(m),yield{type:"file-rejected",fileId:m,message:R,...T(L)};X=yQ(q,new Set(P),J.files);continue}let O=M(L);if(O.code==="aborted"){yield B();return}yield{type:"error",error:O,...T(L)},yield F({type:"finish",reason:"error",usage:x()});return}let k=[],u=!1,c,MQ=!1,v=new Map;try{let L=OQ(I.body,{idleMs:G,maxMs:H},{idle:()=>{let q=new uQ(G);return D.abort(q),q},max:()=>{let q=new cQ(H);return D.abort(q),q}});for await(let q of Z(gQ(L),{structuredOutput:J.structuredOutput})){if(q.type==="tool-call-delta"){let P=(v.get(q.toolCallId)??0)+q.argsDelta.length;if(v.set(q.toolCallId,P),U>0&&P>U){let O=new mQ(U,q.name);throw D.abort(O),O}yield q;continue}if(q.type==="tool-call")v.delete(q.toolCallId);if(u){yield q.type==="finish"?F(q):q;continue}if(r(q)){u=!0,yield*k.splice(0),yield q;continue}if(q.type==="error")c=q.error;k.push(q)}}catch(L){MQ=L instanceof p;let q=M(L);if(q.code==="aborted"||J.signal?.aborted){yield B();return}if(u){yield{type:"error",error:q},yield F({type:"finish",reason:"error",usage:x()});return}c=q,k.push({type:"error",error:q},{type:"finish",reason:"error",usage:x()})}if(u)return;if(c?.retryable&&_<K&&!J.signal?.aborted){let L={};for(let P of k){if(P.type==="finish")W=n(W??x(),P.usage);if(P.type==="error")L=T(P)}if(v.size>0)yield{type:"tool-call-discard",toolCallIds:[...v.keys()]};let q=d(_,j);yield{type:"retry",attempt:_+1,maxRetries:K,error:c,...L,phase:"stream",timedOut:MQ,delayMs:q,elapsedMs:z()-N};try{await QQ(q,J.signal,Q.sleep)}catch{yield B();return}continue}for(let L of k)yield L.type==="finish"?F(L):L;return}}async function o(Q,$,J="user_data"){let Z=new FormData;if(J)Z.set("purpose",J);Z.set("file",$);let Y=await(await h(Q.filesUrl,{method:"POST",headers:await Q.headers(),body:Z},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,fetchImpl:Q.fetchImpl})).json();if(!Y?.id)throw Error("The provider accepted the upload but returned no file id.");return Y.id}function HQ(Q,$){let{capabilities:J}=$,Z={model:$.model,input:h5(Q.messages,J,Q.tools),stream:!0};if(Q.systemPrompt)Z.instructions=Q.systemPrompt;let X=d5(Q.tools,J);if(X.length>0){if(Z.tools=X,!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 h5(Q,$,J){let Z=[],X=new Map;if($.toolSearch){for(let Y of J??[])if(t(Y))X.set(Y.name,Y)}for(let Y of Q){let V=Y.role,K=[],j=()=>{if(K.length===0)return;Z.push({type:"message",role:V,content:K}),K=[]};for(let W of Y.content??[])switch(W.type){case"text":{if(!W.text)break;K.push(E(V,W.text));break}case"output":{if(W.partial)break;K.push(E(V,JSON.stringify(W.value)));break}case"file":{if(V==="assistant")break;let F=BQ(W);if(!$.fileInput){if(F)K.push(E(V,f(W,!1)));break}if(FQ(W,F),W.providerRejected){if(F)K.push(E(V,f(W,!1)));K.push(E(V,b(W.name)));break}if(F)K.push(E(V,f(W,!!W.fileId)));if(W.fileId)K.push(f5(W));break}case"reasoning":{j();let F=c5(W);if(F)Z.push(F);break}case"tool-call":{if(W.partial)break;if(j(),$.toolSearch&&Array.isArray(W.toolSearches))for(let B of W.toolSearches)Z.push(...m5(B,J??[]));let F={type:"function_call",call_id:W.toolCallId,name:String(W.name),arguments:JSON.stringify(W.input??{})};if(W.namespace&&X.has(W.namespace))F.namespace=W.namespace;Z.push(F);break}case"tool-result":{j(),Z.push({type:"function_call_output",call_id:W.toolCallId,output:UQ(W)});break}}j()}return b5(Z)}var y5="No result was recorded for this tool call. Assume it did not complete.";function b5(Q){let $=new Set,J=new Set,Z=[];for(let Y of Q){if(Y.type==="function_call"){let V=String(Y.call_id);if($.has(V))continue;$.add(V)}else if(Y.type==="function_call_output"){let V=String(Y.call_id);if(!$.has(V)||J.has(V))continue;J.add(V)}Z.push(Y)}if(J.size===$.size)return Z;let X=[];for(let Y of Z){if(X.push(Y),Y.type!=="function_call")continue;let V=String(Y.call_id);if(J.has(V))continue;J.add(V),X.push({type:"function_call_output",call_id:V,output:y5})}return X}function E(Q,$){return{type:Q==="assistant"?"output_text":"input_text",text:$}}function BQ(Q){let $=Q.attachmentId;return typeof $==="string"&&$.startsWith(KQ)?$:void 0}function f(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 f5(Q){return{type:jQ(Q)?"input_image":"input_file",file_id:Q.fileId}}function jQ(Q){let $=Q.mimeType?.trim().toLowerCase()??"";return $?$.startsWith("image/")&&$!=="image/svg+xml":g5(Q.name)}function FQ(Q,$){if(Q.fileId?.startsWith(KQ))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 g5(Q){let $=/\.([a-z0-9]+)$/.exec(Q?.trim().toLowerCase()??"");return $?.[1]!==void 0&&u5.has($[1])}var u5=new Set(["jpeg","jpg","png","gif","webp"]);function c5(Q){if(!Q.id)return null;let $={type:"reasoning",id:Q.id};return $.summary=Q.text?[{type:"summary_text",text:Q.text}]:[],$}function UQ(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.${$}`;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 m5(Q,$){let J=new Set(dQ(Q?.loaded)),Z=dQ(Q?.namespaces),X=new Set(Z),Y=[];for(let K of $)if(t(K)){if(!X.has(K.name))continue;let j=K.tools.filter((W)=>J.size===0||J.has(W.name));if(j.length===0)continue;Y.push({type:"namespace",name:K.name,description:K.description,tools:j.map((W)=>w(W,!0))})}else if(K.deferred&&J.has(K.name))Y.push(w(K,!0));if(Y.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:Y}]}function dQ(Q){return Array.isArray(Q)?Q.filter(($)=>typeof $==="string"):[]}function t(Q){return Array.isArray(Q.tools)}function d5(Q,$){if(!Q||Q.length===0)return[];if(!$.toolSearch){let X=[];for(let Y of Q)if(t(Y))for(let V of Y.tools)X.push(w(V,!1));else X.push(w(Y,!1));return X}let J=[],Z=!1;for(let X of Q)if(t(X)){let Y=X.tools.map((V)=>{if(V.deferred)Z=!0;return w(V,!0)});J.push({type:"namespace",name:X.name,description:X.description,tools:Y})}else{if(X.deferred)Z=!0;J.push(w(X,!0))}if(Z)J.push({type:"tool_search"});return J}function w(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 p5=64000;function pQ(Q,$){let J={model:$.model,max_tokens:Q.maxOutputTokens??p5,messages:$6(Q.messages,$.capabilities),stream:!0},Z=Q.output,X=!!Z?.strict&&!t5(Z.schema),Y=Z&&!X?e5(Z.schema):void 0,V=[Q.systemPrompt,Y].filter(Boolean);if(V.length>0)J.system=[{type:"text",text:V.join(`
|
|
6
|
-
|
|
7
|
-
`)}];let K=$.capabilities.reasoning?Q.reasoning:void 0;if(K==="none"){if(/^claude-sonnet-5-5(?:-\d{8})?$/.test($.modelId))J.thinking={type:"between_tools"};J.output_config={effort:"low"}}else if(K)J.thinking={type:"adaptive",display:"summarized"},J.output_config={effort:i5(K,$.modelId)};else if($.capabilities.reasoning&&l5(J.messages))J.thinking={type:"adaptive"};if(J.thinking?.type==="adaptive"&&$.blockBinding)J.thinking.block_binding={prefix_mismatch_behavior:"drop_block"};if(Z&&X)J.output_config={...J.output_config,format:{type:"json_schema",schema:o5(Z.schema)}};let j=B6(Q.tools);if(j.length>0){J.tools=j;let W=Q6(Q.toolChoice,$.forcedToolChoice);if(!$.capabilities.parallelToolCalls)W.disable_parallel_tool_use=!0;if(Q.toolChoice!==void 0||W.disable_parallel_tool_use)J.tool_choice=W}return n5(J)}function l5(Q){return Q.some(($)=>$.content.some((J)=>J.type==="thinking"||J.type==="redacted_thinking"))}var qQ="thinking-binding-controls-2026-08-01";function lQ(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 iQ(Q){let $=[];for(let J of Q.messages){let Z=J.content.filter((Y)=>Y.type!=="thinking"&&Y.type!=="redacted_thinking");if(Z.length===0)continue;let X=$.at(-1);if(X?.role===J.role)X.content.push(...Z);else $.push({role:J.role,content:Z})}return{...Q,messages:$}}function i5(Q,$){if(Q==="none"||Q==="minimal")return"low";if(Q==="xhigh"&&/^claude-(?:opus|sonnet)-4-6(?:-|$)/.test($))return"high";return Q}function n5(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 r5=new Set(["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","maxItems","uniqueItems"]),a5=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]),s5=/\\[1-9]|\(\?<?[=!]|\\[bB]/,nQ=new Set(["properties","patternProperties","$defs","definitions"]);function o5(Q){let $=(J)=>{if(Array.isArray(J))return J.map($);if(!S(J))return J;let Z={},X=[];for(let[Y,V]of Object.entries(J)){if(r5.has(Y)||Y==="minItems"&&typeof V==="number"&&V>1||Y==="format"&&typeof V==="string"&&!a5.has(V)||Y==="pattern"&&typeof V==="string"&&s5.test(V)){X.push(`${Y}: ${JSON.stringify(V)}`);continue}Z[Y]=nQ.has(Y)&&S(V)?Object.fromEntries(Object.entries(V).map(([j,W])=>[j,$(W)])):$(V)}if(X.length>0){let Y=`{${X.join(", ")}}`;Z.description=typeof Z.description==="string"?`${Z.description} ${Y}`:Y}if(Z.type==="object"||S(Z.properties))Z.additionalProperties=!1;return Z};return $(Q)}function t5(Q){let $=0,J=0,Z=(X)=>{if(Array.isArray(X))return X.forEach(Z);if(!S(X))return;if(Array.isArray(X.anyOf)||Array.isArray(X.type))J++;if(S(X.properties)){let Y=new Set(Array.isArray(X.required)?X.required:[]);$+=Object.keys(X.properties).filter((V)=>!Y.has(V)).length}for(let[Y,V]of Object.entries(X))if(nQ.has(Y)&&S(V))Object.values(V).forEach(Z);else Z(V)};return Z(Q),$>24||J>16}function e5(Q){return`Answer with only a JSON value (no prose, no code fence) that matches this JSON schema:
|
|
8
|
-
${JSON.stringify(Q)}`}function Q6(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 $6(Q,$){let J=[],Z=new Map;for(let F of Q){let B=F.role==="assistant"?"assistant":"user";J.push("step-end");for(let G of F.content??[])switch(G.type){case"text":{if(B==="assistant"?!!G.text:!!G.text?.trim())J.push({role:B,block:{type:"text",text:G.text}});break}case"output":{if(G.partial)break;let H=G.text??JSON.stringify(G.value);J.push({role:B,block:{type:"text",text:H}});break}case"file":{if(B==="assistant")break;for(let H of G6(G,$))J.push({role:B,block:H});break}case"reasoning":{let H=B==="assistant"?W6(G):void 0;if(H)J.push({role:B,block:H});break}case"tool-call":{if(G.partial)break;J.push({role:"assistant",block:{type:"tool_use",id:G.toolCallId,name:String(G.name),input:S(G.input)?G.input:{}}});break}case"tool-result":{if(J.push("step-end"),Z.has(G.toolCallId))break;Z.set(G.toolCallId,{type:"tool_result",tool_use_id:G.toolCallId,content:UQ(G),...G.status==="error"?{is_error:!0}:{}});break}}}let X=[],Y=(F,B)=>{let G=X[X.length-1];if(G&&G.role===F)G.content.push(B);else X.push({role:F,content:[B]})},V=new Set,K=[],j=!1,W=()=>{for(let F of K)Y("user",Z.get(F)??Y6(F));K=[],j=!1};for(let F of J){if(F==="step-end"){j=!0;continue}let{role:B,block:G}=F;if(j||B==="user")W();if(G.type==="tool_use"){let H=String(G.id);if(V.has(H))continue;V.add(H),K.push(H)}Y(B,G)}if(W(),X[0]?.role==="assistant")X.unshift({role:"user",content:[{type:"text",text:J6}]});if(X.at(-1)?.role==="assistant")X.push({role:"user",content:[{type:"text",text:Z6}]});return X}var J6="(The conversation continues from an earlier point.)",Z6="Continue.",X6="No result was recorded for this tool call. Assume it did not complete.";function Y6(Q){return{type:"tool_result",tool_use_id:Q,content:X6}}function W6(Q){let $=Q.providerMetadata?.anthropic;if(!S($))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 G6(Q,$){let J=BQ(Q),Z=(Y)=>J?[{type:"text",text:f(Q,Y)}]:[];if(!$.fileInput)return Z(!1);if(FQ(Q,J),!Q.fileId)return Z(!1);let X=Q.providerRejected?void 0:K6(Q);if(!X)return[...Z(!1),{type:"text",text:b(Q.name)}];return[...Z(!0),{type:X,source:{type:"file",file_id:Q.fileId}}]}var V6=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function K6(Q){let $=Q.mimeType?.trim().toLowerCase()??"";if(jQ(Q))return!$||V6.has($)?"image":void 0;if($)return $==="application/pdf"||$==="text/plain"?"document":void 0;return/\.(pdf|txt)$/i.test(Q.name??"")?"document":void 0}function S(Q){return!!Q&&typeof Q==="object"&&!Array.isArray(Q)}function H6(Q){return Array.isArray(Q.tools)}function B6(Q){let $=[];for(let J of Q??[])for(let Z of H6(J)?J.tools:[J])$.push({name:Z.name,description:Z.description,input_schema:Z.parameters,eager_input_streaming:!0});return $}async function*oQ(Q,$={}){let J=new Map,Z=[],X,Y={},V,K,j=!1,W=(F)=>({type:"finish",reason:F,usage:z6(Y),...X?{model:X}:{}});for await(let F of VQ(Q)){let B;try{B=JSON.parse(F.data)}catch{continue}switch(typeof B.type==="string"?B.type:F.event){case"message_start":{let H=B.message??{};if(typeof H.model==="string"&&H.model)X=H.model;Y=sQ(Y,H.usage);break}case"content_block_start":{let H=Number(B.index),U=B.content_block??{},z={type:String(U.type??""),id:typeof U.id==="string"?U.id:void 0,name:typeof U.name==="string"?U.name:void 0,args:"",signature:typeof U.signature==="string"?U.signature:""};if(J.set(H,z),z.type==="redacted_thinking")yield{type:"reasoning-delta",delta:"",providerMetadata:{anthropic:{type:"redacted_thinking",data:String(U.data??"")}}};if(z.type==="text"&&typeof U.text==="string"&&U.text)yield aQ(U.text,$);break}case"content_block_delta":{let H=J.get(Number(B.index)),U=B.delta??{};if(!H)break;if(U.type==="text_delta"){let z=String(U.text??"");if(z)yield aQ(z,$)}else if(U.type==="thinking_delta"){let z=String(U.thinking??"");if(z)yield{type:"reasoning-delta",delta:z}}else if(U.type==="signature_delta")H.signature+=String(U.signature??"");else if(U.type==="input_json_delta"&&H.type==="tool_use"){let z=String(U.partial_json??"");if(!z)break;H.args+=z,yield{type:"tool-call-delta",toolCallId:H.id??"",name:H.name??"",argsDelta:z}}break}case"content_block_stop":{let H=Number(B.index),U=J.get(H);if(J.delete(H),U?.type==="thinking")yield{type:"reasoning-delta",delta:"",providerMetadata:{anthropic:{type:"thinking",signature:U.signature}}};if(U?.type==="tool_use")if(U.args||="{}",j6(U.args))yield rQ(U);else Z.push(U);break}case"message_delta":{if(typeof B.delta?.stop_reason==="string")V=B.delta.stop_reason;if(B.delta?.stop_details)K=B.delta.stop_details;Y=sQ(Y,B.usage);break}case"message_stop":{if(j=!0,V==="refusal"){yield{type:"error",error:U6(K)},yield W("error");break}let H=F6(V);if(Z.length>0&&H==="length")yield{type:"tool-call-discard",toolCallIds:Z.map((U)=>U.id??"")};else for(let U of Z)yield rQ(U);yield W(H);break}case"error":{j=!0,yield{type:"error",error:q6(B.error??B)},yield W("error");break}}if(j)return}yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield W("error")}function rQ(Q){return{type:"tool-call",toolCallId:Q.id??"",name:Q.name??"",args:Q.args}}function j6(Q){try{return JSON.parse(Q),!0}catch{return!1}}function aQ(Q,$){return $.structuredOutput?{type:"output-delta",delta:Q}:{type:"text-delta",delta:Q}}function F6(Q){if(Q==="max_tokens"||Q==="model_context_window_exceeded")return"length";return"stop"}function U6(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 q6(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 sQ(Q,$){if(!$||typeof $!=="object")return Q;let J={...Q};for(let X of["input_tokens","output_tokens","cache_creation_input_tokens","cache_read_input_tokens"])if(typeof $[X]==="number")J[X]=$[X];let Z=$.output_tokens_details?.thinking_tokens;if(typeof Z==="number")J.thinking_tokens=Z;return J}function z6(Q){if(!Q)return x();let{cache_read_input_tokens:$,cache_creation_input_tokens:J}=Q,Z=(Q.input_tokens??0)+($??0)+(J??0),X=Q.output_tokens??0,Y={inputTokens:Z,outputTokens:X,totalTokens:Z+X};if(typeof $==="number")Y.cachedInputTokens=$;if(typeof J==="number")Y.cacheWriteInputTokens=J;if(typeof Q.thinking_tokens==="number")Y.reasoningTokens=Q.thinking_tokens;return Y}function zQ(Q){let $=DQ(Q);if($.startsWith("gpt-3.5")||$.startsWith("text-")||$.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let J=L6($);if(J?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:J.major>1,toolSearch:tQ(J)};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:tQ(J)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function tQ(Q){if(Q.kind==="o")return Q.major>=5;return Q.major>5||Q.major===5&&Q.minor>=2}function LQ(Q){let $=DQ(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}}function eQ(Q){let $=DQ(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 DQ(Q){return Q.trim().toLowerCase()}function L6(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}function C(Q){return typeof process>"u"?void 0:process.env?.[Q]}var D6="preview";function Q5(Q){let $=Q.trim().replace(/\/+$/,"");if(!$)return"";return`${$.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function P6(Q){return/^\d{4}-\d{2}-\d{2}/.test(Q)?"":"/v1"}function PQ(Q,$={}){return{base:(Q.baseURL??C("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let Z=Q.apiKey??C("OPENAI_API_KEY");return{...Z?{authorization:`Bearer ${Z}`}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??120000,streamIdleTimeoutMs:Q.streamIdleTimeoutMs??120000,streamMaxDurationMs:Q.streamMaxDurationMs??300000,maxToolArgumentChars:Q.maxToolArgumentChars??0,maxRetries:Q.maxRetries??2}}function $5(Q){let $=Q.baseURL??Q.endpoint??C("AZURE_OPENAI_ENDPOINT");if($)return Q5($);let J=Q.resourceName??C("AZURE_OPENAI_RESOURCE_NAME")??C("AZURE_RESOURCE_NAME");return J?Q5(`https://${J.trim()}.cognitiveservices.azure.com`):""}function CQ(Q,$={}){let J=Q.apiVersion??C("AZURE_OPENAI_API_VERSION")??D6;return{base:`${$5(Q)}${P6(J)}`,query:`?api-version=${encodeURIComponent(J)}`,headers:async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`,...Q.headers};let Z=Q.apiKey??C("AZURE_OPENAI_API_KEY");return{...Z?{"api-key":Z}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??120000,streamIdleTimeoutMs:Q.streamIdleTimeoutMs??120000,streamMaxDurationMs:Q.streamMaxDurationMs??300000,maxToolArgumentChars:Q.maxToolArgumentChars??0,maxRetries:Q.maxRetries??2}}var C6="2026-10-21";function J5(Q,$={}){let J=Q.baseURL??C("ANTHROPIC_BASE_URL")??"https://api.anthropic.com";return X5(J,Q,$,async()=>{let Z=Q.workspaceId??C("ANTHROPIC_WORKSPACE_ID"),X=Z?{"anthropic-workspace-id":Z}:{},Y=Q.apiKey??C("ANTHROPIC_API_KEY");if(Y)return{"x-api-key":Y,...X};let V=C("ANTHROPIC_AUTH_TOKEN");return V?{authorization:`Bearer ${V}`,...X}:X})}function Z5(Q,$={}){let J=Q.resourceName??C("ANTHROPIC_FOUNDRY_RESOURCE"),Z=Q.baseURL??Q.endpoint??C("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 X5(Z,Q,$,async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`};let X=Q.apiKey??C("ANTHROPIC_FOUNDRY_API_KEY");return X?{"api-key":X}:{}})}function X5(Q,$,J,Z){return{base:`${Q.trim().replace(/\/+$/,"").replace(/\/v1$/,"")}/v1`,query:"",headers:async()=>({...await Z(),"anthropic-version":C6,...$.headers}),timeoutMs:$.timeoutMs??J.timeoutMs??120000,streamIdleTimeoutMs:$.streamIdleTimeoutMs??120000,streamMaxDurationMs:$.streamMaxDurationMs??300000,maxToolArgumentChars:$.maxToolArgumentChars??0,maxRetries:$.maxRetries??2}}function Y5(Q,$={}){return{...CQ(Q,$),base:`${$5(Q)}/v1`,query:""}}class e{static models(){return[]}normalizeError(Q){return M(Q)}}var W5=["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 G5 extends e{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=zQ(Q),this.config=$}static model(Q,$){return new G5(Q,$)}static models(){return W5}stream(Q){let $=HQ(Q,{model:this.model,capabilities:this.capabilities});return s(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output),files:XQ(Q.messages)})}upload(Q){return o(this.endpoint(),Q)}endpoint(){return a(PQ(this.config))}get realtime(){return new i(PQ(this.config,{timeoutMs:JQ}),{model:this.model})}}var N6=["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 NQ extends e{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=LQ(Q),this.config=$}static model(Q,$){return new NQ(Q,$)}static models(){return N6}stream(Q){return this.send(Q)}async*send(Q){let $=Q,J=!1,Z=new Set;for(;;){let X=this.request($);if(J)X=iQ(X);let Y,V=!1;for await(let K of s(this.endpointFor(X),X,{signal:Q.signal,structuredOutput:Boolean(Q.output),parse:oQ})){if(Y)continue;if(!V&&K.type==="error"&&K.status===400){let j=lQ(K.error.message);if(j&&!Z.has(j)){Z.add(j),Y=j;continue}}if(r(K))V=!0;yield K}if(!Y)return;if(Y==="thinking")J=!0;else if($.output)$={...$,output:{...$.output,strict:!1}}}}request(Q){return pQ(Q,{model:this.deployment(),modelId:this.model,capabilities:this.capabilities,forcedToolChoice:eQ(this.model),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(),X=Z["anthropic-beta"];return{...Z,"anthropic-beta":X?`${X},${qQ}`:qQ}}}}bindsThinking(){return!0}deployment(){return this.model}upload(Q){return o(this.endpoint(),Q,null)}endpoint(){return V5(J5(this.config))}}function V5(Q){return{...a(Q),responsesUrl:`${Q.base}/messages`}}class K5 extends NQ{constructor(Q,$={}){super(Q,$);this.capabilities={...LQ(Q),fileInput:!1}}static model(Q,$){return new K5(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."))}deployment(){return this.config.deployment??this.model}bindsThinking(){return!1}endpoint(){return V5(Z5(this.config))}}class H5 extends e{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=zQ(Q),this.config=$}static model(Q,$){return new H5(Q,$)}static models(){return W5}stream(Q){let $=HQ(Q,{model:this.deployment(),capabilities:this.capabilities});return s(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output),files:XQ(Q.messages)})}upload(Q){return o(this.endpoint(),Q,"assistants")}deployment(){return this.config.deployment??this.model}endpoint(){return a(CQ(this.config))}get realtime(){return new i(Y5(this.config,{timeoutMs:JQ}),{model:this.deployment(),callFlow:"ephemeral"})}}
|
|
9
|
-
export{PQ as ca,CQ as da,h as ea,$Q as fa,D5 as ga,ZQ as ha,y as ia,i as ja,x5 as ka,e as la,G5 as ma,NQ as na,K5 as oa,H5 as pa};
|
|
10
|
-
|
|
11
|
-
//# debugId=74434FFA29D30B1564756E2164756E21
|
|
File without changes
|
|
File without changes
|