gemi 0.223.0 → 0.224.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/index.js +1 -1
- package/dist/ai/providers/call.d.ts.map +1 -1
- package/dist/ai/testing/index.js +1 -1
- package/dist/bin/http-client/model.d.ts +1 -1
- package/dist/bin/http-client/model.d.ts.map +1 -1
- package/dist/bin/http-client/patch.d.ts +11 -0
- package/dist/bin/http-client/patch.d.ts.map +1 -0
- package/dist/bin/http-client/render.d.ts +3 -3
- package/dist/bin/http-client/render.d.ts.map +1 -1
- package/dist/{chunk-bs4p7dys.js → chunk-3k4p9agd.js} +22 -22
- package/dist/{chunk-bs4p7dys.js.map → chunk-3k4p9agd.js.map} +5 -5
- package/dist/{chunk-sqyf0gey.js → chunk-79v94sa6.js} +1 -1
- package/dist/{chunk-qvxs1vjh.js → chunk-8pz8yzax.js} +3 -3
- package/dist/{chunk-qvxs1vjh.js.map → chunk-8pz8yzax.js.map} +3 -3
- package/dist/{chunk-ke1q6hfm.js → chunk-99216y02.js} +1 -1
- package/dist/{chunk-9yascc81.js → chunk-dpmvvwts.js} +3 -3
- package/dist/{chunk-9yascc81.js.map → chunk-dpmvvwts.js.map} +3 -3
- package/dist/{chunk-qtczhd81.js → chunk-jyyrgb6j.js} +2 -2
- package/dist/{chunk-qtczhd81.js.map → chunk-jyyrgb6j.js.map} +1 -1
- package/dist/{chunk-fn166jp3.js → chunk-y8cj5cap.js} +1 -1
- package/dist/chunk-zcmz311y.js +8 -0
- package/dist/{chunk-8gnbc9dg.js.map → chunk-zcmz311y.js.map} +3 -3
- 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/file-storage/drivers/FileSystemDriver.d.ts +1 -0
- package/dist/services/file-storage/drivers/FileSystemDriver.d.ts.map +1 -1
- package/dist/services/index.js +1 -1
- package/dist/services/router/ApiRouteDispatcher.d.ts.map +1 -1
- package/dist/utils/apiUrl.d.ts +2 -0
- package/dist/utils/apiUrl.d.ts.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-8gnbc9dg.js +0 -8
- /package/dist/{chunk-sqyf0gey.js.map → chunk-79v94sa6.js.map} +0 -0
- /package/dist/{chunk-ke1q6hfm.js.map → chunk-99216y02.js.map} +0 -0
- /package/dist/{chunk-fn166jp3.js.map → chunk-y8cj5cap.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-qtczhd81.js";import{Da as E,Ha as T,Ia as TJ}from"./chunk-v2fd69at.js";import"./chunk-ba1h9pm6.js";import{We as GJ,ch as IJ,dh as g,lh as AJ,mh as BJ,nh as RJ}from"./chunk-bs4p7dys.js";import"./chunk-j9abwrkv.js";import"./chunk-4v5nwqw6.js";import{si as jJ,ti as YJ,wi as WJ}from"./chunk-8gnbc9dg.js";import{Ej as DJ}from"./chunk-h1wmpa03.js";import"./chunk-t586p2g2.js";import"./chunk-qs2xvc8g.js";import"./chunk-2y0nr525.js";import"./chunk-p4v71qfx.js";import"./chunk-anc5v266.js";import"./chunk-wy82t7mz.js";import"./chunk-tac25cnj.js";import"./chunk-0k2r6bep.js";import"./chunk-0av1gyns.js";import"./chunk-zmt5kdpb.js";import"./chunk-rat2827k.js";import"./chunk-yj7pbbnm.js";import"./chunk-37209psn.js";import"./chunk-fqhkkpq3.js";import{qm as KJ}from"./chunk-swmf6w3z.js";import"./chunk-6r7956dh.js";import{Im as PJ}from"./chunk-5mrtgr7q.js";import{Km as f}from"./chunk-55btq9c7.js";import"./chunk-3dkv4989.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-jyyrgb6j.js";import{Da as E,Ha as T,Ia as TJ}from"./chunk-v2fd69at.js";import"./chunk-ba1h9pm6.js";import{We as GJ,ch as IJ,dh as g,lh as AJ,mh as BJ,nh as RJ}from"./chunk-3k4p9agd.js";import"./chunk-j9abwrkv.js";import"./chunk-4v5nwqw6.js";import{si as jJ,ti as YJ,wi as WJ}from"./chunk-zcmz311y.js";import{Ej as DJ}from"./chunk-h1wmpa03.js";import"./chunk-t586p2g2.js";import"./chunk-qs2xvc8g.js";import"./chunk-2y0nr525.js";import"./chunk-p4v71qfx.js";import"./chunk-anc5v266.js";import"./chunk-wy82t7mz.js";import"./chunk-tac25cnj.js";import"./chunk-0k2r6bep.js";import"./chunk-0av1gyns.js";import"./chunk-zmt5kdpb.js";import"./chunk-rat2827k.js";import"./chunk-yj7pbbnm.js";import"./chunk-37209psn.js";import"./chunk-fqhkkpq3.js";import{qm as KJ}from"./chunk-swmf6w3z.js";import"./chunk-6r7956dh.js";import{Im as PJ}from"./chunk-5mrtgr7q.js";import{Km as f}from"./chunk-55btq9c7.js";import"./chunk-3dkv4989.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" />
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$d as t,Nd as xQ,Vd as S,Wd as s,Xd as Y5,Yd as G5,Zd as PQ,_d as k,ae as D,xd as QQ,zd as e}from"./chunk-kp7wcpx7.js";import{Nj as iQ}from"./chunk-qs2xvc8g.js";function KQ(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 R5=4000,I5=60000;function gQ(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 XQ(Q,$,J,Z,Y){let G=Q.patienceMs-Z;if(G<=0)return;let W=Q.maxWaitMs??I5,z=Q.initialWaitMs??R5,j=J!==void 0?Math.min(J,W):Math.round(Math.min(W,z*2**$)*(0.5+Y()*0.5));return Math.min(j,G)}var A5=500,uQ=20000;function T5(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 r(Q,$){let J=Math.min(uQ,A5*2**Q);return Math.round(J*(0.5+$()*0.5))}function E5(Q){return Q===429||Q===408||Q===409||Q>=500}function w5(Q,$){return E5(Q)&&D($).retryable}function cQ(Q){return Q.reason??new DOMException("The operation was aborted.","AbortError")}function mQ(Q,$){return new Promise((J,Z)=>{let Y=setTimeout(J,Q);$?.addEventListener("abort",()=>{clearTimeout(Y),Z(cQ($))},{once:!0})})}async function BQ(Q,$,J=mQ){if(!$)return await J(Q);$.throwIfAborted();let Z;try{await Promise.race([J(Q,$),new Promise((Y,G)=>{Z=()=>G(cQ($)),$.addEventListener("abort",Z,{once:!0})})])}finally{if(Z)$.removeEventListener("abort",Z)}}async function b(Q,$,J){let Z=J.fetchImpl??((V,X)=>fetch(V,X)),Y=J.sleep??mQ,G=J.random??Math.random,W=J.now??Date.now,z=Math.max(0,J.maxRetries),j=J.startedAt??W(),K=J.retry,B=(V,X,q,F)=>{let N=W()-j;try{J.onRetry?.({attempt:X+1,maxRetries:z,error:D(q),...k(q),timedOut:F,delayMs:V,elapsedMs:N,...K?{remainingMs:Math.max(0,K.patienceMs-N-V)}:{}})}catch{}return BQ(V,J.signal,Y)},H=(V,X,q,F)=>{if(!K)return;let{status:N}=k(q);if(!KQ(K,D(q),{...N?{status:N}:{},timedOut:F}))return;return XQ(K,V-z,X,W()-j,G)};for(let V=0;;V++){J.signal?.throwIfAborted();let X=new AbortController,q=()=>X.abort(J.signal?.reason);J.signal?.addEventListener("abort",q,{once:!0});let F=!1,N=J.timeoutMs>0?setTimeout(()=>{F=!0,X.abort()},J.timeoutMs):void 0,P;try{P=await Z(Q,{...$,signal:X.signal})}catch(R){if(N!==void 0)clearTimeout(N);if(J.signal?.removeEventListener("abort",q),J.signal?.aborted)throw R;let I=F?new s(J.timeoutMs):R;if(F&&J.retryTimeouts===!1)throw I;let A=V<z?r(V,G):H(V,void 0,I,F);if(A===void 0)throw I;await B(A,V,I,F);continue}if(N!==void 0)clearTimeout(N);if(P.ok)return P;J.signal?.removeEventListener("abort",q);let O=await k5(P),L=new S(P.status,O,P.headers.get("x-request-id")??P.headers.get("request-id")??void 0,T5(P.headers.get("retry-after"),W()));if(!w5(P.status,L))throw L;let g=L.retryAfter??(P.status===429?D(L).retryAfter:void 0),v=V>=z?H(V,g,L,!1):g===void 0?r(V,G):Math.min(g,uQ);if(v===void 0)throw L;await B(v,V,L,!1)}}async function k5(Q){let $;try{$=await Q.text()}catch{return null}try{return JSON.parse($)}catch{return $}}function dQ(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,W=Q.getReader();return new ReadableStream({async pull(z){let j,K,B=Math.max(0,G-performance.now()),H=!Z||B<=Z,V=H?B:Z,X=new Promise((q,F)=>{j=setTimeout(()=>{K=H?J.max():J.idle(),F(K)},V)});try{let q=await Promise.race([W.read(),X]);if(q.done)z.close();else z.enqueue(q.value)}catch(q){let F=K??q;z.error(F),W.cancel(F).catch(()=>{})}finally{clearTimeout(j)}},cancel(z){return W.cancel(z)}},{highWaterMark:0})}var jQ=30000,pQ=10,lQ=7200,v5=600,h5="gpt-live-transcribe";function b5(Q){return Q.type==="transcription"}function y5(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??h5};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?nQ(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 f5(Q){if(!Q)return{type:"object",properties:{}};return iQ(Q)?Q.toJSONSchema():Q}function a(Q,$){if(b5(Q))return y5(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((W)=>({type:"function",name:W.name,...W.description?{description:W.description}:{},parameters:f5(W.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&&nQ(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 nQ(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)},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 W=Y?.cached_tokens_details?.audio_tokens;if(typeof W==="number")Z.cachedAudioInputTokens=W;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 m 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 g5=60;class o{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:g5,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(a(Q.session??{},this.model))),J=await this.target.headers(),Z=j}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),W=await G.text(),z=c5(G);if(!z)throw new m({code:"provider_error",message:"The provider started a realtime call but did not say which one (no Location).",retryable:!1});return{sdpAnswer:W,callId:z}}async clientSecret(Q={}){let $=Q.ttlSeconds??v5;if(!Number.isInteger($)||$<pQ||$>lQ)throw RangeError(`ttlSeconds must be a whole number from ${pQ} to ${lQ}, 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:a(Q.session??{},this.model)})},Q.signal)).json();if(typeof Y?.value!=="string")throw new m({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(u5(J,Q))return;throw J}}sideband(Q,$={}){return new HQ({...$,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 b(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 m(D(Z),{cause:Z,...Z instanceof S?{status:Z.status}:{}})}}}function u5(Q,$){if(!(Q instanceof m)||Q.status!==404)return!1;let J=Q.cause instanceof S?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 c5(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 m5={"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 d5(Q){if(typeof Q!=="string")return;let $;try{$=JSON.parse(Q)}catch{return}if(!$||typeof $!=="object"||typeof $.type!=="string")return;let J=m5[$.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 rQ=1,p5=500;function l5(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 HQ{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===rQ)this.socket.send($);else this.outbox.push($)}updateSession(Q){this.send({type:"session.update",session:a(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<=rQ)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??l5)(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=d5(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>p5)this.backlog.shift()}for(let $ of this.subscribers){if($.done)continue;$.queue.push(Q),$.wake?.()}for(let $ of this.listeners)try{$(Q)}catch{}}}var oQ=3;function qQ(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 tQ(Q,$,J=new Map){if(!($ instanceof S))return[];if($.status!==400&&$.status!==404)return[];let Z=UQ($.body);if(!Z)return[];let Y=i5(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])],B=FQ(K)[Number(G[2])],H=B&&typeof B.file_id==="string"?B.file_id:void 0;if(H)return[H]}let W=Z.message??"",z=aQ(Y.map((K)=>K.fileId).filter((K)=>n5(W,K)));if(z.length>0)return z;let j=/Expected (image type|context stuffing file type) to be a supported format:.*but got \.([a-z0-9]+)\.?\s*$/is.exec(W);if(j){let K=j[1].toLowerCase()==="image type"?"input_image":"input_file",B=j[2].toLowerCase(),H=aQ(Y.filter((X)=>X.type===K).map((X)=>X.fileId)),V=H.filter((X)=>(J.get(X)?.name??"").trim().toLowerCase().endsWith(`.${B}`));if(V.length===1)return V;if(V.length===0&&H.length===1)return H}return[]}function eQ(Q,$,J=new Map){return{...Q,input:Q.input.map((Z)=>{let Y=FQ(Z);if(!Y.some((G)=>sQ(G,$)))return Z;return{...Z,content:Y.map((G)=>sQ(G,$)?{type:"input_text",text:d(J.get(String(G.file_id))?.name)}:G)}})}}function d(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 sQ(Q,$){return typeof Q.file_id==="string"&&$.has(Q.file_id)}function FQ(Q){let $=Q?.content;return Array.isArray($)?$:[]}function i5(Q){let $=[];for(let J of Q)for(let Z of FQ(J))if(typeof Z.file_id==="string"&&Z.file_id)$.push({type:String(Z.type),fileId:Z.file_id});return $}function UQ(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 n5(Q,$){let J=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${J}($|[^A-Za-z0-9_-])`).test(Q)}function aQ(Q){return[...new Set(Q)]}function Q5(Q,$){if(!($ instanceof S))return null;if($.status!==400&&$.status!==404)return null;let J=Q?.input;if(!Array.isArray(J))return null;let Z=UQ($.body)?.message??"",Y=/Item with id '([^']+)' not found/i.exec(Z)?.[1];if(!Y)return null;let G=(W)=>W?.type==="reasoning";if(!J.some((W)=>G(W)&&W.id===Y))return null;return{...Q,input:J.filter((W)=>!G(W))}}async function*NQ(Q){let $="",J="",Z=[],Y,G=()=>{if(Z.length===0&&!J)return null;let j={event:J,data:Z.join(`
|
|
2
|
+
import{$d as t,Nd as xQ,Vd as S,Wd as s,Xd as Y5,Yd as G5,Zd as PQ,_d as k,ae as D,xd as QQ,zd as e}from"./chunk-kp7wcpx7.js";import{Nj as iQ}from"./chunk-qs2xvc8g.js";function KQ(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 R5=4000,I5=60000;function gQ(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 XQ(Q,$,J,Z,Y){let G=Q.patienceMs-Z;if(G<=0)return;let W=Q.maxWaitMs??I5,z=Q.initialWaitMs??R5,j=J!==void 0?Math.min(J,W):Math.round(Math.min(W,z*2**$)*(0.5+Y()*0.5));return Math.min(j,G)}var A5=500,uQ=20000;function T5(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 r(Q,$){let J=Math.min(uQ,A5*2**Q);return Math.round(J*(0.5+$()*0.5))}function E5(Q){return Q===429||Q===408||Q===409||Q>=500}function w5(Q,$){return E5(Q)&&D($).retryable}function cQ(Q){return Q.reason??new DOMException("The operation was aborted.","AbortError")}function mQ(Q,$){return new Promise((J,Z)=>{let Y=setTimeout(J,Q);$?.addEventListener("abort",()=>{clearTimeout(Y),Z(cQ($))},{once:!0})})}async function BQ(Q,$,J=mQ){if(!$)return await J(Q);$.throwIfAborted();let Z;try{await Promise.race([J(Q,$),new Promise((Y,G)=>{Z=()=>G(cQ($)),$.addEventListener("abort",Z,{once:!0})})])}finally{if(Z)$.removeEventListener("abort",Z)}}async function b(Q,$,J){let Z=J.fetchImpl??((V,X)=>fetch(V,X)),Y=J.sleep??mQ,G=J.random??Math.random,W=J.now??Date.now,z=Math.max(0,J.maxRetries),j=J.startedAt??W(),K=J.retry,B=(V,X,q,F)=>{let N=W()-j;try{J.onRetry?.({attempt:X+1,maxRetries:z,error:D(q),...k(q),timedOut:F,delayMs:V,elapsedMs:N,...K?{remainingMs:Math.max(0,K.patienceMs-N-V)}:{}})}catch{}return BQ(V,J.signal,Y)},H=(V,X,q,F)=>{if(!K)return;let{status:N}=k(q);if(!KQ(K,D(q),{...N?{status:N}:{},timedOut:F}))return;return XQ(K,V-z,X,W()-j,G)};for(let V=0;;V++){J.signal?.throwIfAborted();let X=new AbortController,q=()=>X.abort(J.signal?.reason);J.signal?.addEventListener("abort",q,{once:!0});let F=!1,N=J.timeoutMs>0?setTimeout(()=>{F=!0,X.abort()},J.timeoutMs):void 0,P;try{P=await Z(Q,{...$,signal:X.signal})}catch(I){if(N!==void 0)clearTimeout(N);if(J.signal?.removeEventListener("abort",q),J.signal?.aborted)throw I;let A=F?new s(J.timeoutMs):I;if(F&&J.retryTimeouts===!1)throw A;let T=V<z?r(V,G):H(V,void 0,A,F);if(T===void 0)throw A;await B(T,V,A,F);continue}if(N!==void 0)clearTimeout(N);if(P.ok)return P;J.signal?.removeEventListener("abort",q);let O=await k5(P),L=new S(P.status,O,P.headers.get("x-request-id")??P.headers.get("request-id")??void 0,T5(P.headers.get("retry-after"),W()));if(!w5(P.status,L))throw L;let g=L.retryAfter??(P.status===429?D(L).retryAfter:void 0),v=V>=z?H(V,g,L,!1):g===void 0?r(V,G):Math.min(g,uQ);if(v===void 0)throw L;await B(v,V,L,!1)}}async function k5(Q){let $;try{$=await Q.text()}catch{return null}try{return JSON.parse($)}catch{return $}}function dQ(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,W=Q.getReader();return new ReadableStream({async pull(z){let j,K,B=Math.max(0,G-performance.now()),H=!Z||B<=Z,V=H?B:Z,X=new Promise((q,F)=>{j=setTimeout(()=>{K=H?J.max():J.idle(),F(K)},V)});try{let q=await Promise.race([W.read(),X]);if(q.done)z.close();else z.enqueue(q.value)}catch(q){let F=K??q;z.error(F),W.cancel(F).catch(()=>{})}finally{clearTimeout(j)}},cancel(z){return W.cancel(z)}},{highWaterMark:0})}var jQ=30000,pQ=10,lQ=7200,v5=600,h5="gpt-live-transcribe";function b5(Q){return Q.type==="transcription"}function y5(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??h5};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?nQ(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 f5(Q){if(!Q)return{type:"object",properties:{}};return iQ(Q)?Q.toJSONSchema():Q}function a(Q,$){if(b5(Q))return y5(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((W)=>({type:"function",name:W.name,...W.description?{description:W.description}:{},parameters:f5(W.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&&nQ(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 nQ(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)},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 W=Y?.cached_tokens_details?.audio_tokens;if(typeof W==="number")Z.cachedAudioInputTokens=W;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 m 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 g5=60;class o{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:g5,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(a(Q.session??{},this.model))),J=await this.target.headers(),Z=j}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),W=await G.text(),z=c5(G);if(!z)throw new m({code:"provider_error",message:"The provider started a realtime call but did not say which one (no Location).",retryable:!1});return{sdpAnswer:W,callId:z}}async clientSecret(Q={}){let $=Q.ttlSeconds??v5;if(!Number.isInteger($)||$<pQ||$>lQ)throw RangeError(`ttlSeconds must be a whole number from ${pQ} to ${lQ}, 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:a(Q.session??{},this.model)})},Q.signal)).json();if(typeof Y?.value!=="string")throw new m({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(u5(J,Q))return;throw J}}sideband(Q,$={}){return new HQ({...$,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 b(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 m(D(Z),{cause:Z,...Z instanceof S?{status:Z.status}:{}})}}}function u5(Q,$){if(!(Q instanceof m)||Q.status!==404)return!1;let J=Q.cause instanceof S?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 c5(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 m5={"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 d5(Q){if(typeof Q!=="string")return;let $;try{$=JSON.parse(Q)}catch{return}if(!$||typeof $!=="object"||typeof $.type!=="string")return;let J=m5[$.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 rQ=1,p5=500;function l5(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 HQ{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===rQ)this.socket.send($);else this.outbox.push($)}updateSession(Q){this.send({type:"session.update",session:a(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<=rQ)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??l5)(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=d5(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>p5)this.backlog.shift()}for(let $ of this.subscribers){if($.done)continue;$.queue.push(Q),$.wake?.()}for(let $ of this.listeners)try{$(Q)}catch{}}}var oQ=3;function qQ(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 tQ(Q,$,J=new Map){if(!($ instanceof S))return[];if($.status!==400&&$.status!==404)return[];let Z=UQ($.body);if(!Z)return[];let Y=i5(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])],B=FQ(K)[Number(G[2])],H=B&&typeof B.file_id==="string"?B.file_id:void 0;if(H)return[H]}let W=Z.message??"",z=aQ(Y.map((K)=>K.fileId).filter((K)=>n5(W,K)));if(z.length>0)return z;let j=/Expected (image type|context stuffing file type) to be a supported format:.*but got \.([a-z0-9]+)\.?\s*$/is.exec(W);if(j){let K=j[1].toLowerCase()==="image type"?"input_image":"input_file",B=j[2].toLowerCase(),H=aQ(Y.filter((X)=>X.type===K).map((X)=>X.fileId)),V=H.filter((X)=>(J.get(X)?.name??"").trim().toLowerCase().endsWith(`.${B}`));if(V.length===1)return V;if(V.length===0&&H.length===1)return H}return[]}function eQ(Q,$,J=new Map){return{...Q,input:Q.input.map((Z)=>{let Y=FQ(Z);if(!Y.some((G)=>sQ(G,$)))return Z;return{...Z,content:Y.map((G)=>sQ(G,$)?{type:"input_text",text:d(J.get(String(G.file_id))?.name)}:G)}})}}function d(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 sQ(Q,$){return typeof Q.file_id==="string"&&$.has(Q.file_id)}function FQ(Q){let $=Q?.content;return Array.isArray($)?$:[]}function i5(Q){let $=[];for(let J of Q)for(let Z of FQ(J))if(typeof Z.file_id==="string"&&Z.file_id)$.push({type:String(Z.type),fileId:Z.file_id});return $}function UQ(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 n5(Q,$){let J=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${J}($|[^A-Za-z0-9_-])`).test(Q)}function aQ(Q){return[...new Set(Q)]}function Q5(Q,$){if(!($ instanceof S))return null;if($.status!==400&&$.status!==404)return null;let J=Q?.input;if(!Array.isArray(J))return null;let Z=UQ($.body)?.message??"",Y=/Item with id '([^']+)' not found/i.exec(Z)?.[1];if(!Y)return null;let G=(W)=>W?.type==="reasoning";if(!J.some((W)=>G(W)&&W.id===Y))return null;return{...Q,input:J.filter((W)=>!G(W))}}async function*NQ(Q){let $="",J="",Z=[],Y,G=()=>{if(Z.length===0&&!J)return null;let j={event:J,data:Z.join(`
|
|
3
3
|
`),id:Y};return J="",Z=[],Y=void 0,j.data?j:null},W=(j)=>{let K=j.endsWith("\r")?j.slice(0,-1):j;if(K==="")return G();if(K.startsWith(":"))return null;let B=K.indexOf(":"),H=B===-1?K:K.slice(0,B),V=B===-1?"":K.slice(B+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 j of Q){$+=j;let K=$.indexOf(`
|
|
4
4
|
`);while(K!==-1){let B=$.slice(0,K);$=$.slice(K+1);let H=W(B);if(H)yield H;K=$.indexOf(`
|
|
5
|
-
`)}}if($.length>0){let j=W($);if(j)yield j}let z=G();if(z)yield z}async function*$5(Q,$={}){let J=new Map,Z=new Set,Y,G=!1,W,z=(j,K)=>({type:"finish",reason:j,usage:K,...W?{model:W}:{}});for await(let j of NQ(Q)){if(j.data==="[DONE]")break;let K;try{K=JSON.parse(j.data)}catch{continue}let B=typeof K.type==="string"?K.type:j.event,H=K.response?.model;if(typeof H==="string"&&H)W=H;switch(B){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 X=String(V.id??K.item_id??V.call_id??"");J.set(X,{callId:String(V.call_id??X),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 X=String(K.delta??"");if(!X)break;yield{type:"tool-call-delta",toolCallId:V.callId,name:V.name,argsDelta:X,...V.namespace?{namespace:V.namespace}:{}};break}case"response.function_call_arguments.done":{let V=String(K.item_id??""),X=J.get(V);if(!X)break;X.done=!0,yield{type:"tool-call",toolCallId:X.callId,name:X.name,args:String(K.arguments??""),...X.namespace?{namespace:X.namespace}:{}};break}case"response.output_item.done":{let V=K.item;if(!V)break;if(V.type==="function_call"){let X=String(V.id??K.item_id??V.call_id??""),q=J.get(X);if(q?.done)break;let F=(typeof V.namespace==="string"?V.namespace:"")||q?.namespace;if(yield{type:"tool-call",toolCallId:String(V.call_id??X),name:String(V.name??q?.name??""),args:String(V.arguments??""),...F?{namespace:F}:{}},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 X=r5(V);if(X.loaded.length===0&&X.namespaces.length===0)break;let q=String(V.tool_search_call_id??V.id??"");if(Z.has(q))break;Z.add(q);let F=Y;Y=void 0,yield{type:"tool-search",...X,...F!==void 0&&F!==null?{arguments:F}:{}}}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",CQ(K.response?.usage));break}case"response.incomplete":{G=!0;let V=CQ(K.response?.usage),X=K.response?.incomplete_details?.reason;if(X==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:s5(K.response?.content_filters),retryable:!1}},yield z("error",V);break}yield z(X==="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:a5(V),...t(V)},yield z("error",CQ(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",M())}function r5(Q){let $=[],J=[];return J5(Q.results??Q.tools??Q.loaded??Q.output,$,J,0),{loaded:LQ($),namespaces:LQ(J)}}function J5(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,W=typeof G.name==="string"?G.name:typeof G.tool_name==="string"?G.tool_name:"",z=G.tools??G.functions;if(Array.isArray(z)){if(W)J.push(W);J5(z,$,J,Z+1);continue}if(W)$.push(W)}}function LQ(Q){return Q.filter(($,J)=>Q.indexOf($)===J)}function s5(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[W,z]of Object.entries(G))if(z&&typeof z==="object"&&z.filtered===!0)J.push(`${W} (${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: ${LQ(J).join(", ")}.`}function a5(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 M(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function CQ(Q){if(!Q)return M();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*Z5(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 $Q(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,...Q.retry?{retry:Q.retry}:{}}}async function*JQ(Q,$,J){let Z=J.parse??$5,Y=$,G=new Set,W=0,z=!1,j=Math.max(0,Q.maxRetries),K=Q.random??Math.random,B,H=(O)=>{if(!B)return O;let L=e(e(M(),B),O.usage);return B=void 0,{...O,usage:L}},V=()=>H({type:"finish",reason:"aborted",usage:M()}),X=Q.streamIdleTimeoutMs??0,q=Q.streamMaxDurationMs??0,F=Q.maxToolArgumentChars??0,N=Q.now??Date.now,P=N();for(let O=0;;O++){let L=new AbortController,g=J.signal?AbortSignal.any([J.signal,L.signal]):L.signal,v;while(v===void 0)try{let C=[],U=()=>{},_=b(Q.responsesUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify(Y)},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,signal:g,fetchImpl:Q.fetchImpl,sleep:Q.sleep,random:Q.random,now:Q.now,startedAt:P,...Q.retry?{retry:Q.retry}:{},onRetry:(h)=>{C.push({type:"retry",...h,phase:"request"}),U()}}),w=_.then(()=>!0,()=>!0);for(;;){let h=new Promise((n)=>U=()=>n(!1)),c=await Promise.race([w,h]);if(yield*C.splice(0),c)break}v=await _}catch(C){let U=Y,_=J.files&&W<oQ?tQ(U,C,J.files).filter((c)=>!G.has(c)):[];if(_.length>0){W++;let c=D(C).message;for(let n of _)G.add(n),yield{type:"file-rejected",fileId:n,message:c,...k(C)};Y=eQ(U,new Set(_),J.files);continue}let w=z?null:Q5(Y,C);if(w){z=!0,Y=w;continue}let h=D(C);if(h.code==="aborted"){yield V();return}yield{type:"error",error:h,...k(C)},yield H({type:"finish",reason:"error",usage:M()});return}let R=[],I=!1,A,WQ=!1,T,u=new Map;try{let C=dQ(v.body,{idleMs:X,maxMs:q},{idle:()=>{let U=new Y5(X);return L.abort(U),U},max:()=>{let U=new G5(q);return L.abort(U),U}});for await(let U of Z(Z5(C),{structuredOutput:J.structuredOutput})){if(U.type==="tool-call-delta"){let _=(u.get(U.toolCallId)??0)+U.argsDelta.length;if(u.set(U.toolCallId,_),F>0&&_>F){let w=new PQ(F,U.name,U.toolCallId,_);throw L.abort(w),w}yield U;continue}if(U.type==="tool-call")u.delete(U.toolCallId);if(I){yield U.type==="finish"?H(U):U;continue}if(QQ(U)){I=!0,yield*R.splice(0),yield U;continue}if(U.type==="error")A=U.error;R.push(U)}}catch(C){WQ=C instanceof s;let U=D(C);if(U.code==="aborted"||J.signal?.aborted){yield V();return}if(I){yield{type:"error",error:U},yield H({type:"finish",reason:"error",usage:M()});return}if(A=U,C instanceof PQ)T=C.detail;R.push({type:"error",error:U,...T?{toolArgumentsTooLong:T}:{}},{type:"finish",reason:"error",usage:M()})}if(I)return;let l={};for(let C of R)if(C.type==="error")l=k(C);let i=!A?.retryable||J.signal?.aborted||T&&J.retryToolArgumentsTooLong===!1?void 0:O<j?r(O,K):Q.retry&&KQ(Q.retry,A,{...l.status!==void 0?{status:l.status}:{},timedOut:WQ,...T?{toolArgumentsTooLong:T}:{}})?XQ(Q.retry,O-j,A.retryAfter,N()-P,K):void 0;if(i!==void 0){for(let U of R)if(U.type==="finish")B=e(B??M(),U.usage);if(u.size>0)yield{type:"tool-call-discard",toolCallIds:[...u.keys()]};let C=N()-P;yield{type:"retry",attempt:O+1,maxRetries:j,error:A,...l,phase:"stream",timedOut:WQ,...T?{toolArgumentsTooLong:T}:{},delayMs:i,elapsedMs:C,...Q.retry?{remainingMs:Math.max(0,Q.retry.patienceMs-C-i)}:{}};try{await BQ(i,J.signal,Q.sleep)}catch{yield V();return}continue}for(let C of R)yield C.type==="finish"?H(C):C;return}}async function ZQ(Q,$,J="user_data"){let Z=new FormData;if(J)Z.set("purpose",J);Z.set("file",$);let G=await(await b(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 YQ(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 b(`${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 S&&G.status===404)return;throw G}}function DQ(Q,$){let{capabilities:J}=$,Z={model:$.model,input:o5(Q.messages,J,Q.tools),stream:!0};if(Q.systemPrompt)Z.instructions=Q.systemPrompt;let Y=V6(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 o5(Q,$,J){let Z=[],Y=new Map;if($.toolSearch){for(let G of J??[])if(GQ(G))Y.set(G.name,G)}for(let G of Q){let W=G.role,z=!Z6.has(G.finishReason),j=[],K=()=>{if(j.length===0)return;Z.push({type:"message",role:W,content:j}),j=[]};for(let B of G.content??[])switch(B.type){case"text":{if(!B.text)break;j.push(y(W,B.text));break}case"output":{if(B.partial)break;j.push(y(W,JSON.stringify(B.value)));break}case"file":{if(W==="assistant")break;let H=OQ(B);if(!$.fileInput){if(H)j.push(y(W,p(B,!1)));break}if(MQ(B,H),B.providerRejected){if(H)j.push(y(W,p(B,!1)));j.push(y(W,d(B.name)));break}if(H)j.push(y(W,p(B,!!B.fileId)));if(B.fileId)j.push(Q6(B));break}case"reasoning":{if(K(),!z)break;let H=Y6(B);if(H)Z.push(H);break}case"tool-call":{if(B.partial)break;if(K(),$.toolSearch&&Array.isArray(B.toolSearches))for(let V of B.toolSearches)Z.push(...G6(V,J??[]));let H={type:"function_call",call_id:B.toolCallId,name:String(B.name),arguments:JSON.stringify(B.input??{})};if(B.namespace&&Y.has(B.namespace))H.namespace=B.namespace;Z.push(H);break}case"tool-result":{K(),Z.push({type:"function_call_output",call_id:B.toolCallId,output:_Q(B)});break}}K()}return e5(Z)}var t5="No result was recorded for this tool call. Assume it did not complete.";function e5(Q){let $=new Set,J=new Set,Z=[];for(let G of Q){if(G.type==="function_call"){let W=String(G.call_id);if($.has(W))continue;$.add(W)}else if(G.type==="function_call_output"){let W=String(G.call_id);if(!$.has(W)||J.has(W))continue;J.add(W)}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 W=String(G.call_id);if(J.has(W))continue;J.add(W),Y.push({type:"function_call_output",call_id:W,output:t5})}return Y}function y(Q,$){return{type:Q==="assistant"?"output_text":"input_text",text:$}}function OQ(Q){let $=Q.attachmentId;return typeof $==="string"&&$.startsWith(xQ)?$:void 0}function p(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 Q6(Q){return{type:SQ(Q)?"input_image":"input_file",file_id:Q.fileId}}function SQ(Q){let $=Q.mimeType?.trim().toLowerCase()??"";return $?$.startsWith("image/")&&$!=="image/svg+xml":$6(Q.name)}function MQ(Q,$){if(Q.fileId?.startsWith(xQ))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 $6(Q){let $=/\.([a-z0-9]+)$/.exec(Q?.trim().toLowerCase()??"");return $?.[1]!==void 0&&J6.has($[1])}var J6=new Set(["jpeg","jpg","png","gif","webp"]),Z6=new Set(["error","aborted","interrupted"]);function Y6(Q){if(!Q.id)return null;let $={type:"reasoning",id:Q.id};return $.summary=Q.text?[{type:"summary_text",text:Q.text}]:[],$}function _Q(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 G6(Q,$){let J=new Set(V5(Q?.loaded)),Z=V5(Q?.namespaces),Y=new Set(Z),G=[];for(let z of $)if(GQ(z)){if(!Y.has(z.name))continue;let j=z.tools.filter((K)=>J.size===0||J.has(K.name));if(j.length===0)continue;G.push({type:"namespace",name:z.name,description:z.description,tools:j.map((K)=>f(K,!0))})}else if(z.deferred&&J.has(z.name))G.push(f(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 V5(Q){return Array.isArray(Q)?Q.filter(($)=>typeof $==="string"):[]}function GQ(Q){return Array.isArray(Q.tools)}function V6(Q,$){if(!Q||Q.length===0)return[];if(!$.toolSearch){let Y=[];for(let G of Q)if(GQ(G))for(let W of G.tools)Y.push(f(W,!1));else Y.push(f(G,!1));return Y}let J=[],Z=!1;for(let Y of Q)if(GQ(Y)){let G=Y.tools.map((W)=>{if(W.deferred)Z=!0;return f(W,!0)});J.push({type:"namespace",name:Y.name,description:Y.description,tools:G})}else{if(Y.deferred)Z=!0;J.push(f(Y,!0))}if(Z)J.push({type:"tool_search"});return J}function f(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 W6=64000;function W5(Q,$){let J={model:$.model,max_tokens:Q.maxOutputTokens??W6,messages:L6(Q.messages,$.capabilities),stream:!0},Z=Q.output,Y=!!Z?.strict&&!F6(Z.schema),G=Z&&!Y?U6(Z.schema):void 0,W=[Q.systemPrompt,G].filter(Boolean);if(W.length>0)J.system=[{type:"text",text:W.join(`
|
|
5
|
+
`)}}if($.length>0){let j=W($);if(j)yield j}let z=G();if(z)yield z}async function*$5(Q,$={}){let J=new Map,Z=new Set,Y,G=!1,W,z=(j,K)=>({type:"finish",reason:j,usage:K,...W?{model:W}:{}});for await(let j of NQ(Q)){if(j.data==="[DONE]")break;let K;try{K=JSON.parse(j.data)}catch{continue}let B=typeof K.type==="string"?K.type:j.event,H=K.response?.model;if(typeof H==="string"&&H)W=H;switch(B){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 X=String(V.id??K.item_id??V.call_id??"");J.set(X,{callId:String(V.call_id??X),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 X=String(K.delta??"");if(!X)break;yield{type:"tool-call-delta",toolCallId:V.callId,name:V.name,argsDelta:X,...V.namespace?{namespace:V.namespace}:{}};break}case"response.function_call_arguments.done":{let V=String(K.item_id??""),X=J.get(V);if(!X)break;X.done=!0,yield{type:"tool-call",toolCallId:X.callId,name:X.name,args:String(K.arguments??""),...X.namespace?{namespace:X.namespace}:{}};break}case"response.output_item.done":{let V=K.item;if(!V)break;if(V.type==="function_call"){let X=String(V.id??K.item_id??V.call_id??""),q=J.get(X);if(q?.done)break;let F=(typeof V.namespace==="string"?V.namespace:"")||q?.namespace;if(yield{type:"tool-call",toolCallId:String(V.call_id??X),name:String(V.name??q?.name??""),args:String(V.arguments??""),...F?{namespace:F}:{}},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 X=r5(V);if(X.loaded.length===0&&X.namespaces.length===0)break;let q=String(V.tool_search_call_id??V.id??"");if(Z.has(q))break;Z.add(q);let F=Y;Y=void 0,yield{type:"tool-search",...X,...F!==void 0&&F!==null?{arguments:F}:{}}}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",CQ(K.response?.usage));break}case"response.incomplete":{G=!0;let V=CQ(K.response?.usage),X=K.response?.incomplete_details?.reason;if(X==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:s5(K.response?.content_filters),retryable:!1}},yield z("error",V);break}yield z(X==="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:a5(V),...t(V)},yield z("error",CQ(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",M())}function r5(Q){let $=[],J=[];return J5(Q.results??Q.tools??Q.loaded??Q.output,$,J,0),{loaded:LQ($),namespaces:LQ(J)}}function J5(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,W=typeof G.name==="string"?G.name:typeof G.tool_name==="string"?G.tool_name:"",z=G.tools??G.functions;if(Array.isArray(z)){if(W)J.push(W);J5(z,$,J,Z+1);continue}if(W)$.push(W)}}function LQ(Q){return Q.filter(($,J)=>Q.indexOf($)===J)}function s5(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[W,z]of Object.entries(G))if(z&&typeof z==="object"&&z.filtered===!0)J.push(`${W} (${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: ${LQ(J).join(", ")}.`}function a5(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 M(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function CQ(Q){if(!Q)return M();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*Z5(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 $Q(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,...Q.retry?{retry:Q.retry}:{}}}async function*JQ(Q,$,J){let Z=J.parse??$5,Y=$,G=new Set,W=0,z=!1,j=Math.max(0,Q.maxRetries),K=Q.random??Math.random,B,H=(O)=>{if(!B)return O;let L=e(e(M(),B),O.usage);return B=void 0,{...O,usage:L}},V=()=>H({type:"finish",reason:"aborted",usage:M()}),X=Q.streamIdleTimeoutMs??0,q=Q.streamMaxDurationMs??0,F=Q.maxToolArgumentChars??0,N=Q.now??Date.now,P=N();for(let O=0;;O++){let L=new AbortController,g=J.signal?AbortSignal.any([J.signal,L.signal]):L.signal,v;while(v===void 0)try{let C=[],U=()=>{},R=b(Q.responsesUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify(Y)},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,signal:g,fetchImpl:Q.fetchImpl,sleep:Q.sleep,random:Q.random,now:Q.now,startedAt:P,...Q.retry?{retry:Q.retry}:{},onRetry:(h)=>{C.push({type:"retry",...h,phase:"request"}),U()}}),w=R.then(()=>!0,()=>!0);for(;;){let h=new Promise((n)=>U=()=>n(!1)),c=await Promise.race([w,h]);if(yield*C.splice(0),c)break}v=await R}catch(C){let U=Y,R=J.files&&W<oQ?tQ(U,C,J.files).filter((c)=>!G.has(c)):[];if(R.length>0){W++;let c=D(C).message;for(let n of R)G.add(n),yield{type:"file-rejected",fileId:n,message:c,...k(C)};Y=eQ(U,new Set(R),J.files);continue}let w=z?null:Q5(Y,C);if(w){z=!0,Y=w;continue}let h=D(C);if(h.code==="aborted"){yield V();return}yield{type:"error",error:h,...k(C)},yield H({type:"finish",reason:"error",usage:M()});return}let I=[],A=!1,T,WQ=!1,_,u=new Map;try{let C=dQ(v.body,{idleMs:X,maxMs:q},{idle:()=>{let U=new Y5(X);return L.abort(U),U},max:()=>{let U=new G5(q);return L.abort(U),U}});for await(let U of Z(Z5(C),{structuredOutput:J.structuredOutput})){if(U.type==="tool-call-delta"){let R=(u.get(U.toolCallId)??0)+U.argsDelta.length;if(u.set(U.toolCallId,R),F>0&&R>F){let w=new PQ(F,U.name,U.toolCallId,R);throw L.abort(w),w}yield U;continue}if(U.type==="tool-call")u.delete(U.toolCallId);if(A){yield U.type==="finish"?H(U):U;continue}if(QQ(U)){A=!0,yield*I.splice(0),yield U;continue}if(U.type==="error")T=U.error;I.push(U)}}catch(C){WQ=C instanceof s;let U=D(C);if(U.code==="aborted"||J.signal?.aborted){yield V();return}if(C instanceof PQ)_=C.detail;if(A){yield{type:"error",error:U,..._?{toolArgumentsTooLong:_}:{}},yield H({type:"finish",reason:"error",usage:M()});return}T=U,I.push({type:"error",error:U,..._?{toolArgumentsTooLong:_}:{}},{type:"finish",reason:"error",usage:M()})}if(A)return;let l={};for(let C of I)if(C.type==="error")l=k(C);let i=!T?.retryable||J.signal?.aborted||_&&J.retryToolArgumentsTooLong===!1?void 0:O<j?r(O,K):Q.retry&&KQ(Q.retry,T,{...l.status!==void 0?{status:l.status}:{},timedOut:WQ,..._?{toolArgumentsTooLong:_}:{}})?XQ(Q.retry,O-j,T.retryAfter,N()-P,K):void 0;if(i!==void 0){for(let U of I)if(U.type==="finish")B=e(B??M(),U.usage);if(u.size>0)yield{type:"tool-call-discard",toolCallIds:[...u.keys()]};let C=N()-P;yield{type:"retry",attempt:O+1,maxRetries:j,error:T,...l,phase:"stream",timedOut:WQ,..._?{toolArgumentsTooLong:_}:{},delayMs:i,elapsedMs:C,...Q.retry?{remainingMs:Math.max(0,Q.retry.patienceMs-C-i)}:{}};try{await BQ(i,J.signal,Q.sleep)}catch{yield V();return}continue}for(let C of I)yield C.type==="finish"?H(C):C;return}}async function ZQ(Q,$,J="user_data"){let Z=new FormData;if(J)Z.set("purpose",J);Z.set("file",$);let G=await(await b(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 YQ(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 b(`${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 S&&G.status===404)return;throw G}}function DQ(Q,$){let{capabilities:J}=$,Z={model:$.model,input:o5(Q.messages,J,Q.tools),stream:!0};if(Q.systemPrompt)Z.instructions=Q.systemPrompt;let Y=V6(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 o5(Q,$,J){let Z=[],Y=new Map;if($.toolSearch){for(let G of J??[])if(GQ(G))Y.set(G.name,G)}for(let G of Q){let W=G.role,z=!Z6.has(G.finishReason),j=[],K=()=>{if(j.length===0)return;Z.push({type:"message",role:W,content:j}),j=[]};for(let B of G.content??[])switch(B.type){case"text":{if(!B.text)break;j.push(y(W,B.text));break}case"output":{if(B.partial)break;j.push(y(W,JSON.stringify(B.value)));break}case"file":{if(W==="assistant")break;let H=OQ(B);if(!$.fileInput){if(H)j.push(y(W,p(B,!1)));break}if(MQ(B,H),B.providerRejected){if(H)j.push(y(W,p(B,!1)));j.push(y(W,d(B.name)));break}if(H)j.push(y(W,p(B,!!B.fileId)));if(B.fileId)j.push(Q6(B));break}case"reasoning":{if(K(),!z)break;let H=Y6(B);if(H)Z.push(H);break}case"tool-call":{if(B.partial)break;if(K(),$.toolSearch&&Array.isArray(B.toolSearches))for(let V of B.toolSearches)Z.push(...G6(V,J??[]));let H={type:"function_call",call_id:B.toolCallId,name:String(B.name),arguments:JSON.stringify(B.input??{})};if(B.namespace&&Y.has(B.namespace))H.namespace=B.namespace;Z.push(H);break}case"tool-result":{K(),Z.push({type:"function_call_output",call_id:B.toolCallId,output:_Q(B)});break}}K()}return e5(Z)}var t5="No result was recorded for this tool call. Assume it did not complete.";function e5(Q){let $=new Set,J=new Set,Z=[];for(let G of Q){if(G.type==="function_call"){let W=String(G.call_id);if($.has(W))continue;$.add(W)}else if(G.type==="function_call_output"){let W=String(G.call_id);if(!$.has(W)||J.has(W))continue;J.add(W)}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 W=String(G.call_id);if(J.has(W))continue;J.add(W),Y.push({type:"function_call_output",call_id:W,output:t5})}return Y}function y(Q,$){return{type:Q==="assistant"?"output_text":"input_text",text:$}}function OQ(Q){let $=Q.attachmentId;return typeof $==="string"&&$.startsWith(xQ)?$:void 0}function p(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 Q6(Q){return{type:SQ(Q)?"input_image":"input_file",file_id:Q.fileId}}function SQ(Q){let $=Q.mimeType?.trim().toLowerCase()??"";return $?$.startsWith("image/")&&$!=="image/svg+xml":$6(Q.name)}function MQ(Q,$){if(Q.fileId?.startsWith(xQ))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 $6(Q){let $=/\.([a-z0-9]+)$/.exec(Q?.trim().toLowerCase()??"");return $?.[1]!==void 0&&J6.has($[1])}var J6=new Set(["jpeg","jpg","png","gif","webp"]),Z6=new Set(["error","aborted","interrupted"]);function Y6(Q){if(!Q.id)return null;let $={type:"reasoning",id:Q.id};return $.summary=Q.text?[{type:"summary_text",text:Q.text}]:[],$}function _Q(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 G6(Q,$){let J=new Set(V5(Q?.loaded)),Z=V5(Q?.namespaces),Y=new Set(Z),G=[];for(let z of $)if(GQ(z)){if(!Y.has(z.name))continue;let j=z.tools.filter((K)=>J.size===0||J.has(K.name));if(j.length===0)continue;G.push({type:"namespace",name:z.name,description:z.description,tools:j.map((K)=>f(K,!0))})}else if(z.deferred&&J.has(z.name))G.push(f(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 V5(Q){return Array.isArray(Q)?Q.filter(($)=>typeof $==="string"):[]}function GQ(Q){return Array.isArray(Q.tools)}function V6(Q,$){if(!Q||Q.length===0)return[];if(!$.toolSearch){let Y=[];for(let G of Q)if(GQ(G))for(let W of G.tools)Y.push(f(W,!1));else Y.push(f(G,!1));return Y}let J=[],Z=!1;for(let Y of Q)if(GQ(Y)){let G=Y.tools.map((W)=>{if(W.deferred)Z=!0;return f(W,!0)});J.push({type:"namespace",name:Y.name,description:Y.description,tools:G})}else{if(Y.deferred)Z=!0;J.push(f(Y,!0))}if(Z)J.push({type:"tool_search"});return J}function f(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 W6=64000;function W5(Q,$){let J={model:$.model,max_tokens:Q.maxOutputTokens??W6,messages:L6(Q.messages,$.capabilities),stream:!0},Z=Q.output,Y=!!Z?.strict&&!F6(Z.schema),G=Z&&!Y?U6(Z.schema):void 0,W=[Q.systemPrompt,G].filter(Boolean);if(W.length>0)J.system=[{type:"text",text:W.join(`
|
|
6
6
|
|
|
7
7
|
`)}];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:X6(z,$.modelId)};else if($.capabilities.reasoning&&K6(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:q6(Z.schema)}};let j=I6(Q.tools);if(j.length>0){J.tools=j;let K=C6(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 B6(J)}function K6(Q){return Q.some(($)=>$.content.some((J)=>J.type==="thinking"||J.type==="redacted_thinking"))}var RQ="thinking-binding-controls-2026-08-01";function K5(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 X6(Q,$){if(Q==="none"||Q==="minimal")return"low";if(Q==="xhigh"&&/^claude-(?:opus|sonnet)-4-6(?:-|$)/.test($))return"high";return Q}function B6(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 H6=new Set(["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","maxItems","uniqueItems"]),j6=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]),z6=/\\[1-9]|\(\?<?[=!]|\\[bB]/,B5=new Set(["properties","patternProperties","$defs","definitions"]);function q6(Q){let $=(J)=>{if(Array.isArray(J))return J.map($);if(!E(J))return J;let Z={},Y=[];for(let[G,W]of Object.entries(J)){if(H6.has(G)||G==="minItems"&&typeof W==="number"&&W>1||G==="format"&&typeof W==="string"&&!j6.has(W)||G==="pattern"&&typeof W==="string"&&z6.test(W)){Y.push(`${G}: ${JSON.stringify(W)}`);continue}Z[G]=B5.has(G)&&E(W)?Object.fromEntries(Object.entries(W).map(([j,K])=>[j,$(K)])):$(W)}if(Y.length>0){let G=`{${Y.join(", ")}}`;Z.description=typeof Z.description==="string"?`${Z.description} ${G}`:G}if(Z.type==="object"||E(Z.properties))Z.additionalProperties=!1;return Z};return $(Q)}function F6(Q){let $=0,J=0,Z=(Y)=>{if(Array.isArray(Y))return Y.forEach(Z);if(!E(Y))return;if(Array.isArray(Y.anyOf)||Array.isArray(Y.type))J++;if(E(Y.properties)){let G=new Set(Array.isArray(Y.required)?Y.required:[]);$+=Object.keys(Y.properties).filter((W)=>!G.has(W)).length}for(let[G,W]of Object.entries(Y))if(B5.has(G)&&E(W))Object.values(W).forEach(Z);else Z(W)};return Z(Q),$>24||J>16}function U6(Q){return`Answer with only a JSON value (no prose, no code fence) that matches this JSON schema:
|
|
8
8
|
${JSON.stringify(Q)}`}function C6(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 L6(Q,$){let J=[],Z=new Map;for(let B of Q){let H=B.role==="assistant"?"assistant":"user";J.push("step-end");for(let V of B.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 X=V.text??JSON.stringify(V.value);J.push({role:H,block:{type:"text",text:X}});break}case"file":{if(H==="assistant")break;for(let X of S6(V,$))J.push({role:H,block:X});break}case"reasoning":{let X=H==="assistant"?O6(V):void 0;if(X)J.push({role:H,block:X});break}case"tool-call":{if(V.partial)break;J.push({role:"assistant",block:{type:"tool_use",id:V.toolCallId,name:String(V.name),input:E(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:_Q(V),...V.status==="error"?{is_error:!0}:{}});break}}}let Y=[],G=(B,H)=>{let V=Y[Y.length-1];if(V&&V.role===B)V.content.push(H);else Y.push({role:B,content:[H]})},W=new Set,z=[],j=!1,K=()=>{for(let B of z)G("user",Z.get(B)??D6(B));z=[],j=!1};for(let B of J){if(B==="step-end"){j=!0;continue}let{role:H,block:V}=B;if(j||H==="user")K();if(V.type==="tool_use"){let X=String(V.id);if(W.has(X))continue;W.add(X),z.push(X)}G(H,V)}if(K(),Y[0]?.role==="assistant")Y.unshift({role:"user",content:[{type:"text",text:N6}]});if(Y.at(-1)?.role==="assistant")Y.push({role:"user",content:[{type:"text",text:P6}]});return Y}var N6="(The conversation continues from an earlier point.)",P6="Continue.",x6="No result was recorded for this tool call. Assume it did not complete.";function D6(Q){return{type:"tool_result",tool_use_id:Q,content:x6}}function O6(Q){let $=Q.providerMetadata?.anthropic;if(!E($))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 S6(Q,$){let J=OQ(Q),Z=(G)=>J?[{type:"text",text:p(Q,G)}]:[];if(!$.fileInput)return Z(!1);if(MQ(Q,J),!Q.fileId)return Z(!1);let Y=Q.providerRejected?void 0:_6(Q);if(!Y)return[...Z(!1),{type:"text",text:d(Q.name)}];return[...Z(!0),{type:Y,source:{type:"file",file_id:Q.fileId}}]}var M6=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function _6(Q){let $=Q.mimeType?.trim().toLowerCase()??"";if(SQ(Q))return!$||M6.has($)?"image":void 0;if($)return $==="application/pdf"||$==="text/plain"?"document":void 0;return/\.(pdf|txt)$/i.test(Q.name??"")?"document":void 0}function E(Q){return!!Q&&typeof Q==="object"&&!Array.isArray(Q)}function R6(Q){return Array.isArray(Q.tools)}function I6(Q){let $=[];for(let J of Q??[])for(let Z of R6(J)?J.tools:[J])$.push({name:Z.name,description:Z.description,input_schema:Z.parameters,eager_input_streaming:!0});return $}async function*q5(Q,$={}){let J=new Map,Z=[],Y,G={},W,z,j=!1,K=(B)=>({type:"finish",reason:B,usage:k6(G),...Y?{model:Y}:{}});for await(let B of NQ(Q)){let H;try{H=JSON.parse(B.data)}catch{continue}switch(typeof H.type==="string"?H.type:B.event){case"message_start":{let X=H.message??{};if(typeof X.model==="string"&&X.model)Y=X.model;G=z5(G,X.usage);break}case"content_block_start":{let X=Number(H.index),q=H.content_block??{},F={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(X,F),F.type==="redacted_thinking")yield{type:"reasoning-delta",delta:"",providerMetadata:{anthropic:{type:"redacted_thinking",data:String(q.data??"")}}};if(F.type==="text"&&typeof q.text==="string"&&q.text)yield j5(q.text,$);break}case"content_block_delta":{let X=J.get(Number(H.index)),q=H.delta??{};if(!X)break;if(q.type==="text_delta"){let F=String(q.text??"");if(F)yield j5(F,$)}else if(q.type==="thinking_delta"){let F=String(q.thinking??"");if(F)yield{type:"reasoning-delta",delta:F}}else if(q.type==="signature_delta")X.signature+=String(q.signature??"");else if(q.type==="input_json_delta"&&X.type==="tool_use"){let F=String(q.partial_json??"");if(!F)break;X.args+=F,yield{type:"tool-call-delta",toolCallId:X.id??"",name:X.name??"",argsDelta:F}}break}case"content_block_stop":{let X=Number(H.index),q=J.get(X);if(J.delete(X),q?.type==="thinking")yield{type:"reasoning-delta",delta:"",providerMetadata:{anthropic:{type:"thinking",signature:q.signature}}};if(q?.type==="tool_use")if(q.args||="{}",A6(q.args))yield H5(q);else Z.push(q);break}case"message_delta":{if(typeof H.delta?.stop_reason==="string")W=H.delta.stop_reason;if(H.delta?.stop_details)z=H.delta.stop_details;G=z5(G,H.usage);break}case"message_stop":{if(j=!0,W==="refusal"){yield{type:"error",error:E6(z)},yield K("error");break}let X=T6(W);if(Z.length>0&&X==="length")yield{type:"tool-call-discard",toolCallIds:Z.map((q)=>q.id??"")};else for(let q of Z)yield H5(q);yield K(X);break}case"error":{j=!0;let X=H.error??H;yield{type:"error",error:w6(X),...t(X)},yield K("error");break}}if(j)return}yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield K("error")}function H5(Q){return{type:"tool-call",toolCallId:Q.id??"",name:Q.name??"",args:Q.args}}function A6(Q){try{return JSON.parse(Q),!0}catch{return!1}}function j5(Q,$){return $.structuredOutput?{type:"output-delta",delta:Q}:{type:"text-delta",delta:Q}}function T6(Q){if(Q==="max_tokens"||Q==="model_context_window_exceeded")return"length";return"stop"}function E6(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 w6(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 z5(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 k6(Q){if(!Q)return M();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 IQ(Q){let $=TQ(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=h6($);if(J?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:J.major>1,toolSearch:F5(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:F5(J),supportsForcedToolChoice:!0};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0,supportsForcedToolChoice:!0}}function F5(Q){if(Q.kind==="o")return Q.major>=5;return Q.major>5||Q.major===5&&Q.minor>=2}function AQ(Q){let $=TQ(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:v6(Q)}}function v6(Q){let $=TQ(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 TQ(Q){return Q.trim().toLowerCase()}function h6(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 EQ=120000,wQ=2,kQ=120000,vQ=300000;function x(Q){return typeof process>"u"?void 0:process.env?.[Q]}var b6="preview";function U5(Q){let $=Q.trim().replace(/\/+$/,"");if(!$)return"";return`${$.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function y6(Q){return/^\d{4}-\d{2}-\d{2}/.test(Q)?"":"/v1"}function hQ(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??EQ,streamIdleTimeoutMs:Q.streamIdleTimeoutMs??kQ,streamMaxDurationMs:Q.streamMaxDurationMs??vQ,maxToolArgumentChars:Q.maxToolArgumentChars??0,maxRetries:Q.maxRetries??wQ,...yQ(Q)}}function C5(Q){let $=Q.baseURL??Q.endpoint??x("AZURE_OPENAI_ENDPOINT");if($)return U5($);let J=Q.resourceName??x("AZURE_OPENAI_RESOURCE_NAME")??x("AZURE_RESOURCE_NAME");return J?U5(`https://${J.trim()}.cognitiveservices.azure.com`):""}function bQ(Q,$={}){let J=Q.apiVersion??x("AZURE_OPENAI_API_VERSION")??b6;return{base:`${C5(Q)}${y6(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??EQ,streamIdleTimeoutMs:Q.streamIdleTimeoutMs??kQ,streamMaxDurationMs:Q.streamMaxDurationMs??vQ,maxToolArgumentChars:Q.maxToolArgumentChars??0,maxRetries:Q.maxRetries??wQ,...yQ(Q)}}var f6="2026-10-21";function L5(Q,$={}){let J=Q.baseURL??x("ANTHROPIC_BASE_URL")??"https://api.anthropic.com";return P5(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 W=x("ANTHROPIC_AUTH_TOKEN");return W?{authorization:`Bearer ${W}`,...Y}:Y})}function N5(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 P5(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 P5(Q,$,J,Z){return{base:`${Q.trim().replace(/\/+$/,"").replace(/\/v1$/,"")}/v1`,query:"",headers:async()=>({...await Z(),"anthropic-version":f6,...$.headers}),timeoutMs:$.timeoutMs??J.timeoutMs??EQ,streamIdleTimeoutMs:$.streamIdleTimeoutMs??kQ,streamMaxDurationMs:$.streamMaxDurationMs??vQ,maxToolArgumentChars:$.maxToolArgumentChars??0,maxRetries:$.maxRetries??wQ,...yQ($)}}function x5(Q,$={}){return{...bQ(Q,$),base:`${C5(Q)}/v1`,query:""}}function yQ(Q){return gQ(Q.retry),Q.retry?{retry:Q.retry}:{}}class VQ{static models(){return[]}normalizeError(Q){return D(Q)}}var D5=["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 O5 extends VQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=IQ(Q),this.config=$}static model(Q,$){return new O5(Q,$)}static models(){return D5}stream(Q){let $=DQ(Q,{model:this.model,capabilities:this.capabilities});return JQ(this.endpoint(),$,{signal:Q.signal,retryToolArgumentsTooLong:Q.retryToolArgumentsTooLong,structuredOutput:Boolean(Q.output),files:qQ(Q.messages)})}upload(Q){return ZQ(this.endpoint(),Q)}deleteFile(Q){return YQ(this.endpoint(),Q)}endpoint(){return $Q(hQ(this.config))}get realtime(){return new o(hQ(this.config,{timeoutMs:jQ}),{model:this.model})}}var g6=["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 fQ extends VQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=AQ(Q),this.config=$}static model(Q,$){return new fQ(Q,$)}static models(){return g6}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,W=!1;for await(let z of JQ(this.endpointFor(Y),Y,{signal:Q.signal,retryToolArgumentsTooLong:Q.retryToolArgumentsTooLong,structuredOutput:Boolean(Q.output),parse:q5})){if(G)continue;if(!W&&z.type==="error"&&z.status===400){let j=K5(z.error.message);if(j&&!Z.has(j)){Z.add(j),G=j;continue}}if(QQ(z))W=!0;yield z}if(!G)return;if(G==="thinking")J=!0;else if($.output)$={...$,output:{...$.output,strict:!1}}}}request(Q){return W5(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},${RQ}`:RQ}}}}bindsThinking(){return!0}deployment(){return this.model}upload(Q){return ZQ(this.endpoint(),Q,null)}deleteFile(Q){return YQ(this.endpoint(),Q)}endpoint(){return S5(L5(this.config))}}function S5(Q){return{...$Q(Q),responsesUrl:`${Q.base}/messages`}}class M5 extends fQ{constructor(Q,$={}){super(Q,$);this.capabilities={...AQ(Q),fileInput:!1}}static model(Q,$){return new M5(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 S5(N5(this.config))}}class _5 extends VQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=IQ(Q),this.config=$}static model(Q,$){return new _5(Q,$)}static models(){return D5}stream(Q){let $=DQ(Q,{model:this.deployment(),capabilities:this.capabilities});return JQ(this.endpoint(),$,{signal:Q.signal,retryToolArgumentsTooLong:Q.retryToolArgumentsTooLong,structuredOutput:Boolean(Q.output),files:qQ(Q.messages)})}upload(Q){return ZQ(this.endpoint(),Q,"assistants")}deleteFile(Q){return YQ(this.endpoint(),Q)}deployment(){return this.config.deployment??this.model}endpoint(){return $Q(bQ(this.config))}get realtime(){return new o(x5(this.config,{timeoutMs:jQ}),{model:this.deployment(),callFlow:"ephemeral"})}}
|
|
9
9
|
export{b as ca,hQ as da,bQ as ea,HQ as fa,h5 as ga,zQ as ha,m as ia,o as ja,u5 as ka,VQ as la,O5 as ma,fQ as na,M5 as oa,_5 as pa};
|
|
10
10
|
|
|
11
|
-
//# debugId=
|
|
11
|
+
//# debugId=84C6C2E434920B7C64756E2164756E21
|