gemi 0.196.0 → 0.196.2

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.
@@ -28,10 +28,13 @@ import type { AgentError, Usage } from "./types";
28
28
  export type FallbackEntry = {
29
29
  provider: AgentProvider;
30
30
  /**
31
- * How long this leg has to produce its FIRST event, in milliseconds. Past
32
- * that it is abandoned (its request aborted) and the next leg is tried. Once
33
- * any event has arrived, this deadline is off and the leg's own request
34
- * timeout applies — a slow answer that has started is not a dead one.
31
+ * How long this leg has to produce its first CONTENT event (text,
32
+ * reasoning, a tool call, structured output), in milliseconds, counted from
33
+ * the leg's start. Past that it is abandoned (its request aborted) and the
34
+ * next leg is tried. A `retry` event does not stop or restart it: a leg
35
+ * whose provider is retrying a 429 has not answered yet. Once content has
36
+ * arrived, this deadline is off and the leg's own request timeout applies —
37
+ * a slow answer that has started is not a dead one.
35
38
  *
36
39
  * Omitted: no deadline of the chain's own.
37
40
  */
@@ -1 +1 @@
1
- {"version":3,"file":"FallbackProvider.d.ts","sourceRoot":"","sources":["../../ai/FallbackProvider.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAC/C,OAAO,EACL,aAAa,EACb,KAAK,oBAAoB,EAEzB,KAAK,cAAc,EACnB,KAAK,oBAAoB,EAC1B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAGL,KAAK,YAAY,EACjB,KAAK,YAAY,EAElB,MAAM,gBAAgB,CAAC;AAGxB,OAAO,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAEjD;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,0BAA0B;AAC1B,MAAM,MAAM,aAAa,GAAG;IAC1B,QAAQ,EAAE,aAAa,CAAC;IACxB;;;;;;;OAOG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;;OAKG;IACH,SAAS,CAAC,EAAE,eAAe,CAAC;IAC5B;;;;OAIG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB,CAAC;AAEF,8DAA8D;AAC9D,MAAM,MAAM,eAAe,GAAG;IAC5B,qFAAqF;IACrF,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,kEAAkE;IAClE,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,iEAAiE;IACjE,QAAQ,EAAE,OAAO,CAAC;CACnB,CAAC;AAEF,2EAA2E;AAC3E,MAAM,MAAM,aAAa,GAAG;IAC1B,mDAAmD;IACnD,KAAK,EAAE,MAAM,CAAC;IACd,kCAAkC;IAClC,KAAK,EAAE,MAAM,CAAC;IACd;;;;OAIG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;6EACyE;IACzE,OAAO,EAAE,MAAM,CAAC;IAChB;;;;OAIG;IACH,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,6EAA6E;IAC7E,OAAO,EAAE,IAAI,GAAG,UAAU,GAAG,QAAQ,GAAG,SAAS,CAAC;IAClD,KAAK,CAAC,EAAE,UAAU,CAAC;CACpB,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG;IAC5B;;;;;;;;OAQG;IACH,UAAU,CAAC,EAAE,CAAC,KAAK,EAAE,UAAU,EAAE,OAAO,EAAE,eAAe,KAAK,OAAO,CAAC;IACtE;8CAC0C;IAC1C,OAAO,CAAC,EAAE,CAAC,MAAM,EAAE,aAAa,KAAK,IAAI,CAAC;IAC1C;;;OAGG;IACH,OAAO,CAAC,EAAE,eAAe,CAAC;CAC3B,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,eAAe,GAAG;IAC5B,8DAA8D;IAC9D,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,+EAA+E;IAC/E,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;OAIG;IACH,KAAK,CAAC,EAAE,YAAY,CAAC;IACrB,2EAA2E;IAC3E,aAAa,CAAC,EAAE,CAAC,MAAM,EAAE,qBAAqB,KAAK,IAAI,CAAC;CACzD,CAAC;AAEF,MAAM,MAAM,qBAAqB,GAAG;IAClC,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,YAAY,CAAC;CACrB,CAAC;AAIF,qBAAa,gBAAiB,SAAQ,aAAa;IACjD,uEAAuE;IACvE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB;;;;;OAKG;IACH,QAAQ,CAAC,YAAY,EAAE,oBAAoB,CAAC;IAC5C,QAAQ,CAAC,OAAO,EAAE,SAAS,aAAa,EAAE,CAAC;IAC3C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAkB;IAC1C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAMV;gBAEF,OAAO,EAAE,SAAS,aAAa,EAAE,EAAE,OAAO,GAAE,eAAoB;IAwD5E,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,SAAS,aAAa,EAAE,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,gBAAgB;IAI5F;;;;OAIG;IACH,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,gBAAgB;IASrC,4FAA4F;IAC5F,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,gBAAgB;IAKpC;;;;;;;OAOG;IACH,MAAM,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC;IAInC,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,UAAU;IAI1C,MAAM,CAAC,MAAM,EAAE,oBAAoB,GAAG,cAAc;YAIrC,GAAG;YA0QJ,KAAK;YAUL,MAAM;IAiBpB,OAAO,CAAC,cAAc;IAStB,OAAO,CAAC,MAAM;CASf;AA8BD,MAAM,MAAM,eAAe,CAAC,CAAC,IAAI;IAC/B,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,qDAAqD;IACrD,OAAO,EAAE,CAAC,EAAE,CAAC;IACb,sEAAsE;IACtE,MAAM,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,OAAO,CAAA;KAAE,EAAE,CAAC;CAC9C,CAAC;AAEF;;;;;;;;;GASG;AACH,wBAAsB,SAAS,CAAC,CAAC,EAC/B,KAAK,EAAE,gBAAgB,EACvB,OAAO,EAAE,CAAC,QAAQ,EAAE,aAAa,EAAE,OAAO,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,KAAK,OAAO,CAAC,CAAC,CAAC,EAC5F,OAAO,GAAE;IAAE,OAAO,CAAC,EAAE,MAAM,CAAA;CAAO,GACjC,OAAO,CAAC,eAAe,CAAC,CAAC,CAAC,EAAE,CAAC,CAmB/B"}
1
+ {"version":3,"file":"FallbackProvider.d.ts","sourceRoot":"","sources":["../../ai/FallbackProvider.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAC/C,OAAO,EACL,aAAa,EACb,KAAK,oBAAoB,EAEzB,KAAK,cAAc,EACnB,KAAK,oBAAoB,EAC1B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAGL,KAAK,YAAY,EACjB,KAAK,YAAY,EAElB,MAAM,gBAAgB,CAAC;AAGxB,OAAO,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAEjD;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,0BAA0B;AAC1B,MAAM,MAAM,aAAa,GAAG;IAC1B,QAAQ,EAAE,aAAa,CAAC;IACxB;;;;;;;;;;OAUG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;;OAKG;IACH,SAAS,CAAC,EAAE,eAAe,CAAC;IAC5B;;;;OAIG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB,CAAC;AAEF,8DAA8D;AAC9D,MAAM,MAAM,eAAe,GAAG;IAC5B,qFAAqF;IACrF,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,kEAAkE;IAClE,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,iEAAiE;IACjE,QAAQ,EAAE,OAAO,CAAC;CACnB,CAAC;AAEF,2EAA2E;AAC3E,MAAM,MAAM,aAAa,GAAG;IAC1B,mDAAmD;IACnD,KAAK,EAAE,MAAM,CAAC;IACd,kCAAkC;IAClC,KAAK,EAAE,MAAM,CAAC;IACd;;;;OAIG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;6EACyE;IACzE,OAAO,EAAE,MAAM,CAAC;IAChB;;;;OAIG;IACH,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,6EAA6E;IAC7E,OAAO,EAAE,IAAI,GAAG,UAAU,GAAG,QAAQ,GAAG,SAAS,CAAC;IAClD,KAAK,CAAC,EAAE,UAAU,CAAC;CACpB,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG;IAC5B;;;;;;;;OAQG;IACH,UAAU,CAAC,EAAE,CAAC,KAAK,EAAE,UAAU,EAAE,OAAO,EAAE,eAAe,KAAK,OAAO,CAAC;IACtE;8CAC0C;IAC1C,OAAO,CAAC,EAAE,CAAC,MAAM,EAAE,aAAa,KAAK,IAAI,CAAC;IAC1C;;;OAGG;IACH,OAAO,CAAC,EAAE,eAAe,CAAC;CAC3B,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,eAAe,GAAG;IAC5B,8DAA8D;IAC9D,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,+EAA+E;IAC/E,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;OAIG;IACH,KAAK,CAAC,EAAE,YAAY,CAAC;IACrB,2EAA2E;IAC3E,aAAa,CAAC,EAAE,CAAC,MAAM,EAAE,qBAAqB,KAAK,IAAI,CAAC;CACzD,CAAC;AAEF,MAAM,MAAM,qBAAqB,GAAG;IAClC,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,YAAY,CAAC;CACrB,CAAC;AAIF,qBAAa,gBAAiB,SAAQ,aAAa;IACjD,uEAAuE;IACvE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB;;;;;OAKG;IACH,QAAQ,CAAC,YAAY,EAAE,oBAAoB,CAAC;IAC5C,QAAQ,CAAC,OAAO,EAAE,SAAS,aAAa,EAAE,CAAC;IAC3C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAkB;IAC1C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAMV;gBAEF,OAAO,EAAE,SAAS,aAAa,EAAE,EAAE,OAAO,GAAE,eAAoB;IAwD5E,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,SAAS,aAAa,EAAE,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,gBAAgB;IAI5F;;;;OAIG;IACH,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,gBAAgB;IASrC,4FAA4F;IAC5F,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,gBAAgB;IAKpC;;;;;;;OAOG;IACH,MAAM,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC;IAInC,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,UAAU;IAI1C,MAAM,CAAC,MAAM,EAAE,oBAAoB,GAAG,cAAc;YAIrC,GAAG;YA6QJ,KAAK;YAUL,MAAM;IAiBpB,OAAO,CAAC,cAAc;IAStB,OAAO,CAAC,MAAM;CASf;AA8BD,MAAM,MAAM,eAAe,CAAC,CAAC,IAAI;IAC/B,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,qDAAqD;IACrD,OAAO,EAAE,CAAC,EAAE,CAAC;IACb,sEAAsE;IACtE,MAAM,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,OAAO,CAAA;KAAE,EAAE,CAAC;CAC9C,CAAC;AAEF;;;;;;;;;GASG;AACH,wBAAsB,SAAS,CAAC,CAAC,EAC/B,KAAK,EAAE,gBAAgB,EACvB,OAAO,EAAE,CAAC,QAAQ,EAAE,aAAa,EAAE,OAAO,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,KAAK,OAAO,CAAC,CAAC,CAAC,EAC5F,OAAO,GAAE;IAAE,OAAO,CAAC,EAAE,MAAM,CAAA;CAAO,GACjC,OAAO,CAAC,eAAe,CAAC,CAAC,CAAC,EAAE,CAAC,CAmB/B"}
package/dist/ai/index.js CHANGED
@@ -143,7 +143,7 @@ import{$c as _6,Ac as T8,Cc as x8,Dc as y8,Ec as q8,Fc as b8,Gc as f8,Hc as v8,I
143
143
  `)}function Q9(J){return J.reduce(($,Q)=>$+Q,0)/J.length}function e8(J){return Math.min(1,Math.max(0,J))}function Z9(J){return J instanceof Error?J.message:String(J)}function VJ(J,$,Q){if(J===void 0||Number.isInteger(J)&&J>=1)return;throw Error(`${$} sets \`${Q}\` to ${String(J)}, but it has to be a whole number of at least 1.`)}var NZ=/^[A-Za-z0-9_-]{1,64}$/;function BZ(J,$){let Q=LZ($)?$:{filter:$},Z=Q.deferred===!0,W=J.descriptors(Q.filter);if(!Q.namespaces)return W.map((H)=>B$(J,H,Z));let K=Object.entries(Q.namespaces),X=new Set(J.descriptors().flatMap((H)=>H.tags));for(let[H,D]of K){if(!NZ.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(!X.has(H))throw Error(`toAgentTools: no tool is tagged "${H}", so its namespace would be empty.`)}let Y=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(B$(J,H,Z));else Y.get(D).push(B$(J,H,!1))}let G=[];for(let[H,D]of K){let z=Y.get(H);if(z.length===0)continue;G.push(L$.create({name:H,description:D.description,tools:z,deferred:D.deferred??Z}))}return[...G,...V]}function LZ(J){return typeof J==="object"&&J!==null&&(("filter"in J)||("namespaces"in J)||("deferred"in J))}function B$(J,$,Q){if($.kind==="tool")return CZ(J,$,Q);return wJ.create({name:$.name,description:$.description,inputSchema:$.inputSchema,...$.outputSchema?{outputSchema:$.outputSchema}:{},requiresApproval:$.requiresApproval,deferred:Q,execute:(Z,W)=>{let K=p.getStore()?.req;if(!K)throw new l(`"${$.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},$.name,Z,W)}})}function CZ(J,$,Q){let Z=J.nativeTool($.name);return wJ.create({name:$.name,description:$.description,inputSchema:$.inputSchema,...$.outputSchema?{outputSchema:$.outputSchema}:{},requiresApproval:J.nativeApproval($.name),deferred:Q,...Z.timeoutMs!==void 0?{timeoutMs:Z.timeoutMs}:{},...Z.async?{async:Z.async}:{},execute:(W,K)=>{let X=p.getStore()?.req;return J.startNative(X?{kind:"local",req:X}:void 0,$.name,W,K)}})}function OZ(J){if(J==="auto")return;let $=/^(\d+)x(\d+)$/.exec(J);if(!$)throw Error(`An image size is "WIDTHxHEIGHT" or "auto"; got ${JSON.stringify(J)}.`);let Q=Number($[1]),Z=Number($[2]);if(Q%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(Q/Z,Z/Q)>3)throw Error(`Image size ${J} is not supported: the maximum aspect ratio is 3:1, either way up.`)}function W9(J,$){if(J.size!==void 0)try{OZ(J.size)}catch(Q){throw Error(`${$}: ${Q.message}`)}if(J.background==="transparent"&&J.format==="jpeg")throw Error(`${$}: a transparent background needs "png"; JPEG has no alpha channel.`);if(J.compression!==void 0){let Q=J.compression;if(!Number.isInteger(Q)||Q<0||Q>100)throw Error(`${$}: compression is an integer from 0 to 100; got ${Q}.`)}}function K9(J,$){if(J instanceof File)return J;let Q=J.type||"image/png",Z=Q==="image/jpeg"?"jpg":Q.split("/")[1]??"png";return new File([J],`${$}.${Z}`,{type:Q})}class C${name;provider;settings;constructor(J){let{name:$,provider:Q,...Z}=J;W9(Z,`ImageModel "${$}"`),this.name=$,this.provider=Q,this.settings=Z}static create(J){return new C$(J)}async generate(J){let $=this.merge(J);return this.present(await this.provider.generate({prompt:J.prompt,...$,signal:J.signal}))}async edit(J){let $=this.merge(J);return this.present(await this.provider.edit({prompt:J.prompt,...$,images:J.images.map((Q,Z)=>K9(Q,`image-${Z}`)),...J.mask?{mask:K9(J.mask,"mask")}:{},signal:J.signal}))}present(J){return X9(this.provider.model,J.usage),_Z(J)}merge(J){let $={...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 W9($,`ImageModel "${this.name}"`),$}}function _Z(J){return{image:new Blob([J.bytes],{type:J.mimeType}),mimeType:J.mimeType,size:J.size,usage:J.usage}}function d(J){return typeof process>"u"?void 0:process.env?.[J]}var MZ="preview";function G9(J){let $=J.trim().replace(/\/+$/,"");if(!$)return"";return`${$.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function SZ(J){return/^\d{4}-\d{2}-\d{2}/.test(J)?"":"/v1"}function zJ(J,$={}){return{base:(J.baseURL??d("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let Z=J.apiKey??d("OPENAI_API_KEY");return{...Z?{authorization:`Bearer ${Z}`}:{},...J.headers}},timeoutMs:J.timeoutMs??$.timeoutMs??120000,streamIdleTimeoutMs:J.streamIdleTimeoutMs??120000,streamMaxDurationMs:J.streamMaxDurationMs??300000,maxToolArgumentChars:J.maxToolArgumentChars??0,maxRetries:J.maxRetries??2}}function Y9(J){let $=J.baseURL??J.endpoint??d("AZURE_OPENAI_ENDPOINT");if($)return G9($);let Q=J.resourceName??d("AZURE_OPENAI_RESOURCE_NAME")??d("AZURE_RESOURCE_NAME");return Q?G9(`https://${Q.trim()}.cognitiveservices.azure.com`):""}function DJ(J,$={}){let Q=J.apiVersion??d("AZURE_OPENAI_API_VERSION")??MZ;return{base:`${Y9(J)}${SZ(Q)}`,query:`?api-version=${encodeURIComponent(Q)}`,headers:async()=>{if(J.getToken)return{authorization:`Bearer ${await J.getToken()}`,...J.headers};let Z=J.apiKey??d("AZURE_OPENAI_API_KEY");return{...Z?{"api-key":Z}:{},...J.headers}},timeoutMs:J.timeoutMs??$.timeoutMs??120000,streamIdleTimeoutMs:J.streamIdleTimeoutMs??120000,streamMaxDurationMs:J.streamMaxDurationMs??300000,maxToolArgumentChars:J.maxToolArgumentChars??0,maxRetries:J.maxRetries??2}}function V9(J,$={}){return{...DJ(J,$),base:`${Y9(J)}/v1`,query:""}}var AZ=500,H9=20000;function RZ(J,$){if(!J)return;let Q=J.trim();if(/^\d+(\.\d+)?$/.test(Q))return Math.max(0,Number(Q)*1000);let Z=Date.parse(Q);if(Number.isNaN(Z))return;return Math.max(0,Z-$)}function qJ(J,$){let Q=Math.min(H9,AZ*2**J);return Math.round(Q*(0.5+$()*0.5))}function EZ(J){return J===429||J===408||J===409||J>=500}function jZ(J,$){return EZ(J)&&T($).retryable}function z9(J){return J.reason??new DOMException("The operation was aborted.","AbortError")}function D9(J,$){return new Promise((Q,Z)=>{let W=setTimeout(Q,J);$?.addEventListener("abort",()=>{clearTimeout(W),Z(z9($))},{once:!0})})}async function O$(J,$,Q=D9){if(!$)return await Q(J);$.throwIfAborted();let Z;try{await Promise.race([Q(J,$),new Promise((W,K)=>{Z=()=>K(z9($)),$.addEventListener("abort",Z,{once:!0})})])}finally{if(Z)$.removeEventListener("abort",Z)}}async function i(J,$,Q){let Z=Q.fetchImpl??((D,z)=>fetch(D,z)),W=Q.sleep??D9,K=Q.random??Math.random,X=Q.now??Date.now,Y=Math.max(0,Q.maxRetries),V=Q.startedAt??X(),G=(D,z,F,B)=>{try{Q.onRetry?.({attempt:z+1,maxRetries:Y,error:T(F),...v(F),timedOut:B,delayMs:D,elapsedMs:X()-V})}catch{}return O$(D,Q.signal,W)},H;for(let D=0;D<=Y;D++){Q.signal?.throwIfAborted();let z=new AbortController,F=()=>z.abort(Q.signal?.reason);Q.signal?.addEventListener("abort",F,{once:!0});let B=!1,N=Q.timeoutMs>0?setTimeout(()=>{B=!0,z.abort()},Q.timeoutMs):void 0,P;try{P=await Z(J,{...$,signal:z.signal})}catch(R){if(N!==void 0)clearTimeout(N);if(Q.signal?.removeEventListener("abort",F),Q.signal?.aborted)throw R;if(H=B?new bJ(Q.timeoutMs):R,B&&Q.retryTimeouts===!1)throw H;if(D===Y)throw H;await G(qJ(D,K),D,H,B);continue}if(N!==void 0)clearTimeout(N);if(P.ok)return P;Q.signal?.removeEventListener("abort",F);let U=await kZ(P),L=new y(P.status,U,P.headers.get("x-request-id")??void 0,RZ(P.headers.get("retry-after"),X()));if(D===Y||!jZ(P.status,L))throw L;let _=L.retryAfter??(P.status===429?T(L).retryAfter:void 0);await G(_===void 0?qJ(D,K):Math.min(_,H9),D,L,!1),H=L}throw H??Error("Provider request failed with no response.")}async function kZ(J){let $;try{$=await J.text()}catch{return null}try{return JSON.parse($)}catch{return $}}function F9(J,$,Q){let Z=$.idleMs>0?$.idleMs:0,W=$.maxMs>0?$.maxMs:0;if(!J||!Z&&!W)return J;let K=W?performance.now()+W:1/0,X=J.getReader();return new ReadableStream({async pull(Y){let V,G,H=Math.max(0,K-performance.now()),D=!Z||H<=Z,z=D?H:Z,F=new Promise((B,N)=>{V=setTimeout(()=>{G=D?Q.max():Q.idle(),N(G)},z)});try{let B=await Promise.race([X.read(),F]);if(B.done)Y.close();else Y.enqueue(B.value)}catch(B){let N=G??B;Y.error(N),X.cancel(N).catch(()=>{})}finally{clearTimeout(V)}},cancel(Y){return X.cancel(Y)}},{highWaterMark:0})}var _$=300000;function M$(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 fJ extends Error{code;retryable;retryAfter;constructor(J,$={}){super(J.message,$);if(this.name="ImageRequestError",this.code=J.code,this.retryable=J.retryable,J.retryAfter!==void 0)this.retryAfter=J.retryAfter}}var TZ={png:"image/png",jpeg:"image/jpeg"};function xZ(J){let $=Number(J?.input_tokens??0),Q=Number(J?.output_tokens??0),Z={inputTokens:$,outputTokens:Q,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 IZ(J){let $=atob(J),Q=new Uint8Array($.length);for(let Z=0;Z<$.length;Z++)Q[Z]=$.charCodeAt(Z);return Q}function wZ(J){let Q=J?.data?.[0]?.b64_json;if(typeof Q!=="string"||Q.length===0)throw new fJ({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:IZ(Q),mimeType:TZ[Z]??`image/${Z}`,size:typeof J.size==="string"?J.size:"",...typeof J.background==="string"?{background:J.background}:{},usage:xZ(J.usage)}}async function P9(J,$,Q,Z){let W;try{W=await i(J,$,{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,retryTimeouts:!1,signal:Z.signal,fetchImpl:Q.fetchImpl})}catch(K){if(Z.signal?.aborted)throw K;throw new fJ(T(K),{cause:K})}return wZ(await W.json())}async function U9(J,$,Q={}){return await P9(J.generationsUrl,{method:"POST",headers:{...await J.headers(),"content-type":"application/json"},body:JSON.stringify($)},J,Q)}async function N9(J,$,Q={}){return await P9(J.editsUrl,{method:"POST",headers:await J.headers(),body:$},J,Q)}class yJ{static models(){return[]}modelName(){return this.model}async generate(J){return await U9(this.endpoint(),this.body(J),{signal:J.signal})}async edit(J){let $=new FormData;for(let[Q,Z]of Object.entries(this.body(J)))if(Z!==void 0)$.set(Q,String(Z));for(let Q of J.images)$.append("image[]",Q,Q.name);if(J.mask)$.set("mask",J.mask,J.mask.name);return await N9(this.endpoint(),$,{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 T(J)}}var B9=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class S$ extends yJ{model;config;constructor(J,$={}){super();this.model=J,this.config=$}static model(J,$){return new S$(J,$)}static models(){return B9}endpoint(){return M$(zJ(this.config,{timeoutMs:_$}))}}class A$ extends yJ{model;config;constructor(J,$={}){super();this.model=J,this.config=$}static model(J,$){return new A$(J,$)}static models(){return B9}modelName(){return this.config.deployment??this.model}endpoint(){return M$(DJ(this.config,{timeoutMs:_$}))}}var O9=3;function R$(J){let $=new Map;for(let Q of J)for(let Z of Q.content??[]){if(Z.type!=="file"||!Z.fileId||$.has(Z.fileId))continue;$.set(Z.fileId,{name:Z.name,mimeType:Z.mimeType})}return $}function _9(J,$,Q=new Map){if(!($ instanceof y))return[];if($.status!==400&&$.status!==404)return[];let Z=bZ($.body);if(!Z)return[];let W=qZ(J.input);if(W.length===0)return[];let K=/^input\[(\d+)\]\.content\[(\d+)\]\.file_id$/.exec(Z.param??"");if(K){let G=J.input[Number(K[1])],H=j$(G)[Number(K[2])],D=H&&typeof H.file_id==="string"?H.file_id:void 0;if(D)return[D]}let X=Z.message??"",Y=C9(W.map((G)=>G.fileId).filter((G)=>fZ(X,G)));if(Y.length>0)return Y;let V=/Expected (image type|context stuffing file type) to be a supported format:.*but got \.([a-z0-9]+)\.?\s*$/is.exec(X);if(V){let G=V[1].toLowerCase()==="image type"?"input_image":"input_file",H=V[2].toLowerCase(),D=C9(W.filter((F)=>F.type===G).map((F)=>F.fileId)),z=D.filter((F)=>(Q.get(F)?.name??"").trim().toLowerCase().endsWith(`.${H}`));if(z.length===1)return z;if(z.length===0&&D.length===1)return D}return[]}function M9(J,$,Q=new Map){return{...J,input:J.input.map((Z)=>{let W=j$(Z);if(!W.some((K)=>L9(K,$)))return Z;return{...Z,content:W.map((K)=>L9(K,$)?{type:"input_text",text:E$(Q.get(String(K.file_id))?.name)}:K)}})}}function E$(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 L9(J,$){return typeof J.file_id==="string"&&$.has(J.file_id)}function j$(J){let $=J?.content;return Array.isArray($)?$:[]}function qZ(J){let $=[];for(let Q of J)for(let Z of j$(Q))if(typeof Z.file_id==="string"&&Z.file_id)$.push({type:String(Z.type),fileId:Z.file_id});return $}function bZ(J){if(!J||typeof J!=="object")return null;let $=J,Q=$.error&&typeof $.error==="object"?$.error:J;return{message:typeof Q.message==="string"?Q.message:void 0,param:typeof Q.param==="string"?Q.param:void 0}}function fZ(J,$){let Q=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${Q}($|[^A-Za-z0-9_-])`).test(J)}function C9(J){return[...new Set(J)]}async function*yZ(J){let $="",Q="",Z=[],W,K=()=>{if(Z.length===0&&!Q)return null;let V={event:Q,data:Z.join(`
144
144
  `),id:W};return Q="",Z=[],W=void 0,V.data?V:null},X=(V)=>{let G=V.endsWith("\r")?V.slice(0,-1):V;if(G==="")return K();if(G.startsWith(":"))return null;let H=G.indexOf(":"),D=H===-1?G:G.slice(0,H),z=H===-1?"":G.slice(H+1);if(z.startsWith(" "))z=z.slice(1);if(D==="event")Q=z;else if(D==="data")Z.push(z);else if(D==="id")W=z;return null};for await(let V of J){$+=V;let G=$.indexOf(`
145
145
  `);while(G!==-1){let H=$.slice(0,G);$=$.slice(G+1);let D=X(H);if(D)yield D;G=$.indexOf(`
146
- `)}}if($.length>0){let V=X($);if(V)yield V}let Y=K();if(Y)yield Y}async function*S9(J,$={}){let Q=new Map,Z=new Set,W,K=!1,X,Y=(V,G)=>({type:"finish",reason:V,usage:G,...X?{model:X}:{}});for await(let V of yZ(J)){if(V.data==="[DONE]")break;let G;try{G=JSON.parse(V.data)}catch{continue}let H=typeof G.type==="string"?G.type:V.event,D=G.response?.model;if(typeof D==="string"&&D)X=D;switch(H){case"response.output_text.delta":{let z=String(G.delta??"");if(!z)break;yield $.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(G.delta??"");if(!z)break;yield{type:"reasoning-delta",delta:z,id:G.item_id};break}case"response.output_item.added":{let z=G.item;if(!z)break;if(z.type==="function_call"){let F=String(z.id??G.item_id??z.call_id??"");Q.set(F,{callId:String(z.call_id??F),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=Q.get(String(G.item_id??""));if(!z)break;let F=String(G.delta??"");if(!F)break;yield{type:"tool-call-delta",toolCallId:z.callId,name:z.name,argsDelta:F,...z.namespace?{namespace:z.namespace}:{}};break}case"response.function_call_arguments.done":{let z=String(G.item_id??""),F=Q.get(z);if(!F)break;F.done=!0,yield{type:"tool-call",toolCallId:F.callId,name:F.name,args:String(G.arguments??""),...F.namespace?{namespace:F.namespace}:{}};break}case"response.output_item.done":{let z=G.item;if(!z)break;if(z.type==="function_call"){let F=String(z.id??G.item_id??z.call_id??""),B=Q.get(F);if(B?.done)break;let N=(typeof z.namespace==="string"?z.namespace:"")||B?.namespace;if(yield{type:"tool-call",toolCallId:String(z.call_id??F),name:String(z.name??B?.name??""),args:String(z.arguments??""),...N?{namespace:N}:{}},B)B.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 F=vZ(z);if(F.loaded.length===0&&F.namespaces.length===0)break;let B=String(z.tool_search_call_id??z.id??"");if(Z.has(B))break;Z.add(B);let N=W;W=void 0,yield{type:"tool-search",...F,...N!==void 0&&N!==null?{arguments:N}:{}}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(G.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{K=!0,yield Y("stop",k$(G.response?.usage));break}case"response.incomplete":{K=!0;let z=k$(G.response?.usage),F=G.response?.incomplete_details?.reason;if(F==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:hZ(G.response?.content_filters),retryable:!1}},yield Y("error",z);break}yield Y(F==="max_output_tokens"?"length":"stop",z);break}case"response.failed":case"error":{K=!0;let z=G.response?.error??G.error??G;yield{type:"error",error:gZ(z)},yield Y("error",k$(G.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 Y("error",h())}function vZ(J){let $=[],Q=[];return A9(J.results??J.tools??J.loaded??J.output,$,Q,0),{loaded:T$($),namespaces:T$(Q)}}function A9(J,$,Q,Z){if(!Array.isArray(J)||Z>4)return;for(let W of J){if(typeof W==="string"){$.push(W);continue}if(!W||typeof W!=="object")continue;let K=W,X=typeof K.name==="string"?K.name:typeof K.tool_name==="string"?K.tool_name:"",Y=K.tools??K.functions;if(Array.isArray(Y)){if(X)Q.push(X);A9(Y,$,Q,Z+1);continue}if(X)$.push(X)}}function T$(J){return J.filter(($,Q)=>J.indexOf($)===Q)}function hZ(J){if(!Array.isArray(J))return"The provider's content filter blocked this request.";let Q=[];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[X,Y]of Object.entries(K))if(Y&&typeof Y==="object"&&Y.filtered===!0)Q.push(`${X} (${String(W.source_type??"unknown")})`)}return Q.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${T$(Q).join(", ")}.`}function gZ(J){let $=typeof J?.message==="string"?J.message:"The provider stream failed.",Q=String(J?.code??"").toLowerCase();if(Q==="rate_limit_exceeded")return{code:"rate_limited",message:$,retryable:!0};if(Q==="context_length_exceeded")return{code:"context_length_exceeded",message:$,retryable:!1};if(Q.includes("content_filter"))return{code:"content_filtered",message:$,retryable:!1};return{code:"provider_error",message:$,retryable:!0}}function h(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function k$(J){if(!J)return h();let $=Number(J.input_tokens??0),Q=Number(J.output_tokens??0),Z={inputTokens:$,outputTokens:Q,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*R9(J){if(!J)return;let $=J.getReader(),Q=new TextDecoder;try{while(!0){let{done:W,value:K}=await $.read();if(W)break;if(K)yield Q.decode(K,{stream:!0})}let Z=Q.decode();if(Z)yield Z}finally{$.releaseLock()}}function x$(J){return{responsesUrl:`${J.base}/responses${J.query}`,filesUrl:`${J.base}/files${J.query}`,headers:J.headers,timeoutMs:J.timeoutMs,streamIdleTimeoutMs:J.streamIdleTimeoutMs,streamMaxDurationMs:J.streamMaxDurationMs,maxToolArgumentChars:J.maxToolArgumentChars,maxRetries:J.maxRetries}}async function*I$(J,$,Q){let Z=$,W=new Set,K=0,X=Math.max(0,J.maxRetries),Y=J.random??Math.random,V,G=(P)=>{if(!V)return P;let U=k(k(h(),V),P.usage);return V=void 0,{...P,usage:U}},H=()=>G({type:"finish",reason:"aborted",usage:h()}),D=J.streamIdleTimeoutMs??0,z=J.streamMaxDurationMs??0,F=J.maxToolArgumentChars??0,B=J.now??Date.now,N=B();for(let P=0;;P++){let U=new AbortController,L=Q.signal?AbortSignal.any([Q.signal,U.signal]):U.signal,_;while(_===void 0)try{let O=[],C=()=>{},M=i(J.responsesUrl,{method:"POST",headers:{...await J.headers(),"content-type":"application/json"},body:JSON.stringify(Z)},{maxRetries:J.maxRetries,timeoutMs:J.timeoutMs,signal:L,fetchImpl:J.fetchImpl,sleep:J.sleep,random:J.random,now:J.now,startedAt:N,onRetry:(I)=>{O.push({type:"retry",...I,phase:"request"}),C()}}),w=M.then(()=>!0,()=>!0);for(;;){let I=new Promise(($$)=>C=()=>$$(!1)),J$=await Promise.race([w,I]);if(yield*O.splice(0),J$)break}_=await M}catch(O){let C=K<O9?_9(Z,O,Q.files).filter((w)=>!W.has(w)):[];if(C.length>0){K++;let w=T(O).message;for(let I of C)W.add(I),yield{type:"file-rejected",fileId:I,message:w,...v(O)};Z=M9(Z,new Set(C),Q.files);continue}let M=T(O);if(M.code==="aborted"){yield H();return}yield{type:"error",error:M,...v(O)},yield G({type:"finish",reason:"error",usage:h()});return}let R=[],A=!1,x,f=!1,q=new Map;try{let O=F9(_.body,{idleMs:D,maxMs:z},{idle:()=>{let C=new E9(D);return U.abort(C),C},max:()=>{let C=new j9(z);return U.abort(C),C}});for await(let C of S9(R9(O),{structuredOutput:Q.structuredOutput})){if(C.type==="tool-call-delta"){let M=(q.get(C.toolCallId)??0)+C.argsDelta.length;if(q.set(C.toolCallId,M),F>0&&M>F){let w=new k9(F,C.name);throw U.abort(w),w}yield C;continue}if(C.type==="tool-call")q.delete(C.toolCallId);if(A){yield C.type==="finish"?G(C):C;continue}if(vJ(C)){A=!0,yield*R.splice(0),yield C;continue}if(C.type==="error")x=C.error;R.push(C)}}catch(O){f=O instanceof bJ;let C=T(O);if(C.code==="aborted"||Q.signal?.aborted){yield H();return}if(A){yield{type:"error",error:C},yield G({type:"finish",reason:"error",usage:h()});return}x=C,R.push({type:"error",error:C},{type:"finish",reason:"error",usage:h()})}if(A)return;if(x?.retryable&&P<X&&!Q.signal?.aborted){let O={};for(let M of R){if(M.type==="finish")V=k(V??h(),M.usage);if(M.type==="error")O=v(M)}if(q.size>0)yield{type:"tool-call-discard",toolCallIds:[...q.keys()]};let C=qJ(P,Y);yield{type:"retry",attempt:P+1,maxRetries:X,error:x,...O,phase:"stream",timedOut:f,delayMs:C,elapsedMs:B()-N};try{await O$(C,Q.signal,J.sleep)}catch{yield H();return}continue}for(let O of R)yield O.type==="finish"?G(O):O;return}}async function w$(J,$,Q="user_data"){let Z=new FormData;Z.set("purpose",Q),Z.set("file",$);let K=await(await i(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 q$(J){let $=uZ(J);if($.startsWith("gpt-3.5")||$.startsWith("text-")||$.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let Q=cZ($);if(Q?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:Q.major>1,toolSearch:T9(Q)};if(Q?.kind==="gpt")return{reasoning:Q.major>=5,structuredOutput:Q.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),fileInput:Q.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:T9(Q)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function T9(J){if(J.kind==="o")return J.major>=5;return J.major>5||J.major===5&&J.minor>=2}function uZ(J){return J.trim().toLowerCase()}function cZ(J){let $=/^gpt-(\d+)(?:\.(\d+))?/.exec(J);if($?.[1])return{kind:"gpt",major:Number($[1]),minor:Number($[2]??0)};let Q=/^o(\d+)(?:[-.]|$)/.exec(J);if(Q?.[1])return{kind:"o",major:Number(Q[1]),minor:0};return null}var mZ={"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 pZ(J){if(typeof J!=="string")return;let $;try{$=JSON.parse(J)}catch{return}if(!$||typeof $!=="object"||typeof $.type!=="string")return;let Q=mZ[$.type];if(Q)$.type=Q;if($.type==="response.done"&&$.response?.usage)$.usage=hJ($.response.usage);if($.type==="conversation.item.input_audio_transcription.completed"&&$.usage)if($.usage.type==="duration"){let Z=Number($.usage.seconds);if(Number.isFinite(Z))$.transcriptionSeconds=Z}else $.transcriptionUsage=hJ($.usage);return $}var x9=1,lZ=500;function dZ(J,$){let Q=globalThis.WebSocket;if(!Q)throw Error("No global WebSocket: the realtime sideband needs Bun or Node 22+.");return new Q(J,{headers:$.headers})}class gJ{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=$,this.rejectReady=Q}),this.ready.catch(()=>{}),this.closed=new Promise(($)=>this.resolveClosed=$),this.open()}send(J){if(this.finished||this.closing)return;let $=JSON.stringify(J);if(this.socket?.readyState===x9)this.socket.send($);else this.outbox.push($)}updateSession(J){this.send({type:"session.update",session:uJ(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,$){this.addItem({type:"function_call_output",call_id:J,output:typeof $==="string"?$:JSON.stringify($)})}createResponse(J={}){let $={};if(J.instructions!==void 0)$.instructions=J.instructions;if(J.toolChoice!==void 0)$.tool_choice=typeof J.toolChoice==="string"?J.toolChoice:{type:"function",name:J.toolChoice.name};if(J.outputModalities)$.output_modalities=J.outputModalities;if(J.conversation)$.conversation=J.conversation;if(J.metadata)$.metadata=J.metadata;Object.assign($,J.vendor),this.send(Object.keys($).length?{type:"response.create",response:$}:{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 Q=J.queue.shift();if(Q)return{value:Q,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,$="closed"){if(this.finished||this.closing)return;if(this.closing=!0,this.socket&&this.socket.readyState<=x9)this.socket.close(J,$);else this.finish(J,$,!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 Q=await this.init.headers();if(this.closing)return this.finish(1000,"closed",!0);J=(this.init.webSocket??dZ)(this.init.url,{headers:Q})}catch(Q){return this.dropped(1006,Q instanceof Error?Q.message:String(Q),!1)}this.socket=J;let $=!1;J.addEventListener("open",()=>{$=!0;let Q=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(),Q)this.emit({type:"sideband.reconnected",attempt:Z})}),J.addEventListener("message",(Q)=>{let Z=pZ(Q.data);if(Z)this.emit(Z)}),J.addEventListener("close",(Q)=>{if(this.socket!==J)return;this.dropped(Q.code??1006,Q.reason??"",$)}),J.addEventListener("error",()=>{})}dropped(J,$,Q){if(this.socket=void 0,this.closing)return this.finish(J,$,!0);let Z=this.init.reconnect?.attempts??3;if(!((J!==1000||!Q)&&this.failures<Z))return this.finish(J,$,!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:$,byClient:Q};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} ${$}).`));this.resolveClosed(Z)}emit(J){if(this.backlog){if(this.backlog.push(J),this.backlog.length>lZ)this.backlog.shift()}for(let $ of this.subscribers){if($.done)continue;$.queue.push(J),$.wake?.()}for(let $ of this.listeners)try{$(J)}catch{}}}var b$=30000,I9=10,w9=7200,iZ=600,b9="gpt-live-transcribe";function nZ(J){return J.type==="transcription"}function oZ(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 $={model:J.model??b9};if(J.prompt!==void 0)$.prompt=J.prompt;if(J.keywords?.length)$.keywords=J.keywords;if(J.languages?.length)$.languages=J.languages;if(J.language!==void 0)$.language=J.language;if(J.delay!==void 0)$.delay=J.delay;let Q={transcription:$,turn_detection:J.turnDetection?f9(J.turnDetection):null};if(J.noiseReduction!==void 0)Q.noise_reduction=J.noiseReduction&&{type:J.noiseReduction};let Z={type:"transcription",audio:{input:Q}};if(J.logprobs)Z.include=["item.input_audio_transcription.logprobs"];return{...Z,...J.vendor}}function sZ(J){if(!J)return{type:"object",properties:{}};return q9(J)?J.toJSONSchema():J}function uJ(J,$){if(nZ(J))return oZ(J);let Q={type:"realtime"},Z=J.model??$;if(Z)Q.model=Z;if(J.instructions!==void 0)Q.instructions=J.instructions;if(J.outputModalities)Q.output_modalities=J.outputModalities;if(J.maxOutputTokens!==void 0)Q.max_output_tokens=J.maxOutputTokens;if(J.truncation!==void 0)Q.truncation=J.truncation;if(J.tools)Q.tools=J.tools.map((X)=>({type:"function",name:X.name,...X.description?{description:X.description}:{},parameters:sZ(X.parameters)}));if(J.toolChoice!==void 0)Q.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&&f9(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)Q.audio={...Object.keys(W).length?{input:W}:{},...Object.keys(K).length?{output:K}:{}};return{...Q,...J.vendor}}function f9(J){let $={type:J.type};if(J.createResponse!==void 0)$.create_response=J.createResponse;if(J.interruptResponse!==void 0)$.interrupt_response=J.interruptResponse;if(J.type==="semantic_vad"){if(J.eagerness!==void 0)$.eagerness=J.eagerness}else{if(J.threshold!==void 0)$.threshold=J.threshold;if(J.prefixPaddingMs!==void 0)$.prefix_padding_ms=J.prefixPaddingMs;if(J.silenceDurationMs!==void 0)$.silence_duration_ms=J.silenceDurationMs;if(J.idleTimeoutMs!==void 0)$.idle_timeout_ms=J.idleTimeoutMs}return $}function hJ(J){let $=Number(J?.input_tokens??0),Q=Number(J?.output_tokens??0),Z={inputTokens:$,outputTokens:Q,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 X=W?.cached_tokens_details?.audio_tokens;if(typeof X==="number")Z.cachedAudioInputTokens=X;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 g extends Error{code;retryable;status;constructor(J,$={}){super(J.message,{cause:$.cause});if(this.name="RealtimeRequestError",this.code=J.code,this.retryable=J.retryable,$.status!==void 0)this.status=$.status}}var aZ=60;class FJ{model;target;options;constructor(J,$){this.target=J,this.options=$,this.model=$.model}url(J){return`${this.target.base}/realtime${J}${this.target.query}`}sidebandUrl(J){let $=this.target.base.replace(/^http(s?):/i,(Z,W)=>`ws${W}:`),Q=this.target.query?`${this.target.query}&`:"?";return`${$}/realtime${Q}call_id=${encodeURIComponent(J)}`}async createCall(J){let $=J.flow??this.options.callFlow??"unified",Q,Z;if($==="ephemeral")Q={authorization:`Bearer ${(await this.clientSecret({session:J.session,ttlSeconds:aZ,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(uJ(J.session??{},this.model))),Q=await this.target.headers(),Z=V}if(J.safetyIdentifier)Q["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:Q,body:Z},J.signal),X=await K.text(),Y=tZ(K);if(!Y)throw new g({code:"provider_error",message:"The provider started a realtime call but did not say which one (no Location).",retryable:!1});return{sdpAnswer:X,callId:Y}}async clientSecret(J={}){let $=J.ttlSeconds??iZ;if(!Number.isInteger($)||$<I9||$>w9)throw RangeError(`ttlSeconds must be a whole number from ${I9} to ${w9}, got ${$}.`);let Q={...await this.target.headers(),"content-type":"application/json"};if(J.safetyIdentifier)Q["OpenAI-Safety-Identifier"]=J.safetyIdentifier;let W=await(await this.request(this.url("/client_secrets"),{method:"POST",headers:Q,body:JSON.stringify({expires_after:{anchor:"created_at",seconds:$},session:uJ(J.session??{},this.model)})},J.signal)).json();if(typeof W?.value!=="string")throw new g({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,$={}){try{await this.request(this.url(`/calls/${encodeURIComponent(J)}/hangup`),{method:"POST",headers:await this.target.headers()},$.signal)}catch(Q){if(y9(Q,J))return;throw Q}}sideband(J,$={}){return new gJ({...$,callId:J,url:this.sidebandUrl(J),headers:this.target.headers,webSocket:$.webSocket??this.options.webSocket,hangup:()=>this.hangup(J)})}async request(J,$,Q){try{return await i(J,$,{maxRetries:this.target.maxRetries,timeoutMs:this.target.timeoutMs,retryTimeouts:!1,signal:Q,fetchImpl:this.options.fetchImpl})}catch(Z){if(Q?.aborted)throw Z;throw new g(T(Z),{cause:Z,...Z instanceof y?{status:Z.status}:{}})}}}function y9(J,$){if(!(J instanceof g)||J.status!==404)return!1;let Q=J.cause instanceof y?J.cause.body:void 0,Z=Q?.error??Q,W=String(Z?.code??"").toLowerCase(),K=String(Z?.message??"").toLowerCase();if(W.includes("call"))return!0;if(K.includes($.toLowerCase()))return!0;return/\bcall\b/.test(K)&&/not (be )?found|does not exist|no longer|ended/.test(K)}function tZ(J){let $=J.headers.get("location");if(!$)return;let Q=$.split("?")[0].replace(/\/+$/,""),Z=Q.slice(Q.lastIndexOf("/")+1);return Z?decodeURIComponent(Z):void 0}function y$(J,$){let{capabilities:Q}=$,Z={model:$.model,input:rZ(J.messages,Q,J.tools),stream:!0};if(J.systemPrompt)Z.instructions=J.systemPrompt;let W=Y0(J.tools,Q);if(W.length>0){if(Z.tools=W,!Q.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&&Q.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 rZ(J,$,Q){let Z=[],W=new Map;if($.toolSearch){for(let K of Q??[])if(cJ(K))W.set(K.name,K)}for(let K of J){let X=K.role,Y=[],V=()=>{if(Y.length===0)return;Z.push({type:"message",role:X,content:Y}),Y=[]};for(let G of K.content??[])switch(G.type){case"text":{if(!G.text)break;Y.push(e(X,G.text));break}case"output":{if(G.partial)break;Y.push(e(X,JSON.stringify(G.value)));break}case"file":{if(X==="assistant")break;let H=$0(G);if(!$.fileInput){if(H)Y.push(e(X,f$(G,!1)));break}if(G.fileId?.startsWith(n))throw Error(`FilePart.fileId holds a gemi attachment id (${G.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(!G.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(G.providerRejected){if(H)Y.push(e(X,f$(G,!1)));Y.push(e(X,E$(G.name)));break}if(H)Y.push(e(X,f$(G,!!G.fileId)));if(G.fileId)Y.push(Q0(G));break}case"reasoning":{V();let H=K0(G);if(H)Z.push(H);break}case"tool-call":{if(G.partial)break;if(V(),$.toolSearch&&Array.isArray(G.toolSearches))for(let D of G.toolSearches)Z.push(...G0(D,Q??[]));let H={type:"function_call",call_id:G.toolCallId,name:String(G.name),arguments:JSON.stringify(G.input??{})};if(G.namespace&&W.has(G.namespace))H.namespace=G.namespace;Z.push(H);break}case"tool-result":{V(),Z.push({type:"function_call_output",call_id:G.toolCallId,output:X0(G)});break}}V()}return J0(Z)}var eZ="No result was recorded for this tool call. Assume it did not complete.";function J0(J){let $=new Set,Q=new Set,Z=[];for(let K of J){if(K.type==="function_call"){let X=String(K.call_id);if($.has(X))continue;$.add(X)}else if(K.type==="function_call_output"){let X=String(K.call_id);if(!$.has(X)||Q.has(X))continue;Q.add(X)}Z.push(K)}if(Q.size===$.size)return Z;let W=[];for(let K of Z){if(W.push(K),K.type!=="function_call")continue;let X=String(K.call_id);if(Q.has(X))continue;Q.add(X),W.push({type:"function_call_output",call_id:X,output:eZ})}return W}function e(J,$){return{type:J==="assistant"?"output_text":"input_text",text:$}}function $0(J){let $=J.attachmentId;return typeof $==="string"&&$.startsWith(n)?$:void 0}function f$(J,$){let Q=[`id=${JSON.stringify(J.attachmentId)}`];if(J.name)Q.push(`name=${JSON.stringify(J.name)}`);if(J.mimeType)Q.push(`mimeType=${JSON.stringify(J.mimeType)}`);let Z=`attachment ${Q.join(" ")}`;return $?`[${Z}]`:`[${Z} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function Q0(J){let $=J.mimeType?.trim().toLowerCase()??"";return{type:($?$.startsWith("image/")&&$!=="image/svg+xml":Z0(J.name))?"input_image":"input_file",file_id:J.fileId}}function Z0(J){let $=/\.([a-z0-9]+)$/.exec(J?.trim().toLowerCase()??"");return $?.[1]!==void 0&&W0.has($[1])}var W0=new Set(["jpeg","jpg","png","gif","webp"]);function K0(J){if(!J.id)return null;let $={type:"reasoning",id:J.id};return $.summary=J.text?[{type:"summary_text",text:J.text}]:[],$}function X0(J){if(J.status==="ok"){let $=J.modelOutput!==void 0?J.modelOutput:J.output;return typeof $==="string"?$:JSON.stringify($??null)}if(J.status==="running"){let $=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.${$}`}if(J.status==="denied"){let $=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.${$}`;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.${$}`;return`The user declined this tool call, so it did not run.${$}`}return`The tool call failed and produced no result. Error (${J.error?.code??"unknown"}): ${J.error?.message??"no message"}`}function G0(J,$){let Q=new Set(v9(J?.loaded)),Z=v9(J?.namespaces),W=new Set(Z),K=[];for(let Y of $)if(cJ(Y)){if(!W.has(Y.name))continue;let V=Y.tools.filter((G)=>Q.size===0||Q.has(G.name));if(V.length===0)continue;K.push({type:"namespace",name:Y.name,description:Y.description,tools:V.map((G)=>JJ(G,!0))})}else if(Y.deferred&&Q.has(Y.name))K.push(JJ(Y,!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:[...Q]}},{type:"tool_search_output",call_id:null,execution:"server",status:"completed",tools:K}]}function v9(J){return Array.isArray(J)?J.filter(($)=>typeof $==="string"):[]}function cJ(J){return Array.isArray(J.tools)}function Y0(J,$){if(!J||J.length===0)return[];if(!$.toolSearch){let W=[];for(let K of J)if(cJ(K))for(let X of K.tools)W.push(JJ(X,!1));else W.push(JJ(K,!1));return W}let Q=[],Z=!1;for(let W of J)if(cJ(W)){let K=W.tools.map((X)=>{if(X.deferred)Z=!0;return JJ(X,!0)});Q.push({type:"namespace",name:W.name,description:W.description,tools:K})}else{if(W.deferred)Z=!0;Q.push(JJ(W,!0))}if(Z)Q.push({type:"tool_search"});return Q}function JJ(J,$){let Q={type:"function",name:J.name,description:J.description,parameters:J.parameters,strict:J.strict};if($&&J.deferred)Q.defer_loading=!0;return Q}class $J{static models(){return[]}normalizeError(J){return T(J)}}var h9=["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 v$ extends $J{model;capabilities;config;constructor(J,$={}){super();this.model=J,this.capabilities=q$(J),this.config=$}static model(J,$){return new v$(J,$)}static models(){return h9}stream(J){let $=y$(J,{model:this.model,capabilities:this.capabilities});return I$(this.endpoint(),$,{signal:J.signal,structuredOutput:Boolean(J.output),files:R$(J.messages)})}upload(J){return w$(this.endpoint(),J)}endpoint(){return x$(zJ(this.config))}get realtime(){return new FJ(zJ(this.config,{timeoutMs:b$}),{model:this.model})}}class h$ extends $J{model;capabilities;config;constructor(J,$={}){super();this.model=J,this.capabilities=q$(J),this.config=$}static model(J,$){return new h$(J,$)}static models(){return h9}stream(J){let $=y$(J,{model:this.deployment(),capabilities:this.capabilities});return I$(this.endpoint(),$,{signal:J.signal,structuredOutput:Boolean(J.output),files:R$(J.messages)})}upload(J){return w$(this.endpoint(),J,"assistants")}deployment(){return this.config.deployment??this.model}endpoint(){return x$(DJ(this.config))}get realtime(){return new FJ(V9(this.config,{timeoutMs:b$}),{model:this.deployment(),callFlow:"ephemeral"})}}class mJ{now;entries=new Map;constructor(J=Date.now){this.now=J}allow(J,$){let Q=this.entries.get(J);if(Q?.openUntil===void 0)return!0;let Z=this.now();if(Z<Q.openUntil)return!1;if(Q.probeUntil!==void 0&&Z<Q.probeUntil)return!1;return Q.probeUntil=Z+$.cooldownMs,!0}record(J,$,Q){let Z=this.entries.get(J)??{failures:0},W=Z.openUntil!==void 0;if($==="success")return this.entries.delete(J),W?"closed":void 0;if($==="none"){delete Z.probeUntil;return}if(Z.failures+=1,this.entries.set(J,Z),W||Z.failures>=Q.failures)return Z.openUntil=this.now()+Q.cooldownMs,delete Z.probeUntil,W?void 0:"open";return}state(J){let $=this.entries.get(J);if($?.openUntil===void 0)return"closed";return this.now()<$.openUntil?"open":"half-open"}}var g9=Symbol("timed-out");class PJ extends $J{model;capabilities;entries;options;circuit;constructor(J,$={}){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(Q){let Z=Q.failures??3,W=Q.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 Y of J){let V=g$(Y);if(K.has(V))throw Error(`FallbackProvider: two legs share the circuit key "${V}". Give one of them a \`circuitKey\`.`);K.add(V)}let X=Q.store??new mJ;this.options={...$,circuit:{...Q,store:X}},this.circuit={policy:{failures:Z,cooldownMs:W},store:X,...Q.onStateChange?{onStateChange:Q.onStateChange}:{}}}else this.options=$,this.circuit=void 0;this.model=J[0].provider.model,this.capabilities=V0(J.map((Z)=>Z.provider.capabilities))}static chain(J,$){return new PJ(J,$)}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 PJ(this.entries.slice(J),this.options)}leg(J){let $=this.from(J).entries[0];return new PJ([$],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],X=W===this.entries.length-1,Y=K.provider.model;if(this.circuit&&!X&&!await this.allow(K))continue;Z+=1;let V=!1,G=async(O)=>{if(V)return;V=!0,await this.record(W,K,O)},H=new AbortController,D=()=>H.abort(Q?.reason);if(Q?.aborted)H.abort(Q.reason);else Q?.addEventListener("abort",D,{once:!0});let z=[],F=!1,B=!1,N,P,U,L=!1,_,R=!1,A=(O)=>{let C=$?k(k(j(),$),O.usage):O.usage;return $=void 0,{...O,usage:C}};try{_=K.provider.stream({...J,...K.reasoning!==void 0?{reasoning:K.reasoning}:{},signal:H.signal})[Symbol.asyncIterator]();let O=!0;for(;;){let C=O&&K.timeoutMs!==void 0?await H0(_.next(),K.timeoutMs):await _.next();if(C===g9){L=!0,U={error:{code:"provider_error",message:`${Y} sent nothing within ${K.timeoutMs}ms.`,retryable:!0}};break}if(O=!1,C.done){R=!0;break}let M=C.value;if(M.type==="finish"&&M.model)P=M.model;if(M.type==="retry"){yield M;continue}if(F){if(M.type==="finish")N=k(N??j(),M.usage),B=!0,yield A(M);else{if(M.type==="error")U={error:M.error};yield M}continue}if(vJ(M)){F=!0,await G("success"),yield*z.splice(0),yield M;continue}if(M.type==="error")U={error:M.error,...M.status!==void 0?{status:M.status}:{},...M.requestId!==void 0?{requestId:M.requestId}:{}};else if(M.type==="finish"){if(N=k(N??j(),M.usage),M.reason==="error"&&!U)U={error:{code:"provider_error",message:`${Y} ended the call with an error and did not say which.`,retryable:!1}}}z.push(M)}}catch(O){let C=K.provider.normalizeError(O);if(F){if(C.code!=="aborted")yield{type:"error",error:C,...v(O)};this.report({index:W,model:Y,responseModel:P,attempt:Z,usage:N,outcome:u$(C),error:C}),yield A({type:"finish",reason:C.code==="aborted"?"aborted":"error",usage:j(),...P?{model:P}:{}});return}U={error:C,...v(O)}}finally{if(Q?.removeEventListener("abort",D),!R)H.abort(),_?.return?.()?.catch(()=>{})}if(F){if(!B&&$)yield{type:"finish",reason:U?"error":"stop",usage:$},$=void 0;this.report({index:W,model:Y,responseModel:P,attempt:Z,usage:N,outcome:U?u$(U.error):"ok",...U?{error:U.error}:{}});return}if(Q?.aborted){await G("none"),this.report({index:W,model:Y,responseModel:P,attempt:Z,usage:N,outcome:"aborted"}),yield A({type:"finish",reason:"aborted",usage:N??j(),...P?{model:P}:{}});return}if(!U){await G("success"),this.report({index:W,model:Y,responseModel:P,attempt:Z,usage:N,outcome:"ok"});for(let O of z)yield O.type==="finish"?A(O):O;return}let x=!X&&U.error.code!=="aborted"&&this.shouldFallBack(U.error,{index:W,model:Y,timedOut:L,...U.status!==void 0?{status:U.status}:{},...U.requestId!==void 0?{requestId:U.requestId}:{}});if(await G(x?"failure":"none"),this.report({index:W,model:Y,responseModel:P,attempt:Z,usage:N,outcome:x?"fallback":u$(U.error),error:U.error}),x){if(N)$=k($??j(),N);continue}let f=!1,q;for(let O of z){if(O.type==="finish"){q=O;continue}if(O.type==="error")f=!0;yield O}if(!f&&U.error.code!=="aborted")yield{type:"error",error:U.error,...U.status!==void 0?{status:U.status}:{},...U.requestId!==void 0?{requestId:U.requestId}:{}};yield A({type:"finish",reason:U.error.code==="aborted"?"aborted":q?.reason??"error",usage:N??j(),...P?{model:P}:{}});return}}async allow(J){if(!this.circuit)return!0;try{return await this.circuit.store.allow(g$(J),this.circuit.policy)}catch{return!0}}async record(J,$,Q){if(!this.circuit)return;let Z=g$($),W;try{W=await this.circuit.store.record(Z,Q,this.circuit.policy)}catch{return}if(!W)return;try{this.circuit.onStateChange?.({index:J,model:$.provider.model,key:Z,state:W})}catch{}}shouldFallBack(J,$){let Q=this.options.fallbackOn??((Z)=>Z.retryable);try{return Q(J,$)}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 g$(J){return J.circuitKey??J.provider.model}function u$(J){return J.code==="aborted"?"aborted":"failed"}function V0(J){return{reasoning:J.every(($)=>$.reasoning),structuredOutput:J.every(($)=>$.structuredOutput),fileInput:J.every(($)=>$.fileInput),parallelToolCalls:J.every(($)=>$.parallelToolCalls),toolSearch:J.every(($)=>$.toolSearch)}}function H0(J,$){let Q,Z=new Promise((W)=>{Q=setTimeout(()=>W(g9),$)});return Promise.race([J,Z]).finally(()=>clearTimeout(Q))}async function z0(J,$,Q={}){let Z=Q.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 X=J.leg(K),Y={index:K,model:X.model,results:[],errors:[]};for(let V=0;V<Z;V++)try{Y.results.push(await $(X,{index:K,sample:V}))}catch(G){Y.errors.push({sample:V,error:G})}W.push(Y)}return W}class lJ extends Error{line;constructor(J){super(J??"Voice session ended by the app.");this.name="VoiceHangup",this.line=J}}var NJ="ask_agent",D0={maxDurationMs:900000,idleTimeoutMs:120000,maxQueued:3,progressIntervalMs:4000,closingLineMs:1e4,tickMs:60000,hangupGraceMs:30000,toolTimeoutMs:60000,maxToolCallsPerMinute:20,toolOutputChars:8000},F0={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 UJ(J={}){return[{name:J.name??NJ,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 pJ=new Map;class o{sessionId;threadId;callId;ended;params;sideband;hangupCall;limits;lines;delegateName;startedAt=Date.now();body;usage=j();transcription={usage:j(),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 o(J)}static get(J){return pJ.get(J)}static async endAll(J){await Promise.all([...pJ.values()].map(($)=>$.end("hangup",J)))}constructor(J){this.params=J,this.sessionId=J.sessionId??crypto.randomUUID(),this.threadId=J.threadId,this.body=J.body??{},this.limits={...D0,...u9(J.limits)},this.lines={...F0,...u9(J.lines)},this.delegateName=J.delegate?.name??NJ;let $=new Set(UJ(J.delegate).map((Q)=>Q.name));for(let Q of J.tools??[]){if($.has(Q.tool.name)||this.toolHandlers.has(Q.tool.name))throw Error(`VoiceBridge: two tools are named "${Q.tool.name}".`);this.toolHandlers.set(Q.tool.name,Q)}if("realtime"in J.call){let{realtime:Q,callId:Z}=J.call;this.callId=Z,this.sideband=Q.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((Q)=>this.resolveEnded=Q),pJ.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 $=this.params.contextNote?.(J);if($)this.sideband.addNote($)}end(J="hangup",$){return this.ending??=this.finish(J,$??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 $=J.usage;if($){this.usage=k(this.usage,$);let Q=this.info();this.hook(()=>this.params.onUsage?.($,Q))}return}case"conversation.item.input_audio_transcription.completed":{let $=J;if(this.say("user",String($.transcript??"")),$.transcriptionUsage||$.transcriptionSeconds!==void 0){this.transcription={usage:$.transcriptionUsage?k(this.transcription.usage,$.transcriptionUsage):this.transcription.usage,seconds:this.transcription.seconds+($.transcriptionSeconds??0)};let Q=this.info(),Z={...$.transcriptionUsage?{usage:$.transcriptionUsage}:{},...$.transcriptionSeconds!==void 0?{seconds:$.transcriptionSeconds}:{}};this.hook(()=>this.params.onTranscriptionUsage?.(Z,Q))}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 $=J;if(this.touch(),!this.ending)this.call($.call_id,$.name,$.arguments);return}case"session.updated":if(this.tampered(J.session))this.end("session_tampered",null);return;case"error":{let $=J.error;if(this.errors.push({code:$?.code,message:String($?.message??"")}),this.pendingCreate&&$?.event_id===this.pendingCreate)if(this.pendingCreate=void 0,$.code==="conversation_already_has_active_response")this.responseActive=!0,this.responseWanted=!0;else this.responseActive=!1;return}case"sideband.closed":{let $=J;if(!this.ending&&!$.byClient)this.end($.code===1000?"call_ended":"sideband_lost",null);return}}}say(J,$){if($.trim())this.transcript.push({role:J,text:$,at:Date.now()})}call(J,$,Q){let Z=P0(Q);if($===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($);if(W)return void this.runTool(J,W,Z);switch($){case"stop_work":{let K=this.running;if(K)K.stopRequested=!0,K.handle?.stop({reason:"Stopped by voice."});let X=this.dropQueue();return this.answer(J,{stopped:Boolean(K),dropped:X})}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:"",X=typeof Z.approve==="boolean"?Z.approve:void 0,Y=this.pending.map((V)=>U0(V,K,X));return this.pending=[],this.enqueue({record:{request:`(answer) ${K}`,status:"queued"},turn:{toolResults:Y},callId:J})}default:return this.answer(J,{status:"error",message:`There is no tool called ${$}.`})}}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 $=new Set;await this.waitForThread($);let Q=await this.latestBody();while(!J.stopRequested&&await this.waitForThread($));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:Q,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($){J.record.status="done",this.complete(J,{status:"failed",message:$ instanceof Error?$.message:"The work failed."})}finally{this.running=void 0,this.flushNote();let $=this.queue.shift();if($&&!this.ending)this.run($);else this.touch()}}async runTool(J,$,Q){let Z=$.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 X=new AbortController,Y=$.timeoutMs??this.limits.toolTimeoutMs,V,G;try{let D=await Promise.race([$.run(Q,{sessionId:this.sessionId,signal:X.signal}),new Promise((z,F)=>{V=setTimeout(()=>{F(new l(`"${Z}" took longer than ${Math.round(Y/1000)} s.`)),X.abort()},Y)})]);K.status="done",G={status:"done",output:this.clip(D)}}catch(D){if(D instanceof lJ){K.status="refused",K.message=D.message,this.end("usage",D.line??null);return}let z=D instanceof l?D.message:"The tool failed.";if(!(D instanceof l))console.error(`[gemi/ai] the voice tool "${Z}" threw.`,D);K.status="failed",K.message=z,G={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,G)}clip(J){let $;try{$=JSON.stringify(J)}catch{return String(J)}if($===void 0||$.length<=this.limits.toolOutputChars)return J;return`${$.slice(0,this.limits.toolOutputChars)}\u2026 (cut: ${$.length} characters in all)`}async waitForThread(J=new Set){let $=this.params.liveRuns;if(!$)return!1;let Q=await $.find({threadId:this.threadId}),Z=Q&&!J.has(Q.runId)?$.get(Q.runId):null;if(!Q||!Z)return!1;return J.add(Q.runId),await Z.result().catch(()=>{return}),!0}async latestBody(){let J=this.params.store;if(!J)return this.body;let $=await J.get(this.sessionId).catch(()=>null);if($)this.body=$.body;return this.body}async follow(J){let $=this.params.progress??N0();try{for await(let Q of J.run){let Z=$(Q);if(Z)this.note(Z)}}catch{}}complete(J,$){if(this.ending)return;if(J.callId)this.sideband.functionOutput(J.callId,$),J.callId=void 0;else this.sideband.addNote(`Update on the earlier request "${J.record.request}": ${JSON.stringify($)}`);this.respond()}answer(J,$){this.sideband.functionOutput(J,$),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 $ of J)$.record.status="dropped";return J.length}note(J){if(J===this.lastProgress)return;this.lastProgress=J;let $=this.lastNoteAt+this.limits.progressIntervalMs-Date.now();if($<=0)return this.flushNote();this.noteTimer??=setTimeout(()=>this.flushNote(),$)}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($){if($ instanceof lJ)this.end("usage",$.line??null);else console.error("[gemi/ai] a voice hook threw; ending the call.",$),this.end("error",this.lines.error)}})}tampered(J){let $=this.params.session;if(!$||!J)return!1;if($.instructions!==void 0&&J.instructions!==void 0&&J.instructions!==$.instructions)return!0;if(Array.isArray(J.tools)){let Q=new Set([...UJ(this.params.delegate),...$.tools??[]].map((W)=>W.name)),Z=new Set(J.tools.map((W)=>String(W?.name)));if(Q.size!==Z.size||[...Q].some((W)=>!Z.has(W)))return!0}return!1}async finish(J,$){for(let X of this.timers)clearTimeout(X);if(this.idleTimer)clearTimeout(this.idleTimer);if(this.noteTimer)clearTimeout(this.noteTimer);if(this.tickTimer)clearInterval(this.tickTimer);if(this.dropQueue(),$&&(J!=="call_ended"&&J!=="sideband_lost"))await this.closingLine($);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};pJ.delete(this.sessionId),await this.params.store?.update(this.sessionId,{endedAt:Z,endReason:J}).catch(()=>{return});try{await this.params.onEnd?.(K)}catch(X){console.error("[gemi/ai] a voice session's onEnd threw.",X)}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 $;await Promise.race([this.sideband.closed,new Promise((Q)=>$=setTimeout(Q,this.limits.hangupGraceMs))]),clearTimeout($),this.sideband.close()}}async closingLine(J){await new Promise(($)=>{let Q=`gemi_voice_closing_${crypto.randomUUID()}`,Z=`gemi_voice_cancel_${crypto.randomUUID()}`,W=this.responseActive?"cancelling":"asked",K,X=setTimeout(Y,this.limits.closingLineMs);function Y(){clearTimeout(X),$()}let V=()=>{W="asked",this.sideband.send({type:"response.create",event_id:Q,response:{instructions:`Say exactly this to the user, and nothing else: "${J}"`,tool_choice:"none"}})};if(this.closingWaiter=(G)=>{let H=G;if(H.type==="sideband.closed")return Y();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===Q)return Y();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))Y()},W==="cancelling")this.sideband.send({type:"response.cancel",event_id:Z});else V()}),this.closingWaiter=void 0}}function u9(J){if(!J)return{};return Object.fromEntries(Object.entries(J).filter(([,$])=>$!==void 0))}function P0(J){try{let $=JSON.parse(J);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function U0(J,$,Q){let Z={toolCallId:J.toolCallId,signature:J.signature,...J.path?{path:J.path}:{}};if(J.kind==="question")return{...Z,output:$};if(J.kind==="approval")return{...Z,approve:Q===!0,...$?{reason:$}:{}};return{...Z,approve:!1,reason:"Not available in a voice call."}}function N0(){let J=new Set;return($)=>{if($.type==="tool-call"){if($.part.partial||$.resent||J.has($.part.toolCallId))return;return J.add($.part.toolCallId),`running ${String($.part.name)}`}if($.type==="tool-progress"){let Q=$.data;if(typeof Q==="string")return Q;if(Q&&typeof Q==="object")for(let Z of["message","label","title"]){let W=Q[Z];if(typeof W==="string"&&W)return W}}return}}var c9="http://gemi.internal/__gemi__/voice/mcp";async function c$(J,$){if(!$.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:Q}=J,Z=J.scopes??Q.scopes().map((X)=>X.name),W=(X)=>({kind:"remote",req:X,principal:{user:$.user,via:"voice",id:`voice:${$.sessionId}`,scopes:Z}});return(await Q.available(W(m9()),J.filter)).filter((X)=>!X.requiresApproval).map((X)=>({tool:{name:X.name,description:X.description,parameters:X.inputSchema},...J.timeoutMs!==void 0?{timeoutMs:J.timeoutMs}:{},run:(Y,V)=>{let G=m9();return p.run(G,async()=>{return await J.authorize?.({name:X.name,input:Y,sessionId:V.sessionId}),Q.execute(W(G),X.name,Y,void 0,{signal:V.signal})},{user:$.user})}}))}function m9(){return new b(new Request(c9,{method:"POST"}),{},"api",new URL(c9).pathname)}class m${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 $=this.records.get(J);return $?structuredClone($):null}async update(J,$){let Q=this.records.get(J);if(!Q)return;this.records.set(J,{...Q,...structuredClone($),id:J})}sweep(){let J=Date.now()-this.retainEndedMs;for(let[$,Q]of this.records)if(Q.endedAt!==void 0&&Q.endedAt<J)this.records.delete($)}}var p$=new m$;var p9=new WeakMap,l9=100;class l${threadsTable;messagesTable;scope=null;sql;dialect;connection;options;constructor(J,$={}){this.threadsTable=d9($.threadsTable??"gemi_agent_threads","threads"),this.messagesTable=d9($.messagesTable??"gemi_agent_messages","messages"),this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name,this.options=$}forScope(J){if(typeof J!=="string"||J==="")throw TypeError("A DatabaseAgentStore scope is a non-empty string.");let $=new l$({sql:this.sql,dialect:this.dialect,name:this.connection},this.options);return $.scope=J,$}async createTable(){let J=C0(this.dialect,this.threadsTable,this.messagesTable);for(let $ of J)await this.sql.unsafe($);await this.addScopeColumns()}async addScopeColumns(){let J=O0(this.dialect,this.threadsTable,this.messagesTable);for(let[$,Q]of J){if(await this.hasColumn($,"scope"))continue;for(let Z of Q)await this.sql.unsafe(Z)}}async hasColumn(J,$){try{return await this.sql.unsafe(`SELECT ${$} FROM ${this.quote(J)} WHERE 1 = 0`),!0}catch{return!1}}async createThread(J){let $=crypto.randomUUID(),Q=J.userId===void 0||J.userId===null?null:String(J.userId);return await this.run(async(Z)=>{let W=this.clock(Z);if(this.scope===null)await Z`
146
+ `)}}if($.length>0){let V=X($);if(V)yield V}let Y=K();if(Y)yield Y}async function*S9(J,$={}){let Q=new Map,Z=new Set,W,K=!1,X,Y=(V,G)=>({type:"finish",reason:V,usage:G,...X?{model:X}:{}});for await(let V of yZ(J)){if(V.data==="[DONE]")break;let G;try{G=JSON.parse(V.data)}catch{continue}let H=typeof G.type==="string"?G.type:V.event,D=G.response?.model;if(typeof D==="string"&&D)X=D;switch(H){case"response.output_text.delta":{let z=String(G.delta??"");if(!z)break;yield $.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(G.delta??"");if(!z)break;yield{type:"reasoning-delta",delta:z,id:G.item_id};break}case"response.output_item.added":{let z=G.item;if(!z)break;if(z.type==="function_call"){let F=String(z.id??G.item_id??z.call_id??"");Q.set(F,{callId:String(z.call_id??F),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=Q.get(String(G.item_id??""));if(!z)break;let F=String(G.delta??"");if(!F)break;yield{type:"tool-call-delta",toolCallId:z.callId,name:z.name,argsDelta:F,...z.namespace?{namespace:z.namespace}:{}};break}case"response.function_call_arguments.done":{let z=String(G.item_id??""),F=Q.get(z);if(!F)break;F.done=!0,yield{type:"tool-call",toolCallId:F.callId,name:F.name,args:String(G.arguments??""),...F.namespace?{namespace:F.namespace}:{}};break}case"response.output_item.done":{let z=G.item;if(!z)break;if(z.type==="function_call"){let F=String(z.id??G.item_id??z.call_id??""),B=Q.get(F);if(B?.done)break;let N=(typeof z.namespace==="string"?z.namespace:"")||B?.namespace;if(yield{type:"tool-call",toolCallId:String(z.call_id??F),name:String(z.name??B?.name??""),args:String(z.arguments??""),...N?{namespace:N}:{}},B)B.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 F=vZ(z);if(F.loaded.length===0&&F.namespaces.length===0)break;let B=String(z.tool_search_call_id??z.id??"");if(Z.has(B))break;Z.add(B);let N=W;W=void 0,yield{type:"tool-search",...F,...N!==void 0&&N!==null?{arguments:N}:{}}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(G.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{K=!0,yield Y("stop",k$(G.response?.usage));break}case"response.incomplete":{K=!0;let z=k$(G.response?.usage),F=G.response?.incomplete_details?.reason;if(F==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:hZ(G.response?.content_filters),retryable:!1}},yield Y("error",z);break}yield Y(F==="max_output_tokens"?"length":"stop",z);break}case"response.failed":case"error":{K=!0;let z=G.response?.error??G.error??G;yield{type:"error",error:gZ(z)},yield Y("error",k$(G.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 Y("error",h())}function vZ(J){let $=[],Q=[];return A9(J.results??J.tools??J.loaded??J.output,$,Q,0),{loaded:T$($),namespaces:T$(Q)}}function A9(J,$,Q,Z){if(!Array.isArray(J)||Z>4)return;for(let W of J){if(typeof W==="string"){$.push(W);continue}if(!W||typeof W!=="object")continue;let K=W,X=typeof K.name==="string"?K.name:typeof K.tool_name==="string"?K.tool_name:"",Y=K.tools??K.functions;if(Array.isArray(Y)){if(X)Q.push(X);A9(Y,$,Q,Z+1);continue}if(X)$.push(X)}}function T$(J){return J.filter(($,Q)=>J.indexOf($)===Q)}function hZ(J){if(!Array.isArray(J))return"The provider's content filter blocked this request.";let Q=[];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[X,Y]of Object.entries(K))if(Y&&typeof Y==="object"&&Y.filtered===!0)Q.push(`${X} (${String(W.source_type??"unknown")})`)}return Q.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${T$(Q).join(", ")}.`}function gZ(J){let $=typeof J?.message==="string"?J.message:"The provider stream failed.",Q=String(J?.code??"").toLowerCase();if(Q==="rate_limit_exceeded")return{code:"rate_limited",message:$,retryable:!0};if(Q==="context_length_exceeded")return{code:"context_length_exceeded",message:$,retryable:!1};if(Q.includes("content_filter"))return{code:"content_filtered",message:$,retryable:!1};return{code:"provider_error",message:$,retryable:!0}}function h(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function k$(J){if(!J)return h();let $=Number(J.input_tokens??0),Q=Number(J.output_tokens??0),Z={inputTokens:$,outputTokens:Q,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*R9(J){if(!J)return;let $=J.getReader(),Q=new TextDecoder;try{while(!0){let{done:W,value:K}=await $.read();if(W)break;if(K)yield Q.decode(K,{stream:!0})}let Z=Q.decode();if(Z)yield Z}finally{$.releaseLock()}}function x$(J){return{responsesUrl:`${J.base}/responses${J.query}`,filesUrl:`${J.base}/files${J.query}`,headers:J.headers,timeoutMs:J.timeoutMs,streamIdleTimeoutMs:J.streamIdleTimeoutMs,streamMaxDurationMs:J.streamMaxDurationMs,maxToolArgumentChars:J.maxToolArgumentChars,maxRetries:J.maxRetries}}async function*I$(J,$,Q){let Z=$,W=new Set,K=0,X=Math.max(0,J.maxRetries),Y=J.random??Math.random,V,G=(P)=>{if(!V)return P;let U=k(k(h(),V),P.usage);return V=void 0,{...P,usage:U}},H=()=>G({type:"finish",reason:"aborted",usage:h()}),D=J.streamIdleTimeoutMs??0,z=J.streamMaxDurationMs??0,F=J.maxToolArgumentChars??0,B=J.now??Date.now,N=B();for(let P=0;;P++){let U=new AbortController,L=Q.signal?AbortSignal.any([Q.signal,U.signal]):U.signal,_;while(_===void 0)try{let O=[],C=()=>{},M=i(J.responsesUrl,{method:"POST",headers:{...await J.headers(),"content-type":"application/json"},body:JSON.stringify(Z)},{maxRetries:J.maxRetries,timeoutMs:J.timeoutMs,signal:L,fetchImpl:J.fetchImpl,sleep:J.sleep,random:J.random,now:J.now,startedAt:N,onRetry:(I)=>{O.push({type:"retry",...I,phase:"request"}),C()}}),w=M.then(()=>!0,()=>!0);for(;;){let I=new Promise(($$)=>C=()=>$$(!1)),J$=await Promise.race([w,I]);if(yield*O.splice(0),J$)break}_=await M}catch(O){let C=K<O9?_9(Z,O,Q.files).filter((w)=>!W.has(w)):[];if(C.length>0){K++;let w=T(O).message;for(let I of C)W.add(I),yield{type:"file-rejected",fileId:I,message:w,...v(O)};Z=M9(Z,new Set(C),Q.files);continue}let M=T(O);if(M.code==="aborted"){yield H();return}yield{type:"error",error:M,...v(O)},yield G({type:"finish",reason:"error",usage:h()});return}let R=[],A=!1,x,f=!1,q=new Map;try{let O=F9(_.body,{idleMs:D,maxMs:z},{idle:()=>{let C=new E9(D);return U.abort(C),C},max:()=>{let C=new j9(z);return U.abort(C),C}});for await(let C of S9(R9(O),{structuredOutput:Q.structuredOutput})){if(C.type==="tool-call-delta"){let M=(q.get(C.toolCallId)??0)+C.argsDelta.length;if(q.set(C.toolCallId,M),F>0&&M>F){let w=new k9(F,C.name);throw U.abort(w),w}yield C;continue}if(C.type==="tool-call")q.delete(C.toolCallId);if(A){yield C.type==="finish"?G(C):C;continue}if(vJ(C)){A=!0,yield*R.splice(0),yield C;continue}if(C.type==="error")x=C.error;R.push(C)}}catch(O){f=O instanceof bJ;let C=T(O);if(C.code==="aborted"||Q.signal?.aborted){yield H();return}if(A){yield{type:"error",error:C},yield G({type:"finish",reason:"error",usage:h()});return}x=C,R.push({type:"error",error:C},{type:"finish",reason:"error",usage:h()})}if(A)return;if(x?.retryable&&P<X&&!Q.signal?.aborted){let O={};for(let M of R){if(M.type==="finish")V=k(V??h(),M.usage);if(M.type==="error")O=v(M)}if(q.size>0)yield{type:"tool-call-discard",toolCallIds:[...q.keys()]};let C=qJ(P,Y);yield{type:"retry",attempt:P+1,maxRetries:X,error:x,...O,phase:"stream",timedOut:f,delayMs:C,elapsedMs:B()-N};try{await O$(C,Q.signal,J.sleep)}catch{yield H();return}continue}for(let O of R)yield O.type==="finish"?G(O):O;return}}async function w$(J,$,Q="user_data"){let Z=new FormData;Z.set("purpose",Q),Z.set("file",$);let K=await(await i(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 q$(J){let $=uZ(J);if($.startsWith("gpt-3.5")||$.startsWith("text-")||$.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let Q=cZ($);if(Q?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:Q.major>1,toolSearch:T9(Q)};if(Q?.kind==="gpt")return{reasoning:Q.major>=5,structuredOutput:Q.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),fileInput:Q.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:T9(Q)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function T9(J){if(J.kind==="o")return J.major>=5;return J.major>5||J.major===5&&J.minor>=2}function uZ(J){return J.trim().toLowerCase()}function cZ(J){let $=/^gpt-(\d+)(?:\.(\d+))?/.exec(J);if($?.[1])return{kind:"gpt",major:Number($[1]),minor:Number($[2]??0)};let Q=/^o(\d+)(?:[-.]|$)/.exec(J);if(Q?.[1])return{kind:"o",major:Number(Q[1]),minor:0};return null}var mZ={"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 pZ(J){if(typeof J!=="string")return;let $;try{$=JSON.parse(J)}catch{return}if(!$||typeof $!=="object"||typeof $.type!=="string")return;let Q=mZ[$.type];if(Q)$.type=Q;if($.type==="response.done"&&$.response?.usage)$.usage=hJ($.response.usage);if($.type==="conversation.item.input_audio_transcription.completed"&&$.usage)if($.usage.type==="duration"){let Z=Number($.usage.seconds);if(Number.isFinite(Z))$.transcriptionSeconds=Z}else $.transcriptionUsage=hJ($.usage);return $}var x9=1,lZ=500;function dZ(J,$){let Q=globalThis.WebSocket;if(!Q)throw Error("No global WebSocket: the realtime sideband needs Bun or Node 22+.");return new Q(J,{headers:$.headers})}class gJ{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=$,this.rejectReady=Q}),this.ready.catch(()=>{}),this.closed=new Promise(($)=>this.resolveClosed=$),this.open()}send(J){if(this.finished||this.closing)return;let $=JSON.stringify(J);if(this.socket?.readyState===x9)this.socket.send($);else this.outbox.push($)}updateSession(J){this.send({type:"session.update",session:uJ(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,$){this.addItem({type:"function_call_output",call_id:J,output:typeof $==="string"?$:JSON.stringify($)})}createResponse(J={}){let $={};if(J.instructions!==void 0)$.instructions=J.instructions;if(J.toolChoice!==void 0)$.tool_choice=typeof J.toolChoice==="string"?J.toolChoice:{type:"function",name:J.toolChoice.name};if(J.outputModalities)$.output_modalities=J.outputModalities;if(J.conversation)$.conversation=J.conversation;if(J.metadata)$.metadata=J.metadata;Object.assign($,J.vendor),this.send(Object.keys($).length?{type:"response.create",response:$}:{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 Q=J.queue.shift();if(Q)return{value:Q,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,$="closed"){if(this.finished||this.closing)return;if(this.closing=!0,this.socket&&this.socket.readyState<=x9)this.socket.close(J,$);else this.finish(J,$,!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 Q=await this.init.headers();if(this.closing)return this.finish(1000,"closed",!0);J=(this.init.webSocket??dZ)(this.init.url,{headers:Q})}catch(Q){return this.dropped(1006,Q instanceof Error?Q.message:String(Q),!1)}this.socket=J;let $=!1;J.addEventListener("open",()=>{$=!0;let Q=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(),Q)this.emit({type:"sideband.reconnected",attempt:Z})}),J.addEventListener("message",(Q)=>{let Z=pZ(Q.data);if(Z)this.emit(Z)}),J.addEventListener("close",(Q)=>{if(this.socket!==J)return;this.dropped(Q.code??1006,Q.reason??"",$)}),J.addEventListener("error",()=>{})}dropped(J,$,Q){if(this.socket=void 0,this.closing)return this.finish(J,$,!0);let Z=this.init.reconnect?.attempts??3;if(!((J!==1000||!Q)&&this.failures<Z))return this.finish(J,$,!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:$,byClient:Q};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} ${$}).`));this.resolveClosed(Z)}emit(J){if(this.backlog){if(this.backlog.push(J),this.backlog.length>lZ)this.backlog.shift()}for(let $ of this.subscribers){if($.done)continue;$.queue.push(J),$.wake?.()}for(let $ of this.listeners)try{$(J)}catch{}}}var b$=30000,I9=10,w9=7200,iZ=600,b9="gpt-live-transcribe";function nZ(J){return J.type==="transcription"}function oZ(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 $={model:J.model??b9};if(J.prompt!==void 0)$.prompt=J.prompt;if(J.keywords?.length)$.keywords=J.keywords;if(J.languages?.length)$.languages=J.languages;if(J.language!==void 0)$.language=J.language;if(J.delay!==void 0)$.delay=J.delay;let Q={transcription:$,turn_detection:J.turnDetection?f9(J.turnDetection):null};if(J.noiseReduction!==void 0)Q.noise_reduction=J.noiseReduction&&{type:J.noiseReduction};let Z={type:"transcription",audio:{input:Q}};if(J.logprobs)Z.include=["item.input_audio_transcription.logprobs"];return{...Z,...J.vendor}}function sZ(J){if(!J)return{type:"object",properties:{}};return q9(J)?J.toJSONSchema():J}function uJ(J,$){if(nZ(J))return oZ(J);let Q={type:"realtime"},Z=J.model??$;if(Z)Q.model=Z;if(J.instructions!==void 0)Q.instructions=J.instructions;if(J.outputModalities)Q.output_modalities=J.outputModalities;if(J.maxOutputTokens!==void 0)Q.max_output_tokens=J.maxOutputTokens;if(J.truncation!==void 0)Q.truncation=J.truncation;if(J.tools)Q.tools=J.tools.map((X)=>({type:"function",name:X.name,...X.description?{description:X.description}:{},parameters:sZ(X.parameters)}));if(J.toolChoice!==void 0)Q.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&&f9(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)Q.audio={...Object.keys(W).length?{input:W}:{},...Object.keys(K).length?{output:K}:{}};return{...Q,...J.vendor}}function f9(J){let $={type:J.type};if(J.createResponse!==void 0)$.create_response=J.createResponse;if(J.interruptResponse!==void 0)$.interrupt_response=J.interruptResponse;if(J.type==="semantic_vad"){if(J.eagerness!==void 0)$.eagerness=J.eagerness}else{if(J.threshold!==void 0)$.threshold=J.threshold;if(J.prefixPaddingMs!==void 0)$.prefix_padding_ms=J.prefixPaddingMs;if(J.silenceDurationMs!==void 0)$.silence_duration_ms=J.silenceDurationMs;if(J.idleTimeoutMs!==void 0)$.idle_timeout_ms=J.idleTimeoutMs}return $}function hJ(J){let $=Number(J?.input_tokens??0),Q=Number(J?.output_tokens??0),Z={inputTokens:$,outputTokens:Q,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 X=W?.cached_tokens_details?.audio_tokens;if(typeof X==="number")Z.cachedAudioInputTokens=X;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 g extends Error{code;retryable;status;constructor(J,$={}){super(J.message,{cause:$.cause});if(this.name="RealtimeRequestError",this.code=J.code,this.retryable=J.retryable,$.status!==void 0)this.status=$.status}}var aZ=60;class FJ{model;target;options;constructor(J,$){this.target=J,this.options=$,this.model=$.model}url(J){return`${this.target.base}/realtime${J}${this.target.query}`}sidebandUrl(J){let $=this.target.base.replace(/^http(s?):/i,(Z,W)=>`ws${W}:`),Q=this.target.query?`${this.target.query}&`:"?";return`${$}/realtime${Q}call_id=${encodeURIComponent(J)}`}async createCall(J){let $=J.flow??this.options.callFlow??"unified",Q,Z;if($==="ephemeral")Q={authorization:`Bearer ${(await this.clientSecret({session:J.session,ttlSeconds:aZ,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(uJ(J.session??{},this.model))),Q=await this.target.headers(),Z=V}if(J.safetyIdentifier)Q["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:Q,body:Z},J.signal),X=await K.text(),Y=tZ(K);if(!Y)throw new g({code:"provider_error",message:"The provider started a realtime call but did not say which one (no Location).",retryable:!1});return{sdpAnswer:X,callId:Y}}async clientSecret(J={}){let $=J.ttlSeconds??iZ;if(!Number.isInteger($)||$<I9||$>w9)throw RangeError(`ttlSeconds must be a whole number from ${I9} to ${w9}, got ${$}.`);let Q={...await this.target.headers(),"content-type":"application/json"};if(J.safetyIdentifier)Q["OpenAI-Safety-Identifier"]=J.safetyIdentifier;let W=await(await this.request(this.url("/client_secrets"),{method:"POST",headers:Q,body:JSON.stringify({expires_after:{anchor:"created_at",seconds:$},session:uJ(J.session??{},this.model)})},J.signal)).json();if(typeof W?.value!=="string")throw new g({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,$={}){try{await this.request(this.url(`/calls/${encodeURIComponent(J)}/hangup`),{method:"POST",headers:await this.target.headers()},$.signal)}catch(Q){if(y9(Q,J))return;throw Q}}sideband(J,$={}){return new gJ({...$,callId:J,url:this.sidebandUrl(J),headers:this.target.headers,webSocket:$.webSocket??this.options.webSocket,hangup:()=>this.hangup(J)})}async request(J,$,Q){try{return await i(J,$,{maxRetries:this.target.maxRetries,timeoutMs:this.target.timeoutMs,retryTimeouts:!1,signal:Q,fetchImpl:this.options.fetchImpl})}catch(Z){if(Q?.aborted)throw Z;throw new g(T(Z),{cause:Z,...Z instanceof y?{status:Z.status}:{}})}}}function y9(J,$){if(!(J instanceof g)||J.status!==404)return!1;let Q=J.cause instanceof y?J.cause.body:void 0,Z=Q?.error??Q,W=String(Z?.code??"").toLowerCase(),K=String(Z?.message??"").toLowerCase();if(W.includes("call"))return!0;if(K.includes($.toLowerCase()))return!0;return/\bcall\b/.test(K)&&/not (be )?found|does not exist|no longer|ended/.test(K)}function tZ(J){let $=J.headers.get("location");if(!$)return;let Q=$.split("?")[0].replace(/\/+$/,""),Z=Q.slice(Q.lastIndexOf("/")+1);return Z?decodeURIComponent(Z):void 0}function y$(J,$){let{capabilities:Q}=$,Z={model:$.model,input:rZ(J.messages,Q,J.tools),stream:!0};if(J.systemPrompt)Z.instructions=J.systemPrompt;let W=Y0(J.tools,Q);if(W.length>0){if(Z.tools=W,!Q.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&&Q.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 rZ(J,$,Q){let Z=[],W=new Map;if($.toolSearch){for(let K of Q??[])if(cJ(K))W.set(K.name,K)}for(let K of J){let X=K.role,Y=[],V=()=>{if(Y.length===0)return;Z.push({type:"message",role:X,content:Y}),Y=[]};for(let G of K.content??[])switch(G.type){case"text":{if(!G.text)break;Y.push(e(X,G.text));break}case"output":{if(G.partial)break;Y.push(e(X,JSON.stringify(G.value)));break}case"file":{if(X==="assistant")break;let H=$0(G);if(!$.fileInput){if(H)Y.push(e(X,f$(G,!1)));break}if(G.fileId?.startsWith(n))throw Error(`FilePart.fileId holds a gemi attachment id (${G.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(!G.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(G.providerRejected){if(H)Y.push(e(X,f$(G,!1)));Y.push(e(X,E$(G.name)));break}if(H)Y.push(e(X,f$(G,!!G.fileId)));if(G.fileId)Y.push(Q0(G));break}case"reasoning":{V();let H=K0(G);if(H)Z.push(H);break}case"tool-call":{if(G.partial)break;if(V(),$.toolSearch&&Array.isArray(G.toolSearches))for(let D of G.toolSearches)Z.push(...G0(D,Q??[]));let H={type:"function_call",call_id:G.toolCallId,name:String(G.name),arguments:JSON.stringify(G.input??{})};if(G.namespace&&W.has(G.namespace))H.namespace=G.namespace;Z.push(H);break}case"tool-result":{V(),Z.push({type:"function_call_output",call_id:G.toolCallId,output:X0(G)});break}}V()}return J0(Z)}var eZ="No result was recorded for this tool call. Assume it did not complete.";function J0(J){let $=new Set,Q=new Set,Z=[];for(let K of J){if(K.type==="function_call"){let X=String(K.call_id);if($.has(X))continue;$.add(X)}else if(K.type==="function_call_output"){let X=String(K.call_id);if(!$.has(X)||Q.has(X))continue;Q.add(X)}Z.push(K)}if(Q.size===$.size)return Z;let W=[];for(let K of Z){if(W.push(K),K.type!=="function_call")continue;let X=String(K.call_id);if(Q.has(X))continue;Q.add(X),W.push({type:"function_call_output",call_id:X,output:eZ})}return W}function e(J,$){return{type:J==="assistant"?"output_text":"input_text",text:$}}function $0(J){let $=J.attachmentId;return typeof $==="string"&&$.startsWith(n)?$:void 0}function f$(J,$){let Q=[`id=${JSON.stringify(J.attachmentId)}`];if(J.name)Q.push(`name=${JSON.stringify(J.name)}`);if(J.mimeType)Q.push(`mimeType=${JSON.stringify(J.mimeType)}`);let Z=`attachment ${Q.join(" ")}`;return $?`[${Z}]`:`[${Z} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function Q0(J){let $=J.mimeType?.trim().toLowerCase()??"";return{type:($?$.startsWith("image/")&&$!=="image/svg+xml":Z0(J.name))?"input_image":"input_file",file_id:J.fileId}}function Z0(J){let $=/\.([a-z0-9]+)$/.exec(J?.trim().toLowerCase()??"");return $?.[1]!==void 0&&W0.has($[1])}var W0=new Set(["jpeg","jpg","png","gif","webp"]);function K0(J){if(!J.id)return null;let $={type:"reasoning",id:J.id};return $.summary=J.text?[{type:"summary_text",text:J.text}]:[],$}function X0(J){if(J.status==="ok"){let $=J.modelOutput!==void 0?J.modelOutput:J.output;return typeof $==="string"?$:JSON.stringify($??null)}if(J.status==="running"){let $=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.${$}`}if(J.status==="denied"){let $=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.${$}`;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.${$}`;return`The user declined this tool call, so it did not run.${$}`}return`The tool call failed and produced no result. Error (${J.error?.code??"unknown"}): ${J.error?.message??"no message"}`}function G0(J,$){let Q=new Set(v9(J?.loaded)),Z=v9(J?.namespaces),W=new Set(Z),K=[];for(let Y of $)if(cJ(Y)){if(!W.has(Y.name))continue;let V=Y.tools.filter((G)=>Q.size===0||Q.has(G.name));if(V.length===0)continue;K.push({type:"namespace",name:Y.name,description:Y.description,tools:V.map((G)=>JJ(G,!0))})}else if(Y.deferred&&Q.has(Y.name))K.push(JJ(Y,!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:[...Q]}},{type:"tool_search_output",call_id:null,execution:"server",status:"completed",tools:K}]}function v9(J){return Array.isArray(J)?J.filter(($)=>typeof $==="string"):[]}function cJ(J){return Array.isArray(J.tools)}function Y0(J,$){if(!J||J.length===0)return[];if(!$.toolSearch){let W=[];for(let K of J)if(cJ(K))for(let X of K.tools)W.push(JJ(X,!1));else W.push(JJ(K,!1));return W}let Q=[],Z=!1;for(let W of J)if(cJ(W)){let K=W.tools.map((X)=>{if(X.deferred)Z=!0;return JJ(X,!0)});Q.push({type:"namespace",name:W.name,description:W.description,tools:K})}else{if(W.deferred)Z=!0;Q.push(JJ(W,!0))}if(Z)Q.push({type:"tool_search"});return Q}function JJ(J,$){let Q={type:"function",name:J.name,description:J.description,parameters:J.parameters,strict:J.strict};if($&&J.deferred)Q.defer_loading=!0;return Q}class $J{static models(){return[]}normalizeError(J){return T(J)}}var h9=["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 v$ extends $J{model;capabilities;config;constructor(J,$={}){super();this.model=J,this.capabilities=q$(J),this.config=$}static model(J,$){return new v$(J,$)}static models(){return h9}stream(J){let $=y$(J,{model:this.model,capabilities:this.capabilities});return I$(this.endpoint(),$,{signal:J.signal,structuredOutput:Boolean(J.output),files:R$(J.messages)})}upload(J){return w$(this.endpoint(),J)}endpoint(){return x$(zJ(this.config))}get realtime(){return new FJ(zJ(this.config,{timeoutMs:b$}),{model:this.model})}}class h$ extends $J{model;capabilities;config;constructor(J,$={}){super();this.model=J,this.capabilities=q$(J),this.config=$}static model(J,$){return new h$(J,$)}static models(){return h9}stream(J){let $=y$(J,{model:this.deployment(),capabilities:this.capabilities});return I$(this.endpoint(),$,{signal:J.signal,structuredOutput:Boolean(J.output),files:R$(J.messages)})}upload(J){return w$(this.endpoint(),J,"assistants")}deployment(){return this.config.deployment??this.model}endpoint(){return x$(DJ(this.config))}get realtime(){return new FJ(V9(this.config,{timeoutMs:b$}),{model:this.deployment(),callFlow:"ephemeral"})}}class mJ{now;entries=new Map;constructor(J=Date.now){this.now=J}allow(J,$){let Q=this.entries.get(J);if(Q?.openUntil===void 0)return!0;let Z=this.now();if(Z<Q.openUntil)return!1;if(Q.probeUntil!==void 0&&Z<Q.probeUntil)return!1;return Q.probeUntil=Z+$.cooldownMs,!0}record(J,$,Q){let Z=this.entries.get(J)??{failures:0},W=Z.openUntil!==void 0;if($==="success")return this.entries.delete(J),W?"closed":void 0;if($==="none"){delete Z.probeUntil;return}if(Z.failures+=1,this.entries.set(J,Z),W||Z.failures>=Q.failures)return Z.openUntil=this.now()+Q.cooldownMs,delete Z.probeUntil,W?void 0:"open";return}state(J){let $=this.entries.get(J);if($?.openUntil===void 0)return"closed";return this.now()<$.openUntil?"open":"half-open"}}var g9=Symbol("timed-out");class PJ extends $J{model;capabilities;entries;options;circuit;constructor(J,$={}){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(Q){let Z=Q.failures??3,W=Q.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 Y of J){let V=g$(Y);if(K.has(V))throw Error(`FallbackProvider: two legs share the circuit key "${V}". Give one of them a \`circuitKey\`.`);K.add(V)}let X=Q.store??new mJ;this.options={...$,circuit:{...Q,store:X}},this.circuit={policy:{failures:Z,cooldownMs:W},store:X,...Q.onStateChange?{onStateChange:Q.onStateChange}:{}}}else this.options=$,this.circuit=void 0;this.model=J[0].provider.model,this.capabilities=V0(J.map((Z)=>Z.provider.capabilities))}static chain(J,$){return new PJ(J,$)}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 PJ(this.entries.slice(J),this.options)}leg(J){let $=this.from(J).entries[0];return new PJ([$],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],X=W===this.entries.length-1,Y=K.provider.model;if(this.circuit&&!X&&!await this.allow(K))continue;Z+=1;let V=!1,G=async(O)=>{if(V)return;V=!0,await this.record(W,K,O)},H=new AbortController,D=()=>H.abort(Q?.reason);if(Q?.aborted)H.abort(Q.reason);else Q?.addEventListener("abort",D,{once:!0});let z=[],F=!1,B=!1,N,P,U,L=!1,_,R=!1,A=(O)=>{let C=$?k(k(j(),$),O.usage):O.usage;return $=void 0,{...O,usage:C}};try{_=K.provider.stream({...J,...K.reasoning!==void 0?{reasoning:K.reasoning}:{},signal:H.signal})[Symbol.asyncIterator]();let O=K.timeoutMs!==void 0?Date.now()+K.timeoutMs:void 0;for(;;){let C=!F&&O!==void 0?await H0(_.next(),Math.max(0,O-Date.now())):await _.next();if(C===g9){L=!0,U={error:{code:"provider_error",message:`${Y} did not start answering within ${K.timeoutMs}ms.`,retryable:!0}};break}if(C.done){R=!0;break}let M=C.value;if(M.type==="finish"&&M.model)P=M.model;if(M.type==="retry"){yield M;continue}if(F){if(M.type==="finish")N=k(N??j(),M.usage),B=!0,yield A(M);else{if(M.type==="error")U={error:M.error};yield M}continue}if(vJ(M)){F=!0,await G("success"),yield*z.splice(0),yield M;continue}if(M.type==="error")U={error:M.error,...M.status!==void 0?{status:M.status}:{},...M.requestId!==void 0?{requestId:M.requestId}:{}};else if(M.type==="finish"){if(N=k(N??j(),M.usage),M.reason==="error"&&!U)U={error:{code:"provider_error",message:`${Y} ended the call with an error and did not say which.`,retryable:!1}}}z.push(M)}}catch(O){let C=K.provider.normalizeError(O);if(F){if(C.code!=="aborted")yield{type:"error",error:C,...v(O)};this.report({index:W,model:Y,responseModel:P,attempt:Z,usage:N,outcome:u$(C),error:C}),yield A({type:"finish",reason:C.code==="aborted"?"aborted":"error",usage:j(),...P?{model:P}:{}});return}U={error:C,...v(O)}}finally{if(Q?.removeEventListener("abort",D),!R)H.abort(),_?.return?.()?.catch(()=>{})}if(F){if(!B&&$)yield{type:"finish",reason:U?"error":"stop",usage:$},$=void 0;this.report({index:W,model:Y,responseModel:P,attempt:Z,usage:N,outcome:U?u$(U.error):"ok",...U?{error:U.error}:{}});return}if(Q?.aborted){await G("none"),this.report({index:W,model:Y,responseModel:P,attempt:Z,usage:N,outcome:"aborted"}),yield A({type:"finish",reason:"aborted",usage:N??j(),...P?{model:P}:{}});return}if(!U){await G("success"),this.report({index:W,model:Y,responseModel:P,attempt:Z,usage:N,outcome:"ok"});for(let O of z)yield O.type==="finish"?A(O):O;return}let x=!X&&U.error.code!=="aborted"&&this.shouldFallBack(U.error,{index:W,model:Y,timedOut:L,...U.status!==void 0?{status:U.status}:{},...U.requestId!==void 0?{requestId:U.requestId}:{}});if(await G(x?"failure":"none"),this.report({index:W,model:Y,responseModel:P,attempt:Z,usage:N,outcome:x?"fallback":u$(U.error),error:U.error}),x){if(N)$=k($??j(),N);continue}let f=!1,q;for(let O of z){if(O.type==="finish"){q=O;continue}if(O.type==="error")f=!0;yield O}if(!f&&U.error.code!=="aborted")yield{type:"error",error:U.error,...U.status!==void 0?{status:U.status}:{},...U.requestId!==void 0?{requestId:U.requestId}:{}};yield A({type:"finish",reason:U.error.code==="aborted"?"aborted":q?.reason??"error",usage:N??j(),...P?{model:P}:{}});return}}async allow(J){if(!this.circuit)return!0;try{return await this.circuit.store.allow(g$(J),this.circuit.policy)}catch{return!0}}async record(J,$,Q){if(!this.circuit)return;let Z=g$($),W;try{W=await this.circuit.store.record(Z,Q,this.circuit.policy)}catch{return}if(!W)return;try{this.circuit.onStateChange?.({index:J,model:$.provider.model,key:Z,state:W})}catch{}}shouldFallBack(J,$){let Q=this.options.fallbackOn??((Z)=>Z.retryable);try{return Q(J,$)}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 g$(J){return J.circuitKey??J.provider.model}function u$(J){return J.code==="aborted"?"aborted":"failed"}function V0(J){return{reasoning:J.every(($)=>$.reasoning),structuredOutput:J.every(($)=>$.structuredOutput),fileInput:J.every(($)=>$.fileInput),parallelToolCalls:J.every(($)=>$.parallelToolCalls),toolSearch:J.every(($)=>$.toolSearch)}}function H0(J,$){let Q,Z=new Promise((W)=>{Q=setTimeout(()=>W(g9),$)});return Promise.race([J,Z]).finally(()=>clearTimeout(Q))}async function z0(J,$,Q={}){let Z=Q.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 X=J.leg(K),Y={index:K,model:X.model,results:[],errors:[]};for(let V=0;V<Z;V++)try{Y.results.push(await $(X,{index:K,sample:V}))}catch(G){Y.errors.push({sample:V,error:G})}W.push(Y)}return W}class lJ extends Error{line;constructor(J){super(J??"Voice session ended by the app.");this.name="VoiceHangup",this.line=J}}var NJ="ask_agent",D0={maxDurationMs:900000,idleTimeoutMs:120000,maxQueued:3,progressIntervalMs:4000,closingLineMs:1e4,tickMs:60000,hangupGraceMs:30000,toolTimeoutMs:60000,maxToolCallsPerMinute:20,toolOutputChars:8000},F0={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 UJ(J={}){return[{name:J.name??NJ,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 pJ=new Map;class o{sessionId;threadId;callId;ended;params;sideband;hangupCall;limits;lines;delegateName;startedAt=Date.now();body;usage=j();transcription={usage:j(),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 o(J)}static get(J){return pJ.get(J)}static async endAll(J){await Promise.all([...pJ.values()].map(($)=>$.end("hangup",J)))}constructor(J){this.params=J,this.sessionId=J.sessionId??crypto.randomUUID(),this.threadId=J.threadId,this.body=J.body??{},this.limits={...D0,...u9(J.limits)},this.lines={...F0,...u9(J.lines)},this.delegateName=J.delegate?.name??NJ;let $=new Set(UJ(J.delegate).map((Q)=>Q.name));for(let Q of J.tools??[]){if($.has(Q.tool.name)||this.toolHandlers.has(Q.tool.name))throw Error(`VoiceBridge: two tools are named "${Q.tool.name}".`);this.toolHandlers.set(Q.tool.name,Q)}if("realtime"in J.call){let{realtime:Q,callId:Z}=J.call;this.callId=Z,this.sideband=Q.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((Q)=>this.resolveEnded=Q),pJ.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 $=this.params.contextNote?.(J);if($)this.sideband.addNote($)}end(J="hangup",$){return this.ending??=this.finish(J,$??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 $=J.usage;if($){this.usage=k(this.usage,$);let Q=this.info();this.hook(()=>this.params.onUsage?.($,Q))}return}case"conversation.item.input_audio_transcription.completed":{let $=J;if(this.say("user",String($.transcript??"")),$.transcriptionUsage||$.transcriptionSeconds!==void 0){this.transcription={usage:$.transcriptionUsage?k(this.transcription.usage,$.transcriptionUsage):this.transcription.usage,seconds:this.transcription.seconds+($.transcriptionSeconds??0)};let Q=this.info(),Z={...$.transcriptionUsage?{usage:$.transcriptionUsage}:{},...$.transcriptionSeconds!==void 0?{seconds:$.transcriptionSeconds}:{}};this.hook(()=>this.params.onTranscriptionUsage?.(Z,Q))}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 $=J;if(this.touch(),!this.ending)this.call($.call_id,$.name,$.arguments);return}case"session.updated":if(this.tampered(J.session))this.end("session_tampered",null);return;case"error":{let $=J.error;if(this.errors.push({code:$?.code,message:String($?.message??"")}),this.pendingCreate&&$?.event_id===this.pendingCreate)if(this.pendingCreate=void 0,$.code==="conversation_already_has_active_response")this.responseActive=!0,this.responseWanted=!0;else this.responseActive=!1;return}case"sideband.closed":{let $=J;if(!this.ending&&!$.byClient)this.end($.code===1000?"call_ended":"sideband_lost",null);return}}}say(J,$){if($.trim())this.transcript.push({role:J,text:$,at:Date.now()})}call(J,$,Q){let Z=P0(Q);if($===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($);if(W)return void this.runTool(J,W,Z);switch($){case"stop_work":{let K=this.running;if(K)K.stopRequested=!0,K.handle?.stop({reason:"Stopped by voice."});let X=this.dropQueue();return this.answer(J,{stopped:Boolean(K),dropped:X})}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:"",X=typeof Z.approve==="boolean"?Z.approve:void 0,Y=this.pending.map((V)=>U0(V,K,X));return this.pending=[],this.enqueue({record:{request:`(answer) ${K}`,status:"queued"},turn:{toolResults:Y},callId:J})}default:return this.answer(J,{status:"error",message:`There is no tool called ${$}.`})}}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 $=new Set;await this.waitForThread($);let Q=await this.latestBody();while(!J.stopRequested&&await this.waitForThread($));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:Q,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($){J.record.status="done",this.complete(J,{status:"failed",message:$ instanceof Error?$.message:"The work failed."})}finally{this.running=void 0,this.flushNote();let $=this.queue.shift();if($&&!this.ending)this.run($);else this.touch()}}async runTool(J,$,Q){let Z=$.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 X=new AbortController,Y=$.timeoutMs??this.limits.toolTimeoutMs,V,G;try{let D=await Promise.race([$.run(Q,{sessionId:this.sessionId,signal:X.signal}),new Promise((z,F)=>{V=setTimeout(()=>{F(new l(`"${Z}" took longer than ${Math.round(Y/1000)} s.`)),X.abort()},Y)})]);K.status="done",G={status:"done",output:this.clip(D)}}catch(D){if(D instanceof lJ){K.status="refused",K.message=D.message,this.end("usage",D.line??null);return}let z=D instanceof l?D.message:"The tool failed.";if(!(D instanceof l))console.error(`[gemi/ai] the voice tool "${Z}" threw.`,D);K.status="failed",K.message=z,G={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,G)}clip(J){let $;try{$=JSON.stringify(J)}catch{return String(J)}if($===void 0||$.length<=this.limits.toolOutputChars)return J;return`${$.slice(0,this.limits.toolOutputChars)}\u2026 (cut: ${$.length} characters in all)`}async waitForThread(J=new Set){let $=this.params.liveRuns;if(!$)return!1;let Q=await $.find({threadId:this.threadId}),Z=Q&&!J.has(Q.runId)?$.get(Q.runId):null;if(!Q||!Z)return!1;return J.add(Q.runId),await Z.result().catch(()=>{return}),!0}async latestBody(){let J=this.params.store;if(!J)return this.body;let $=await J.get(this.sessionId).catch(()=>null);if($)this.body=$.body;return this.body}async follow(J){let $=this.params.progress??N0();try{for await(let Q of J.run){let Z=$(Q);if(Z)this.note(Z)}}catch{}}complete(J,$){if(this.ending)return;if(J.callId)this.sideband.functionOutput(J.callId,$),J.callId=void 0;else this.sideband.addNote(`Update on the earlier request "${J.record.request}": ${JSON.stringify($)}`);this.respond()}answer(J,$){this.sideband.functionOutput(J,$),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 $ of J)$.record.status="dropped";return J.length}note(J){if(J===this.lastProgress)return;this.lastProgress=J;let $=this.lastNoteAt+this.limits.progressIntervalMs-Date.now();if($<=0)return this.flushNote();this.noteTimer??=setTimeout(()=>this.flushNote(),$)}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($){if($ instanceof lJ)this.end("usage",$.line??null);else console.error("[gemi/ai] a voice hook threw; ending the call.",$),this.end("error",this.lines.error)}})}tampered(J){let $=this.params.session;if(!$||!J)return!1;if($.instructions!==void 0&&J.instructions!==void 0&&J.instructions!==$.instructions)return!0;if(Array.isArray(J.tools)){let Q=new Set([...UJ(this.params.delegate),...$.tools??[]].map((W)=>W.name)),Z=new Set(J.tools.map((W)=>String(W?.name)));if(Q.size!==Z.size||[...Q].some((W)=>!Z.has(W)))return!0}return!1}async finish(J,$){for(let X of this.timers)clearTimeout(X);if(this.idleTimer)clearTimeout(this.idleTimer);if(this.noteTimer)clearTimeout(this.noteTimer);if(this.tickTimer)clearInterval(this.tickTimer);if(this.dropQueue(),$&&(J!=="call_ended"&&J!=="sideband_lost"))await this.closingLine($);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};pJ.delete(this.sessionId),await this.params.store?.update(this.sessionId,{endedAt:Z,endReason:J}).catch(()=>{return});try{await this.params.onEnd?.(K)}catch(X){console.error("[gemi/ai] a voice session's onEnd threw.",X)}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 $;await Promise.race([this.sideband.closed,new Promise((Q)=>$=setTimeout(Q,this.limits.hangupGraceMs))]),clearTimeout($),this.sideband.close()}}async closingLine(J){await new Promise(($)=>{let Q=`gemi_voice_closing_${crypto.randomUUID()}`,Z=`gemi_voice_cancel_${crypto.randomUUID()}`,W=this.responseActive?"cancelling":"asked",K,X=setTimeout(Y,this.limits.closingLineMs);function Y(){clearTimeout(X),$()}let V=()=>{W="asked",this.sideband.send({type:"response.create",event_id:Q,response:{instructions:`Say exactly this to the user, and nothing else: "${J}"`,tool_choice:"none"}})};if(this.closingWaiter=(G)=>{let H=G;if(H.type==="sideband.closed")return Y();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===Q)return Y();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))Y()},W==="cancelling")this.sideband.send({type:"response.cancel",event_id:Z});else V()}),this.closingWaiter=void 0}}function u9(J){if(!J)return{};return Object.fromEntries(Object.entries(J).filter(([,$])=>$!==void 0))}function P0(J){try{let $=JSON.parse(J);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function U0(J,$,Q){let Z={toolCallId:J.toolCallId,signature:J.signature,...J.path?{path:J.path}:{}};if(J.kind==="question")return{...Z,output:$};if(J.kind==="approval")return{...Z,approve:Q===!0,...$?{reason:$}:{}};return{...Z,approve:!1,reason:"Not available in a voice call."}}function N0(){let J=new Set;return($)=>{if($.type==="tool-call"){if($.part.partial||$.resent||J.has($.part.toolCallId))return;return J.add($.part.toolCallId),`running ${String($.part.name)}`}if($.type==="tool-progress"){let Q=$.data;if(typeof Q==="string")return Q;if(Q&&typeof Q==="object")for(let Z of["message","label","title"]){let W=Q[Z];if(typeof W==="string"&&W)return W}}return}}var c9="http://gemi.internal/__gemi__/voice/mcp";async function c$(J,$){if(!$.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:Q}=J,Z=J.scopes??Q.scopes().map((X)=>X.name),W=(X)=>({kind:"remote",req:X,principal:{user:$.user,via:"voice",id:`voice:${$.sessionId}`,scopes:Z}});return(await Q.available(W(m9()),J.filter)).filter((X)=>!X.requiresApproval).map((X)=>({tool:{name:X.name,description:X.description,parameters:X.inputSchema},...J.timeoutMs!==void 0?{timeoutMs:J.timeoutMs}:{},run:(Y,V)=>{let G=m9();return p.run(G,async()=>{return await J.authorize?.({name:X.name,input:Y,sessionId:V.sessionId}),Q.execute(W(G),X.name,Y,void 0,{signal:V.signal})},{user:$.user})}}))}function m9(){return new b(new Request(c9,{method:"POST"}),{},"api",new URL(c9).pathname)}class m${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 $=this.records.get(J);return $?structuredClone($):null}async update(J,$){let Q=this.records.get(J);if(!Q)return;this.records.set(J,{...Q,...structuredClone($),id:J})}sweep(){let J=Date.now()-this.retainEndedMs;for(let[$,Q]of this.records)if(Q.endedAt!==void 0&&Q.endedAt<J)this.records.delete($)}}var p$=new m$;var p9=new WeakMap,l9=100;class l${threadsTable;messagesTable;scope=null;sql;dialect;connection;options;constructor(J,$={}){this.threadsTable=d9($.threadsTable??"gemi_agent_threads","threads"),this.messagesTable=d9($.messagesTable??"gemi_agent_messages","messages"),this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name,this.options=$}forScope(J){if(typeof J!=="string"||J==="")throw TypeError("A DatabaseAgentStore scope is a non-empty string.");let $=new l$({sql:this.sql,dialect:this.dialect,name:this.connection},this.options);return $.scope=J,$}async createTable(){let J=C0(this.dialect,this.threadsTable,this.messagesTable);for(let $ of J)await this.sql.unsafe($);await this.addScopeColumns()}async addScopeColumns(){let J=O0(this.dialect,this.threadsTable,this.messagesTable);for(let[$,Q]of J){if(await this.hasColumn($,"scope"))continue;for(let Z of Q)await this.sql.unsafe(Z)}}async hasColumn(J,$){try{return await this.sql.unsafe(`SELECT ${$} FROM ${this.quote(J)} WHERE 1 = 0`),!0}catch{return!1}}async createThread(J){let $=crypto.randomUUID(),Q=J.userId===void 0||J.userId===null?null:String(J.userId);return await this.run(async(Z)=>{let W=this.clock(Z);if(this.scope===null)await Z`
147
147
  INSERT INTO ${this.threads(Z)} (id, user_id, created_at, updated_at)
148
148
  VALUES (${$}, ${Q}, ${W}, ${W})
149
149
  `;else await Z`
@@ -264,4 +264,4 @@ return 0`;class t${injectedClient;prefix;constructor(J={}){this.injectedClient=J
264
264
 
265
265
  `)||void 0,L=await this.context(J,{body:V}),_=await this.reasoning(J,{body:V})||void 0,R=await this.skills(J,{body:V})||void 0,A=await this.runTools(J,{body:V,context:L})||void 0,x=await this.usageLimits(J,{body:V,context:L})||void 0,f=await this.attachmentsFor(J,Z,{body:V}),q=this.agent.memory?await this.memoryScopes(J,{body:V}):void 0;if(H?.cancelled)return _Q();let O=Z?new J8(this.store,Z,N,(E)=>this.reportHookFailure(E)):null,C=`run_${crypto.randomUUID()}`,M={req:J,runId:C,threadId:Z},w={id:null,notified:Promise.resolve()},I=this.agent.stream({runId:C,messages:N,turn:K,threadId:Z,...O?{onMessage:(E)=>O.finish(E)}:{},onTurn:(E)=>{if(w.id!==null)return;w.id=E.id;let a=O?O.settled():Promise.resolve();w.notified=a.then(()=>this.safely(()=>this.onMessage(E,M)))},instructions:U,...Q8.has(J)?{event:Q8.get(J)}:{},...ZJ.has(J)?{echoTurn:!0}:{},..._?{reasoning:_}:{},...R&&R.length>0?{skills:R}:{},...A?.tools&&A.tools.length>0?{tools:A.tools}:{},...A?.activeTools?{activeTools:A.activeTools}:{},...x?{usageLimits:x}:{},context:L,attachments:f,body:V,redactError:(E,a)=>this.redactError(E,a,M),onProviderRetry:(E)=>this.onProviderRetry(E,M),nonces:this.nonces,receipts:this.receipts,subject:G,...q?{memory:{scopes:q,...this.memoryMaxTokens!==void 0?{maxTokens:this.memoryMaxTokens}:{}}}:{},...Z?{jobs:{owner:G}}:{},...this.contextWindow!==void 0?{contextWindow:this.contextWindow}:{},...Z&&pQ(this.store)?{summaryStore:this.store}:{},...this.prepareStep!==F8.prototype.prepareStep||this.hooks?.prepareStep?{prepareStep:(E)=>this.prepareStep(E,M)}:{}}),J$=this.liveRuns.register(I,{threadId:Z,owner:G,clientRunId:Y,onEvent:(E)=>this.dispatchEvent(E,M),onInternalError:(E)=>this.reportHookFailure(E),maxRunDurationMs:this.agent.maxRunDurationMs});if(D=I,O)this.follow(I,O);if(Z)p0(this.liveRuns,Z,I.runId);let{stored:$$,hooks:P8}=this.persistRun(I,M,J$,O,w);if($8.set(I,$$),ZJ.has(J))ZJ.set(J,{run:I,hooks:P8});return J.ctx?.()?.waitUntil(P8),I.toResponse()};try{await this.authorizeRequest(J,{route:"stream",threadId:Z,body:V});let N=await this.foreignFile([...K?.files??[],...Z?[]:K6(Q.messages)],G);if(N)return N;if(H?.cancelled)return _Q();let P=await this.runLimitKey(J,{owner:G,threadId:Z}),U=P===null?KJ:l0(this.liveRuns).take(P,Z?`thread:${Z}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!U)return Y8(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,G,F,FQ.get(J)??"supersede"):await F()}finally{let L=D;if(L)L.result().then(U,U);else U()}}finally{if(H&&nJ.get(Y)===H)nJ.delete(Y)}}async withThread(J,$,Q,Z="supersede"){if(Z==="skip"&&OJ.has(J))return MQ(J);for(;;){let W=await this.underThreadLock(J,$,Q,Z);if(!("waitFor"in W))return W.response;await W.waitFor}}async underThreadLock(J,$,Q,Z){let W=OJ.get(J)??Promise.resolve(),K,X=new Promise((V)=>{K=V}),Y=W.then(()=>X);OJ.set(J,Y),await W;try{let V=await this.liveRuns.find({threadId:J});if(V&&Z!=="supersede"&&this.liveRuns.isRunning(V.runId)){if(Z==="skip")return{response:MQ(J)};let H=this.liveRuns.get(V.runId),D=H?$8.get(H)??H.result():null;if(D)return{waitFor:D.then(KJ,KJ)}}if(V&&this.liveRuns.isRunning(V.runId)&&!this.liveRuns.mayAccess(V.runId,$))return{response:MJ()};let G=V?this.liveRuns.get(V.runId):null;if(G)G.stop({reason:"superseded by a later turn on this thread"}),await $8.get(G);return{response:await Q()}}finally{if(K(),OJ.get(J)===Y)OJ.delete(J)}}async attach(J=new b){let $=await WJ(J,_J);if($.error)return s($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:OQ(J,"threadId");if(!Z)return S(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});if(await this.authorizeRequest(J,{route:"attach",threadId:Z}),!await this.threadInScope(J,Z))return EQ(Z);let W=await this.liveRuns.find({threadId:Z});if(W&&!this.liveRuns.mayAccess(W.runId,await this.runOwner(J)))return MJ();if(!W)return EQ(Z);let K=typeof Q.runId==="string"?Q.runId:void 0,X=K&&K!==W.runId?void 0:$6(J,Q);try{return bQ(this.liveRuns.replay(W.runId,X))}catch(Y){if(Y instanceof QJ)return S(410,{code:Y.code,message:Y.message,oldestSeq:Y.oldest});if(Y instanceof LJ)return S(404,{code:Y.code,message:Y.message});throw Y}}async watch(J=new b){let $=await WJ(J,_J);if($.error)return s($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:OQ(J,"threadId");if(!Z)return S(400,{code:"invalid_request",message:"watch needs a threadId: it is the thread whose runs are announced."});if(await this.authorizeRequest(J,{route:"attach",threadId:Z}),!await this.threadInScope(J,Z))return S(404,{code:"thread_not_found",message:`Thread ${Z} does not exist here, or has expired.`});let W=await this.runOwner(J),K=this.liveRuns,X=m0(K),Y=await K.find({threadId:Z}),V=null,G=null,H=0,D=()=>{if(G?.stop(),!V)return;let F=X.get(Z);if(F?.delete(V),F&&F.size===0)X.delete(Z);V=null},z=new ReadableStream({start(F){G=wQ(F);let B=(P)=>{if(!K.mayAccess(P,W))return;try{F.enqueue(new TextEncoder().encode(IQ({seq:++H,event:{type:"run-start",runId:P,threadId:Z}}))),G?.touch()}catch{D()}};V=B;let N=X.get(Z);if(!N)N=new Set,X.set(Z,N);if(N.add(B),Y&&K.isRunning(Y.runId))B(Y.runId)},cancel(){D()}});return J.rawRequest?.signal?.addEventListener("abort",D,{once:!0}),new Response(z,{status:200,headers:qQ()})}async stop(J=new b){let $=await WJ(J,_J);if($.error)return s($);let Q=$.body;await this.authorizeRequest(J,{route:"stop",threadId:typeof Q.threadId==="string"?Q.threadId:void 0});let Z=await this.runOwner(J),W=typeof Q.runId==="string"?Q.runId:void 0;if(!W&&typeof Q.clientRunId==="string"){if(W=this.liveRuns.findByClientRunId(Q.clientRunId)??void 0,!W){let X=nJ.get(Q.clientRunId);if(X){if(X.owner!==null&&X.owner!==Z)return MJ();return X.cancelled=!0,{stopped:!0}}}}if(!W&&typeof Q.threadId==="string")W=(await this.liveRuns.find({threadId:Q.threadId}))?.runId;let K=W?this.liveRuns.get(W):null;if(!K)return{stopped:!1};if(!this.liveRuns.mayAccess(K.runId,Z))return MJ();return K.stop({reason:typeof Q.reason==="string"?Q.reason:void 0}),{stopped:!0}}attachmentScope(J,$,Q){let Z=this.hooks?.attachmentScope;if(Z)return Z(J,$,Q);let W=J.ctx()?.user,K=W?.id??W?.publicId;if(K!==void 0&&K!==null&&String(K)!=="")return{key:`user:${String(K)}`};if($)return{key:`thread:${$}`};return null}attachmentLimits(J){let $=this.hooks?.attachmentLimits;if($)return $(J);return null}checkUpload(J,$,Q){return this.hooks?.checkUpload?.(J,$,Q)}attachmentDestination(J,$,Q){let Z=this.hooks?.attachmentDestination;if(Z)return Z(J,$,Q);return"both"}async attachmentsFor(J,$,Q={body:{}}){let Z=await this.attachmentScope(J,$,Q);if(!Z)return null;return new tJ(this.attachments,this.attachmentStorage,Z)}async voiceStart(J=new b){let $=this.voice;if(!$)return Z8();let Q=await WJ(J,_J);if(Q.error)return s(Q);let{sdp:Z,threadId:W,pushToTalk:K}=Q.body;if(typeof Z!=="string"||!Z.trimStart().startsWith("v="))return S(400,{code:"invalid_request",message:"`sdp` must be the browser's SDP offer."});let X=oJ(Q.body,X6),Y=typeof W==="string"&&W!==""?W:void 0;await this.authorizeRequest(J,{route:"stream",threadId:Y,body:X});let V=J.ctx?.()?.user??null,G=await $.start({req:J,body:X,threadId:Y,user:V,pushToTalk:K===!0}),H=Date.now(),D,z=async(L)=>{if(L!==void 0)console.error("[gemi/ai] a voice session could not start.",L);if(D)await $.realtime.hangup(D).catch((_)=>{console.error("[gemi/ai] a voice call that failed to start could not be hung up.",_)});try{await G.onEnd?.({sessionId:"",...D?{callId:D}:{},threadId:G.threadId??Y??"",reason:"start_failed",startedAt:H,endedAt:Date.now(),durationMs:0,seconds:0,usage:j(),transcription:{usage:j(),seconds:0},transcript:[],requests:[],toolCalls:[],errors:[]})}catch(_){console.error("[gemi/ai] a voice session's onEnd threw.",_)}},F=G.threadId??Y;if(!F)return await z(void 0),S(400,{code:"invalid_request",message:"A voice session needs a thread: send `threadId`, or answer one from `voice.start`."});try{if(F!==Y)await this.authorizeRequest(J,{route:"stream",threadId:F,body:X})}catch(L){throw await z(void 0),L}let B=crypto.randomUUID(),N=G.tools??[];try{if(G.mcp)N=[...N,...await c$(G.mcp,{user:V,sessionId:B})]}catch(L){return await z(L),S(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}let P={...G.session,tools:[...UJ($.delegate),...G.session?.tools??[],...N.map((L)=>L.tool)],...K===!0?{turnDetection:null}:{}},U;try{U=await $.realtime.createCall({sdp:Z,session:P,safetyIdentifier:G.safetyIdentifier})}catch(L){await z(L);let _=L instanceof g&&L.code==="rate_limited";return S(_?429:502,{code:"voice_unavailable",message:"Voice isn't available right now."})}D=U.callId;try{await this.voiceStore.create({id:B,callId:U.callId,threadId:F,owner:await this.runOwner(J),body:X,startedAt:H});let{threadId:L,session:_,safetyIdentifier:R,mcp:A,tools:x,...f}=G;return{sessionId:o.start({...f,tools:N,controller:this.constructor,threadId:F,user:V,body:X,call:{realtime:$.realtime,callId:U.callId},sessionId:B,store:this.voiceStore,liveRuns:this.liveRuns,delegate:$.delegate,session:P}).sessionId,sdp:U.sdpAnswer,threadId:F,delegate:$.delegate?.name??NJ,endsAt:H+(G.limits?.maxDurationMs??900000)}}catch(L){return await z(L),S(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}}async voiceUpdate(J=new b){if(!this.voice)return Z8();let $=await this.voiceSession(J);if($ instanceof Response)return $;let Q=await WJ(J,_J);if(Q.error)return s(Q);let Z=oJ(Q.body,[]);if(await this.authorizeRequest(J,{route:"stream",threadId:$.threadId,body:Z}),$.endedAt!==void 0)return S(409,{code:"voice_ended",message:"This voice session has ended."});return await this.voiceStore.update($.id,{body:Z}),o.get($.id)?.setBody(Z),{updated:!0}}async voiceEnd(J=new b){let $=this.voice;if(!$)return Z8();let Q=await this.voiceSession(J);if(Q instanceof Response)return Q;if(await this.authorizeRequest(J,{route:"stream",threadId:Q.threadId,body:Q.body}),Q.endedAt!==void 0)return{ended:!1};let Z=o.get(Q.id);if(Z)await Z.end("hangup");else await $.realtime.hangup(Q.callId),await this.voiceStore.update(Q.id,{endedAt:Date.now(),endReason:"hangup"});return{ended:!0}}async voiceSession(J){let $=J.params?.sessionId,Q=typeof $==="string"&&$?await this.voiceStore.get($):null;if(!Q)return S(404,{code:"voice_not_found",message:"No such voice session."});if(Q.owner!==null&&Q.owner!==await this.runOwner(J))return MJ();return Q}async upload(J=new b){let $=await J.rawRequest.formData(),Q=$.get("file");if(!(Q instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let Z=Q instanceof File&&Q.name?Q.name:"upload",W=Q.type||"application/octet-stream",K=n0($.get("body")),X=$.get("threadId");await this.authorizeRequest(J,{route:"upload",threadId:typeof X==="string"&&X.length>0?X:void 0,body:K});let Y=s0(await this.attachmentLimits(J),Q,Z,W);if(Y)throw new G8(Y.code,Y.message);await this.scopeStore(J,K);let V=typeof X==="string"&&X.length>0&&await this.store.loadThread(X)!==null?X:void 0,G=await this.runOwner(J),H=(A)=>this.fileOwners.record(A,{owner:G,name:Z,mimeType:W,size:Q.size,createdAt:new Date().toISOString()}),D={body:K,threadId:V},z=await this.checkUpload({name:Z,size:Q.size,mimeType:W},J,D);if(z)throw new G8(z.code||"upload_refused",z.message);let F=await this.attachmentDestination(Q,J,D),B=G6(F,$.get("destination")),N=await this.attachmentScope(J,V,{body:K}),P=B!=="provider"&&!N;if(P){if(B==="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()`.');Y6()}if(B==="provider"||!N){let A=await NQ(this.agent.provider,Q);await H(A);let x={fileId:A,name:Z,mimeType:W,size:Q.size,destination:"provider"};if(P)x.downgraded="no_scope";return x}let U=uQ(),L=await this.attachmentStorage.put({name:cQ(U,Z),body:Q,contentType:W}),_=B==="both"?await NQ(this.agent.provider,Q):void 0;if(_)await H(_);let R={id:U,scopeKey:N.key,fileId:_,objectName:L,name:Z,mimeType:W,size:Q.size,createdAt:new Date().toISOString(),destination:B};return await this.attachments.put(N,R),{fileId:_,attachmentId:U,name:Z,mimeType:W,size:Q.size,destination:B}}async foreignFile(J,$){let Q=new Set(J.map((Z)=>Z.fileId).filter((Z)=>typeof Z==="string"));for(let Z of Q){let W=await this.fileOwners.get(Z);if(W?W.owner!==null&&W.owner!==$:this.requireKnownFiles)return W6()}return null}onMessage(J,$){return this.hooks?.onMessage?.(J,$)}onToolCall(J,$){return this.hooks?.onToolCall?.(J,$)}onToolResult(J,$,Q){return this.hooks?.onToolResult?.(J,$,Q)}onAwaitingInput(J,$){return this.hooks?.onAwaitingInput?.(J,$)}redactError(J,$,Q){let Z=this.hooks?.redactError;if(Z)return Z(J,$,Q);return z8(J,$)}onError(J,$){return this.hooks?.onError?.(J,$)}onProviderRetry(J,$){return this.hooks?.onProviderRetry?.(J,$)}onStreamComplete(J,$){return this.hooks?.onStreamComplete?.(J,$)}reportHookFailure(J){let $=this.hooks?.reportHookFailure;if($)try{return $(J)}catch(Q){console.error("[gemi/ai] reportHookFailure hook failed",Q)}console.error("[gemi/ai] agent controller hook failed",J)}async dispatchEvent(J,$){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},$);return;case"tool-result":{let Q=J.part;await this.onToolResult(Q,$,{toolCallId:Q.toolCallId,name:String(Q.name),input:dQ(Q)});return}case"awaiting-input":await this.onAwaitingInput(J.pending,$);return;case"error":await this.onError(vQ(J.error),$);return;default:return}}async readThread(J,$={}){let Z=await($.scope===null||$.scope===void 0?this.store:RQ(this.store,$.scope)).loadThread(J);if(!Z)return null;let{messages:W}=await this.settleThread(J,Z,{write:!1});return W}isRunLive(J,$){return this.liveRuns.get(J)!==null}async settleThread(J,$,{write:Q}){let Z=(V)=>this.isRunLive(V,J),W=await XQ($,Z),K=W.messages,X=[],Y=new Map(W.settled.map((V)=>[V.id,V]));if(D6(K)||Q)try{let V=await HQ(K,{threadId:J,store:c.store,isRunLive:Z,outputSchemaFor:(G)=>this.toolNamed(G)?.outputSchema,modelOutputFor:(G,H)=>lQ(this.toolNamed(G),H,(D)=>this.reportHookFailure(D)),scan:this.jobsBlockMax()});K=V.messages,X=V.jobs;for(let G of V.settled)Y.set(G.id,G);if(Q&&V.orphans.length>0){await zQ(c.store,V.orphans,(H)=>this.reportHookFailure(H));let G=new Set(V.orphans.map((H)=>H.id));X=X.map((H)=>G.has(H.id)?{...H,orphaned:!0}:H)}}catch(V){this.reportHookFailure(V)}if(Q&&Y.size>0)try{await this.store.appendMessages(J,[...Y.values()])}catch(V){this.reportHookFailure(V)}return{messages:K,jobs:X}}jobsBlockMax(){let J=this.agent.jobs?.contextBlock;if(J===!1)return 0;return J?.max??EJ}jobsBlock(J){return S8(J,this.jobsBlockMax())}toolNamed(J){let $=(Q)=>{for(let Z of Q){let W=Z;if(Array.isArray(W.tools)){let K=$(W.tools);if(K)return K}else if(W.name===J)return W}return};return $(this.agent.tools??[])}follow(J,$){(async()=>{try{for await(let Q of J.frames())$.frame(Q)}catch(Q){this.reportHookFailure(Q)}})()}persistRun(J,$,Q,Z=null,W={id:null,notified:Promise.resolve()}){let K=Promise.resolve(),X=(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},$)));return}let G=V.messages;if(Z?.close(G),await Z?.settled(),$.threadId&&G.length>0)try{await this.store.appendMessages($.threadId,G)}catch(H){this.reportHookFailure(H)}K=this.notifyRun(V,G,$,W)})(),Y=X.then(()=>H6(Promise.all([K,Q]).then(()=>{}),this.hookHoldMs));return{stored:X,hooks:Y}}async notifyRun(J,$,Q,Z){await Z.notified;for(let W of $){if(W.id===Z.id)continue;await this.safely(()=>this.onMessage(W,Q))}await this.safely(()=>this.onStreamComplete(J,Q))}async safely(J){try{await J()}catch($){this.reportHookFailure($)}}}var K8=["turn","clientRunId","threadId","messages","regenerate"],i0=["text","files","toolResults"];function oJ(J,$=sQ(J)?K8:[...K8,...i0]){let Q={};for(let[Z,W]of Object.entries(J)){if($.includes(Z))continue;Object.defineProperty(Q,Z,{value:W,writable:!0,enumerable:!0,configurable:!0})}return Q}function n0(J){if(J===null)return{};let $;if(typeof J==="string")try{$=JSON.parse(J)}catch{throw new X8("The upload's `body` field is not valid JSON.")}if($===null||typeof $!=="object"||Array.isArray($))throw new X8("The upload's `body` field must be a JSON object.");return oJ($,K8)}class X8 extends sJ{constructor(J){super(J);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:J}}},view:{}}}}async function NQ(J,$){try{return await J.upload($)}catch(Q){if(Q instanceof y&&o0.has(Q.status))throw new oQ(T(Q).message);throw Q}}var o0=new Set([400,413,415,422]);class G8 extends sJ{constructor(J,$){super($);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:J,message:$}}},view:{}}}}function s0(J,$,Q,Z){if(!J)return null;let{maxBytes:W,accept:K}=J;if(typeof W==="number"&&$.size>W)return{code:"file_too_large",message:`${JSON.stringify(Q)} is ${BQ($.size)}; the limit is ${BQ(W)}.`};if(K&&K.length>0&&!K.some((X)=>a0(X,Q,Z)))return{code:"unsupported_file_type",message:`${JSON.stringify(Q)} is not a type this chat accepts. Accepted: ${K.join(", ")}.`};return null}function a0(J,$,Q){let Z=J.trim().toLowerCase();if(!Z)return!1;if(Z.startsWith("."))return $.toLowerCase().endsWith(Z);let W=Q.toLowerCase().split(";")[0].trim();if(Z.endsWith("/*"))return W.startsWith(Z.slice(0,-1));return W===Z}function BQ(J){if(J<1024)return`${J} B`;let $=["KB","MB","GB"],Q=J/1024,Z=0;while(Q>=1024&&Z<$.length-1)Q/=1024,Z++;return`${Math.round(Q*10)/10} ${$[Z]}`}class oQ extends sJ{constructor(J){super(J);this.name="RejectedUploadError";let $=/(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:$,message:J}}},view:{}}}}async function WJ(J,$){let Q=J?.rawRequest;if(!Q||Q.method==="GET"||Q.method==="HEAD"||!Q.body)return{body:{}};if(!t0(Q.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(Q.headers.get("Content-Length"));if(Number.isFinite(Z)&&Z>$)return LQ($);let W;try{let X=await r0(Q,$);if(X===null)return LQ($);W=X}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 t0(J){return TQ(J)==="application/json"}async function r0(J,$){if(!Number.isFinite($)||!J.body)return await J.text();let Q=J.body.getReader(),Z=[],W=0;for(;;){let{done:Y,value:V}=await Q.read();if(Y)break;if(W+=V.byteLength,W>$)return await Q.cancel().catch(KJ),null;Z.push(V)}let K=new Uint8Array(W),X=0;for(let Y of Z)K.set(Y,X),X+=Y.byteLength;return new TextDecoder().decode(K)}function LQ(J){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${J} bytes).`}}function Y8(J,$,Q){return S(J,{...aJ(kQ(J),Q,J),code:$})}function s(J){if(J.status===413)return Y8(413,J.code??"body_too_large",J.error??"");return S(J.status??400,{code:J.code??"invalid_request",message:J.error})}function sQ(J){return Boolean(J.turn)&&typeof J.turn==="object"}function e0(J){let $=sQ(J)?J.turn:J,Q={};if(typeof $.text==="string")Q.text=$.text;if(Array.isArray($.files)){let Z=J6($.files);if(typeof Z==="string")return{error:Z};Q.files=Z}if(Array.isArray($.toolResults))Q.toolResults=$.toolResults;if(Object.keys(Q).length===0)return{};if($===J.turn&&$.localId!==void 0&&$.localId!==null&&$.localId!==""){let{localId:Z}=$;if(typeof Z!=="string")return{error:"turn.localId must be a string."};if(Z.length>CQ)return{error:`turn.localId is longer than ${CQ} characters.`};Q.localId=Z}return{turn:Q}}var CQ=200;function J6(J){let $=[];for(let[Q,Z]of J.entries()){let W=`turn.files[${Q}]`;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:X,attachmentId:Y,name:V,mimeType:G}=K;if(X?.startsWith(n))return`${W}.fileId holds a gemi attachment id (${X}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(Y!==void 0&&!Y.startsWith(n))return`${W}.attachmentId is not a gemi attachment id: it must start with "${n}".`;if(!X&&!Y)return`${W} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;$.push({...X?{fileId:X}:{},...Y?{attachmentId:Y}:{},...V!==void 0?{name:V}:{},...G!==void 0?{mimeType:G}:{}})}return $}function $6(J,$){if(typeof $.from==="number"&&Number.isFinite($.from))return Math.max(0,Math.floor($.from));if(typeof $.cursor==="number"&&Number.isFinite($.cursor)){let Z=Math.floor($.cursor);if(Z>=0)return Z+1;return}let Q=J?.rawRequest?.headers?.get("Last-Event-ID");if(Q){let Z=Number.parseInt(Q,10);if(Number.isFinite(Z))return Math.max(0,Z+1)}return}function OQ(J,$){let Q=J?.search?.get($);return typeof Q==="string"?Q:void 0}function Q6(J){let $=D8(J);for(let Q=J.length-1;Q>=0;Q--){let Z=J[Q];if(Z.role!=="user"||$.has(Z.id))continue;let W="",K=[];for(let X of Z.content){if(X.type==="text")W+=X.text;if(X.type==="file")K.push({...X.fileId?{fileId:X.fileId}:{},...X.attachmentId?{attachmentId:X.attachmentId}:{},...X.name?{name:X.name}:{},...X.mimeType?{mimeType:X.mimeType}:{}})}if(!W&&K.length===0)continue;return{index:Q,turn:{...W?{text:W}:{},...K.length>0?{files:K}:{}}}}return null}function _Q(){return S(409,{code:"stopped",message:"The turn was stopped before it started."})}function Z6(J){let $=J.event;if(J.text!==void 0||J.turn!==void 0)throw TypeError("AgentController.startTurn takes an `event` or a `text`/`turn`, not both: an event is not a person's message.");if(typeof $!=="object"||$===null||typeof $.name!=="string"||!y0.test($.name))throw TypeError('AgentController.startTurn\'s `event.name` must be letters, digits and `.`, `_`, `:`, `-` (at most 64), like "job-settled".');if($.text!==void 0&&typeof $.text!=="string")throw TypeError("AgentController.startTurn's `event.text` must be a string.");let Q;if($.data!==void 0)try{Q=JSON.parse(JSON.stringify($.data))}catch(Z){throw TypeError(`AgentController.startTurn's \`event.data\` is not JSON: ${String(Z)}`)}return{name:$.name,...$.text?{text:$.text}:{},...Q!==void 0?{data:Q}:{}}}function MQ(J){return S(409,{code:iQ,message:`Thread ${J} has a run going, and this turn was not to interrupt it.`})}function MJ(){return S(403,aJ("permission","This run belongs to someone else.",403))}function W6(){return S(403,aJ("permission","A file in this turn was uploaded by someone else.",403))}function K6(J){if(!Array.isArray(J))return[];let $=[];for(let Q of J){let Z=Q?.content;if(!Array.isArray(Z))continue;for(let W of Z)if(W&&typeof W==="object"&&typeof W.fileId==="string")$.push({fileId:W.fileId})}return $}var X6=["sdp","threadId","pushToTalk"];function Z8(){return S(404,{code:"voice_not_enabled",message:"This agent has no voice: set `voice` on its controller."})}function S(J,$){return new Response(JSON.stringify({error:$}),{status:J,headers:{"Content-Type":"application/json"}})}function G6(J,$){if(typeof $!=="string"||$.length===0)return J;if($!=="both"&&$!=="provider"&&$!=="storage")throw Error(`Unknown attachment destination "${$}". Expected "both", "provider" or "storage".`);if($===J||J==="both"&&$==="storage")return $;if(J==="both"&&$==="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 "${$}" 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 SQ=!1;function Y6(){if(SQ)return;SQ=!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 V6=2147483647;function H6(J,$){let Q=J.then(()=>{},()=>{});if(!($<=V6))return Q;let Z,W=new Promise((K)=>{Z=setTimeout(K,$)});return Promise.race([Q,W]).finally(()=>clearTimeout(Z))}var AQ=!1;function z6(J){if(AQ||Bun.env.NODE_ENV!=="production")return;if(!(J instanceof V8))return;AQ=!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 D6(J){return J.some(($)=>$.content.some((Q)=>Q.type==="tool-result"&&Q.status==="running"))}function RQ(J,$){if(typeof $!=="string"||$==="")throw TypeError("A store scope is a non-empty string.");if(!J.forScope)throw Error("This controller's store cannot be scoped: storeScope() or a turn's `scope` needs a store that implements `forScope` (DatabaseAgentStore or MemoryAgentStore).");return J.forScope($)}function EQ(J){return S(404,{code:"no_live_run",message:`No run in progress for thread ${J} in this process.`})}export{M6 as windowMessages,UJ as voiceTools,B6 as turnStarts,hJ as toRealtimeUsage,BZ as toAgentTools,U6 as supportsStrict,L6 as splitTurns,T6 as settleSummaries,P6 as s,z8 as redactError,h6 as parsePartialJson,C6 as messageSize,HJ as measureUsage,c$ as mcpVoiceTools,i$ as liveRuns,BJ as keepSummary,y9 as isCallNotFound,D8 as injectedMessageIds,N$ as generate,z0 as evalChain,d0 as defineAgentHooks,p$ as defaultVoiceStore,I6 as defaultUsageLimitStore,k6 as defaultSummaryStore,H8 as defaultNonceStore,n$ as defaultFileOwners,rJ as defaultAttachmentStore,r$ as defaultAgentStore,lJ as VoiceHangup,o as VoiceBridge,N6 as Usage,L$ as ToolNamespace,l as ToolError,q6 as Skill,tJ as ScopedAttachments,b6 as SKILLS_NAMESPACE,t$ as RedisReceiptStore,fQ as RedisNonceStore,gJ as RealtimeSideband,g as RealtimeRequestError,FJ as RealtimeClient,O8 as Prompt,yQ as PrismaNonceStore,w6 as PendingEscalation,v$ as OpenAIProvider,S$ as OpenAIImageProvider,m$ as MemoryVoiceSessionStore,x6 as MemoryUsageLimitStore,j6 as MemorySummaryStore,a$ as MemoryReceiptStore,V8 as MemoryNonceStore,dJ as MemoryLiveRuns,iJ as MemoryFileOwners,mJ as MemoryCircuitStore,mQ as MemoryAttachmentStore,CJ as MemoryAgentStore,E8 as MemoryAgentJobStore,p8 as MEMORY_NAMESPACE,LJ as LiveRunNotFoundError,k8 as JobsRequireThreadError,j8 as JobHandle,F6 as JSONSchemaError,gQ as InvalidAttachmentScopeError,v8 as InMemoryAgentMemoryStore,fJ as ImageRequestError,yJ as ImageProvider,C$ as ImageModel,QJ as FrameCursorEvictedError,PJ as FallbackProvider,c8 as FakeAgentMemoryStore,IJ as Eval,l$ as DatabaseAgentStore,H$ as DatabaseAgentMemoryStore,Y$ as DatabaseAgentJobStore,b9 as DEFAULT_TRANSCRIPTION_MODEL,y8 as DEFAULT_MEMORY_MAX_TOKENS,m8 as DEFAULT_MEMORY_LIMITS,S6 as DEFAULT_MAX_SUMMARY_TOKENS,f6 as DEFAULT_MAX_RUN_DURATION_MS,T8 as DEFAULT_JOB_DEADLINE_MS,EJ as DEFAULT_JOBS_CONTEXT_MAX,NJ as DEFAULT_DELEGATE_NAME,O6 as DEFAULT_CONTEXT_WINDOW_STEP,_6 as DEFAULT_CONTEXT_WINDOW_NOTE,A6 as DEFAULT_COMPACT_TRIGGER_TOKENS,R6 as DEFAULT_COMPACT_INSTRUCTIONS,E6 as COMPACT_SUMMARY_HEADER,h$ as AzureOpenAIProvider,A$ as AzureOpenAIImageProvider,hQ as AttachmentNotFoundError,eJ as AgentTurnError,wJ as AgentTool,y6 as AgentRunError,$J as AgentProvider,h8 as AgentMemoryRefusedError,g8 as AgentMemoryConflictError,u8 as AgentMemories,c as AgentJobs,K$ as AgentJobDeadlineSweep,x8 as AgentJob,F8 as AgentController,v6 as Agent};
266
266
 
267
- //# debugId=57A50FCE9BAD468464756E2164756E21
267
+ //# debugId=F8D8BBBC3BCAB23A64756E2164756E21