gemi 0.137.0 → 0.138.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +3 -3
- package/dist/ai/index.js.map +4 -4
- package/dist/ai/providers/errors.d.ts +9 -1
- package/dist/ai/providers/errors.d.ts.map +1 -1
- package/dist/ai/providers/http.d.ts.map +1 -1
- package/dist/ai/providers/images.d.ts +2 -0
- package/dist/ai/providers/images.d.ts.map +1 -1
- package/dist/ai/types.d.ts +10 -1
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/{chunk-t0p6zb29.js → chunk-1y6hxv30.js} +1 -1
- package/dist/{chunk-fjw51b91.js → chunk-4wyhf6j2.js} +1 -1
- package/dist/{chunk-x1j7e46e.js → chunk-es3mah07.js} +1 -1
- package/dist/chunk-n1n7qb34.js +117 -0
- package/dist/{chunk-z19rwc6x.js.map → chunk-n1n7qb34.js.map} +6 -5
- package/dist/{chunk-4zjtbgnr.js → chunk-vtc1khbm.js} +2 -2
- package/dist/{chunk-4zjtbgnr.js.map → chunk-vtc1khbm.js.map} +1 -1
- package/dist/{chunk-atmw5c0q.js → chunk-z88axcxg.js} +15 -15
- package/dist/{chunk-atmw5c0q.js.map → chunk-z88axcxg.js.map} +3 -3
- package/dist/chunks/{RealtimeClient-DsWbFRC7.js → RealtimeClient-B345JtXu.js} +2 -2
- package/dist/chunks/{RealtimeClient-DsWbFRC7.js.map → RealtimeClient-B345JtXu.js.map} +1 -1
- package/dist/chunks/{ThemeProvider-gWqXjGh-.js → ThemeProvider-BwlMubvu.js} +97 -30
- package/dist/chunks/ThemeProvider-BwlMubvu.js.map +1 -0
- package/dist/chunks/{fetchFileRequest-BSrgYnAy.js → fetchFileRequest-DKKdn8Yp.js} +2 -2
- package/dist/chunks/{fetchFileRequest-BSrgYnAy.js.map → fetchFileRequest-DKKdn8Yp.js.map} +1 -1
- package/dist/chunks/{live-CUdMhXHL.js → live-Cq65lqVg.js} +3 -3
- package/dist/chunks/{live-CUdMhXHL.js.map → live-Cq65lqVg.js.map} +1 -1
- package/dist/chunks/{mutationExtras-CtY-X9m7.js → mutationExtras-KMQj-GZD.js} +2 -2
- package/dist/chunks/{mutationExtras-CtY-X9m7.js.map → mutationExtras-KMQj-GZD.js.map} +1 -1
- package/dist/client/ServerDataProvider.d.ts +3 -0
- package/dist/client/ServerDataProvider.d.ts.map +1 -1
- package/dist/client/ThemeProvider.d.ts +23 -8
- package/dist/client/ThemeProvider.d.ts.map +1 -1
- package/dist/client/index.d.ts +1 -0
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +3 -3
- package/dist/client/theme.d.ts +47 -0
- package/dist/client/theme.d.ts.map +1 -0
- package/dist/facades/index.js +1 -1
- package/dist/http/index.js +1 -1
- package/dist/i18n/index.js +1 -1
- package/dist/kernel/index.js +1 -1
- package/dist/server/index.js +1 -1
- package/dist/services/index.js +1 -1
- package/dist/services/router/ViewRouteDispatcher.d.ts +3 -1
- package/dist/services/router/ViewRouteDispatcher.d.ts.map +1 -1
- package/dist/services/router/config.d.ts +27 -0
- package/dist/services/router/config.d.ts.map +1 -1
- package/dist/testing/index.js +2 -2
- package/package.json +1 -1
- package/dist/chunk-z19rwc6x.js +0 -122
- package/dist/chunks/ThemeProvider-gWqXjGh-.js.map +0 -1
- /package/dist/{chunk-t0p6zb29.js.map → chunk-1y6hxv30.js.map} +0 -0
- /package/dist/{chunk-fjw51b91.js.map → chunk-4wyhf6j2.js.map} +0 -0
- /package/dist/{chunk-x1j7e46e.js.map → chunk-es3mah07.js.map} +0 -0
package/dist/ai/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$c as E6,Ac as J$,Bc as $$,Cc as Z$,Dc as W$,Ec as K$,Fc as G$,Gc as X$,Hc as Y$,Jc as I,Kc as U$,Lc as i,Mc as k,Nc as vQ,Oc as E9,Pc as x9,Qc as q9,Rc as I9,Sc as w9,Tc as b9,Uc as f9,Vc as v9,Wc as y9,Xb as wQ,Xc as h9,Yb as _6,Yc as g9,Zb as bQ,Zc as AQ,_c as u9,ac as T,ad as c9,bc as w,bd as m9,cc as h,cd as UJ,dc as fQ,dd as iJ,ec as S6,ed as p9,fc as A6,fd as l9,gc as k6,gd as d9,hc as c,hd as i9,ic as R6,id as n9,jc as vJ,jd as o9,kc as T6,lc as j6,mc as yJ,nc as dQ,oc as iQ,qc as nQ,rc as v,sc as Z6,tc as W6,uc as oQ,wc as aQ,xc as Q$,yc as rQ,zc as eQ}from"../chunk-
|
|
2
|
+
import{$c as E6,Ac as J$,Bc as $$,Cc as Z$,Dc as W$,Ec as K$,Fc as G$,Gc as X$,Hc as Y$,Jc as I,Kc as U$,Lc as i,Mc as k,Nc as vQ,Oc as E9,Pc as x9,Qc as q9,Rc as I9,Sc as w9,Tc as b9,Uc as f9,Vc as v9,Wc as y9,Xb as wQ,Xc as h9,Yb as _6,Yc as g9,Zb as bQ,Zc as AQ,_c as u9,ac as T,ad as c9,bc as w,bd as m9,cc as h,cd as UJ,dc as fQ,dd as iJ,ec as S6,ed as p9,fc as A6,fd as l9,gc as k6,gd as d9,hc as c,hd as i9,ic as R6,id as n9,jc as vJ,jd as o9,kc as T6,lc as j6,mc as yJ,nc as dQ,oc as iQ,qc as nQ,rc as v,sc as Z6,tc as W6,uc as oQ,wc as aQ,xc as Q$,yc as rQ,zc as eQ}from"../chunk-z88axcxg.js";import{Bd as gQ}from"../chunk-zvzvgrrn.js";import"../chunk-85k70cme.js";import{Ai as C6,Lh as f$,Mh as R9,Nh as T9,Oh as j9,Ph as E,sh as O6,ti as M6,vh as L6,wi as CQ}from"../chunk-md6wfc1h.js";import{Bi as N6,Di as bJ,Ei as fJ}from"../chunk-p2c7z2nr.js";import{Ni as y}from"../chunk-yhp70t40.js";import"../chunk-7d26eqv1.js";import"../chunk-qfhcec6q.js";import{Qj as BJ,Rj as FJ,dk as lQ}from"../chunk-ghbzre7k.js";import"../chunk-c6c7p43e.js";import{Sk as n$}from"../chunk-xwmy6fby.js";import"../chunk-27xv8kty.js";import"../chunk-z969a4nt.js";import"../chunk-aj2sr77y.js";import"../chunk-038xtqpm.js";class gJ extends gQ{name="AgentJobDeadlineSweep";cron="* * * * *";async callback(){while(await v.sweep({limit:100})===100);}}var HJ=20;function cQ(J,Q){if(Q<=0||J.length===0)return null;let $=(K,G)=>G.createdAt-K.createdAt||(K.id<G.id?1:-1);return["<jobs>","Background jobs that tools started in this conversation, running ones first. A running job's result replaces its tool result when it finishes. Do not start the same work again while a job for it is running.",...[...J.filter((K)=>K.state==="running").sort($),...J.filter((K)=>K.state!=="running").sort($)].slice(0,Q).map((K)=>{let G=[`- ${K.id} (${K.toolName})`];if(K.state==="running")G.push(`running since ${uJ(K.createdAt)}`);else if(K.state==="ok")G.push(`finished at ${uJ(K.settledAt??K.updatedAt)}`);else{let X=K.error?`${K.error.code}: ${uQ(K.error.message,200)}`:"failed";G.push(`failed at ${uJ(K.settledAt??K.updatedAt)} (${X})`)}if(K.summary!==void 0)G.push(`summary: ${uQ(JSON.stringify(K.summary),300)}`);if(K.orphaned)G.push("its tool call was lost when the turn that started it was cut short");return G.join("; ")}),"</jobs>"].join(`
|
|
3
3
|
`)}function uJ(J){return new Date(J).toISOString().replace(/\.\d{3}Z$/,"Z")}function uQ(J,Q){return J.length<=Q?J:`${J.slice(0,Q-1)}\u2026`}class mJ{table;sql;dialect;connection;constructor(J,Q={}){let $=Q.table??"gemi_agent_jobs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test($))throw Error(`The agent jobs table name "${$}" is not a plain identifier. Use letters, digits and underscores.`);this.table=$,this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name}async createTable(){for(let J of b6(this.dialect,this.table))await this.sql.unsafe(J)}async transaction(J){if(this.connection===void 0||this.joinable())return J();return lQ(this.sql,()=>J(),{connection:this.connection})}async create(J){let Q=this.q(),$=this.clock(Q);await Q`
|
|
4
4
|
INSERT INTO ${this.name(Q)}
|
|
5
5
|
(id, thread_id, run_id, tool_call_id, tool_name, owner, job, summary, state,
|
|
@@ -139,7 +139,7 @@ import{$c as E6,Ac as J$,Bc as $$,Cc as Z$,Dc as W$,Ec as K$,Fc as G$,Gc as X$,H
|
|
|
139
139
|
"updated_at" BIGINT NOT NULL,
|
|
140
140
|
"last_used_at" BIGINT,
|
|
141
141
|
"expires_at" BIGINT${Z}
|
|
142
|
-
)`,`CREATE INDEX IF NOT EXISTS "${Q}_scope_kind_created_at_idx" ON "${Q}"("scope", "kind", "created_at")`,`CREATE INDEX IF NOT EXISTS "${Q}_expires_at_idx" ON "${Q}"("expires_at")`,`CREATE UNIQUE INDEX IF NOT EXISTS "${Q}_scope_key_key" ON "${Q}"("scope", "key")`]}var v6=/^[A-Za-z0-9_-]{1,64}$/;function y6(J,Q){let $=h6(Q)?Q:{filter:Q},Z=$.deferred===!0,W=J.descriptors($.filter);if(!$.namespaces)return W.map((H)=>dJ(J,H,Z));let K=Object.entries($.namespaces),G=new Set(J.descriptors().flatMap((H)=>H.tags));for(let[H,D]of K){if(!v6.test(H))throw Error(`toAgentTools: "${H}" is not a valid namespace name. A namespace is named by its tag and sent to the provider as a tool name is \u2014 letters, digits, "_" and "-", at most 64.`);if(typeof D?.description!=="string"||D.description.trim()==="")throw Error(`toAgentTools: the namespace "${H}" needs a description. It is what the model reads to decide whether to look inside.`);if(!G.has(H))throw Error(`toAgentTools: no tool is tagged "${H}", so its namespace would be empty.`)}let X=new Map(K.map(([H])=>[H,[]])),V=[];for(let H of W){let D=K.find(([z])=>H.tags.includes(z))?.[0];if(D===void 0)V.push(dJ(J,H,Z));else X.get(D).push(dJ(J,H,!1))}let Y=[];for(let[H,D]of K){let z=X.get(H);if(z.length===0)continue;Y.push(iJ.create({name:H,description:D.description,tools:z,deferred:D.deferred??Z}))}return[...Y,...V]}function h6(J){return typeof J==="object"&&J!==null&&(("filter"in J)||("namespaces"in J)||("deferred"in J))}function dJ(J,Q,$){if(Q.kind==="tool")return g6(J,Q,$);return UJ.create({name:Q.name,description:Q.description,inputSchema:Q.inputSchema,...Q.outputSchema?{outputSchema:Q.outputSchema}:{},requiresApproval:Q.requiresApproval,deferred:$,execute:(Z,W)=>{let K=y.getStore()?.req;if(!K)throw new h(`"${Q.name}" calls an api route as the user who started this run, and this run was not started inside a request. Run it from an AgentController, or give this agent tools that do not go through the MCP registry.`);return J.execute({kind:"local",req:K},Q.name,Z,W)}})}function g6(J,Q,$){let Z=J.nativeTool(Q.name);return UJ.create({name:Q.name,description:Q.description,inputSchema:Q.inputSchema,...Q.outputSchema?{outputSchema:Q.outputSchema}:{},requiresApproval:Q.requiresApproval,deferred:$,...Z.timeoutMs!==void 0?{timeoutMs:Z.timeoutMs}:{},...Z.async?{async:Z.async}:{},execute:(W,K)=>{let G=y.getStore()?.req;return J.startNative(G?{kind:"local",req:G}:void 0,Q.name,W,K)}})}function u6(J){if(J==="auto")return;let Q=/^(\d+)x(\d+)$/.exec(J);if(!Q)throw Error(`An image size is "WIDTHxHEIGHT" or "auto"; got ${JSON.stringify(J)}.`);let $=Number(Q[1]),Z=Number(Q[2]);if($%16!==0||Z%16!==0)throw Error(`Image size ${J} is not supported: width and height must both be divisible by 16.`);if(Math.max($/Z,Z/$)>3)throw Error(`Image size ${J} is not supported: the maximum aspect ratio is 3:1, either way up.`)}function V$(J,Q){if(J.size!==void 0)try{u6(J.size)}catch($){throw Error(`${Q}: ${$.message}`)}if(J.background==="transparent"&&J.format==="jpeg")throw Error(`${Q}: a transparent background needs "png"; JPEG has no alpha channel.`);if(J.compression!==void 0){let $=J.compression;if(!Number.isInteger($)||$<0||$>100)throw Error(`${Q}: compression is an integer from 0 to 100; got ${$}.`)}}function H$(J,Q){if(J instanceof File)return J;let $=J.type||"image/png",Z=$==="image/jpeg"?"jpg":$.split("/")[1]??"png";return new File([J],`${Q}.${Z}`,{type:$})}class nJ{name;provider;settings;constructor(J){let{name:Q,provider:$,...Z}=J;V$(Z,`ImageModel "${Q}"`),this.name=Q,this.provider=$,this.settings=Z}static create(J){return new nJ(J)}async generate(J){let Q=this.merge(J);return z$(await this.provider.generate({prompt:J.prompt,...Q,signal:J.signal}))}async edit(J){let Q=this.merge(J);return z$(await this.provider.edit({prompt:J.prompt,...Q,images:J.images.map(($,Z)=>H$($,`image-${Z}`)),...J.mask?{mask:H$(J.mask,"mask")}:{},signal:J.signal}))}merge(J){let Q={...this.settings,...J.size!==void 0?{size:J.size}:{},...J.quality!==void 0?{quality:J.quality}:{},...J.background!==void 0?{background:J.background}:{},...J.format!==void 0?{format:J.format}:{},...J.compression!==void 0?{compression:J.compression}:{}};return V$(Q,`ImageModel "${this.name}"`),Q}}function z$(J){return{image:new Blob([J.bytes],{type:J.mimeType}),mimeType:J.mimeType,size:J.size,usage:J.usage}}function g(J){return typeof process>"u"?void 0:process.env?.[J]}var c6="preview";function D$(J){let Q=J.trim().replace(/\/+$/,"");if(!Q)return"";return`${Q.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function m6(J){return/^\d{4}-\d{2}-\d{2}/.test(J)?"":"/v1"}function JJ(J,Q={}){return{base:(J.baseURL??g("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let Z=J.apiKey??g("OPENAI_API_KEY");return{...Z?{authorization:`Bearer ${Z}`}:{},...J.headers}},timeoutMs:J.timeoutMs??Q.timeoutMs??120000,maxRetries:J.maxRetries??2}}function B$(J){let Q=J.baseURL??J.endpoint??g("AZURE_OPENAI_ENDPOINT");if(Q)return D$(Q);let $=J.resourceName??g("AZURE_OPENAI_RESOURCE_NAME")??g("AZURE_RESOURCE_NAME");return $?D$(`https://${$.trim()}.cognitiveservices.azure.com`):""}function QJ(J,Q={}){let $=J.apiVersion??g("AZURE_OPENAI_API_VERSION")??c6;return{base:`${B$(J)}${m6($)}`,query:`?api-version=${encodeURIComponent($)}`,headers:async()=>{if(J.getToken)return{authorization:`Bearer ${await J.getToken()}`,...J.headers};let Z=J.apiKey??g("AZURE_OPENAI_API_KEY");return{...Z?{"api-key":Z}:{},...J.headers}},timeoutMs:J.timeoutMs??Q.timeoutMs??120000,maxRetries:J.maxRetries??2}}function F$(J,Q={}){return{...QJ(J,Q),base:`${B$(J)}/v1`,query:""}}var p6=500,O$=20000;function l6(J,Q){if(!J)return;let $=J.trim();if(/^\d+(\.\d+)?$/.test($))return Math.max(0,Number($)*1000);let Z=Date.parse($);if(Number.isNaN(Z))return;return Math.max(0,Z-Q)}function P$(J,Q){let $=Math.min(O$,p6*2**J);return Math.round($*(0.5+Q()*0.5))}function d6(J){return J===429||J===408||J===409||J>=500}function i6(J,Q){return d6(J)&&k(Q).retryable}function N$(J){return J.reason??new DOMException("The operation was aborted.","AbortError")}function n6(J,Q){return new Promise(($,Z)=>{let W=setTimeout($,J);Q?.addEventListener("abort",()=>{clearTimeout(W),Z(N$(Q))},{once:!0})})}async function u(J,Q,$){let Z=$.fetchImpl??((H,D)=>fetch(H,D)),W=$.sleep??n6,K=$.random??Math.random,G=$.now??Date.now,X=Math.max(0,$.maxRetries),V=async(H)=>{let D=$.signal;if(!D)return await W(H);D.throwIfAborted();let z;try{await Promise.race([W(H,D),new Promise((B,U)=>{z=()=>U(N$(D)),D.addEventListener("abort",z,{once:!0})})])}finally{if(z)D.removeEventListener("abort",z)}},Y;for(let H=0;H<=X;H++){$.signal?.throwIfAborted();let D=new AbortController,z=()=>D.abort($.signal?.reason);$.signal?.addEventListener("abort",z,{once:!0});let B=!1,U=$.timeoutMs>0?setTimeout(()=>{B=!0,D.abort()},$.timeoutMs):void 0,F;try{F=await Z(J,{...Q,signal:D.signal})}catch(M){if(U!==void 0)clearTimeout(U);if($.signal?.removeEventListener("abort",z),$.signal?.aborted)throw M;if(Y=B?new U$($.timeoutMs):M,B&&$.retryTimeouts===!1)throw Y;if(H===X)throw Y;await V(P$(H,K));continue}if(U!==void 0)clearTimeout(U);if(F.ok)return F;$.signal?.removeEventListener("abort",z);let O=await o6(F),P=new I(F.status,O,F.headers.get("x-request-id")??void 0);if(H===X||!i6(F.status,P))throw P;let N=l6(F.headers.get("retry-after"),G());await V(N===void 0?P$(H,K):Math.min(N,O$)),Y=P}throw Y??Error("Provider request failed with no response.")}async function o6(J){let Q;try{Q=await J.text()}catch{return null}try{return JSON.parse(Q)}catch{return Q}}var oJ=300000;function aJ(J){return{generationsUrl:`${J.base}/images/generations${J.query}`,editsUrl:`${J.base}/images/edits${J.query}`,headers:J.headers,timeoutMs:J.timeoutMs,maxRetries:J.maxRetries}}class OJ extends Error{code;retryable;constructor(J,Q={}){super(J.message,Q);this.name="ImageRequestError",this.code=J.code,this.retryable=J.retryable}}var a6={png:"image/png",jpeg:"image/jpeg"};function s6(J){let Q=Number(J?.input_tokens??0),$=Number(J?.output_tokens??0),Z={inputTokens:Q,outputTokens:$,totalTokens:Number(J?.total_tokens??Q+$)},W=J?.input_tokens_details?.image_tokens;if(typeof W==="number")Z.imageInputTokens=W;let K=J?.output_tokens_details?.image_tokens;if(typeof K==="number")Z.imageOutputTokens=K;return Z}function t6(J){let Q=atob(J),$=new Uint8Array(Q.length);for(let Z=0;Z<Q.length;Z++)$[Z]=Q.charCodeAt(Z);return $}function r6(J){let $=J?.data?.[0]?.b64_json;if(typeof $!=="string"||$.length===0)throw new OJ({code:"provider_error",message:"The provider answered an image call with no base64 image data.",retryable:!1});let Z=typeof J.output_format==="string"?J.output_format:"png";return{bytes:t6($),mimeType:a6[Z]??`image/${Z}`,size:typeof J.size==="string"?J.size:"",...typeof J.background==="string"?{background:J.background}:{},usage:s6(J.usage)}}async function L$(J,Q,$,Z){let W;try{W=await u(J,Q,{maxRetries:$.maxRetries,timeoutMs:$.timeoutMs,retryTimeouts:!1,signal:Z.signal,fetchImpl:$.fetchImpl})}catch(K){if(Z.signal?.aborted)throw K;throw new OJ(k(K),{cause:K})}return r6(await W.json())}async function M$(J,Q,$={}){return await L$(J.generationsUrl,{method:"POST",headers:{...await J.headers(),"content-type":"application/json"},body:JSON.stringify(Q)},J,$)}async function C$(J,Q,$={}){return await L$(J.editsUrl,{method:"POST",headers:await J.headers(),body:Q},J,$)}class NJ{static models(){return[]}modelName(){return this.model}async generate(J){return await M$(this.endpoint(),this.body(J),{signal:J.signal})}async edit(J){let Q=new FormData;for(let[$,Z]of Object.entries(this.body(J)))if(Z!==void 0)Q.set($,String(Z));for(let $ of J.images)Q.append("image[]",$,$.name);if(J.mask)Q.set("mask",J.mask,J.mask.name);return await C$(this.endpoint(),Q,{signal:J.signal})}body(J){return{model:this.modelName(),prompt:J.prompt,...J.size?{size:J.size}:{},...J.quality?{quality:J.quality}:{},...J.background?{background:J.background}:{},...J.format?{output_format:J.format}:{},...J.compression!==void 0?{output_compression:J.compression}:{}}}normalizeError(J){return k(J)}}var _$=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class sJ extends NJ{model;config;constructor(J,Q={}){super();this.model=J,this.config=Q}static model(J,Q){return new sJ(J,Q)}static models(){return _$}endpoint(){return aJ(JJ(this.config,{timeoutMs:oJ}))}}class tJ extends NJ{model;config;constructor(J,Q={}){super();this.model=J,this.config=Q}static model(J,Q){return new tJ(J,Q)}static models(){return _$}modelName(){return this.config.deployment??this.model}endpoint(){return aJ(QJ(this.config,{timeoutMs:oJ}))}}var k$=3;function rJ(J){let Q=new Map;for(let $ of J)for(let Z of $.content??[]){if(Z.type!=="file"||!Z.fileId||Q.has(Z.fileId))continue;Q.set(Z.fileId,{name:Z.name,mimeType:Z.mimeType})}return Q}function R$(J,Q,$=new Map){if(!(Q instanceof I))return[];if(Q.status!==400&&Q.status!==404)return[];let Z=J8(Q.body);if(!Z)return[];let W=e6(J.input);if(W.length===0)return[];let K=/^input\[(\d+)\]\.content\[(\d+)\]\.file_id$/.exec(Z.param??"");if(K){let Y=J.input[Number(K[1])],H=JQ(Y)[Number(K[2])],D=H&&typeof H.file_id==="string"?H.file_id:void 0;if(D)return[D]}let G=Z.message??"",X=A$(W.map((Y)=>Y.fileId).filter((Y)=>Q8(G,Y)));if(X.length>0)return X;let V=/Expected (image type|context stuffing file type) to be a supported format:.*but got \.([a-z0-9]+)\.?\s*$/is.exec(G);if(V){let Y=V[1].toLowerCase()==="image type"?"input_image":"input_file",H=V[2].toLowerCase(),D=A$(W.filter((B)=>B.type===Y).map((B)=>B.fileId)),z=D.filter((B)=>($.get(B)?.name??"").trim().toLowerCase().endsWith(`.${H}`));if(z.length===1)return z;if(z.length===0&&D.length===1)return D}return[]}function T$(J,Q,$=new Map){return{...J,input:J.input.map((Z)=>{let W=JQ(Z);if(!W.some((K)=>S$(K,Q)))return Z;return{...Z,content:W.map((K)=>S$(K,Q)?{type:"input_text",text:eJ($.get(String(K.file_id))?.name)}:K)}})}}function eJ(J){return`[${J?`attachment ${JSON.stringify(J)}`:"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 S$(J,Q){return typeof J.file_id==="string"&&Q.has(J.file_id)}function JQ(J){let Q=J?.content;return Array.isArray(Q)?Q:[]}function e6(J){let Q=[];for(let $ of J)for(let Z of JQ($))if(typeof Z.file_id==="string"&&Z.file_id)Q.push({type:String(Z.type),fileId:Z.file_id});return Q}function J8(J){if(!J||typeof J!=="object")return null;let Q=J,$=Q.error&&typeof Q.error==="object"?Q.error:J;return{message:typeof $.message==="string"?$.message:void 0,param:typeof $.param==="string"?$.param:void 0}}function Q8(J,Q){let $=Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${$}($|[^A-Za-z0-9_-])`).test(J)}function A$(J){return[...new Set(J)]}async function*$8(J){let Q="",$="",Z=[],W,K=()=>{if(Z.length===0&&!$)return null;let V={event:$,data:Z.join(`
|
|
142
|
+
)`,`CREATE INDEX IF NOT EXISTS "${Q}_scope_kind_created_at_idx" ON "${Q}"("scope", "kind", "created_at")`,`CREATE INDEX IF NOT EXISTS "${Q}_expires_at_idx" ON "${Q}"("expires_at")`,`CREATE UNIQUE INDEX IF NOT EXISTS "${Q}_scope_key_key" ON "${Q}"("scope", "key")`]}var v6=/^[A-Za-z0-9_-]{1,64}$/;function y6(J,Q){let $=h6(Q)?Q:{filter:Q},Z=$.deferred===!0,W=J.descriptors($.filter);if(!$.namespaces)return W.map((H)=>dJ(J,H,Z));let K=Object.entries($.namespaces),G=new Set(J.descriptors().flatMap((H)=>H.tags));for(let[H,D]of K){if(!v6.test(H))throw Error(`toAgentTools: "${H}" is not a valid namespace name. A namespace is named by its tag and sent to the provider as a tool name is \u2014 letters, digits, "_" and "-", at most 64.`);if(typeof D?.description!=="string"||D.description.trim()==="")throw Error(`toAgentTools: the namespace "${H}" needs a description. It is what the model reads to decide whether to look inside.`);if(!G.has(H))throw Error(`toAgentTools: no tool is tagged "${H}", so its namespace would be empty.`)}let X=new Map(K.map(([H])=>[H,[]])),V=[];for(let H of W){let D=K.find(([z])=>H.tags.includes(z))?.[0];if(D===void 0)V.push(dJ(J,H,Z));else X.get(D).push(dJ(J,H,!1))}let Y=[];for(let[H,D]of K){let z=X.get(H);if(z.length===0)continue;Y.push(iJ.create({name:H,description:D.description,tools:z,deferred:D.deferred??Z}))}return[...Y,...V]}function h6(J){return typeof J==="object"&&J!==null&&(("filter"in J)||("namespaces"in J)||("deferred"in J))}function dJ(J,Q,$){if(Q.kind==="tool")return g6(J,Q,$);return UJ.create({name:Q.name,description:Q.description,inputSchema:Q.inputSchema,...Q.outputSchema?{outputSchema:Q.outputSchema}:{},requiresApproval:Q.requiresApproval,deferred:$,execute:(Z,W)=>{let K=y.getStore()?.req;if(!K)throw new h(`"${Q.name}" calls an api route as the user who started this run, and this run was not started inside a request. Run it from an AgentController, or give this agent tools that do not go through the MCP registry.`);return J.execute({kind:"local",req:K},Q.name,Z,W)}})}function g6(J,Q,$){let Z=J.nativeTool(Q.name);return UJ.create({name:Q.name,description:Q.description,inputSchema:Q.inputSchema,...Q.outputSchema?{outputSchema:Q.outputSchema}:{},requiresApproval:Q.requiresApproval,deferred:$,...Z.timeoutMs!==void 0?{timeoutMs:Z.timeoutMs}:{},...Z.async?{async:Z.async}:{},execute:(W,K)=>{let G=y.getStore()?.req;return J.startNative(G?{kind:"local",req:G}:void 0,Q.name,W,K)}})}function u6(J){if(J==="auto")return;let Q=/^(\d+)x(\d+)$/.exec(J);if(!Q)throw Error(`An image size is "WIDTHxHEIGHT" or "auto"; got ${JSON.stringify(J)}.`);let $=Number(Q[1]),Z=Number(Q[2]);if($%16!==0||Z%16!==0)throw Error(`Image size ${J} is not supported: width and height must both be divisible by 16.`);if(Math.max($/Z,Z/$)>3)throw Error(`Image size ${J} is not supported: the maximum aspect ratio is 3:1, either way up.`)}function V$(J,Q){if(J.size!==void 0)try{u6(J.size)}catch($){throw Error(`${Q}: ${$.message}`)}if(J.background==="transparent"&&J.format==="jpeg")throw Error(`${Q}: a transparent background needs "png"; JPEG has no alpha channel.`);if(J.compression!==void 0){let $=J.compression;if(!Number.isInteger($)||$<0||$>100)throw Error(`${Q}: compression is an integer from 0 to 100; got ${$}.`)}}function H$(J,Q){if(J instanceof File)return J;let $=J.type||"image/png",Z=$==="image/jpeg"?"jpg":$.split("/")[1]??"png";return new File([J],`${Q}.${Z}`,{type:$})}class nJ{name;provider;settings;constructor(J){let{name:Q,provider:$,...Z}=J;V$(Z,`ImageModel "${Q}"`),this.name=Q,this.provider=$,this.settings=Z}static create(J){return new nJ(J)}async generate(J){let Q=this.merge(J);return z$(await this.provider.generate({prompt:J.prompt,...Q,signal:J.signal}))}async edit(J){let Q=this.merge(J);return z$(await this.provider.edit({prompt:J.prompt,...Q,images:J.images.map(($,Z)=>H$($,`image-${Z}`)),...J.mask?{mask:H$(J.mask,"mask")}:{},signal:J.signal}))}merge(J){let Q={...this.settings,...J.size!==void 0?{size:J.size}:{},...J.quality!==void 0?{quality:J.quality}:{},...J.background!==void 0?{background:J.background}:{},...J.format!==void 0?{format:J.format}:{},...J.compression!==void 0?{compression:J.compression}:{}};return V$(Q,`ImageModel "${this.name}"`),Q}}function z$(J){return{image:new Blob([J.bytes],{type:J.mimeType}),mimeType:J.mimeType,size:J.size,usage:J.usage}}function g(J){return typeof process>"u"?void 0:process.env?.[J]}var c6="preview";function D$(J){let Q=J.trim().replace(/\/+$/,"");if(!Q)return"";return`${Q.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function m6(J){return/^\d{4}-\d{2}-\d{2}/.test(J)?"":"/v1"}function JJ(J,Q={}){return{base:(J.baseURL??g("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let Z=J.apiKey??g("OPENAI_API_KEY");return{...Z?{authorization:`Bearer ${Z}`}:{},...J.headers}},timeoutMs:J.timeoutMs??Q.timeoutMs??120000,maxRetries:J.maxRetries??2}}function B$(J){let Q=J.baseURL??J.endpoint??g("AZURE_OPENAI_ENDPOINT");if(Q)return D$(Q);let $=J.resourceName??g("AZURE_OPENAI_RESOURCE_NAME")??g("AZURE_RESOURCE_NAME");return $?D$(`https://${$.trim()}.cognitiveservices.azure.com`):""}function QJ(J,Q={}){let $=J.apiVersion??g("AZURE_OPENAI_API_VERSION")??c6;return{base:`${B$(J)}${m6($)}`,query:`?api-version=${encodeURIComponent($)}`,headers:async()=>{if(J.getToken)return{authorization:`Bearer ${await J.getToken()}`,...J.headers};let Z=J.apiKey??g("AZURE_OPENAI_API_KEY");return{...Z?{"api-key":Z}:{},...J.headers}},timeoutMs:J.timeoutMs??Q.timeoutMs??120000,maxRetries:J.maxRetries??2}}function F$(J,Q={}){return{...QJ(J,Q),base:`${B$(J)}/v1`,query:""}}var p6=500,O$=20000;function l6(J,Q){if(!J)return;let $=J.trim();if(/^\d+(\.\d+)?$/.test($))return Math.max(0,Number($)*1000);let Z=Date.parse($);if(Number.isNaN(Z))return;return Math.max(0,Z-Q)}function P$(J,Q){let $=Math.min(O$,p6*2**J);return Math.round($*(0.5+Q()*0.5))}function d6(J){return J===429||J===408||J===409||J>=500}function i6(J,Q){return d6(J)&&k(Q).retryable}function N$(J){return J.reason??new DOMException("The operation was aborted.","AbortError")}function n6(J,Q){return new Promise(($,Z)=>{let W=setTimeout($,J);Q?.addEventListener("abort",()=>{clearTimeout(W),Z(N$(Q))},{once:!0})})}async function u(J,Q,$){let Z=$.fetchImpl??((H,D)=>fetch(H,D)),W=$.sleep??n6,K=$.random??Math.random,G=$.now??Date.now,X=Math.max(0,$.maxRetries),V=async(H)=>{let D=$.signal;if(!D)return await W(H);D.throwIfAborted();let z;try{await Promise.race([W(H,D),new Promise((B,U)=>{z=()=>U(N$(D)),D.addEventListener("abort",z,{once:!0})})])}finally{if(z)D.removeEventListener("abort",z)}},Y;for(let H=0;H<=X;H++){$.signal?.throwIfAborted();let D=new AbortController,z=()=>D.abort($.signal?.reason);$.signal?.addEventListener("abort",z,{once:!0});let B=!1,U=$.timeoutMs>0?setTimeout(()=>{B=!0,D.abort()},$.timeoutMs):void 0,F;try{F=await Z(J,{...Q,signal:D.signal})}catch(M){if(U!==void 0)clearTimeout(U);if($.signal?.removeEventListener("abort",z),$.signal?.aborted)throw M;if(Y=B?new U$($.timeoutMs):M,B&&$.retryTimeouts===!1)throw Y;if(H===X)throw Y;await V(P$(H,K));continue}if(U!==void 0)clearTimeout(U);if(F.ok)return F;$.signal?.removeEventListener("abort",z);let O=await o6(F),P=new I(F.status,O,F.headers.get("x-request-id")??void 0,l6(F.headers.get("retry-after"),G()));if(H===X||!i6(F.status,P))throw P;let N=P.retryAfter??(F.status===429?k(P).retryAfter:void 0);await V(N===void 0?P$(H,K):Math.min(N,O$)),Y=P}throw Y??Error("Provider request failed with no response.")}async function o6(J){let Q;try{Q=await J.text()}catch{return null}try{return JSON.parse(Q)}catch{return Q}}var oJ=300000;function aJ(J){return{generationsUrl:`${J.base}/images/generations${J.query}`,editsUrl:`${J.base}/images/edits${J.query}`,headers:J.headers,timeoutMs:J.timeoutMs,maxRetries:J.maxRetries}}class OJ extends Error{code;retryable;retryAfter;constructor(J,Q={}){super(J.message,Q);if(this.name="ImageRequestError",this.code=J.code,this.retryable=J.retryable,J.retryAfter!==void 0)this.retryAfter=J.retryAfter}}var a6={png:"image/png",jpeg:"image/jpeg"};function s6(J){let Q=Number(J?.input_tokens??0),$=Number(J?.output_tokens??0),Z={inputTokens:Q,outputTokens:$,totalTokens:Number(J?.total_tokens??Q+$)},W=J?.input_tokens_details?.image_tokens;if(typeof W==="number")Z.imageInputTokens=W;let K=J?.output_tokens_details?.image_tokens;if(typeof K==="number")Z.imageOutputTokens=K;return Z}function t6(J){let Q=atob(J),$=new Uint8Array(Q.length);for(let Z=0;Z<Q.length;Z++)$[Z]=Q.charCodeAt(Z);return $}function r6(J){let $=J?.data?.[0]?.b64_json;if(typeof $!=="string"||$.length===0)throw new OJ({code:"provider_error",message:"The provider answered an image call with no base64 image data.",retryable:!1});let Z=typeof J.output_format==="string"?J.output_format:"png";return{bytes:t6($),mimeType:a6[Z]??`image/${Z}`,size:typeof J.size==="string"?J.size:"",...typeof J.background==="string"?{background:J.background}:{},usage:s6(J.usage)}}async function L$(J,Q,$,Z){let W;try{W=await u(J,Q,{maxRetries:$.maxRetries,timeoutMs:$.timeoutMs,retryTimeouts:!1,signal:Z.signal,fetchImpl:$.fetchImpl})}catch(K){if(Z.signal?.aborted)throw K;throw new OJ(k(K),{cause:K})}return r6(await W.json())}async function M$(J,Q,$={}){return await L$(J.generationsUrl,{method:"POST",headers:{...await J.headers(),"content-type":"application/json"},body:JSON.stringify(Q)},J,$)}async function C$(J,Q,$={}){return await L$(J.editsUrl,{method:"POST",headers:await J.headers(),body:Q},J,$)}class NJ{static models(){return[]}modelName(){return this.model}async generate(J){return await M$(this.endpoint(),this.body(J),{signal:J.signal})}async edit(J){let Q=new FormData;for(let[$,Z]of Object.entries(this.body(J)))if(Z!==void 0)Q.set($,String(Z));for(let $ of J.images)Q.append("image[]",$,$.name);if(J.mask)Q.set("mask",J.mask,J.mask.name);return await C$(this.endpoint(),Q,{signal:J.signal})}body(J){return{model:this.modelName(),prompt:J.prompt,...J.size?{size:J.size}:{},...J.quality?{quality:J.quality}:{},...J.background?{background:J.background}:{},...J.format?{output_format:J.format}:{},...J.compression!==void 0?{output_compression:J.compression}:{}}}normalizeError(J){return k(J)}}var _$=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class sJ extends NJ{model;config;constructor(J,Q={}){super();this.model=J,this.config=Q}static model(J,Q){return new sJ(J,Q)}static models(){return _$}endpoint(){return aJ(JJ(this.config,{timeoutMs:oJ}))}}class tJ extends NJ{model;config;constructor(J,Q={}){super();this.model=J,this.config=Q}static model(J,Q){return new tJ(J,Q)}static models(){return _$}modelName(){return this.config.deployment??this.model}endpoint(){return aJ(QJ(this.config,{timeoutMs:oJ}))}}var k$=3;function rJ(J){let Q=new Map;for(let $ of J)for(let Z of $.content??[]){if(Z.type!=="file"||!Z.fileId||Q.has(Z.fileId))continue;Q.set(Z.fileId,{name:Z.name,mimeType:Z.mimeType})}return Q}function R$(J,Q,$=new Map){if(!(Q instanceof I))return[];if(Q.status!==400&&Q.status!==404)return[];let Z=J8(Q.body);if(!Z)return[];let W=e6(J.input);if(W.length===0)return[];let K=/^input\[(\d+)\]\.content\[(\d+)\]\.file_id$/.exec(Z.param??"");if(K){let Y=J.input[Number(K[1])],H=JQ(Y)[Number(K[2])],D=H&&typeof H.file_id==="string"?H.file_id:void 0;if(D)return[D]}let G=Z.message??"",X=A$(W.map((Y)=>Y.fileId).filter((Y)=>Q8(G,Y)));if(X.length>0)return X;let V=/Expected (image type|context stuffing file type) to be a supported format:.*but got \.([a-z0-9]+)\.?\s*$/is.exec(G);if(V){let Y=V[1].toLowerCase()==="image type"?"input_image":"input_file",H=V[2].toLowerCase(),D=A$(W.filter((B)=>B.type===Y).map((B)=>B.fileId)),z=D.filter((B)=>($.get(B)?.name??"").trim().toLowerCase().endsWith(`.${H}`));if(z.length===1)return z;if(z.length===0&&D.length===1)return D}return[]}function T$(J,Q,$=new Map){return{...J,input:J.input.map((Z)=>{let W=JQ(Z);if(!W.some((K)=>S$(K,Q)))return Z;return{...Z,content:W.map((K)=>S$(K,Q)?{type:"input_text",text:eJ($.get(String(K.file_id))?.name)}:K)}})}}function eJ(J){return`[${J?`attachment ${JSON.stringify(J)}`:"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 S$(J,Q){return typeof J.file_id==="string"&&Q.has(J.file_id)}function JQ(J){let Q=J?.content;return Array.isArray(Q)?Q:[]}function e6(J){let Q=[];for(let $ of J)for(let Z of JQ($))if(typeof Z.file_id==="string"&&Z.file_id)Q.push({type:String(Z.type),fileId:Z.file_id});return Q}function J8(J){if(!J||typeof J!=="object")return null;let Q=J,$=Q.error&&typeof Q.error==="object"?Q.error:J;return{message:typeof $.message==="string"?$.message:void 0,param:typeof $.param==="string"?$.param:void 0}}function Q8(J,Q){let $=Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${$}($|[^A-Za-z0-9_-])`).test(J)}function A$(J){return[...new Set(J)]}async function*$8(J){let Q="",$="",Z=[],W,K=()=>{if(Z.length===0&&!$)return null;let V={event:$,data:Z.join(`
|
|
143
143
|
`),id:W};return $="",Z=[],W=void 0,V.data?V:null},G=(V)=>{let Y=V.endsWith("\r")?V.slice(0,-1):V;if(Y==="")return K();if(Y.startsWith(":"))return null;let H=Y.indexOf(":"),D=H===-1?Y:Y.slice(0,H),z=H===-1?"":Y.slice(H+1);if(z.startsWith(" "))z=z.slice(1);if(D==="event")$=z;else if(D==="data")Z.push(z);else if(D==="id")W=z;return null};for await(let V of J){Q+=V;let Y=Q.indexOf(`
|
|
144
144
|
`);while(Y!==-1){let H=Q.slice(0,Y);Q=Q.slice(Y+1);let D=G(H);if(D)yield D;Y=Q.indexOf(`
|
|
145
145
|
`)}}if(Q.length>0){let V=G(Q);if(V)yield V}let X=K();if(X)yield X}async function*j$(J,Q={}){let $=new Map,Z=new Set,W,K=!1,G,X=(V,Y)=>({type:"finish",reason:V,usage:Y,...G?{model:G}:{}});for await(let V of $8(J)){if(V.data==="[DONE]")break;let Y;try{Y=JSON.parse(V.data)}catch{continue}let H=typeof Y.type==="string"?Y.type:V.event,D=Y.response?.model;if(typeof D==="string"&&D)G=D;switch(H){case"response.output_text.delta":{let z=String(Y.delta??"");if(!z)break;yield Q.structuredOutput?{type:"output-delta",delta:z}:{type:"text-delta",delta:z};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let z=String(Y.delta??"");if(!z)break;yield{type:"reasoning-delta",delta:z,id:Y.item_id};break}case"response.output_item.added":{let z=Y.item;if(!z)break;if(z.type==="function_call"){let B=String(z.id??Y.item_id??z.call_id??"");$.set(B,{callId:String(z.call_id??B),name:String(z.name??""),namespace:typeof z.namespace==="string"&&z.namespace?z.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let z=$.get(String(Y.item_id??""));if(!z)break;let B=String(Y.delta??"");if(!B)break;yield{type:"tool-call-delta",toolCallId:z.callId,name:z.name,argsDelta:B,...z.namespace?{namespace:z.namespace}:{}};break}case"response.function_call_arguments.done":{let z=String(Y.item_id??""),B=$.get(z);if(!B)break;B.done=!0,yield{type:"tool-call",toolCallId:B.callId,name:B.name,args:String(Y.arguments??""),...B.namespace?{namespace:B.namespace}:{}};break}case"response.output_item.done":{let z=Y.item;if(!z)break;if(z.type==="function_call"){let B=String(z.id??Y.item_id??z.call_id??""),U=$.get(B);if(U?.done)break;let F=(typeof z.namespace==="string"?z.namespace:"")||U?.namespace;if(yield{type:"tool-call",toolCallId:String(z.call_id??B),name:String(z.name??U?.name??""),args:String(z.arguments??""),...F?{namespace:F}:{}},U)U.done=!0;break}if(z.type==="tool_search_call"||z.type==="tool_search_output"){if(z.type==="tool_search_call"&&z.arguments!==void 0)W=z.arguments;let B=Z8(z);if(B.loaded.length===0&&B.namespaces.length===0)break;let U=String(z.tool_search_call_id??z.id??"");if(Z.has(U))break;Z.add(U);let F=W;W=void 0,yield{type:"tool-search",...B,...F!==void 0&&F!==null?{arguments:F}:{}}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(Y.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{K=!0,yield X("stop",QQ(Y.response?.usage));break}case"response.incomplete":{K=!0;let z=QQ(Y.response?.usage),B=Y.response?.incomplete_details?.reason;if(B==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:W8(Y.response?.content_filters),retryable:!1}},yield X("error",z);break}yield X(B==="max_output_tokens"?"length":"stop",z);break}case"response.failed":case"error":{K=!0;let z=Y.response?.error??Y.error??Y;yield{type:"error",error:K8(z)},yield X("error",QQ(Y.response?.usage));break}}if(K)return}if(!K)yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield X("error",d())}function Z8(J){let Q=[],$=[];return E$(J.results??J.tools??J.loaded??J.output,Q,$,0),{loaded:$Q(Q),namespaces:$Q($)}}function E$(J,Q,$,Z){if(!Array.isArray(J)||Z>4)return;for(let W of J){if(typeof W==="string"){Q.push(W);continue}if(!W||typeof W!=="object")continue;let K=W,G=typeof K.name==="string"?K.name:typeof K.tool_name==="string"?K.tool_name:"",X=K.tools??K.functions;if(Array.isArray(X)){if(G)$.push(G);E$(X,Q,$,Z+1);continue}if(G)Q.push(G)}}function $Q(J){return J.filter((Q,$)=>J.indexOf(Q)===$)}function W8(J){if(!Array.isArray(J))return"The provider's content filter blocked this request.";let $=[];for(let Z of J){if(!Z||typeof Z!=="object")continue;let W=Z,K=W.content_filter_results;if(!K||typeof K!=="object")continue;for(let[G,X]of Object.entries(K))if(X&&typeof X==="object"&&X.filtered===!0)$.push(`${G} (${String(W.source_type??"unknown")})`)}return $.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${$Q($).join(", ")}.`}function K8(J){let Q=typeof J?.message==="string"?J.message:"The provider stream failed.",$=String(J?.code??"").toLowerCase();if($==="rate_limit_exceeded")return{code:"rate_limited",message:Q,retryable:!0};if($==="context_length_exceeded")return{code:"context_length_exceeded",message:Q,retryable:!1};if($.includes("content_filter"))return{code:"content_filtered",message:Q,retryable:!1};return{code:"provider_error",message:Q,retryable:!0}}function d(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function QQ(J){if(!J)return d();let Q=Number(J.input_tokens??0),$=Number(J.output_tokens??0),Z={inputTokens:Q,outputTokens:$,totalTokens:Number(J.total_tokens??Q+$)},W=J.output_tokens_details?.reasoning_tokens;if(typeof W==="number")Z.reasoningTokens=W;let K=J.input_tokens_details?.cached_tokens;if(typeof K==="number")Z.cachedInputTokens=K;return Z}async function*x$(J){if(!J)return;let Q=J.getReader(),$=new TextDecoder;try{while(!0){let{done:W,value:K}=await Q.read();if(W)break;if(K)yield $.decode(K,{stream:!0})}let Z=$.decode();if(Z)yield Z}finally{Q.releaseLock()}}function ZQ(J){return{responsesUrl:`${J.base}/responses${J.query}`,filesUrl:`${J.base}/files${J.query}`,headers:J.headers,timeoutMs:J.timeoutMs,maxRetries:J.maxRetries}}async function*WQ(J,Q,$){let Z,W=Q,K=new Set;for(let G=0;Z===void 0;G++)try{Z=await u(J.responsesUrl,{method:"POST",headers:{...await J.headers(),"content-type":"application/json"},body:JSON.stringify(W)},{maxRetries:J.maxRetries,timeoutMs:J.timeoutMs,signal:$.signal,fetchImpl:J.fetchImpl})}catch(X){let V=G<k$?R$(W,X,$.files).filter((H)=>!K.has(H)):[];if(V.length>0){let H=k(X).message;for(let D of V)K.add(D),yield{type:"file-rejected",fileId:D,message:H,...i(X)};W=T$(W,new Set(V),$.files);continue}let Y=k(X);if(Y.code!=="aborted")yield{type:"error",error:Y,...i(X)};yield{type:"finish",reason:Y.code==="aborted"?"aborted":"error",usage:d()};return}try{yield*j$(x$(Z.body),{structuredOutput:$.structuredOutput})}catch(G){let X=k(G);if(X.code==="aborted"){yield{type:"finish",reason:"aborted",usage:d()};return}yield{type:"error",error:X},yield{type:"finish",reason:"error",usage:d()}}}async function KQ(J,Q,$="user_data"){let Z=new FormData;Z.set("purpose",$),Z.set("file",Q);let K=await(await u(J.filesUrl,{method:"POST",headers:await J.headers(),body:Z},{maxRetries:J.maxRetries,timeoutMs:J.timeoutMs,fetchImpl:J.fetchImpl})).json();if(!K?.id)throw Error("The provider accepted the upload but returned no file id.");return K.id}function GQ(J){let Q=G8(J);if(Q.startsWith("gpt-3.5")||Q.startsWith("text-")||Q.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let $=X8(Q);if($?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:$.major>1,toolSearch:q$($)};if($?.kind==="gpt")return{reasoning:$.major>=5,structuredOutput:$.major>4||Q.startsWith("gpt-4o")||Q.startsWith("gpt-4.1"),fileInput:$.major>4||Q.startsWith("gpt-4o")||Q.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:q$($)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function q$(J){if(J.kind==="o")return J.major>=5;return J.major>5||J.major===5&&J.minor>=2}function G8(J){return J.trim().toLowerCase()}function X8(J){let Q=/^gpt-(\d+)(?:\.(\d+))?/.exec(J);if(Q?.[1])return{kind:"gpt",major:Number(Q[1]),minor:Number(Q[2]??0)};let $=/^o(\d+)(?:[-.]|$)/.exec(J);if($?.[1])return{kind:"o",major:Number($[1]),minor:0};return null}var Y8={"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 V8(J){if(typeof J!=="string")return;let Q;try{Q=JSON.parse(J)}catch{return}if(!Q||typeof Q!=="object"||typeof Q.type!=="string")return;let $=Y8[Q.type];if($)Q.type=$;if(Q.type==="response.done"&&Q.response?.usage)Q.usage=LJ(Q.response.usage);if(Q.type==="conversation.item.input_audio_transcription.completed"&&Q.usage)if(Q.usage.type==="duration"){let Z=Number(Q.usage.seconds);if(Number.isFinite(Z))Q.transcriptionSeconds=Z}else Q.transcriptionUsage=LJ(Q.usage);return Q}var I$=1,H8=500;function z8(J,Q){let $=globalThis.WebSocket;if(!$)throw Error("No global WebSocket: the realtime sideband needs Bun or Node 22+.");return new $(J,{headers:Q.headers})}class MJ{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(J){this.init=J,this.callId=J.callId,this.ready=new Promise((Q,$)=>{this.resolveReady=Q,this.rejectReady=$}),this.ready.catch(()=>{}),this.closed=new Promise((Q)=>this.resolveClosed=Q),this.open()}send(J){if(this.finished||this.closing)return;let Q=JSON.stringify(J);if(this.socket?.readyState===I$)this.socket.send(Q);else this.outbox.push(Q)}updateSession(J){this.send({type:"session.update",session:CJ(J)})}addItem(J){this.send({type:"conversation.item.create",item:J})}addNote(J){this.addItem({type:"message",role:"system",content:[{type:"input_text",text:J}]})}functionOutput(J,Q){this.addItem({type:"function_call_output",call_id:J,output:typeof Q==="string"?Q:JSON.stringify(Q)})}createResponse(J={}){let Q={};if(J.instructions!==void 0)Q.instructions=J.instructions;if(J.toolChoice!==void 0)Q.tool_choice=typeof J.toolChoice==="string"?J.toolChoice:{type:"function",name:J.toolChoice.name};if(J.outputModalities)Q.output_modalities=J.outputModalities;if(J.conversation)Q.conversation=J.conversation;if(J.metadata)Q.metadata=J.metadata;Object.assign(Q,J.vendor),this.send(Object.keys(Q).length?{type:"response.create",response:Q}:{type:"response.create"})}cancelResponse(J){this.send(J?{type:"response.cancel",response_id:J}:{type:"response.cancel"})}on(J){return this.listeners.add(J),()=>this.listeners.delete(J)}[Symbol.asyncIterator](){let J={queue:this.backlog??[],done:this.finished};return this.backlog=void 0,this.subscribers.add(J),{next:async()=>{for(;;){let $=J.queue.shift();if($)return{value:$,done:!1};if(J.done)return this.subscribers.delete(J),{value:void 0,done:!0};await new Promise((Z)=>J.wake=Z),J.wake=void 0}},return:async()=>{return J.done=!0,J.queue.length=0,this.subscribers.delete(J),{value:void 0,done:!0}}}}close(J=1000,Q="closed"){if(this.finished||this.closing)return;if(this.closing=!0,this.socket&&this.socket.readyState<=I$)this.socket.close(J,Q);else this.finish(J,Q,!0)}async hangup(){try{await this.init.hangup()}catch(J){if(this.finalEvent&&!this.finalEvent.byClient&&this.finalEvent.code===1000)return;throw J}this.close(1000,"hangup")}async open(){let J;try{let $=await this.init.headers();if(this.closing)return this.finish(1000,"closed",!0);J=(this.init.webSocket??z8)(this.init.url,{headers:$})}catch($){return this.dropped(1006,$ instanceof Error?$.message:String($),!1)}this.socket=J;let Q=!1;J.addEventListener("open",()=>{Q=!0;let $=this.everOpened;this.everOpened=!0;let Z=this.failures;this.failures=0;for(let W of this.outbox.splice(0))J.send(W);if(this.resolveReady(),$)this.emit({type:"sideband.reconnected",attempt:Z})}),J.addEventListener("message",($)=>{let Z=V8($.data);if(Z)this.emit(Z)}),J.addEventListener("close",($)=>{if(this.socket!==J)return;this.dropped($.code??1006,$.reason??"",Q)}),J.addEventListener("error",()=>{})}dropped(J,Q,$){if(this.socket=void 0,this.closing)return this.finish(J,Q,!0);let Z=this.init.reconnect?.attempts??3;if(!((J!==1000||!$)&&this.failures<Z))return this.finish(J,Q,!1);this.failures+=1;let K=(this.init.reconnect?.delayMs??500)*2**(this.failures-1);setTimeout(()=>void this.open(),K)}finish(J,Q,$){if(this.finished)return;this.finished=!0,this.outbox.length=0;let Z={type:"sideband.closed",code:J,reason:Q,byClient:$};this.finalEvent=Z,this.emit(Z);for(let W of this.subscribers)W.done=!0,W.wake?.();if(!this.everOpened)this.rejectReady(Error(`Realtime sideband did not open (${J} ${Q}).`));this.resolveClosed(Z)}emit(J){if(this.backlog){if(this.backlog.push(J),this.backlog.length>H8)this.backlog.shift()}for(let Q of this.subscribers){if(Q.done)continue;Q.queue.push(J),Q.wake?.()}for(let Q of this.listeners)try{Q(J)}catch{}}}var XQ=30000,w$=10,b$=7200,D8=600,v$="gpt-live-transcribe";function B8(J){return J.type==="transcription"}function F8(J){if(J.language!==void 0&&J.languages!==void 0)throw TypeError("A transcription session takes `languages` or `language`, not both (gpt-live-transcribe reads `languages`).");for(let W of J.keywords??[])if(/[<>\r\n]/.test(W))throw TypeError(`Transcription keywords must be one line without "<" or ">", got ${JSON.stringify(W)}.`);let Q={model:J.model??v$};if(J.prompt!==void 0)Q.prompt=J.prompt;if(J.keywords?.length)Q.keywords=J.keywords;if(J.languages?.length)Q.languages=J.languages;if(J.language!==void 0)Q.language=J.language;if(J.delay!==void 0)Q.delay=J.delay;let $={transcription:Q,turn_detection:J.turnDetection?y$(J.turnDetection):null};if(J.noiseReduction!==void 0)$.noise_reduction=J.noiseReduction&&{type:J.noiseReduction};let Z={type:"transcription",audio:{input:$}};if(J.logprobs)Z.include=["item.input_audio_transcription.logprobs"];return{...Z,...J.vendor}}function P8(J){if(!J)return{type:"object",properties:{}};return f$(J)?J.toJSONSchema():J}function CJ(J,Q){if(B8(J))return F8(J);let $={type:"realtime"},Z=J.model??Q;if(Z)$.model=Z;if(J.instructions!==void 0)$.instructions=J.instructions;if(J.outputModalities)$.output_modalities=J.outputModalities;if(J.maxOutputTokens!==void 0)$.max_output_tokens=J.maxOutputTokens;if(J.truncation!==void 0)$.truncation=J.truncation;if(J.tools)$.tools=J.tools.map((G)=>({type:"function",name:G.name,...G.description?{description:G.description}:{},parameters:P8(G.parameters)}));if(J.toolChoice!==void 0)$.tool_choice=typeof J.toolChoice==="string"?J.toolChoice:{type:"function",name:J.toolChoice.name};let W={};if(J.turnDetection!==void 0)W.turn_detection=J.turnDetection&&y$(J.turnDetection);if(J.transcription!==void 0)W.transcription=J.transcription;if(J.noiseReduction!==void 0)W.noise_reduction=J.noiseReduction&&{type:J.noiseReduction};let K={};if(J.voice!==void 0)K.voice=J.voice;if(J.speed!==void 0)K.speed=J.speed;if(Object.keys(W).length||Object.keys(K).length)$.audio={...Object.keys(W).length?{input:W}:{},...Object.keys(K).length?{output:K}:{}};return{...$,...J.vendor}}function y$(J){let Q={type:J.type};if(J.createResponse!==void 0)Q.create_response=J.createResponse;if(J.interruptResponse!==void 0)Q.interrupt_response=J.interruptResponse;if(J.type==="semantic_vad"){if(J.eagerness!==void 0)Q.eagerness=J.eagerness}else{if(J.threshold!==void 0)Q.threshold=J.threshold;if(J.prefixPaddingMs!==void 0)Q.prefix_padding_ms=J.prefixPaddingMs;if(J.silenceDurationMs!==void 0)Q.silence_duration_ms=J.silenceDurationMs;if(J.idleTimeoutMs!==void 0)Q.idle_timeout_ms=J.idleTimeoutMs}return Q}function LJ(J){let Q=Number(J?.input_tokens??0),$=Number(J?.output_tokens??0),Z={inputTokens:Q,outputTokens:$,totalTokens:Number(J?.total_tokens??Q+$)},W=J?.input_token_details??J?.input_tokens_details,K=J?.output_token_details??J?.output_tokens_details;if(typeof W?.cached_tokens==="number")Z.cachedInputTokens=W.cached_tokens;if(typeof W?.audio_tokens==="number")Z.audioInputTokens=W.audio_tokens;let G=W?.cached_tokens_details?.audio_tokens;if(typeof G==="number")Z.cachedAudioInputTokens=G;if(typeof W?.image_tokens==="number"&&W.image_tokens>0)Z.imageInputTokens=W.image_tokens;if(typeof K?.audio_tokens==="number")Z.audioOutputTokens=K.audio_tokens;return Z}class f extends Error{code;retryable;status;constructor(J,Q={}){super(J.message,{cause:Q.cause});if(this.name="RealtimeRequestError",this.code=J.code,this.retryable=J.retryable,Q.status!==void 0)this.status=Q.status}}var U8=60;class $J{model;target;options;constructor(J,Q){this.target=J,this.options=Q,this.model=Q.model}url(J){return`${this.target.base}/realtime${J}${this.target.query}`}sidebandUrl(J){let Q=this.target.base.replace(/^http(s?):/i,(Z,W)=>`ws${W}:`),$=this.target.query?`${this.target.query}&`:"?";return`${Q}/realtime${$}call_id=${encodeURIComponent(J)}`}async createCall(J){let Q=J.flow??this.options.callFlow??"unified",$,Z;if(Q==="ephemeral")$={authorization:`Bearer ${(await this.clientSecret({session:J.session,ttlSeconds:U8,signal:J.signal})).value}`,"content-type":"application/sdp"},Z=J.sdp;else{let V=new FormData;V.set("sdp",J.sdp),V.set("session",JSON.stringify(CJ(J.session??{},this.model))),$=await this.target.headers(),Z=V}if(J.safetyIdentifier)$["OpenAI-Safety-Identifier"]=J.safetyIdentifier;let W=this.url("/calls"),K=await this.request(J.webrtcFilter?`${W}${W.includes("?")?"&":"?"}webrtcfilter=on`:W,{method:"POST",headers:$,body:Z},J.signal),G=await K.text(),X=O8(K);if(!X)throw new f({code:"provider_error",message:"The provider started a realtime call but did not say which one (no Location).",retryable:!1});return{sdpAnswer:G,callId:X}}async clientSecret(J={}){let Q=J.ttlSeconds??D8;if(!Number.isInteger(Q)||Q<w$||Q>b$)throw RangeError(`ttlSeconds must be a whole number from ${w$} to ${b$}, got ${Q}.`);let $={...await this.target.headers(),"content-type":"application/json"};if(J.safetyIdentifier)$["OpenAI-Safety-Identifier"]=J.safetyIdentifier;let W=await(await this.request(this.url("/client_secrets"),{method:"POST",headers:$,body:JSON.stringify({expires_after:{anchor:"created_at",seconds:Q},session:CJ(J.session??{},this.model)})},J.signal)).json();if(typeof W?.value!=="string")throw new f({code:"provider_error",message:"The provider answered a client secret request with no secret.",retryable:!1});return{value:W.value,expiresAt:Number(W.expires_at??0),session:W.session,callsUrl:this.url("/calls")}}async hangup(J,Q={}){try{await this.request(this.url(`/calls/${encodeURIComponent(J)}/hangup`),{method:"POST",headers:await this.target.headers()},Q.signal)}catch($){if(h$($,J))return;throw $}}sideband(J,Q={}){return new MJ({...Q,callId:J,url:this.sidebandUrl(J),headers:this.target.headers,webSocket:Q.webSocket??this.options.webSocket,hangup:()=>this.hangup(J)})}async request(J,Q,$){try{return await u(J,Q,{maxRetries:this.target.maxRetries,timeoutMs:this.target.timeoutMs,retryTimeouts:!1,signal:$,fetchImpl:this.options.fetchImpl})}catch(Z){if($?.aborted)throw Z;throw new f(k(Z),{cause:Z,...Z instanceof I?{status:Z.status}:{}})}}}function h$(J,Q){if(!(J instanceof f)||J.status!==404)return!1;let $=J.cause instanceof I?J.cause.body:void 0,Z=$?.error??$,W=String(Z?.code??"").toLowerCase(),K=String(Z?.message??"").toLowerCase();if(W.includes("call"))return!0;if(K.includes(Q.toLowerCase()))return!0;return/\bcall\b/.test(K)&&/not (be )?found|does not exist|no longer|ended/.test(K)}function O8(J){let Q=J.headers.get("location");if(!Q)return;let $=Q.split("?")[0].replace(/\/+$/,""),Z=$.slice($.lastIndexOf("/")+1);return Z?decodeURIComponent(Z):void 0}function VQ(J,Q){let{capabilities:$}=Q,Z={model:Q.model,input:N8(J.messages,$,J.tools),stream:!0};if(J.systemPrompt)Z.instructions=J.systemPrompt;let W=j8(J.tools,$);if(W.length>0){if(Z.tools=W,!$.parallelToolCalls)Z.parallel_tool_calls=!1}if(J.output)Z.text={format:{type:"json_schema",name:J.output.name,schema:J.output.schema,strict:J.output.strict}};if(J.reasoning&&$.reasoning)Z.reasoning=J.reasoning==="none"?{effort:"none"}:{effort:J.reasoning,summary:"auto"};if(typeof J.temperature==="number")Z.temperature=J.temperature;if(typeof J.maxOutputTokens==="number")Z.max_output_tokens=J.maxOutputTokens;return Z}function N8(J,Q,$){let Z=[],W=new Map;if(Q.toolSearch){for(let K of $??[])if(_J(K))W.set(K.name,K)}for(let K of J){let G=K.role,X=[],V=()=>{if(X.length===0)return;Z.push({type:"message",role:G,content:X}),X=[]};for(let Y of K.content??[])switch(Y.type){case"text":{if(!Y.text)break;X.push(n(G,Y.text));break}case"output":{if(Y.partial)break;X.push(n(G,JSON.stringify(Y.value)));break}case"file":{if(G==="assistant")break;let H=C8(Y);if(!Q.fileInput){if(H)X.push(n(G,YQ(Y,!1)));break}if(Y.fileId?.startsWith(c))throw Error(`FilePart.fileId holds a gemi attachment id (${Y.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(!Y.fileId&&!H)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.");if(Y.providerRejected){if(H)X.push(n(G,YQ(Y,!1)));X.push(n(G,eJ(Y.name)));break}if(H)X.push(n(G,YQ(Y,!!Y.fileId)));if(Y.fileId)X.push(_8(Y));break}case"reasoning":{V();let H=k8(Y);if(H)Z.push(H);break}case"tool-call":{if(Y.partial)break;if(V(),Q.toolSearch&&Array.isArray(Y.toolSearches))for(let D of Y.toolSearches)Z.push(...T8(D,$??[]));let H={type:"function_call",call_id:Y.toolCallId,name:String(Y.name),arguments:JSON.stringify(Y.input??{})};if(Y.namespace&&W.has(Y.namespace))H.namespace=Y.namespace;Z.push(H);break}case"tool-result":{V(),Z.push({type:"function_call_output",call_id:Y.toolCallId,output:R8(Y)});break}}V()}return M8(Z)}var L8="No result was recorded for this tool call. Assume it did not complete.";function M8(J){let Q=new Set,$=new Set,Z=[];for(let K of J){if(K.type==="function_call"){let G=String(K.call_id);if(Q.has(G))continue;Q.add(G)}else if(K.type==="function_call_output"){let G=String(K.call_id);if(!Q.has(G)||$.has(G))continue;$.add(G)}Z.push(K)}if($.size===Q.size)return Z;let W=[];for(let K of Z){if(W.push(K),K.type!=="function_call")continue;let G=String(K.call_id);if($.has(G))continue;$.add(G),W.push({type:"function_call_output",call_id:G,output:L8})}return W}function n(J,Q){return{type:J==="assistant"?"output_text":"input_text",text:Q}}function C8(J){let Q=J.attachmentId;return typeof Q==="string"&&Q.startsWith(c)?Q:void 0}function YQ(J,Q){let $=[`id=${JSON.stringify(J.attachmentId)}`];if(J.name)$.push(`name=${JSON.stringify(J.name)}`);if(J.mimeType)$.push(`mimeType=${JSON.stringify(J.mimeType)}`);let Z=`attachment ${$.join(" ")}`;return Q?`[${Z}]`:`[${Z} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function _8(J){let Q=J.mimeType?.trim().toLowerCase()??"";return{type:(Q?Q.startsWith("image/")&&Q!=="image/svg+xml":S8(J.name))?"input_image":"input_file",file_id:J.fileId}}function S8(J){let Q=/\.([a-z0-9]+)$/.exec(J?.trim().toLowerCase()??"");return Q?.[1]!==void 0&&A8.has(Q[1])}var A8=new Set(["jpeg","jpg","png","gif","webp"]);function k8(J){if(!J.id)return null;let Q={type:"reasoning",id:J.id};return Q.summary=J.text?[{type:"summary_text",text:J.text}]:[],Q}function R8(J){if(J.status==="ok")return typeof J.output==="string"?J.output:JSON.stringify(J.output??null);if(J.status==="running"){let Q=J.job?.summary===void 0?"":` Started with: ${JSON.stringify(J.job.summary)}.`;return`Started background job ${J.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.${Q}`}if(J.status==="denied"){let Q=J.reason?` Reason given: ${J.reason}`:"";if(J.cause==="stopped")return`The run was stopped before this tool call could complete, so it did not run.${Q}`;if(J.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.${Q}`;return`The user declined this tool call, so it did not run.${Q}`}return`The tool call failed and produced no result. Error (${J.error?.code??"unknown"}): ${J.error?.message??"no message"}`}function T8(J,Q){let $=new Set(g$(J?.loaded)),Z=g$(J?.namespaces),W=new Set(Z),K=[];for(let X of Q)if(_J(X)){if(!W.has(X.name))continue;let V=X.tools.filter((Y)=>$.size===0||$.has(Y.name));if(V.length===0)continue;K.push({type:"namespace",name:X.name,description:X.description,tools:V.map((Y)=>o(Y,!0))})}else if(X.deferred&&$.has(X.name))K.push(o(X,!0));if(K.length===0)return[];return[{type:"tool_search_call",call_id:null,execution:"server",status:"completed",arguments:J.arguments&&typeof J.arguments==="object"?J.arguments:{paths:Z.length>0?Z:[...$]}},{type:"tool_search_output",call_id:null,execution:"server",status:"completed",tools:K}]}function g$(J){return Array.isArray(J)?J.filter((Q)=>typeof Q==="string"):[]}function _J(J){return Array.isArray(J.tools)}function j8(J,Q){if(!J||J.length===0)return[];if(!Q.toolSearch){let W=[];for(let K of J)if(_J(K))for(let G of K.tools)W.push(o(G,!1));else W.push(o(K,!1));return W}let $=[],Z=!1;for(let W of J)if(_J(W)){let K=W.tools.map((G)=>{if(G.deferred)Z=!0;return o(G,!0)});$.push({type:"namespace",name:W.name,description:W.description,tools:K})}else{if(W.deferred)Z=!0;$.push(o(W,!0))}if(Z)$.push({type:"tool_search"});return $}function o(J,Q){let $={type:"function",name:J.name,description:J.description,parameters:J.parameters,strict:J.strict};if(Q&&J.deferred)$.defer_loading=!0;return $}class a{static models(){return[]}normalizeError(J){return k(J)}}var u$=["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 HQ extends a{model;capabilities;config;constructor(J,Q={}){super();this.model=J,this.capabilities=GQ(J),this.config=Q}static model(J,Q){return new HQ(J,Q)}static models(){return u$}stream(J){let Q=VQ(J,{model:this.model,capabilities:this.capabilities});return WQ(this.endpoint(),Q,{signal:J.signal,structuredOutput:Boolean(J.output),files:rJ(J.messages)})}upload(J){return KQ(this.endpoint(),J)}endpoint(){return ZQ(JJ(this.config))}get realtime(){return new $J(JJ(this.config,{timeoutMs:XQ}),{model:this.model})}}class zQ extends a{model;capabilities;config;constructor(J,Q={}){super();this.model=J,this.capabilities=GQ(J),this.config=Q}static model(J,Q){return new zQ(J,Q)}static models(){return u$}stream(J){let Q=VQ(J,{model:this.deployment(),capabilities:this.capabilities});return WQ(this.endpoint(),Q,{signal:J.signal,structuredOutput:Boolean(J.output),files:rJ(J.messages)})}upload(J){return KQ(this.endpoint(),J,"assistants")}deployment(){return this.config.deployment??this.model}endpoint(){return ZQ(QJ(this.config))}get realtime(){return new $J(F$(this.config,{timeoutMs:XQ}),{model:this.deployment(),callFlow:"ephemeral"})}}class SJ{now;entries=new Map;constructor(J=Date.now){this.now=J}allow(J,Q){let $=this.entries.get(J);if($?.openUntil===void 0)return!0;let Z=this.now();if(Z<$.openUntil)return!1;if($.probeUntil!==void 0&&Z<$.probeUntil)return!1;return $.probeUntil=Z+Q.cooldownMs,!0}record(J,Q,$){let Z=this.entries.get(J)??{failures:0},W=Z.openUntil!==void 0;if(Q==="success")return this.entries.delete(J),W?"closed":void 0;if(Q==="none"){delete Z.probeUntil;return}if(Z.failures+=1,this.entries.set(J,Z),W||Z.failures>=$.failures)return Z.openUntil=this.now()+$.cooldownMs,delete Z.probeUntil,W?void 0:"open";return}state(J){let Q=this.entries.get(J);if(Q?.openUntil===void 0)return"closed";return this.now()<Q.openUntil?"open":"half-open"}}function E8(J){switch(J.type){case"text-delta":case"reasoning-delta":case"tool-call-delta":case"tool-call":case"tool-search":case"output-delta":return!0;default:return!1}}var c$=Symbol("timed-out");class ZJ extends a{model;capabilities;entries;options;circuit;constructor(J,Q={}){super();if(J.length===0)throw Error("FallbackProvider needs at least one provider.");for(let Z of J)if(Z.timeoutMs!==void 0&&!(Z.timeoutMs>0))throw Error(`FallbackProvider: timeoutMs for ${Z.provider.model} must be a positive number, got ${Z.timeoutMs}.`);this.entries=[...J];let $=Q.circuit;if($){let Z=$.failures??3,W=$.cooldownMs??30000;if(!Number.isInteger(Z)||Z<1)throw Error(`FallbackProvider: circuit.failures must be a positive integer, got ${Z}.`);if(!(W>0))throw Error(`FallbackProvider: circuit.cooldownMs must be a positive number, got ${W}.`);let K=new Set;for(let X of J){let V=DQ(X);if(K.has(V))throw Error(`FallbackProvider: two legs share the circuit key "${V}". Give one of them a \`circuitKey\`.`);K.add(V)}let G=$.store??new SJ;this.options={...Q,circuit:{...$,store:G}},this.circuit={policy:{failures:Z,cooldownMs:W},store:G,...$.onStateChange?{onStateChange:$.onStateChange}:{}}}else this.options=Q,this.circuit=void 0;this.model=J[0].provider.model,this.capabilities=x8(J.map((Z)=>Z.provider.capabilities))}static chain(J,Q){return new ZJ(J,Q)}from(J){if(!Number.isInteger(J)||J<0||J>=this.entries.length)throw RangeError(`FallbackProvider.from(${J}): the chain has ${this.entries.length} entries.`);return new ZJ(this.entries.slice(J),this.options)}leg(J){let Q=this.from(J).entries[0];return new ZJ([Q],this.options)}upload(J){return this.entries[0].provider.upload(J)}normalizeError(J){return this.entries[0].provider.normalizeError(J)}stream(J){return this.run(J)}async*run(J){let Q,$=J.signal,Z=0;for(let W=0;W<this.entries.length;W++){let K=this.entries[W],G=W===this.entries.length-1,X=K.provider.model;if(this.circuit&&!G&&!await this.allow(K))continue;Z+=1;let V=!1,Y=async(L)=>{if(V)return;V=!0,await this.record(W,K,L)},H=new AbortController,D=()=>H.abort($?.reason);if($?.aborted)H.abort($.reason);else $?.addEventListener("abort",D,{once:!0});let z=[],B=!1,U=!1,F,O,P,N=!1,M,j=!1,S=(L)=>{let R=Q?w(w(T(),Q),L.usage):L.usage;return Q=void 0,{...L,usage:R}};try{M=K.provider.stream({...J,...K.reasoning!==void 0?{reasoning:K.reasoning}:{},signal:H.signal})[Symbol.asyncIterator]();let L=!0;for(;;){let R=L&&K.timeoutMs!==void 0?await q8(M.next(),K.timeoutMs):await M.next();if(R===c$){N=!0,P={error:{code:"provider_error",message:`${X} sent nothing within ${K.timeoutMs}ms.`,retryable:!0}};break}if(L=!1,R.done){j=!0;break}let C=R.value;if(C.type==="finish"&&C.model)O=C.model;if(B){if(C.type==="finish")F=w(F??T(),C.usage),U=!0,yield S(C);else{if(C.type==="error")P={error:C.error};yield C}continue}if(E8(C)){B=!0,await Y("success"),yield*z.splice(0),yield C;continue}if(C.type==="error")P={error:C.error,...C.status!==void 0?{status:C.status}:{},...C.requestId!==void 0?{requestId:C.requestId}:{}};else if(C.type==="finish"){if(F=w(F??T(),C.usage),C.reason==="error"&&!P)P={error:{code:"provider_error",message:`${X} ended the call with an error and did not say which.`,retryable:!1}}}z.push(C)}}catch(L){let R=K.provider.normalizeError(L);if(B){if(R.code!=="aborted")yield{type:"error",error:R,...i(L)};this.report({index:W,model:X,responseModel:O,attempt:Z,usage:F,outcome:BQ(R),error:R}),yield S({type:"finish",reason:R.code==="aborted"?"aborted":"error",usage:T(),...O?{model:O}:{}});return}P={error:R,...i(L)}}finally{if($?.removeEventListener("abort",D),!j)H.abort(),M?.return?.()?.catch(()=>{})}if(B){if(!U&&Q)yield{type:"finish",reason:P?"error":"stop",usage:Q},Q=void 0;this.report({index:W,model:X,responseModel:O,attempt:Z,usage:F,outcome:P?BQ(P.error):"ok",...P?{error:P.error}:{}});return}if($?.aborted){await Y("none"),this.report({index:W,model:X,responseModel:O,attempt:Z,usage:F,outcome:"aborted"}),yield S({type:"finish",reason:"aborted",usage:F??T(),...O?{model:O}:{}});return}if(!P){await Y("success"),this.report({index:W,model:X,responseModel:O,attempt:Z,usage:F,outcome:"ok"});for(let L of z)yield L.type==="finish"?S(L):L;return}let x=!G&&P.error.code!=="aborted"&&this.shouldFallBack(P.error,{index:W,model:X,timedOut:N,...P.status!==void 0?{status:P.status}:{},...P.requestId!==void 0?{requestId:P.requestId}:{}});if(await Y(x?"failure":"none"),this.report({index:W,model:X,responseModel:O,attempt:Z,usage:F,outcome:x?"fallback":BQ(P.error),error:P.error}),x){if(F)Q=w(Q??T(),F);continue}let q=!1,b;for(let L of z){if(L.type==="finish"){b=L;continue}if(L.type==="error")q=!0;yield L}if(!q&&P.error.code!=="aborted")yield{type:"error",error:P.error,...P.status!==void 0?{status:P.status}:{},...P.requestId!==void 0?{requestId:P.requestId}:{}};yield S({type:"finish",reason:P.error.code==="aborted"?"aborted":b?.reason??"error",usage:F??T(),...O?{model:O}:{}});return}}async allow(J){if(!this.circuit)return!0;try{return await this.circuit.store.allow(DQ(J),this.circuit.policy)}catch{return!0}}async record(J,Q,$){if(!this.circuit)return;let Z=DQ(Q),W;try{W=await this.circuit.store.record(Z,$,this.circuit.policy)}catch{return}if(!W)return;try{this.circuit.onStateChange?.({index:J,model:Q.provider.model,key:Z,state:W})}catch{}}shouldFallBack(J,Q){let $=this.options.fallbackOn??((Z)=>Z.retryable);try{return $(J,Q)}catch{return!1}}report(J){if(J.usage===void 0)delete J.usage;if(J.responseModel===void 0)delete J.responseModel;try{this.options.onUsage?.(J)}catch{}}}function DQ(J){return J.circuitKey??J.provider.model}function BQ(J){return J.code==="aborted"?"aborted":"failed"}function x8(J){return{reasoning:J.every((Q)=>Q.reasoning),structuredOutput:J.every((Q)=>Q.structuredOutput),fileInput:J.every((Q)=>Q.fileInput),parallelToolCalls:J.every((Q)=>Q.parallelToolCalls),toolSearch:J.every((Q)=>Q.toolSearch)}}function q8(J,Q){let $,Z=new Promise((W)=>{$=setTimeout(()=>W(c$),Q)});return Promise.race([J,Z]).finally(()=>clearTimeout($))}async function I8(J,Q,$={}){let Z=$.samples??1;if(!Number.isInteger(Z)||Z<1)throw RangeError(`evalChain: samples must be a positive integer, got ${Z}.`);let W=[];for(let K=0;K<J.entries.length;K++){let G=J.leg(K),X={index:K,model:G.model,results:[],errors:[]};for(let V=0;V<Z;V++)try{X.results.push(await Q(G,{index:K,sample:V}))}catch(Y){X.errors.push({sample:V,error:Y})}W.push(X)}return W}class kJ extends Error{line;constructor(J){super(J??"Voice session ended by the app.");this.name="VoiceHangup",this.line=J}}var KJ="ask_agent",w8={maxDurationMs:900000,idleTimeoutMs:120000,maxQueued:3,progressIntervalMs:4000,closingLineMs:1e4,tickMs:60000,hangupGraceMs:30000,toolTimeoutMs:60000,maxToolCallsPerMinute:20,toolOutputChars:8000},b8={maxDuration:"We've reached the time limit for this voice session. Tap the microphone to start again.",idle:"It's gone quiet, so I'll hang up. Tap the microphone when you want to talk again.",error:null};function WJ(J={}){return[{name:J.name??KJ,description:J.description??"Hand one self-contained request to the agent that does the work, in the user's own words with references resolved. It can take minutes; the result comes back when it is done, so tell the user you are on it.",parameters:{type:"object",properties:{request:{type:"string",description:"What the user wants done."}},required:["request"],additionalProperties:!1}},{name:"stop_work",description:"Stop the work that is running, and drop any requests waiting behind it.",parameters:{type:"object",properties:{},additionalProperties:!1}},{name:"work_status",description:"What the agent is doing right now, and what is waiting.",parameters:{type:"object",properties:{},additionalProperties:!1}},{name:"answer_question",description:"Answer the question the agent asked (it came back from a request with status needs_input). For an approval, set approve.",parameters:{type:"object",properties:{answer:{type:"string",description:"The user's answer, in their words."},approve:{type:"boolean",description:"For an approval: whether the user approved."}},required:["answer"],additionalProperties:!1}}]}var AJ=new Map;class m{sessionId;threadId;callId;ended;params;sideband;hangupCall;limits;lines;delegateName;startedAt=Date.now();body;usage=T();transcription={usage:T(),seconds:0};hooks=Promise.resolve();pendingCreate;transcript=[];requests=[];toolCalls=[];toolHandlers=new Map;toolsRunning=0;toolCallTimes=[];errors=[];running;queue=[];pending=[];lastProgress;lastNoteAt=0;noteTimer;responseActive=!1;responseWanted=!1;ending;timers=[];idleTimer;tickTimer;resolveEnded;closingWaiter;static start(J){return new m(J)}static get(J){return AJ.get(J)}static async endAll(J){await Promise.all([...AJ.values()].map((Q)=>Q.end("hangup",J)))}constructor(J){this.params=J,this.sessionId=J.sessionId??crypto.randomUUID(),this.threadId=J.threadId,this.body=J.body??{},this.limits={...w8,...m$(J.limits)},this.lines={...b8,...m$(J.lines)},this.delegateName=J.delegate?.name??KJ;let Q=new Set(WJ(J.delegate).map(($)=>$.name));for(let $ of J.tools??[]){if(Q.has($.tool.name)||this.toolHandlers.has($.tool.name))throw Error(`VoiceBridge: two tools are named "${$.tool.name}".`);this.toolHandlers.set($.tool.name,$)}if("realtime"in J.call){let{realtime:$,callId:Z}=J.call;this.callId=Z,this.sideband=$.sideband(Z),this.hangupCall=()=>this.sideband.hangup()}else this.callId=J.call.callId??J.call.sideband.callId,this.sideband=J.call.sideband,this.hangupCall=()=>this.sideband.hangup();this.ended=new Promise(($)=>this.resolveEnded=$),AJ.set(this.sessionId,this),this.timers.push(setTimeout(()=>void this.end("max_duration",this.lines.maxDuration),this.limits.maxDurationMs)),this.tickTimer=setInterval(()=>void this.tick(),this.limits.tickMs),this.touch(),this.listen()}setBody(J){this.body=J;let Q=this.params.contextNote?.(J);if(Q)this.sideband.addNote(Q)}end(J="hangup",Q){return this.ending??=this.finish(J,Q??null)}async listen(){for await(let J of this.sideband){try{this.params.onEvent?.(J)}catch{}this.closingWaiter?.(J),await this.handle(J)}}async handle(J){switch(J.type){case"input_audio_buffer.speech_started":this.touch();return;case"response.created":this.responseActive=!0,this.pendingCreate=void 0,this.touch();return;case"response.done":{if(this.responseActive=!1,this.responseWanted&&!this.ending)this.responseWanted=!1,this.createResponse();let Q=J.usage;if(Q){this.usage=w(this.usage,Q);let $=this.info();this.hook(()=>this.params.onUsage?.(Q,$))}return}case"conversation.item.input_audio_transcription.completed":{let Q=J;if(this.say("user",String(Q.transcript??"")),Q.transcriptionUsage||Q.transcriptionSeconds!==void 0){this.transcription={usage:Q.transcriptionUsage?w(this.transcription.usage,Q.transcriptionUsage):this.transcription.usage,seconds:this.transcription.seconds+(Q.transcriptionSeconds??0)};let $=this.info(),Z={...Q.transcriptionUsage?{usage:Q.transcriptionUsage}:{},...Q.transcriptionSeconds!==void 0?{seconds:Q.transcriptionSeconds}:{}};this.hook(()=>this.params.onTranscriptionUsage?.(Z,$))}return}case"response.output_audio_transcript.done":this.say("assistant",String(J.transcript??""));return;case"response.output_text.done":this.say("assistant",String(J.text??""));return;case"response.function_call_arguments.done":{let Q=J;if(this.touch(),!this.ending)this.call(Q.call_id,Q.name,Q.arguments);return}case"session.updated":if(this.tampered(J.session))this.end("session_tampered",null);return;case"error":{let Q=J.error;if(this.errors.push({code:Q?.code,message:String(Q?.message??"")}),this.pendingCreate&&Q?.event_id===this.pendingCreate)if(this.pendingCreate=void 0,Q.code==="conversation_already_has_active_response")this.responseActive=!0,this.responseWanted=!0;else this.responseActive=!1;return}case"sideband.closed":{let Q=J;if(!this.ending&&!Q.byClient)this.end(Q.code===1000?"call_ended":"sideband_lost",null);return}}}say(J,Q){if(Q.trim())this.transcript.push({role:J,text:Q,at:Date.now()})}call(J,Q,$){let Z=f8($);if(Q===this.delegateName){let K=typeof Z.request==="string"?Z.request.trim():"";if(!K)return this.answer(J,{status:"error",message:"The request was empty."});return this.enqueue({record:{request:K,status:"queued"},turn:{text:K},callId:J})}let W=this.toolHandlers.get(Q);if(W)return void this.runTool(J,W,Z);switch(Q){case"stop_work":{let K=this.running;if(K)K.stopRequested=!0,K.handle?.stop({reason:"Stopped by voice."});let G=this.dropQueue();return this.answer(J,{stopped:Boolean(K),dropped:G})}case"work_status":return this.answer(J,{running:this.running?{request:this.running.record.request,step:this.lastProgress??"starting"}:null,queued:this.queue.map((K)=>K.record.request),...this.pending.length?{needsInput:this.questions()}:{}});case"answer_question":{if(!this.pending.length)return this.answer(J,{status:"error",message:"There is no open question."});let K=typeof Z.answer==="string"?Z.answer:"",G=typeof Z.approve==="boolean"?Z.approve:void 0,X=this.pending.map((V)=>v8(V,K,G));return this.pending=[],this.enqueue({record:{request:`(answer) ${K}`,status:"queued"},turn:{toolResults:X},callId:J})}default:return this.answer(J,{status:"error",message:`There is no tool called ${Q}.`})}}enqueue(J){if(!this.running){this.requests.push(J.record),this.run(J);return}if(this.queue.length>=this.limits.maxQueued)return this.answer(J.callId,{status:"busy",message:"Too many requests are waiting. Ask the user to wait for the current one."});this.requests.push(J.record),this.queue.push(J),this.answer(J.callId,{status:"queued",position:this.queue.length,message:"It will start when the current request is done."}),J.callId=void 0}async run(J){this.running=J,J.record.status="running",this.lastProgress=void 0,this.pauseIdle();try{let Q=new Set;await this.waitForThread(Q);let $=await this.latestBody();while(!J.stopRequested&&await this.waitForThread(Q));if(J.stopRequested||this.ending){J.record.status="dropped",this.complete(J,{status:"stopped"});return}let Z;try{Z=await this.params.controller.startTurn({threadId:this.threadId,user:this.params.user,body:$,turn:J.turn})}catch(K){J.record.status="refused",this.complete(J,{status:"refused",message:K instanceof Error?K.message:"The request could not be started."});return}J.handle=Z,J.record.runId=Z.runId,this.follow(Z);let W=await Z.result();if(J.record.status="done",J.record.finishReason=W.finishReason,W.finishReason==="awaiting-input"&&W.pending.length)this.pending=W.pending,this.complete(J,{status:"needs_input",text:W.text,questions:this.questions()});else if(W.finishReason==="error")this.complete(J,{status:"failed",message:W.error?.message??"The work failed."});else if(W.finishReason==="aborted")this.complete(J,{status:"stopped",text:W.text});else this.complete(J,{status:"done",text:W.text})}catch(Q){J.record.status="done",this.complete(J,{status:"failed",message:Q instanceof Error?Q.message:"The work failed."})}finally{this.running=void 0,this.flushNote();let Q=this.queue.shift();if(Q&&!this.ending)this.run(Q);else this.touch()}}async runTool(J,Q,$){let Z=Q.tool.name,W=Date.now();if(this.toolCallTimes=this.toolCallTimes.filter((D)=>W-D<60000),this.toolCallTimes.length>=this.limits.maxToolCallsPerMinute){let D={name:Z,status:"busy"};this.toolCalls.push(D),this.answer(J,{status:"busy",message:"Too many tool calls in the last minute. Tell the user to wait a moment."});return}this.toolCallTimes.push(W);let K={name:Z,status:"running"};this.toolCalls.push(K),this.toolsRunning+=1,this.pauseIdle();let G=new AbortController,X=Q.timeoutMs??this.limits.toolTimeoutMs,V,Y;try{let D=await Promise.race([Q.run($,{sessionId:this.sessionId,signal:G.signal}),new Promise((z,B)=>{V=setTimeout(()=>{B(new h(`"${Z}" took longer than ${Math.round(X/1000)} s.`)),G.abort()},X)})]);K.status="done",Y={status:"done",output:this.clip(D)}}catch(D){if(D instanceof kJ){K.status="refused",K.message=D.message,this.end("usage",D.line??null);return}let z=D instanceof h?D.message:"The tool failed.";if(!(D instanceof h))console.error(`[gemi/ai] the voice tool "${Z}" threw.`,D);K.status="failed",K.message=z,Y={status:"failed",message:z}}finally{clearTimeout(V),K.durationMs=Date.now()-W,this.toolsRunning-=1,this.touch()}let H=this.info();if(this.hook(()=>this.params.onToolCall?.({...K},H)),!this.ending)this.answer(J,Y)}clip(J){let Q;try{Q=JSON.stringify(J)}catch{return String(J)}if(Q===void 0||Q.length<=this.limits.toolOutputChars)return J;return`${Q.slice(0,this.limits.toolOutputChars)}\u2026 (cut: ${Q.length} characters in all)`}async waitForThread(J=new Set){let Q=this.params.liveRuns;if(!Q)return!1;let $=await Q.find({threadId:this.threadId}),Z=$&&!J.has($.runId)?Q.get($.runId):null;if(!$||!Z)return!1;return J.add($.runId),await Z.result().catch(()=>{return}),!0}async latestBody(){let J=this.params.store;if(!J)return this.body;let Q=await J.get(this.sessionId).catch(()=>null);if(Q)this.body=Q.body;return this.body}async follow(J){let Q=this.params.progress??y8();try{for await(let $ of J.run){let Z=Q($);if(Z)this.note(Z)}}catch{}}complete(J,Q){if(this.ending)return;if(J.callId)this.sideband.functionOutput(J.callId,Q),J.callId=void 0;else this.sideband.addNote(`Update on the earlier request "${J.record.request}": ${JSON.stringify(Q)}`);this.respond()}answer(J,Q){this.sideband.functionOutput(J,Q),this.respond()}respond(){if(this.ending)return;if(this.responseActive){this.responseWanted=!0;return}this.responseActive=!0,this.createResponse()}createResponse(){let J=`gemi_voice_${crypto.randomUUID()}`;this.pendingCreate=J,this.sideband.send({type:"response.create",event_id:J})}questions(){return this.pending.map((J)=>({kind:J.kind,tool:String(J.name),input:J.input}))}dropQueue(){let J=this.queue.splice(0);for(let Q of J)Q.record.status="dropped";return J.length}note(J){if(J===this.lastProgress)return;this.lastProgress=J;let Q=this.lastNoteAt+this.limits.progressIntervalMs-Date.now();if(Q<=0)return this.flushNote();this.noteTimer??=setTimeout(()=>this.flushNote(),Q)}flushNote(){if(this.noteTimer)clearTimeout(this.noteTimer);if(this.noteTimer=void 0,!this.lastProgress||this.ending||!this.running)return;this.lastNoteAt=Date.now(),this.sideband.addNote(`Progress on "${this.running.record.request}": ${this.lastProgress}`)}touch(){if(this.idleTimer)clearTimeout(this.idleTimer);if(this.idleTimer=void 0,this.running||this.toolsRunning>0||this.ending)return;this.idleTimer=setTimeout(()=>void this.end("idle",this.lines.idle),this.limits.idleTimeoutMs)}pauseIdle(){if(this.idleTimer)clearTimeout(this.idleTimer);this.idleTimer=void 0}info(){return{sessionId:this.sessionId,total:this.usage,elapsedMs:Date.now()-this.startedAt,transcription:this.transcription}}tick(){if(this.ending)return;let J=this.info();this.hook(()=>this.params.onTick?.(J))}hook(J){this.hooks=this.hooks.then(async()=>{try{await J()}catch(Q){if(Q instanceof kJ)this.end("usage",Q.line??null);else console.error("[gemi/ai] a voice hook threw; ending the call.",Q),this.end("error",this.lines.error)}})}tampered(J){let Q=this.params.session;if(!Q||!J)return!1;if(Q.instructions!==void 0&&J.instructions!==void 0&&J.instructions!==Q.instructions)return!0;if(Array.isArray(J.tools)){let $=new Set([...WJ(this.params.delegate),...Q.tools??[]].map((W)=>W.name)),Z=new Set(J.tools.map((W)=>String(W?.name)));if($.size!==Z.size||[...$].some((W)=>!Z.has(W)))return!0}return!1}async finish(J,Q){for(let G of this.timers)clearTimeout(G);if(this.idleTimer)clearTimeout(this.idleTimer);if(this.noteTimer)clearTimeout(this.noteTimer);if(this.tickTimer)clearInterval(this.tickTimer);if(this.dropQueue(),Q&&(J!=="call_ended"&&J!=="sideband_lost"))await this.closingLine(Q);if(J!=="call_ended")await this.hangUp();else this.sideband.close();await this.hooks;let Z=Date.now(),W=Z-this.startedAt,K={sessionId:this.sessionId,...this.callId?{callId:this.callId}:{},threadId:this.threadId,reason:J,startedAt:this.startedAt,endedAt:Z,durationMs:W,seconds:Math.ceil(W/1000),usage:this.usage,transcription:this.transcription,transcript:this.transcript,requests:this.requests,toolCalls:this.toolCalls,errors:this.errors};AJ.delete(this.sessionId),await this.params.store?.update(this.sessionId,{endedAt:Z,endReason:J}).catch(()=>{return});try{await this.params.onEnd?.(K)}catch(G){console.error("[gemi/ai] a voice session's onEnd threw.",G)}return this.resolveEnded(K),K}async hangUp(){try{await this.hangupCall()}catch(J){console.error("[gemi/ai] a voice call could not be hung up; waiting for the vendor.",J),this.errors.push({code:"hangup_failed",message:J instanceof Error?J.message:String(J)});let Q;await Promise.race([this.sideband.closed,new Promise(($)=>Q=setTimeout($,this.limits.hangupGraceMs))]),clearTimeout(Q),this.sideband.close()}}async closingLine(J){await new Promise((Q)=>{let $=`gemi_voice_closing_${crypto.randomUUID()}`,Z=`gemi_voice_cancel_${crypto.randomUUID()}`,W=this.responseActive?"cancelling":"asked",K,G=setTimeout(X,this.limits.closingLineMs);function X(){clearTimeout(G),Q()}let V=()=>{W="asked",this.sideband.send({type:"response.create",event_id:$,response:{instructions:`Say exactly this to the user, and nothing else: "${J}"`,tool_choice:"none"}})};if(this.closingWaiter=(Y)=>{let H=Y;if(H.type==="sideband.closed")return X();if(W==="cancelling"){if(H.type==="response.done"||H.type==="error"&&H.error?.event_id===Z)V();return}if(H.type==="error"&&H.error?.event_id===$)return X();if(H.type==="response.created"&&!K){K=H.response?.id;return}let D=(z)=>!K||!z||z===K;if(H.type==="response.done"&&D(H.response?.id))W="playing";else if(H.type==="output_audio_buffer.stopped"&&W==="playing"&&D(H.response_id))X()},W==="cancelling")this.sideband.send({type:"response.cancel",event_id:Z});else V()}),this.closingWaiter=void 0}}function m$(J){if(!J)return{};return Object.fromEntries(Object.entries(J).filter(([,Q])=>Q!==void 0))}function f8(J){try{let Q=JSON.parse(J);return Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{}}catch{return{}}}function v8(J,Q,$){let Z={toolCallId:J.toolCallId,signature:J.signature,...J.path?{path:J.path}:{}};if(J.kind==="question")return{...Z,output:Q};if(J.kind==="approval")return{...Z,approve:$===!0,...Q?{reason:Q}:{}};return{...Z,approve:!1,reason:"Not available in a voice call."}}function y8(){let J=new Set;return(Q)=>{if(Q.type==="tool-call"){if(Q.part.partial||Q.resent||J.has(Q.part.toolCallId))return;return J.add(Q.part.toolCallId),`running ${String(Q.part.name)}`}if(Q.type==="tool-progress"){let $=Q.data;if(typeof $==="string")return $;if($&&typeof $==="object")for(let Z of["message","label","title"]){let W=$[Z];if(typeof W==="string"&&W)return W}}return}}var p$="http://gemi.internal/__gemi__/voice/mcp";async function FQ(J,Q){if(!Q.user)throw Error("Voice MCP tools run as the signed-in user, and this voice session has none. Give `mcp` only to a signed-in user's session.");let{registry:$}=J,Z=J.scopes??$.scopes().map((G)=>G.name),W=(G)=>({kind:"remote",req:G,principal:{user:Q.user,via:"voice",id:`voice:${Q.sessionId}`,scopes:Z}});return(await $.available(W(l$()),J.filter)).filter((G)=>!G.requiresApproval).map((G)=>({tool:{name:G.name,description:G.description,parameters:G.inputSchema},...J.timeoutMs!==void 0?{timeoutMs:J.timeoutMs}:{},run:(X,V)=>{let Y=l$();return y.run(Y,async()=>{return await J.authorize?.({name:G.name,input:X,sessionId:V.sessionId}),$.execute(W(Y),G.name,X,void 0,{signal:V.signal})},{user:Q.user})}}))}function l$(){return new E(new Request(p$,{method:"POST"}),{},"api",new URL(p$).pathname)}class PQ{records=new Map;retainEndedMs;constructor(J={}){this.retainEndedMs=J.retainEndedMs??600000}async create(J){this.sweep(),this.records.set(J.id,structuredClone(J))}async get(J){let Q=this.records.get(J);return Q?structuredClone(Q):null}async update(J,Q){let $=this.records.get(J);if(!$)return;this.records.set(J,{...$,...structuredClone(Q),id:J})}sweep(){let J=Date.now()-this.retainEndedMs;for(let[Q,$]of this.records)if($.endedAt!==void 0&&$.endedAt<J)this.records.delete(Q)}}var UQ=new PQ;class s extends Error{runId;requested;oldest;code="frame_cursor_evicted";constructor(J,Q,$){super(`Frame ${Q} of run ${J} has been evicted; the oldest frame still buffered is ${$}. Reload the thread instead of resuming.`);this.runId=J;this.requested=Q;this.oldest=$}}class GJ extends Error{runId;code="live_run_not_found";constructor(J){super(`No live run ${J} in this process.`);this.runId=J}}class RJ{ttlMs;maxFrames;maxAgeMs;runs=new Map;byThread=new Map;byClientRun=new Map;constructor(J={}){this.ttlMs=J.ttlMs??60000,this.maxFrames=J.maxFrames??4096,this.maxAgeMs=J.maxAgeMs===void 0?3600000:J.maxAgeMs}register(J,Q={}){let $={run:J,threadId:Q.threadId,owner:Q.owner??null,clientRunId:Q.clientRunId,frames:[],lastSeq:-1,lostBefore:0,ended:!1,evicted:!1,evictAt:null,expireAt:null,wake:new Set,version:0};if(this.runs.set(J.runId,$),Q.threadId)this.byThread.set(Q.threadId,J.runId);if(Q.clientRunId)this.byClientRun.set(Q.clientRunId,J.runId);return this.scheduleExpiry($,Q.maxRunDurationMs),this.pump($,Q)}findByClientRunId(J){let Q=this.byClientRun.get(J);return Q&&this.runs.has(Q)?Q:null}async find(J){let Q=this.byThread.get(J.threadId);if(!Q)return null;let $=this.runs.get(Q);if(!$)return null;return{runId:Q,seq:$.lastSeq}}get(J){return this.runs.get(J)?.run??null}ownerOf(J){return this.runs.get(J)?.owner??null}mayAccess(J,Q){let $=this.ownerOf(J);return $===null||$===Q}isRunning(J){let Q=this.runs.get(J);return!!Q&&!Q.ended&&!Q.evicted}replay(J,Q){let $=this.runs.get(J);if(!$)throw new GJ(J);if(Q!==void 0&&Q<$.lostBefore)throw new s(J,Q,$.lostBefore);let Z=$.frames[0]?.seq;return this.drain($,J,Q??Z??$.lastSeq+1)}clear(){for(let J of this.runs.values()){if(J.evictAt)clearTimeout(J.evictAt);if(J.expireAt)clearTimeout(J.expireAt);J.ended=!0,this.notify(J)}this.runs.clear(),this.byThread.clear(),this.byClientRun.clear()}get size(){return this.runs.size}async pump(J,Q){let $=Promise.resolve();try{for await(let Z of J.run.frames()){if(J.evicted){let K=Q.onEvent;if(K)$=$.then(()=>K(Z.event)).catch((G)=>OQ(Q,G));continue}if(J.frames.push(Z),J.lastSeq=Z.seq,J.frames.length>this.maxFrames){let K=J.frames.shift();if(K)J.lostBefore=K.seq+1}this.notify(J);let W=Q.onEvent;if(W)$=$.then(()=>W(Z.event)).catch((K)=>OQ(Q,K))}}catch(Z){OQ(Q,Z)}finally{if(J.ended=!0,J.expireAt)clearTimeout(J.expireAt),J.expireAt=null;this.notify(J),this.scheduleEviction(J),await $}}async*drain(J,Q,$){let Z=$;while(!0){let W=J.version;for(;;){if(Z<J.lostBefore)throw new s(Q,Z,J.lostBefore);let K=J.frames,G=K[0]?.seq;if(G===void 0)break;let X=Math.max(0,Z-G);if(X>=K.length)break;let V=K[X];yield V,Z=V.seq+1}if(J.ended&&Z>J.lastSeq||J.evicted)return;await this.wait(J,W)}}wait(J,Q){if(J.version!==Q)return Promise.resolve();return new Promise(($)=>J.wake.add($))}notify(J){J.version++;let Q=Array.from(J.wake);J.wake.clear();for(let $ of Q)$()}scheduleEviction(J){if(J.evictAt)return;let Q=setTimeout(()=>{let $=J.run.runId;if(!J.ended)J.evicted=!0,J.frames=[];if(this.runs.get($)===J)this.runs.delete($);if(J.threadId&&this.byThread.get(J.threadId)===$)this.byThread.delete(J.threadId);if(J.clientRunId&&this.byClientRun.get(J.clientRunId)===$)this.byClientRun.delete(J.clientRunId);this.notify(J)},this.ttlMs);Q.unref?.(),J.evictAt=Q}scheduleExpiry(J,Q){if(this.maxAgeMs===null||Q===null)return;let $=Q===void 0?this.maxAgeMs:Math.max(this.maxAgeMs,Q+this.ttlMs);if(!Number.isFinite($)||$>2147483647)return;let Z=setTimeout(()=>{if(J.expireAt=null,J.ended)return;try{J.run.stop({reason:`The run was still going ${Math.round($/1000)}s after it started, past the live-run registry's age limit.`})}catch{}this.scheduleEviction(J)},$);Z.unref?.(),J.expireAt=Z}}var NQ=new RJ;function OQ(J,Q){try{J.onInternalError?.(Q)}catch{}}class TJ{maxEntries;records=new Map;constructor(J=1e5){this.maxEntries=J}async record(J,Q){if(this.records.has(J))return;this.records.set(J,{...Q});while(this.records.size>this.maxEntries){let $=this.records.keys().next().value;if($===void 0)break;this.records.delete($)}}async get(J){let Q=this.records.get(J);return Q?{...Q}:null}}var LQ=new TJ;class _Q{now;receipts=new Map;sweepAt=1024;constructor(J=Date.now){this.now=J}async claim(J,Q){let $=this.now();if(this.receipts.size>=this.sweepAt)this.sweep($);let Z=this.receipts.get(J);if(Z&&Z.expiresAt>$)return Z.result?{status:"replay",result:structuredClone(Z.result)}:{status:"blocked"};return this.receipts.set(J,{expiresAt:Q}),{status:"claimed"}}async complete(J,Q,$){this.receipts.set(J,{result:structuredClone(Q),expiresAt:$})}async release(J){let Q=this.receipts.get(J);if(Q&&!Q.result)this.receipts.delete(J)}get size(){return this.receipts.size}sweep(J){for(let[Q,$]of this.receipts)if($.expiresAt<=J)this.receipts.delete(Q);this.sweepAt=Math.max(1024,this.receipts.size*2)}}var d$="pending",MQ="done:",h8=`
|
|
@@ -152,4 +152,4 @@ return 0`;class SQ{injectedClient;prefix;constructor(J={}){this.injectedClient=J
|
|
|
152
152
|
|
|
153
153
|
`)||void 0,N=await this.context(J,{body:V}),M=await this.attachmentsFor(J,Z,{body:V}),j=this.agent.memory?await this.memoryScopes(J,{body:V}):void 0;if(H?.cancelled)return F6();let S=Z?new TQ(this.store,Z,F,(A)=>this.reportHookFailure(A)):null,x=`run_${crypto.randomUUID()}`,q={req:J,runId:x,threadId:Z},b={id:null,notified:Promise.resolve()},L=this.agent.stream({runId:x,messages:F,turn:K,threadId:Z,...S?{onMessage:(A)=>S.finish(A)}:{},onTurn:(A)=>{if(b.id!==null)return;b.id=A.id;let l=S?S.settled():Promise.resolve();b.notified=l.then(()=>this.safely(()=>this.onMessage(A,q)))},instructions:P,context:N,attachments:M,body:V,redactError:(A,l)=>this.redactError(A,l,q),nonces:this.nonces,receipts:this.receipts,subject:Y,...j?{memory:{scopes:j,...this.memoryMaxTokens!==void 0?{maxTokens:this.memoryMaxTokens}:{}}}:{},...Z?{jobs:{owner:Y}}:{},...this.contextWindow!==void 0?{contextWindow:this.contextWindow}:{},...Z&&E6(this.store)?{summaryStore:this.store}:{},...this.prepareStep!==yQ.prototype.prepareStep?{prepareStep:(A)=>this.prepareStep(A,q)}:{}}),R=this.liveRuns.register(L,{threadId:Z,owner:Y,clientRunId:X,onEvent:(A)=>this.dispatchEvent(A,q),onInternalError:(A)=>this.reportHookFailure(A),maxRunDurationMs:this.agent.maxRunDurationMs});if(D=L,S)this.follow(L,S);let{stored:C,hooks:hQ}=this.persistRun(L,q,R,S,b);if(X6.set(L,C),XJ.has(J))XJ.set(J,{run:L,hooks:hQ});return J.ctx?.()?.waitUntil(hQ),L.toResponse()};try{await this.authorizeRequest(J,{route:"stream",threadId:Z,body:V});let F=await this.foreignFile([...K?.files??[],...Z?[]:N9($.messages)],Y);if(F)return F;if(H?.cancelled)return F6();let O=await this.runLimitKey(J,{owner:Y,threadId:Z}),P=O===null?IJ:W9(this.liveRuns).take(O,Z?`thread:${Z}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!P)return IQ(429,"too_many_runs",`You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`);try{return Z?await this.withThread(Z,Y,B):await B()}finally{let N=D;if(N)N.result().then(P,P);else P()}}finally{if(H&&xJ.get(X)===H)xJ.delete(X)}}async withThread(J,Q,$){let Z=EJ.get(J)??Promise.resolve(),W,K=new Promise((X)=>{W=X}),G=Z.then(()=>K);EJ.set(J,G),await Z;try{let X=await this.liveRuns.find({threadId:J});if(X&&this.liveRuns.isRunning(X.runId)&&!this.liveRuns.mayAccess(X.runId,Q))return VJ();let V=X?this.liveRuns.get(X.runId):null;if(V)V.stop({reason:"superseded by a later turn on this thread"}),await X6.get(V);return await $()}finally{if(W(),EJ.get(J)===G)EJ.delete(J)}}async attach(J=new E){let Q=await YJ(J,qJ);if(Q.error)return t(Q);let $=Q.body,Z=typeof $.threadId==="string"?$.threadId:P9(J,"threadId");if(!Z)return _(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});await this.authorizeRequest(J,{route:"attach",threadId:Z});let W=await this.liveRuns.find({threadId:Z});if(W&&!this.liveRuns.mayAccess(W.runId,await this.runOwner(J)))return VJ();if(!W)return _(404,{code:"no_live_run",message:`No run in progress for thread ${Z} in this process.`});let K=typeof $.runId==="string"?$.runId:void 0,G=K&&K!==W.runId?void 0:F9(J,$);try{return C6(this.liveRuns.replay(W.runId,G))}catch(X){if(X instanceof s)return _(410,{code:X.code,message:X.message,oldestSeq:X.oldest});if(X instanceof GJ)return _(404,{code:X.code,message:X.message});throw X}}async stop(J=new E){let Q=await YJ(J,qJ);if(Q.error)return t(Q);let $=Q.body;await this.authorizeRequest(J,{route:"stop",threadId:typeof $.threadId==="string"?$.threadId:void 0});let Z=await this.runOwner(J),W=typeof $.runId==="string"?$.runId:void 0;if(!W&&typeof $.clientRunId==="string"){if(W=this.liveRuns.findByClientRunId($.clientRunId)??void 0,!W){let G=xJ.get($.clientRunId);if(G){if(G.owner!==null&&G.owner!==Z)return VJ();return G.cancelled=!0,{stopped:!0}}}}if(!W&&typeof $.threadId==="string")W=(await this.liveRuns.find({threadId:$.threadId}))?.runId;let K=W?this.liveRuns.get(W):null;if(!K)return{stopped:!1};if(!this.liveRuns.mayAccess(K.runId,Z))return VJ();return K.stop({reason:typeof $.reason==="string"?$.reason:void 0}),{stopped:!0}}attachmentScope(J,Q,$){let Z=J.ctx()?.user,W=Z?.id??Z?.publicId;if(W!==void 0&&W!==null&&String(W)!=="")return{key:`user:${String(W)}`};if(Q)return{key:`thread:${Q}`};return null}attachmentLimits(J){return null}checkUpload(J,Q,$){}attachmentDestination(J,Q,$){return"both"}async attachmentsFor(J,Q,$={body:{}}){let Z=await this.attachmentScope(J,Q,$);if(!Z)return null;return new vJ(this.attachments,this.attachmentStorage,Z)}async voiceStart(J=new E){let Q=this.voice;if(!Q)return jQ();let $=await YJ(J,qJ);if($.error)return t($);let{sdp:Z,threadId:W,pushToTalk:K}=$.body;if(typeof Z!=="string"||!Z.trimStart().startsWith("v="))return _(400,{code:"invalid_request",message:"`sdp` must be the browser's SDP offer."});let G=wJ($.body,L9),X=typeof W==="string"&&W!==""?W:void 0;await this.authorizeRequest(J,{route:"stream",threadId:X,body:G});let V=J.ctx?.()?.user??null,Y=await Q.start({req:J,body:G,threadId:X,user:V,pushToTalk:K===!0}),H=Date.now(),D,z=async(N)=>{if(N!==void 0)console.error("[gemi/ai] a voice session could not start.",N);if(D)await Q.realtime.hangup(D).catch((M)=>{console.error("[gemi/ai] a voice call that failed to start could not be hung up.",M)});try{await Y.onEnd?.({sessionId:"",...D?{callId:D}:{},threadId:Y.threadId??X??"",reason:"start_failed",startedAt:H,endedAt:Date.now(),durationMs:0,seconds:0,usage:T(),transcription:{usage:T(),seconds:0},transcript:[],requests:[],toolCalls:[],errors:[]})}catch(M){console.error("[gemi/ai] a voice session's onEnd threw.",M)}},B=Y.threadId??X;if(!B)return await z(void 0),_(400,{code:"invalid_request",message:"A voice session needs a thread: send `threadId`, or answer one from `voice.start`."});try{if(B!==X)await this.authorizeRequest(J,{route:"stream",threadId:B,body:G})}catch(N){throw await z(void 0),N}let U=crypto.randomUUID(),F=Y.tools??[];try{if(Y.mcp)F=[...F,...await FQ(Y.mcp,{user:V,sessionId:U})]}catch(N){return await z(N),_(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}let O={...Y.session,tools:[...WJ(Q.delegate),...Y.session?.tools??[],...F.map((N)=>N.tool)],...K===!0?{turnDetection:null}:{}},P;try{P=await Q.realtime.createCall({sdp:Z,session:O,safetyIdentifier:Y.safetyIdentifier})}catch(N){await z(N);let M=N instanceof f&&N.code==="rate_limited";return _(M?429:502,{code:"voice_unavailable",message:"Voice isn't available right now."})}D=P.callId;try{await this.voiceStore.create({id:U,callId:P.callId,threadId:B,owner:await this.runOwner(J),body:G,startedAt:H});let{threadId:N,session:M,safetyIdentifier:j,mcp:S,tools:x,...q}=Y;return{sessionId:m.start({...q,tools:F,controller:this.constructor,threadId:B,user:V,body:G,call:{realtime:Q.realtime,callId:P.callId},sessionId:U,store:this.voiceStore,liveRuns:this.liveRuns,delegate:Q.delegate,session:O}).sessionId,sdp:P.sdpAnswer,threadId:B,delegate:Q.delegate?.name??KJ,endsAt:H+(Y.limits?.maxDurationMs??900000)}}catch(N){return await z(N),_(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}}async voiceUpdate(J=new E){if(!this.voice)return jQ();let Q=await this.voiceSession(J);if(Q instanceof Response)return Q;let $=await YJ(J,qJ);if($.error)return t($);let Z=wJ($.body,[]);if(await this.authorizeRequest(J,{route:"stream",threadId:Q.threadId,body:Z}),Q.endedAt!==void 0)return _(409,{code:"voice_ended",message:"This voice session has ended."});return await this.voiceStore.update(Q.id,{body:Z}),m.get(Q.id)?.setBody(Z),{updated:!0}}async voiceEnd(J=new E){let Q=this.voice;if(!Q)return jQ();let $=await this.voiceSession(J);if($ instanceof Response)return $;if(await this.authorizeRequest(J,{route:"stream",threadId:$.threadId,body:$.body}),$.endedAt!==void 0)return{ended:!1};let Z=m.get($.id);if(Z)await Z.end("hangup");else await Q.realtime.hangup($.callId),await this.voiceStore.update($.id,{endedAt:Date.now(),endReason:"hangup"});return{ended:!0}}async voiceSession(J){let Q=J.params?.sessionId,$=typeof Q==="string"&&Q?await this.voiceStore.get(Q):null;if(!$)return _(404,{code:"voice_not_found",message:"No such voice session."});if($.owner!==null&&$.owner!==await this.runOwner(J))return VJ();return $}async upload(J=new E){let Q=await J.rawRequest.formData(),$=Q.get("file");if(!($ instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let Z=$ instanceof File&&$.name?$.name:"upload",W=$.type||"application/octet-stream",K=G9(Q.get("body")),G=Q.get("threadId");await this.authorizeRequest(J,{route:"upload",threadId:typeof G==="string"&&G.length>0?G:void 0,body:K});let X=Y9(await this.attachmentLimits(J),$,Z,W);if(X)throw new qQ(X.code,X.message);let V=typeof G==="string"&&G.length>0&&await this.store.loadThread(G)!==null?G:void 0,Y=await this.runOwner(J),H=(S)=>this.fileOwners.record(S,{owner:Y,name:Z,mimeType:W,size:$.size,createdAt:new Date().toISOString()}),D={body:K,threadId:V},z=await this.checkUpload({name:Z,size:$.size,mimeType:W},J,D);if(z)throw new qQ(z.code||"upload_refused",z.message);let B=await this.attachmentDestination($,J,D),U=M9(B,Q.get("destination")),F=await this.attachmentScope(J,V,{body:K}),O=U!=="provider"&&!F;if(O){if(U==="storage")throw Error('This upload was routed to storage, but `attachmentScope()` returned null for the request, so there is no subject to file the attachment under. Guard the route (`this.agent(Chat).middleware({ upload: "auth" })`), send a `threadId` with the upload, or override `attachmentScope()`.');C9()}if(U==="provider"||!F){let S=await H6(this.agent.provider,$);await H(S);let x={fileId:S,name:Z,mimeType:W,size:$.size,destination:"provider"};if(O)x.downgraded="no_scope";return x}let P=R6(),N=await this.attachmentStorage.put({name:T6(P,Z),body:$,contentType:W}),M=U==="both"?await H6(this.agent.provider,$):void 0;if(M)await H(M);let j={id:P,scopeKey:F.key,fileId:M,objectName:N,name:Z,mimeType:W,size:$.size,createdAt:new Date().toISOString(),destination:U};return await this.attachments.put(F,j),{fileId:M,attachmentId:P,name:Z,mimeType:W,size:$.size,destination:U}}async foreignFile(J,Q){let $=new Set(J.map((Z)=>Z.fileId).filter((Z)=>typeof Z==="string"));for(let Z of $){let W=await this.fileOwners.get(Z);if(W?W.owner!==null&&W.owner!==Q:this.requireKnownFiles)return O9()}return null}onMessage(J,Q){}onToolCall(J,Q){}onAwaitingInput(J,Q){}redactError(J,Q,$){return fQ(J,Q)}onError(J,Q){}onStreamComplete(J,Q){}reportHookFailure(J){console.error("[gemi/ai] agent controller hook failed",J)}async dispatchEvent(J,Q){switch(J.type){case"tool-call":if(!J.part.partial&&!J.resent)await this.onToolCall({toolCallId:J.part.toolCallId,name:String(J.part.name),input:J.part.input},Q);return;case"awaiting-input":await this.onAwaitingInput(J.pending,Q);return;case"error":await this.onError(S6(J.error),Q);return;default:return}}async readThread(J){let Q=await this.store.loadThread(J);return Q?(await this.settleThread(J,Q,{write:!1})).messages:null}isRunLive(J,Q){return this.liveRuns.get(J)!==null}async settleThread(J,Q,{write:$}){let Z=(V)=>this.isRunLive(V,J),W=await Q6(Q,Z),K=W.messages,G=[],X=new Map(W.settled.map((V)=>[V.id,V]));if(k9(K)||$)try{let V=await K6(K,{threadId:J,store:v.store,isRunLive:Z,outputSchemaFor:(Y)=>this.toolOutputSchema(Y),scan:this.jobsBlockMax()});K=V.messages,G=V.jobs;for(let Y of V.settled)X.set(Y.id,Y);if($&&V.orphans.length>0){await G6(v.store,V.orphans,(H)=>this.reportHookFailure(H));let Y=new Set(V.orphans.map((H)=>H.id));G=G.map((H)=>Y.has(H.id)?{...H,orphaned:!0}:H)}}catch(V){this.reportHookFailure(V)}if($&&X.size>0)try{await this.store.appendMessages(J,[...X.values()])}catch(V){this.reportHookFailure(V)}return{messages:K,jobs:G}}jobsBlockMax(){let J=this.agent.jobs?.contextBlock;if(J===!1)return 0;return J?.max??HJ}jobsBlock(J){return cQ(J,this.jobsBlockMax())}toolOutputSchema(J){let Q=($)=>{for(let Z of $){let W=Z;if(Array.isArray(W.tools)){let K=Q(W.tools);if(K)return K}else if(W.name===J)return W.outputSchema}return};return Q(this.agent.tools??[])}follow(J,Q){(async()=>{try{for await(let $ of J.frames())Q.frame($)}catch($){this.reportHookFailure($)}})()}persistRun(J,Q,$,Z=null,W={id:null,notified:Promise.resolve()}){let K=Promise.resolve(),G=(async()=>{let V;try{V=await J.result()}catch(H){Z?.close(),await Z?.settled(),K=W.notified.then(()=>this.safely(()=>this.onError({code:"unknown",message:H instanceof Error?H.message:String(H),retryable:!1},Q)));return}let Y=V.messages;if(Z?.close(Y),await Z?.settled(),Q.threadId&&Y.length>0)try{await this.store.appendMessages(Q.threadId,Y)}catch(H){this.reportHookFailure(H)}K=this.notifyRun(V,Y,Q,W)})(),X=G.then(()=>S9(Promise.all([K,$]).then(()=>{}),this.hookHoldMs));return{stored:G,hooks:X}}async notifyRun(J,Q,$,Z){await Z.notified;for(let W of Q){if(W.id===Z.id)continue;await this.safely(()=>this.onMessage(W,$))}await this.safely(()=>this.onStreamComplete(J,$))}async safely(J){try{await J()}catch(Q){this.reportHookFailure(Q)}}}var EQ=["turn","clientRunId","threadId","messages","regenerate"],K9=["text","files","toolResults"];function wJ(J,Q=I6(J)?EQ:[...EQ,...K9]){let $={};for(let[Z,W]of Object.entries(J)){if(Q.includes(Z))continue;Object.defineProperty($,Z,{value:W,writable:!0,enumerable:!0,configurable:!0})}return $}function G9(J){if(J===null)return{};let Q;if(typeof J==="string")try{Q=JSON.parse(J)}catch{throw new xQ("The upload's `body` field is not valid JSON.")}if(Q===null||typeof Q!=="object"||Array.isArray(Q))throw new xQ("The upload's `body` field must be a JSON object.");return wJ(Q,EQ)}class xQ extends bJ{constructor(J){super(J);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:J}}},view:{}}}}async function H6(J,Q){try{return await J.upload(Q)}catch($){if($ instanceof I&&X9.has($.status))throw new q6(k($).message);throw $}}var X9=new Set([400,413,415,422]);class qQ extends bJ{constructor(J,Q){super(Q);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:J,message:Q}}},view:{}}}}function Y9(J,Q,$,Z){if(!J)return null;let{maxBytes:W,accept:K}=J;if(typeof W==="number"&&Q.size>W)return{code:"file_too_large",message:`${JSON.stringify($)} is ${z6(Q.size)}; the limit is ${z6(W)}.`};if(K&&K.length>0&&!K.some((G)=>V9(G,$,Z)))return{code:"unsupported_file_type",message:`${JSON.stringify($)} is not a type this chat accepts. Accepted: ${K.join(", ")}.`};return null}function V9(J,Q,$){let Z=J.trim().toLowerCase();if(!Z)return!1;if(Z.startsWith("."))return Q.toLowerCase().endsWith(Z);let W=$.toLowerCase().split(";")[0].trim();if(Z.endsWith("/*"))return W.startsWith(Z.slice(0,-1));return W===Z}function z6(J){if(J<1024)return`${J} B`;let Q=["KB","MB","GB"],$=J/1024,Z=0;while($>=1024&&Z<Q.length-1)$/=1024,Z++;return`${Math.round($*10)/10} ${Q[Z]}`}class q6 extends bJ{constructor(J){super(J);this.name="RejectedUploadError";let Q=/(unsupported|invalid) (extension|file type|format|mime)|supported (extensions|formats?)/i.test(J)?"unsupported_file_type":"file_rejected";this.payload={api:{status:422,data:{error:{code:Q,message:J}}},view:{}}}}async function YJ(J,Q){let $=J?.rawRequest;if(!$||$.method==="GET"||$.method==="HEAD"||!$.body)return{body:{}};if(!H9($.headers.get("Content-Type")))return{body:{},status:415,code:"unsupported_media_type",error:"The request body must be sent as application/json."};let Z=Number($.headers.get("Content-Length"));if(Number.isFinite(Z)&&Z>Q)return D6(Q);let W;try{let G=await z9($,Q);if(G===null)return D6(Q);W=G}catch{return{body:{},error:"The request body could not be read."}}if(!W.trim())return{body:{}};let K;try{K=JSON.parse(W)}catch{return{body:{},error:"The request body is not valid JSON."}}if(K===null||typeof K!=="object"||Array.isArray(K))return{body:{},error:"The request body must be a JSON object."};return{body:K}}function H9(J){return L6(J)==="application/json"}async function z9(J,Q){if(!Number.isFinite(Q)||!J.body)return await J.text();let $=J.body.getReader(),Z=[],W=0;for(;;){let{done:X,value:V}=await $.read();if(X)break;if(W+=V.byteLength,W>Q)return await $.cancel().catch(IJ),null;Z.push(V)}let K=new Uint8Array(W),G=0;for(let X of Z)K.set(X,G),G+=X.byteLength;return new TextDecoder().decode(K)}function D6(J){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${J} bytes).`}}function IQ(J,Q,$){return _(J,{...fJ(N6(J),$,J),code:Q})}function t(J){if(J.status===413)return IQ(413,J.code??"body_too_large",J.error??"");return _(J.status??400,{code:J.code??"invalid_request",message:J.error})}function I6(J){return Boolean(J.turn)&&typeof J.turn==="object"}function D9(J){let Q=I6(J)?J.turn:J,$={};if(typeof Q.text==="string")$.text=Q.text;if(Array.isArray(Q.files)){let Z=B9(Q.files);if(typeof Z==="string")return{error:Z};$.files=Z}if(Array.isArray(Q.toolResults))$.toolResults=Q.toolResults;if(Object.keys($).length===0)return{};if(Q===J.turn&&Q.localId!==void 0&&Q.localId!==null&&Q.localId!==""){let{localId:Z}=Q;if(typeof Z!=="string")return{error:"turn.localId must be a string."};if(Z.length>B6)return{error:`turn.localId is longer than ${B6} characters.`};$.localId=Z}return{turn:$}}var B6=200;function B9(J){let Q=[];for(let[$,Z]of J.entries()){let W=`turn.files[${$}]`;if(!Z||typeof Z!=="object"||Array.isArray(Z))return`${W} must be an object.`;let K={};for(let H of["fileId","attachmentId","name","mimeType"]){let D=Z[H];if(D===void 0||D===null||D==="")continue;if(typeof D!=="string")return`${W}.${H} must be a string.`;K[H]=D}let{fileId:G,attachmentId:X,name:V,mimeType:Y}=K;if(G?.startsWith(c))return`${W}.fileId holds a gemi attachment id (${G}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(X!==void 0&&!X.startsWith(c))return`${W}.attachmentId is not a gemi attachment id: it must start with "${c}".`;if(!G&&!X)return`${W} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;Q.push({...G?{fileId:G}:{},...X?{attachmentId:X}:{},...V!==void 0?{name:V}:{},...Y!==void 0?{mimeType:Y}:{}})}return Q}function F9(J,Q){if(typeof Q.from==="number"&&Number.isFinite(Q.from))return Math.max(0,Math.floor(Q.from));if(typeof Q.cursor==="number"&&Number.isFinite(Q.cursor)){let Z=Math.floor(Q.cursor);if(Z>=0)return Z+1;return}let $=J?.rawRequest?.headers?.get("Last-Event-ID");if($){let Z=Number.parseInt($,10);if(Number.isFinite(Z))return Math.max(0,Z+1)}return}function P9(J,Q){let $=J?.search?.get(Q);return typeof $==="string"?$:void 0}function U9(J){let Q=vQ(J);for(let $=J.length-1;$>=0;$--){let Z=J[$];if(Z.role!=="user"||Q.has(Z.id))continue;let W="",K=[];for(let G of Z.content){if(G.type==="text")W+=G.text;if(G.type==="file")K.push({...G.fileId?{fileId:G.fileId}:{},...G.attachmentId?{attachmentId:G.attachmentId}:{},...G.name?{name:G.name}:{},...G.mimeType?{mimeType:G.mimeType}:{}})}if(!W&&K.length===0)continue;return{index:$,turn:{...W?{text:W}:{},...K.length>0?{files:K}:{}}}}return null}function F6(){return _(409,{code:"stopped",message:"The turn was stopped before it started."})}function VJ(){return _(403,fJ("permission","This run belongs to someone else.",403))}function O9(){return _(403,fJ("permission","A file in this turn was uploaded by someone else.",403))}function N9(J){if(!Array.isArray(J))return[];let Q=[];for(let $ of J){let Z=$?.content;if(!Array.isArray(Z))continue;for(let W of Z)if(W&&typeof W==="object"&&typeof W.fileId==="string")Q.push({fileId:W.fileId})}return Q}var L9=["sdp","threadId","pushToTalk"];function jQ(){return _(404,{code:"voice_not_enabled",message:"This agent has no voice: set `voice` on its controller."})}function _(J,Q){return new Response(JSON.stringify({error:Q}),{status:J,headers:{"Content-Type":"application/json"}})}function M9(J,Q){if(typeof Q!=="string"||Q.length===0)return J;if(Q!=="both"&&Q!=="provider"&&Q!=="storage")throw Error(`Unknown attachment destination "${Q}". Expected "both", "provider" or "storage".`);if(Q===J||J==="both"&&Q==="storage")return Q;if(J==="both"&&Q==="provider")throw Error('This upload asked for the "provider" destination under a "both" policy. A client may ask for "storage", which keeps a file away from the model provider, but it may not ask the server to stop keeping its own copy while the vendor still gets the file \u2014 that is the app\'s retention decision. Change `attachmentDestination()` if this file should not be kept.');throw Error(`This upload asked for the "${Q}" destination, but the server's policy for it is "${J}", and a client hint may only ask for "storage" under a "both" policy. Change \`attachmentDestination()\` if the file really should go there.`)}var P6=!1;function C9(){if(P6)return;P6=!0,console.warn("[gemi/ai] An upload had no attachment scope, so its bytes were sent to the model provider only and no attachment id was minted \u2014 a tool cannot forward this file. Guard the route with auth, send a `threadId` with the upload, or override `attachmentScope()`.")}var _9=2147483647;function S9(J,Q){let $=J.then(()=>{},()=>{});if(!(Q<=_9))return $;let Z,W=new Promise((K)=>{Z=setTimeout(K,Q)});return Promise.race([$,W]).finally(()=>clearTimeout(Z))}var U6=!1;function A9(J){if(U6||Bun.env.NODE_ENV!=="production")return;if(!(J instanceof wQ))return;U6=!0,console.warn("[gemi/ai] A stateless agent chat is spending approval nonces in process memory. With more than one instance a replayed approval is accepted once per instance. Set `nonces = new RedisNonceStore()` (or your own NonceStore) on the AgentController.")}function k9(J){return J.some((Q)=>Q.content.some(($)=>$.type==="tool-result"&&$.status==="running"))}export{b9 as windowMessages,WJ as voiceTools,E9 as turnStarts,LJ as toRealtimeUsage,y6 as toAgentTools,j9 as supportsStrict,x9 as splitTurns,c9 as settleSummaries,T9 as s,fQ as redactError,q9 as messageSize,FQ as mcpVoiceTools,NQ as liveRuns,AQ as keepSummary,h$ as isCallNotFound,vQ as injectedMessageIds,o9 as generate,I8 as evalChain,UQ as defaultVoiceStore,u9 as defaultSummaryStore,bQ as defaultNonceStore,LQ as defaultFileOwners,yJ as defaultAttachmentStore,kQ as defaultAgentStore,kJ as VoiceHangup,m as VoiceBridge,iJ as ToolNamespace,h as ToolError,p9 as Skill,vJ as ScopedAttachments,l9 as SKILLS_NAMESPACE,SQ as RedisReceiptStore,_6 as RedisNonceStore,MJ as RealtimeSideband,f as RealtimeRequestError,$J as RealtimeClient,m9 as PendingEscalation,HQ as OpenAIProvider,sJ as OpenAIImageProvider,PQ as MemoryVoiceSessionStore,g9 as MemorySummaryStore,_Q as MemoryReceiptStore,wQ as MemoryNonceStore,RJ as MemoryLiveRuns,TJ as MemoryFileOwners,SJ as MemoryCircuitStore,j6 as MemoryAttachmentStore,jJ as MemoryAgentStore,dQ as MemoryAgentJobStore,Y$ as MEMORY_NAMESPACE,GJ as LiveRunNotFoundError,nQ as JobsRequireThreadError,iQ as JobHandle,R9 as JSONSchemaError,k6 as InvalidAttachmentScopeError,$$ as InMemoryAgentMemoryStore,OJ as ImageRequestError,NJ as ImageProvider,nJ as ImageModel,s as FrameCursorEvictedError,ZJ as FallbackProvider,G$ as FakeAgentMemoryStore,lJ as DatabaseAgentMemoryStore,mJ as DatabaseAgentJobStore,v$ as DEFAULT_TRANSCRIPTION_MODEL,Q$ as DEFAULT_MEMORY_MAX_TOKENS,X$ as DEFAULT_MEMORY_LIMITS,f9 as DEFAULT_MAX_SUMMARY_TOKENS,d9 as DEFAULT_MAX_RUN_DURATION_MS,oQ as DEFAULT_JOB_DEADLINE_MS,HJ as DEFAULT_JOBS_CONTEXT_MAX,KJ as DEFAULT_DELEGATE_NAME,I9 as DEFAULT_CONTEXT_WINDOW_STEP,w9 as DEFAULT_CONTEXT_WINDOW_NOTE,v9 as DEFAULT_COMPACT_TRIGGER_TOKENS,y9 as DEFAULT_COMPACT_INSTRUCTIONS,h9 as COMPACT_SUMMARY_HEADER,zQ as AzureOpenAIProvider,tJ as AzureOpenAIImageProvider,A6 as AttachmentNotFoundError,hJ as AgentTurnError,UJ as AgentTool,i9 as AgentRunError,a as AgentProvider,Z$ as AgentMemoryRefusedError,W$ as AgentMemoryConflictError,K$ as AgentMemories,v as AgentJobs,gJ as AgentJobDeadlineSweep,aQ as AgentJob,yQ as AgentController,n9 as Agent};
|
|
154
154
|
|
|
155
|
-
//# debugId=
|
|
155
|
+
//# debugId=4F8192EF64AFAF0064756E2164756E21
|