gemi 0.66.0 → 0.67.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/ai/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Ib as X$,Jb as r}from"../chunk-hq496pa4.js";import{Ce as m6,Te as g,ef as p6}from"../chunk-a85fn4zf.js";import"../chunk-g2ywq30n.js";import"../chunk-pcxxnnad.js";import"../chunk-p5m0da00.js";import"../chunk-5g1j29p2.js";import"../chunk-r6v21jn6.js";import{createHmac as i6,randomBytes as lQ,timingSafeEqual as dQ}from"crypto";var zQ="agt1",iQ=86400000;function m(Q){let $=Q??process.env.SECRET;if(!$)throw Error("Signing a pending tool call needs an app secret. Set SECRET in the environment.");return $}function q(Q){if(Q===null||typeof Q!=="object")return JSON.stringify(Q)??"null";if(Array.isArray(Q))return`[${Q.map(q).join(",")}]`;let $=Q;return`{${Object.keys($).filter((J)=>$[J]!==void 0).sort().map((J)=>`${JSON.stringify(J)}:${q($[J])}`).join(",")}}`}function n6(Q){return Q.map(($)=>`${$.length}:${$}`).join("")}function p(Q,$){return i6("sha256",Q).update(n6($)).digest()}function nQ(Q,$,Z){let J=[zQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(Z),q(Q.input)];if(Q.path&&Q.path.length>0)J.push(q(Q.path));return J}var oQ=(Q)=>Buffer.from(Q,"utf8").toString("base64url"),o6=(Q)=>Buffer.from(Q,"base64url").toString("utf8");function sQ(Q,$={}){let Z=m($.secret),G=($.now??Date.now())+($.ttlMs??iQ),W=lQ(12).toString("base64url"),Y=p(Z,nQ(Q,W,G)).toString("base64url");return[zQ,oQ(Q.runId),W,G.toString(36),Y].join(".")}function l(Q){return FQ(Q,zQ)}function FQ(Q,$){let Z=Q.split(".");if(Z.length!==5||Z[0]!==$)return null;let J=Number.parseInt(Z[3],36);if(!Number.isFinite(J))return null;try{return{runId:o6(Z[1]),nonce:Z[2],expiresAt:J}}catch{return null}}function tQ(Q,$,Z={}){let J=m(Z.secret),G=l(Q);if(!G)return{ok:!1,reason:"malformed"};let W=Buffer.from(Q.split(".")[4],"base64url"),Y=p(J,nQ($,G.nonce,G.expiresAt));if(W.length!==Y.length||!dQ(W,Y))return{ok:!1,reason:"forged"};if((Z.now??Date.now())>G.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:G.runId,nonce:G.nonce,expiresAt:G.expiresAt}}var d="agn1";function aQ(Q,$,Z){return[d,Q.runId,q(Q.path),Q.nestedRunId,$,String(Z),q([...Q.open].sort()),q(Q.input)]}function rQ(Q,$={}){let Z=m($.secret),G=($.now??Date.now())+($.ttlMs??iQ),W=lQ(12).toString("base64url"),Y=p(Z,aQ(Q,W,G)).toString("base64url");return[d,oQ(Q.runId),W,G.toString(36),Y].join(".")}function eQ(Q,$,Z={}){let J=m(Z.secret),G=FQ(Q,d);if(!G)return{ok:!1,reason:"malformed"};let W=Buffer.from(Q.split(".")[4],"base64url"),Y=p(J,aQ({...$,runId:G.runId},G.nonce,G.expiresAt));if(W.length!==Y.length||!dQ(W,Y))return{ok:!1,reason:"forged"};if((Z.now??Date.now())>G.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:G.runId,nonce:G.nonce,expiresAt:G.expiresAt}}var E=new Map,Q6=1024;function s6(Q){for(let[$,Z]of E)if(Z<=Q)E.delete($);Q6=Math.max(1024,E.size*2)}function $6(Q,$={}){return J6(l(Q),$)}function Z6(Q,$={}){return J6(FQ(Q,d),$)}function J6(Q,$){if(!Q)return!1;let Z=$.now??Date.now();if(E.size>=Q6)s6(Z);let J=E.get(Q.nonce);if(J!==void 0&&J>Z)return!1;return E.set(Q.nonce,Q.expiresAt),!0}class v extends Error{id;code="attachment_not_found";constructor(Q){super(`No attachment ${Q}.`);this.id=Q;this.name="AttachmentNotFoundError"}}class A extends Error{code="invalid_attachment_scope";constructor(Q){super(Q);this.name="InvalidAttachmentScopeError"}}function LQ(Q){if(!Q||typeof Q.key!=="string"||Q.key.length===0)throw new A("An attachment scope needs a non-empty key. Return `null` from `attachmentScope()` for a request that has no subject \u2014 an empty key is a bucket every caller shares.");return Q}var N="gemi_att_";function CQ(){return`${N}${crypto.randomUUID()}`}class f{store;storage;scope;constructor(Q,$,Z){this.store=Q;this.storage=$;this.scope=Z;LQ(Z)}async get(Q){let $=await this.store.find(this.scope,Q);if(!$||$.scopeKey!==this.scope.key)throw new v(Q);return $}async read(Q){return await this.readRecord(Q,await this.get(Q))}async readRecord(Q,$){if(!$.objectName)throw new v(Q);return await this.storage.read({name:$.objectName})}async file(Q){let $=await this.get(Q),J=(await this.readRecord(Q,$)).body,G=J instanceof Blob?J:J?await new Response(J).blob():new Blob([]);return new File([G],$.name,{type:$.mimeType})}async put(Q,$={}){let Z=CQ(),J=$.mimeType??Q.type??"",G=$.name??(Q instanceof File?Q.name:Z),W=await this.storage.put({name:OQ(Z,G),body:Q,contentType:J||void 0}),Y={id:Z,scopeKey:this.scope.key,objectName:W,name:G,mimeType:J||"application/octet-stream",size:Q.size,createdAt:new Date().toISOString(),destination:$.fileId?"both":"storage",...$.fileId?{fileId:$.fileId}:{}};return await this.store.put(this.scope,Y),Y}}function OQ(Q,$){let Z=/\.([A-Za-z0-9]{1,8})$/.exec($);return`attachments/${Q}${Z?`.${Z[1].toLowerCase()}`:""}`}class i{rows=new Map;async put(Q,$){LQ(Q),this.rows.set($.id,{...$,scopeKey:Q.key})}async find(Q,$){LQ(Q);let Z=this.rows.get($);if(!Z||Z.scopeKey!==Q.key)return null;return Z}get size(){return this.rows.size}}var n=new i;var jQ=new TextEncoder;function G6(Q){return`id: ${Q.seq}
2
+ import{Ib as X$,Jb as r}from"../chunk-hq496pa4.js";import{Ce as m6,Te as g,ef as p6}from"../chunk-z7vmrf00.js";import"../chunk-g2ywq30n.js";import"../chunk-pcxxnnad.js";import"../chunk-p5m0da00.js";import"../chunk-5g1j29p2.js";import"../chunk-2dvjj3ad.js";import"../chunk-r6v21jn6.js";import{createHmac as i6,randomBytes as lQ,timingSafeEqual as dQ}from"crypto";var zQ="agt1",iQ=86400000;function m(Q){let $=Q??process.env.SECRET;if(!$)throw Error("Signing a pending tool call needs an app secret. Set SECRET in the environment.");return $}function q(Q){if(Q===null||typeof Q!=="object")return JSON.stringify(Q)??"null";if(Array.isArray(Q))return`[${Q.map(q).join(",")}]`;let $=Q;return`{${Object.keys($).filter((J)=>$[J]!==void 0).sort().map((J)=>`${JSON.stringify(J)}:${q($[J])}`).join(",")}}`}function n6(Q){return Q.map(($)=>`${$.length}:${$}`).join("")}function p(Q,$){return i6("sha256",Q).update(n6($)).digest()}function nQ(Q,$,Z){let J=[zQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(Z),q(Q.input)];if(Q.path&&Q.path.length>0)J.push(q(Q.path));return J}var oQ=(Q)=>Buffer.from(Q,"utf8").toString("base64url"),o6=(Q)=>Buffer.from(Q,"base64url").toString("utf8");function sQ(Q,$={}){let Z=m($.secret),G=($.now??Date.now())+($.ttlMs??iQ),W=lQ(12).toString("base64url"),Y=p(Z,nQ(Q,W,G)).toString("base64url");return[zQ,oQ(Q.runId),W,G.toString(36),Y].join(".")}function l(Q){return FQ(Q,zQ)}function FQ(Q,$){let Z=Q.split(".");if(Z.length!==5||Z[0]!==$)return null;let J=Number.parseInt(Z[3],36);if(!Number.isFinite(J))return null;try{return{runId:o6(Z[1]),nonce:Z[2],expiresAt:J}}catch{return null}}function tQ(Q,$,Z={}){let J=m(Z.secret),G=l(Q);if(!G)return{ok:!1,reason:"malformed"};let W=Buffer.from(Q.split(".")[4],"base64url"),Y=p(J,nQ($,G.nonce,G.expiresAt));if(W.length!==Y.length||!dQ(W,Y))return{ok:!1,reason:"forged"};if((Z.now??Date.now())>G.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:G.runId,nonce:G.nonce,expiresAt:G.expiresAt}}var d="agn1";function aQ(Q,$,Z){return[d,Q.runId,q(Q.path),Q.nestedRunId,$,String(Z),q([...Q.open].sort()),q(Q.input)]}function rQ(Q,$={}){let Z=m($.secret),G=($.now??Date.now())+($.ttlMs??iQ),W=lQ(12).toString("base64url"),Y=p(Z,aQ(Q,W,G)).toString("base64url");return[d,oQ(Q.runId),W,G.toString(36),Y].join(".")}function eQ(Q,$,Z={}){let J=m(Z.secret),G=FQ(Q,d);if(!G)return{ok:!1,reason:"malformed"};let W=Buffer.from(Q.split(".")[4],"base64url"),Y=p(J,aQ({...$,runId:G.runId},G.nonce,G.expiresAt));if(W.length!==Y.length||!dQ(W,Y))return{ok:!1,reason:"forged"};if((Z.now??Date.now())>G.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:G.runId,nonce:G.nonce,expiresAt:G.expiresAt}}var E=new Map,Q6=1024;function s6(Q){for(let[$,Z]of E)if(Z<=Q)E.delete($);Q6=Math.max(1024,E.size*2)}function $6(Q,$={}){return J6(l(Q),$)}function Z6(Q,$={}){return J6(FQ(Q,d),$)}function J6(Q,$){if(!Q)return!1;let Z=$.now??Date.now();if(E.size>=Q6)s6(Z);let J=E.get(Q.nonce);if(J!==void 0&&J>Z)return!1;return E.set(Q.nonce,Q.expiresAt),!0}class v extends Error{id;code="attachment_not_found";constructor(Q){super(`No attachment ${Q}.`);this.id=Q;this.name="AttachmentNotFoundError"}}class A extends Error{code="invalid_attachment_scope";constructor(Q){super(Q);this.name="InvalidAttachmentScopeError"}}function LQ(Q){if(!Q||typeof Q.key!=="string"||Q.key.length===0)throw new A("An attachment scope needs a non-empty key. Return `null` from `attachmentScope()` for a request that has no subject \u2014 an empty key is a bucket every caller shares.");return Q}var N="gemi_att_";function CQ(){return`${N}${crypto.randomUUID()}`}class f{store;storage;scope;constructor(Q,$,Z){this.store=Q;this.storage=$;this.scope=Z;LQ(Z)}async get(Q){let $=await this.store.find(this.scope,Q);if(!$||$.scopeKey!==this.scope.key)throw new v(Q);return $}async read(Q){return await this.readRecord(Q,await this.get(Q))}async readRecord(Q,$){if(!$.objectName)throw new v(Q);return await this.storage.read({name:$.objectName})}async file(Q){let $=await this.get(Q),J=(await this.readRecord(Q,$)).body,G=J instanceof Blob?J:J?await new Response(J).blob():new Blob([]);return new File([G],$.name,{type:$.mimeType})}async put(Q,$={}){let Z=CQ(),J=$.mimeType??Q.type??"",G=$.name??(Q instanceof File?Q.name:Z),W=await this.storage.put({name:OQ(Z,G),body:Q,contentType:J||void 0}),Y={id:Z,scopeKey:this.scope.key,objectName:W,name:G,mimeType:J||"application/octet-stream",size:Q.size,createdAt:new Date().toISOString(),destination:$.fileId?"both":"storage",...$.fileId?{fileId:$.fileId}:{}};return await this.store.put(this.scope,Y),Y}}function OQ(Q,$){let Z=/\.([A-Za-z0-9]{1,8})$/.exec($);return`attachments/${Q}${Z?`.${Z[1].toLowerCase()}`:""}`}class i{rows=new Map;async put(Q,$){LQ(Q),this.rows.set($.id,{...$,scopeKey:Q.key})}async find(Q,$){LQ(Q);let Z=this.rows.get($);if(!Z||Z.scopeKey!==Q.key)return null;return Z}get size(){return this.rows.size}}var n=new i;var jQ=new TextEncoder;function G6(Q){return`id: ${Q.seq}
3
3
  data: ${JSON.stringify(Q.event)}
4
4
 
5
5
  `}var t6=5000,a6=`: keepalive
@@ -17,4 +17,4 @@ data: ${JSON.stringify(V.event)}
17
17
  `);while(K!==-1){let H=$.slice(0,K);$=$.slice(K+1);let B=Y(H);if(B)yield B;K=$.indexOf(`
18
18
  `)}}if($.length>0){let X=Y($);if(X)yield X}let V=W();if(V)yield V}async function*E6(Q,$={}){let Z=new Map,J=new Set,G=!1;for await(let W of w9(Q)){if(W.data==="[DONE]")break;let Y;try{Y=JSON.parse(W.data)}catch{continue}switch(typeof Y.type==="string"?Y.type:W.event){case"response.output_text.delta":{let X=String(Y.delta??"");if(!X)break;yield $.structuredOutput?{type:"output-delta",delta:X}:{type:"text-delta",delta:X};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let X=String(Y.delta??"");if(!X)break;yield{type:"reasoning-delta",delta:X,id:Y.item_id};break}case"response.output_item.added":{let X=Y.item;if(!X)break;if(X.type==="function_call"){let K=String(X.id??Y.item_id??X.call_id??"");Z.set(K,{callId:String(X.call_id??K),name:String(X.name??""),namespace:typeof X.namespace==="string"&&X.namespace?X.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let X=Z.get(String(Y.item_id??""));if(!X)break;let K=String(Y.delta??"");if(!K)break;yield{type:"tool-call-delta",toolCallId:X.callId,name:X.name,argsDelta:K,...X.namespace?{namespace:X.namespace}:{}};break}case"response.function_call_arguments.done":{let X=String(Y.item_id??""),K=Z.get(X);if(!K)break;K.done=!0,yield{type:"tool-call",toolCallId:K.callId,name:K.name,args:String(Y.arguments??""),...K.namespace?{namespace:K.namespace}:{}};break}case"response.output_item.done":{let X=Y.item;if(!X)break;if(X.type==="function_call"){let K=String(X.id??Y.item_id??X.call_id??""),H=Z.get(K);if(H?.done)break;let B=(typeof X.namespace==="string"?X.namespace:"")||H?.namespace;if(yield{type:"tool-call",toolCallId:String(X.call_id??K),name:String(X.name??H?.name??""),args:String(X.arguments??""),...B?{namespace:B}:{}},H)H.done=!0;break}if(X.type==="tool_search_call"||X.type==="tool_search_output"){let K=b9(X);if(K.loaded.length===0&&K.namespaces.length===0)break;let H=String(X.tool_search_call_id??X.id??"");if(J.has(H))break;J.add(H),yield{type:"tool-search",...K}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(Y.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{G=!0,yield{type:"finish",reason:"stop",usage:AQ(Y.response?.usage)};break}case"response.incomplete":{G=!0;let X=AQ(Y.response?.usage),K=Y.response?.incomplete_details?.reason;if(K==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:v9(Y.response?.content_filters),retryable:!1}},yield{type:"finish",reason:"error",usage:X};break}yield{type:"finish",reason:K==="max_output_tokens"?"length":"stop",usage:X};break}case"response.failed":case"error":{G=!0;let X=Y.response?.error??Y.error??Y;yield{type:"error",error:f9(X)},yield{type:"finish",reason:"error",usage:AQ(Y.response?.usage)};break}}if(G)return}if(!G)yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield{type:"finish",reason:"error",usage:I()}}function b9(Q){let $=[],Z=[];return A6(Q.results??Q.tools??Q.loaded??Q.output,$,Z,0),{loaded:IQ($),namespaces:IQ(Z)}}function A6(Q,$,Z,J){if(!Array.isArray(Q)||J>4)return;for(let G of Q){if(typeof G==="string"){$.push(G);continue}if(!G||typeof G!=="object")continue;let W=G,Y=typeof W.name==="string"?W.name:typeof W.tool_name==="string"?W.tool_name:"",V=W.tools??W.functions;if(Array.isArray(V)){if(Y)Z.push(Y);A6(V,$,Z,J+1);continue}if(Y)$.push(Y)}}function IQ(Q){return Q.filter(($,Z)=>Q.indexOf($)===Z)}function v9(Q){if(!Array.isArray(Q))return"The provider's content filter blocked this request.";let Z=[];for(let J of Q){if(!J||typeof J!=="object")continue;let G=J,W=G.content_filter_results;if(!W||typeof W!=="object")continue;for(let[Y,V]of Object.entries(W))if(V&&typeof V==="object"&&V.filtered===!0)Z.push(`${Y} (${String(G.source_type??"unknown")})`)}return Z.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${IQ(Z).join(", ")}.`}function f9(Q){let $=typeof Q?.message==="string"?Q.message:"The provider stream failed.",Z=String(Q?.code??"").toLowerCase();if(Z==="rate_limit_exceeded")return{code:"rate_limited",message:$,retryable:!0};if(Z==="context_length_exceeded")return{code:"context_length_exceeded",message:$,retryable:!1};if(Z.includes("content_filter"))return{code:"content_filtered",message:$,retryable:!1};return{code:"provider_error",message:$,retryable:!0}}function I(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function AQ(Q){if(!Q)return I();let $=Number(Q.input_tokens??0),Z=Number(Q.output_tokens??0),J={inputTokens:$,outputTokens:Z,totalTokens:Number(Q.total_tokens??$+Z)},G=Q.output_tokens_details?.reasoning_tokens;if(typeof G==="number")J.reasoningTokens=G;let W=Q.input_tokens_details?.cached_tokens;if(typeof W==="number")J.cachedInputTokens=W;return J}async function*I6(Q){if(!Q)return;let $=Q.getReader(),Z=new TextDecoder;try{while(!0){let{done:G,value:W}=await $.read();if(G)break;if(W)yield Z.decode(W,{stream:!0})}let J=Z.decode();if(J)yield J}finally{$.releaseLock()}}function wQ(Q){return{responsesUrl:`${Q.base}/responses${Q.query}`,filesUrl:`${Q.base}/files${Q.query}`,headers:Q.headers,timeoutMs:Q.timeoutMs,maxRetries:Q.maxRetries}}async function*bQ(Q,$,Z){let J;try{J=await y(Q.responsesUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify($)},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,signal:Z.signal,fetchImpl:Q.fetchImpl})}catch(G){let W=j(G);if(W.code!=="aborted")yield{type:"error",error:W};yield{type:"finish",reason:W.code==="aborted"?"aborted":"error",usage:I()};return}try{yield*E6(I6(J.body),{structuredOutput:Z.structuredOutput})}catch(G){let W=j(G);if(W.code==="aborted"){yield{type:"finish",reason:"aborted",usage:I()};return}yield{type:"error",error:W},yield{type:"finish",reason:"error",usage:I()}}}async function vQ(Q,$){let Z=new FormData;Z.set("purpose","user_data"),Z.set("file",$);let G=await(await y(Q.filesUrl,{method:"POST",headers:await Q.headers(),body:Z},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,fetchImpl:Q.fetchImpl})).json();if(!G?.id)throw Error("The provider accepted the upload but returned no file id.");return G.id}function fQ(Q){let $=h9(Q);if($.startsWith("gpt-3.5")||$.startsWith("text-")||$.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let Z=y9($);if(Z?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:Z.major>1,toolSearch:w6(Z)};if(Z?.kind==="gpt")return{reasoning:Z.major>=5,structuredOutput:Z.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),fileInput:Z.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:w6(Z)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function w6(Q){if(Q.kind==="o")return Q.major>=5;return Q.major>5||Q.major===5&&Q.minor>=2}function h9(Q){return Q.trim().toLowerCase()}function y9(Q){let $=/^gpt-(\d+)(?:\.(\d+))?/.exec(Q);if($?.[1])return{kind:"gpt",major:Number($[1]),minor:Number($[2]??0)};let Z=/^o(\d+)(?:[-.]|$)/.exec(Q);if(Z?.[1])return{kind:"o",major:Number(Z[1]),minor:0};return null}function hQ(Q,$){let{capabilities:Z}=$,J={model:$.model,input:u9(Q.messages,Z),stream:!0};if(Q.systemPrompt)J.instructions=Q.systemPrompt;let G=o9(Q.tools,Z);if(G.length>0){if(J.tools=G,!Z.parallelToolCalls)J.parallel_tool_calls=!1}if(Q.output)J.text={format:{type:"json_schema",name:Q.output.name,schema:Q.output.schema,strict:Q.output.strict}};if(Q.reasoning&&Z.reasoning)J.reasoning={effort:Q.reasoning,summary:"auto"};if(typeof Q.temperature==="number")J.temperature=Q.temperature;if(typeof Q.maxOutputTokens==="number")J.max_output_tokens=Q.maxOutputTokens;return J}function u9(Q,$){let Z=[];for(let J of Q){let G=J.role,W=[],Y=()=>{if(W.length===0)return;Z.push({type:"message",role:G,content:W}),W=[]};for(let V of J.content??[])switch(V.type){case"text":{if(!V.text)break;W.push(YQ(G,V.text));break}case"output":{if(V.partial)break;W.push(YQ(G,JSON.stringify(V.value)));break}case"file":{if(G==="assistant")break;let X=m9(V);if(!$.fileInput){if(X)W.push(YQ(G,b6(V,!1)));break}if(V.fileId?.startsWith(N))throw Error(`FilePart.fileId holds a gemi attachment id (${V.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(!V.fileId&&!X)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(X)W.push(YQ(G,b6(V,!!V.fileId)));if(V.fileId)W.push(p9(V));break}case"reasoning":{Y();let X=i9(V);if(X)Z.push(X);break}case"tool-call":{if(V.partial)break;Y(),Z.push({type:"function_call",call_id:V.toolCallId,name:String(V.name),arguments:JSON.stringify(V.input??{})});break}case"tool-result":{Y(),Z.push({type:"function_call_output",call_id:V.toolCallId,output:n9(V)});break}}Y()}return c9(Z)}var g9="No result was recorded for this tool call. Assume it did not complete.";function c9(Q){let $=new Set,Z=new Set,J=[];for(let W of Q){if(W.type==="function_call"){let Y=String(W.call_id);if($.has(Y))continue;$.add(Y)}else if(W.type==="function_call_output"){let Y=String(W.call_id);if(!$.has(Y)||Z.has(Y))continue;Z.add(Y)}J.push(W)}if(Z.size===$.size)return J;let G=[];for(let W of J){if(G.push(W),W.type!=="function_call")continue;let Y=String(W.call_id);if(Z.has(Y))continue;Z.add(Y),G.push({type:"function_call_output",call_id:Y,output:g9})}return G}function YQ(Q,$){return{type:Q==="assistant"?"output_text":"input_text",text:$}}function m9(Q){let $=Q.attachmentId;return typeof $==="string"&&$.startsWith(N)?$:void 0}function b6(Q,$){let Z=[`id=${JSON.stringify(Q.attachmentId)}`];if(Q.name)Z.push(`name=${JSON.stringify(Q.name)}`);if(Q.mimeType)Z.push(`mimeType=${JSON.stringify(Q.mimeType)}`);let J=`attachment ${Z.join(" ")}`;return $?`[${J}]`:`[${J} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function p9(Q){let $=Q.mimeType?.trim().toLowerCase()??"";return{type:($?$.startsWith("image/")&&$!=="image/svg+xml":l9(Q.name))?"input_image":"input_file",file_id:Q.fileId}}function l9(Q){let $=/\.([a-z0-9]+)$/.exec(Q?.trim().toLowerCase()??"");return $?.[1]!==void 0&&d9.has($[1])}var d9=new Set(["jpeg","jpg","png","gif","webp"]);function i9(Q){if(!Q.id)return null;let $={type:"reasoning",id:Q.id};return $.summary=Q.text?[{type:"summary_text",text:Q.text}]:[],$}function n9(Q){if(Q.status==="ok")return typeof Q.output==="string"?Q.output:JSON.stringify(Q.output??null);if(Q.status==="denied"){let $=Q.reason?` Reason given: ${Q.reason}`:"";if(Q.cause==="stopped")return`The run was stopped before this tool call could complete, so it did not run.${$}`;return`The user declined this tool call, so it did not run.${$}`}return`The tool call failed and produced no result. Error (${Q.error?.code??"unknown"}): ${Q.error?.message??"no message"}`}function v6(Q){return Array.isArray(Q.tools)}function o9(Q,$){if(!Q||Q.length===0)return[];if(!$.toolSearch){let G=[];for(let W of Q)if(v6(W))for(let Y of W.tools)G.push(XQ(Y,!1));else G.push(XQ(W,!1));return G}let Z=[],J=!1;for(let G of Q)if(v6(G)){let W=G.tools.map((Y)=>{if(Y.deferred)J=!0;return XQ(Y,!0)});Z.push({type:"namespace",name:G.name,description:G.description,tools:W})}else{if(G.deferred)J=!0;Z.push(XQ(G,!0))}if(J)Z.push({type:"tool_search"});return Z}function XQ(Q,$){let Z={type:"function",name:Q.name,description:Q.description,parameters:Q.parameters,strict:Q.strict};if($&&Q.deferred)Z.defer_loading=!0;return Z}class VQ{static models(){return[]}normalizeError(Q){return j(Q)}}var f6=["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 yQ extends VQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=fQ(Q),this.config=$}static model(Q,$){return new yQ(Q,$)}static models(){return f6}stream(Q){let $=hQ(Q,{model:this.model,capabilities:this.capabilities});return bQ(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output)})}upload(Q){return vQ(this.endpoint(),Q)}endpoint(){return wQ(QQ(this.config))}}class uQ extends VQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=fQ(Q),this.config=$}static model(Q,$){return new uQ(Q,$)}static models(){return f6}stream(Q){let $=hQ(Q,{model:this.deployment(),capabilities:this.capabilities});return bQ(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output)})}upload(Q){return vQ(this.endpoint(),Q)}deployment(){return this.config.deployment??this.model}endpoint(){return wQ($Q(this.config))}}class w extends Error{runId;requested;oldest;code="frame_cursor_evicted";constructor(Q,$,Z){super(`Frame ${$} of run ${Q} has been evicted; the oldest frame still buffered is ${Z}. Reload the thread instead of resuming.`);this.runId=Q;this.requested=$;this.oldest=Z}}class u extends Error{runId;code="live_run_not_found";constructor(Q){super(`No live run ${Q} in this process.`);this.runId=Q}}class KQ{ttlMs;maxFrames;runs=new Map;byThread=new Map;byClientRun=new Map;constructor(Q={}){this.ttlMs=Q.ttlMs??60000,this.maxFrames=Q.maxFrames??4096}register(Q,$={}){let Z={run:Q,threadId:$.threadId,clientRunId:$.clientRunId,frames:[],lastSeq:-1,lostBefore:0,ended:!1,evictAt:null,wake:new Set,version:0};if(this.runs.set(Q.runId,Z),$.threadId)this.byThread.set($.threadId,Q.runId);if($.clientRunId)this.byClientRun.set($.clientRunId,Q.runId);return this.pump(Z,$)}findByClientRunId(Q){let $=this.byClientRun.get(Q);return $&&this.runs.has($)?$:null}async find(Q){let $=this.byThread.get(Q.threadId);if(!$)return null;let Z=this.runs.get($);if(!Z)return null;return{runId:$,seq:Z.lastSeq}}get(Q){return this.runs.get(Q)?.run??null}replay(Q,$){let Z=this.runs.get(Q);if(!Z)throw new u(Q);if($!==void 0&&$<Z.lostBefore)throw new w(Q,$,Z.lostBefore);let J=Z.frames[0]?.seq;return this.drain(Z,Q,$??J??Z.lastSeq+1)}clear(){for(let Q of this.runs.values()){if(Q.evictAt)clearTimeout(Q.evictAt);Q.ended=!0,this.notify(Q)}this.runs.clear(),this.byThread.clear(),this.byClientRun.clear()}get size(){return this.runs.size}async pump(Q,$){let Z=Promise.resolve();try{for await(let J of Q.run.frames()){if(Q.frames.push(J),Q.lastSeq=J.seq,Q.frames.length>this.maxFrames){let W=Q.frames.shift();if(W)Q.lostBefore=W.seq+1}this.notify(Q);let G=$.onEvent;if(G)Z=Z.then(()=>G(J.event)).catch((W)=>h6($,W))}}catch(J){h6($,J)}finally{Q.ended=!0,this.notify(Q),this.scheduleEviction(Q),await Z}}async*drain(Q,$,Z){let J=Z;while(!0){let G=Q.version;for(;;){if(J<Q.lostBefore)throw new w($,J,Q.lostBefore);let W=Q.frames,Y=W[0]?.seq;if(Y===void 0)break;let V=Math.max(0,J-Y);if(V>=W.length)break;let X=W[V];yield X,J=X.seq+1}if(Q.ended&&J>Q.lastSeq)return;await this.wait(Q,G)}}wait(Q,$){if(Q.version!==$)return Promise.resolve();return new Promise((Z)=>Q.wake.add(Z))}notify(Q){Q.version++;let $=Array.from(Q.wake);Q.wake.clear();for(let Z of $)Z()}scheduleEviction(Q){if(Q.evictAt)return;let $=setTimeout(()=>{let Z=Q.run.runId;if(this.runs.delete(Z),Q.threadId&&this.byThread.get(Q.threadId)===Z)this.byThread.delete(Q.threadId);if(Q.clientRunId&&this.byClientRun.get(Q.clientRunId)===Z)this.byClientRun.delete(Q.clientRunId);this.notify(Q)},this.ttlMs);$.unref?.(),Q.evictAt=$}}var gQ=new KQ;function h6(Q,$){try{Q.onInternalError?.($)}catch{}}class HQ{ttlMs;clientOwnedIds;threads=new Map;lastSweep=0;constructor(Q={}){this.ttlMs=Q.ttlMs??86400000,this.clientOwnedIds=Q.clientOwnedIds??!1}async createThread(Q){let $=crypto.randomUUID();return this.threads.set($,{messages:[],touchedAt:Date.now()}),this.sweep(),{threadId:$}}async loadThread(Q){this.sweep();let $=this.threads.get(Q);if(!$)return this.clientOwnedIds?[]:null;return $.touchedAt=Date.now(),$.messages.slice()}async appendMessages(Q,$){this.sweep();let Z=this.threads.get(Q);if(!Z){if(!this.clientOwnedIds)throw Error(`Thread ${Q} does not exist here, or has expired.`);Z={messages:[],touchedAt:Date.now()},this.threads.set(Q,Z)}for(let J of $){let G=Z.messages.findIndex((W)=>W.id===J.id);if(G===-1)Z.messages.push(J);else Z.messages[G]=J}Z.touchedAt=Date.now()}delete(Q){this.threads.delete(Q)}get size(){return this.threads.size}sweep(Q=Date.now()){if(Q-this.lastSweep<60000)return;this.lastSweep=Q;for(let[$,Z]of this.threads)if(Q-Z.touchedAt>this.ttlMs)this.threads.delete($)}}var cQ=new HQ;var s9=m6,BQ=new Map,y6=new WeakMap,DQ=new Map;class l6 extends s9{static kind="agent-controller";store=cQ;liveRuns=gQ;attachments=n;attachmentStorage=p6;hookHoldMs=30000;instructions(Q,$){}requireThread=!1;authorizeRequest(Q,$){}async stream(Q=new g){let $=await mQ(Q);if($.error)return UQ($);let Z=$.body,J=typeof Z.threadId==="string"?Z.threadId:void 0,G=e9(Z);if(G.error)return UQ({body:{},error:G.error});let W=G.turn,Y=typeof Z.clientRunId==="string"?Z.clientRunId:void 0;if(this.requireThread&&!J)return _(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});let V=Y?{cancelled:!1}:null;if(V)DQ.set(Y,V);let X=async()=>{let K;if(J){let O=await this.store.loadThread(J);if(!O)return _(404,{code:"thread_not_found",message:`Thread ${J} does not exist here, or has expired.`});K=O}else K=Array.isArray(Z.messages)?Z.messages:[];let H=a9(Z),B=await this.instructions(Q,{body:H})||void 0,D=await this.attachmentsFor(Q,J);if(V?.cancelled)return g6();let z=this.agent.stream({messages:K,turn:W,req:Q,threadId:J,instructions:B,attachments:D,body:H}),U={req:Q,runId:z.runId,threadId:J},F=this.liveRuns.register(z,{threadId:J,clientRunId:Y,onEvent:(O)=>this.dispatchEvent(O,U),onInternalError:(O)=>this.reportHookFailure(O)}),{stored:L,hooks:P}=this.persistRun(z,U,F);return y6.set(z,L),Q.ctx?.()?.waitUntil(P),z.toResponse()};try{if(await this.authorizeRequest(Q,{route:"stream",threadId:J}),V?.cancelled)return g6();return J?await this.withThread(J,X):await X()}finally{if(V&&DQ.get(Y)===V)DQ.delete(Y)}}async withThread(Q,$){let Z=BQ.get(Q)??Promise.resolve(),J,G=new Promise((Y)=>{J=Y}),W=Z.then(()=>G);BQ.set(Q,W),await Z;try{let Y=await this.liveRuns.find({threadId:Q}),V=Y?this.liveRuns.get(Y.runId):null;if(V)V.stop({reason:"superseded by a later turn on this thread"}),await y6.get(V);return await $()}finally{if(J(),BQ.get(Q)===W)BQ.delete(Q)}}async attach(Q=new g){let $=await mQ(Q);if($.error)return UQ($);let Z=$.body,J=typeof Z.threadId==="string"?Z.threadId:Z$(Q,"threadId");if(!J)return _(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});await this.authorizeRequest(Q,{route:"attach",threadId:J});let G=await this.liveRuns.find({threadId:J});if(!G)return _(404,{code:"no_live_run",message:`No run in progress for thread ${J} in this process.`});let W=typeof Z.runId==="string"?Z.runId:void 0,Y=W&&W!==G.runId?void 0:$$(Q,Z);try{return W6(this.liveRuns.replay(G.runId,Y))}catch(V){if(V instanceof w)return _(410,{code:V.code,message:V.message,oldestSeq:V.oldest});if(V instanceof u)return _(404,{code:V.code,message:V.message});throw V}}async stop(Q=new g){let $=await mQ(Q);if($.error)return UQ($);let Z=$.body;await this.authorizeRequest(Q,{route:"stop",threadId:typeof Z.threadId==="string"?Z.threadId:void 0});let J=typeof Z.runId==="string"?Z.runId:void 0;if(!J&&typeof Z.clientRunId==="string"){if(J=this.liveRuns.findByClientRunId(Z.clientRunId)??void 0,!J){let W=DQ.get(Z.clientRunId);if(W)return W.cancelled=!0,{stopped:!0}}}if(!J&&typeof Z.threadId==="string")J=(await this.liveRuns.find({threadId:Z.threadId}))?.runId;let G=J?this.liveRuns.get(J):null;if(!G)return{stopped:!1};return G.stop({reason:typeof Z.reason==="string"?Z.reason:void 0}),{stopped:!0}}attachmentScope(Q,$){let Z=Q.ctx()?.user,J=Z?.id??Z?.publicId;if(J!==void 0&&J!==null&&String(J)!=="")return{key:`user:${String(J)}`};if($)return{key:`thread:${$}`};return null}attachmentDestination(Q,$){return"both"}async attachmentsFor(Q,$){let Z=await this.attachmentScope(Q,$);if(!Z)return null;return new f(this.attachments,this.attachmentStorage,Z)}async upload(Q=new g){let $=await Q.rawRequest.formData(),Z=$.get("file");if(!(Z instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let J=Z instanceof File&&Z.name?Z.name:"upload",G=Z.type||"application/octet-stream",W=$.get("threadId");await this.authorizeRequest(Q,{route:"upload",threadId:typeof W==="string"&&W.length>0?W:void 0});let Y=typeof W==="string"&&W.length>0&&await this.store.loadThread(W)!==null?W:void 0,V=await this.attachmentDestination(Z,Q),X=J$(V,$.get("destination")),K=await this.attachmentScope(Q,Y),H=X!=="provider"&&!K;if(H){if(X==="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()`.');G$()}if(X==="provider"||!K){let L={fileId:await this.agent.provider.upload(Z),name:J,mimeType:G,size:Z.size,destination:"provider"};if(H)L.downgraded="no_scope";return L}let B=CQ(),D=await this.attachmentStorage.put({name:OQ(B,J),body:Z,contentType:G}),z=X==="both"?await this.agent.provider.upload(Z):void 0,U={id:B,scopeKey:K.key,fileId:z,objectName:D,name:J,mimeType:G,size:Z.size,createdAt:new Date().toISOString(),destination:X};return await this.attachments.put(K,U),{fileId:z,attachmentId:B,name:J,mimeType:G,size:Z.size,destination:X}}onMessage(Q,$){}onToolCall(Q,$){}onAwaitingInput(Q,$){}onError(Q,$){}onStreamComplete(Q,$){}reportHookFailure(Q){console.error("[gemi/ai] agent controller hook failed",Q)}async dispatchEvent(Q,$){switch(Q.type){case"tool-call":if(!Q.part.partial&&!Q.resent)await this.onToolCall({toolCallId:Q.part.toolCallId,name:String(Q.part.name),input:Q.part.input},$);return;case"awaiting-input":await this.onAwaitingInput(Q.pending,$);return;case"error":await this.onError(Q.error,$);return;default:return}}persistRun(Q,$,Z){let J=Promise.resolve(),G=(async()=>{let Y;try{Y=await Q.result()}catch(X){J=this.safely(()=>this.onError({code:"unknown",message:X instanceof Error?X.message:String(X),retryable:!1},$));return}let V=Y.messages;if($.threadId&&V.length>0)try{await this.store.appendMessages($.threadId,V)}catch(X){this.reportHookFailure(X)}J=this.notifyRun(Y,V,$)})(),W=G.then(()=>Y$(Promise.all([J,Z]).then(()=>{}),this.hookHoldMs));return{stored:G,hooks:W}}async notifyRun(Q,$,Z){for(let J of $)await this.safely(()=>this.onMessage(J,Z));await this.safely(()=>this.onStreamComplete(Q,Z))}async safely(Q){try{await Q()}catch($){this.reportHookFailure($)}}}var u6=["turn","clientRunId","threadId","messages"],t9=["text","files","toolResults"];function a9(Q){let $=d6(Q)?u6:[...u6,...t9],Z={};for(let[J,G]of Object.entries(Q)){if($.includes(J))continue;Object.defineProperty(Z,J,{value:G,writable:!0,enumerable:!0,configurable:!0})}return Z}async function mQ(Q){let $=Q?.rawRequest;if(!$||$.method==="GET"||$.method==="HEAD"||!$.body)return{body:{}};if(!r9($.headers.get("Content-Type")))return{body:{},status:415,code:"unsupported_media_type",error:"The request body must be sent as application/json."};let Z;try{Z=await $.text()}catch{return{body:{},error:"The request body could not be read."}}if(!Z.trim())return{body:{}};let J;try{J=JSON.parse(Z)}catch{return{body:{},error:"The request body is not valid JSON."}}if(J===null||typeof J!=="object"||Array.isArray(J))return{body:{},error:"The request body must be a JSON object."};return{body:J}}function r9(Q){if(typeof Q!=="string")return!1;let[$]=Q.split(";",1);return $.trim().toLowerCase()==="application/json"}function UQ(Q){return _(Q.status??400,{code:Q.code??"invalid_request",message:Q.error})}function d6(Q){return Boolean(Q.turn)&&typeof Q.turn==="object"}function e9(Q){let $=d6(Q)?Q.turn:Q,Z={};if(typeof $.text==="string")Z.text=$.text;if(Array.isArray($.files)){let J=Q$($.files);if(typeof J==="string")return{error:J};Z.files=J}if(Array.isArray($.toolResults))Z.toolResults=$.toolResults;return Object.keys(Z).length>0?{turn:Z}:{}}function Q$(Q){let $=[];for(let[Z,J]of Q.entries()){let G=`turn.files[${Z}]`;if(!J||typeof J!=="object"||Array.isArray(J))return`${G} must be an object.`;let W={};for(let H of["fileId","attachmentId","name","mimeType"]){let B=J[H];if(B===void 0||B===null||B==="")continue;if(typeof B!=="string")return`${G}.${H} must be a string.`;W[H]=B}let{fileId:Y,attachmentId:V,name:X,mimeType:K}=W;if(Y?.startsWith(N))return`${G}.fileId holds a gemi attachment id (${Y}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(V!==void 0&&!V.startsWith(N))return`${G}.attachmentId is not a gemi attachment id: it must start with "${N}".`;if(!Y&&!V)return`${G} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;$.push({...Y?{fileId:Y}:{},...V?{attachmentId:V}:{},...X!==void 0?{name:X}:{},...K!==void 0?{mimeType:K}:{}})}return $}function $$(Q,$){if(typeof $.from==="number"&&Number.isFinite($.from))return Math.max(0,Math.floor($.from));if(typeof $.cursor==="number"&&Number.isFinite($.cursor)){let J=Math.floor($.cursor);if(J>=0)return J+1;return}let Z=Q?.rawRequest?.headers?.get("Last-Event-ID");if(Z){let J=Number.parseInt(Z,10);if(Number.isFinite(J))return Math.max(0,J+1)}return}function Z$(Q,$){let Z=Q?.search?.get($);return typeof Z==="string"?Z:void 0}function g6(){return _(409,{code:"stopped",message:"The turn was stopped before it started."})}function _(Q,$){return new Response(JSON.stringify({error:$}),{status:Q,headers:{"Content-Type":"application/json"}})}function J$(Q,$){if(typeof $!=="string"||$.length===0)return Q;if($!=="both"&&$!=="provider"&&$!=="storage")throw Error(`Unknown attachment destination "${$}". Expected "both", "provider" or "storage".`);if($===Q||Q==="both"&&$==="storage")return $;if(Q==="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 "${Q}", and a client hint may only ask for "storage" under a "both" policy. Change \`attachmentDestination()\` if the file really should go there.`)}var c6=!1;function G$(){if(c6)return;c6=!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 W$=2147483647;function Y$(Q,$){let Z=Q.then(()=>{},()=>{});if(!($<=W$))return Z;let J,G=new Promise((W)=>{J=setTimeout(W,$)});return Promise.race([Z,G]).finally(()=>clearTimeout(J))}export{U9 as toAgentTools,r as supportsStrict,X$ as s,gQ as liveRuns,n as defaultAttachmentStore,cQ as defaultAgentStore,e as ToolNamespace,qQ as Skill,f as ScopedAttachments,h as SKILLS_NAMESPACE,S as PendingEscalation,yQ as OpenAIProvider,xQ as OpenAIImageProvider,KQ as MemoryLiveRuns,i as MemoryAttachmentStore,HQ as MemoryAgentStore,u as LiveRunNotFoundError,A as InvalidAttachmentScopeError,GQ as ImageRequestError,WQ as ImageProvider,RQ as ImageModel,w as FrameCursorEvictedError,uQ as AzureOpenAIProvider,EQ as AzureOpenAIImageProvider,v as AttachmentNotFoundError,T as AgentTool,VQ as AgentProvider,l6 as AgentController,SQ as Agent};
19
19
 
20
- //# debugId=17ABCDE313E1DC1364756E2164756E21
20
+ //# debugId=EEDD7F37FDA1D72864756E2164756E21