gemi 0.166.0 → 0.167.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.
Files changed (43) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/ai/index.js.map +2 -2
  3. package/dist/{chunk-k4asa3bz.js → chunk-matvbghh.js} +2 -2
  4. package/dist/{chunk-k4asa3bz.js.map → chunk-matvbghh.js.map} +1 -1
  5. package/dist/{chunk-xafdc093.js → chunk-mcavkjh4.js} +1 -1
  6. package/dist/chunk-ndawdgtt.js +15 -0
  7. package/dist/{chunk-ty9s0z7q.js.map → chunk-ndawdgtt.js.map} +3 -3
  8. package/dist/{chunk-8yxjrjef.js → chunk-ndj94vde.js} +1 -1
  9. package/dist/{chunk-vg53hn9x.js → chunk-qnv9w5g5.js} +4 -4
  10. package/dist/{chunk-vg53hn9x.js.map → chunk-qnv9w5g5.js.map} +3 -3
  11. package/dist/{chunk-h11r8h31.js → chunk-tqgpahmn.js} +11 -11
  12. package/dist/{chunk-h11r8h31.js.map → chunk-tqgpahmn.js.map} +3 -3
  13. package/dist/{chunk-qeayzybn.js → chunk-z316fasf.js} +1 -1
  14. package/dist/chunks/{RealtimeClient-BX_HwEBK.js → RealtimeClient-DpAJYcF5.js} +2 -2
  15. package/dist/chunks/{RealtimeClient-BX_HwEBK.js.map → RealtimeClient-DpAJYcF5.js.map} +1 -1
  16. package/dist/chunks/{ThemeProvider-D4mhhONE.js → ThemeProvider-DAbL-cqC.js} +36 -8
  17. package/dist/chunks/{ThemeProvider-D4mhhONE.js.map → ThemeProvider-DAbL-cqC.js.map} +1 -1
  18. package/dist/chunks/{fetchFileRequest-C3wMigR3.js → fetchFileRequest-yAKa_pKx.js} +2 -2
  19. package/dist/chunks/{fetchFileRequest-C3wMigR3.js.map → fetchFileRequest-yAKa_pKx.js.map} +1 -1
  20. package/dist/chunks/{live-CJOuf1Gu.js → live-BvhWo-yY.js} +3 -3
  21. package/dist/chunks/{live-CJOuf1Gu.js.map → live-BvhWo-yY.js.map} +1 -1
  22. package/dist/chunks/{mutationExtras-DpB8MtNs.js → mutationExtras-_hbHxr6-.js} +2 -2
  23. package/dist/chunks/{mutationExtras-DpB8MtNs.js.map → mutationExtras-_hbHxr6-.js.map} +1 -1
  24. package/dist/client/ClientRouter.d.ts.map +1 -1
  25. package/dist/client/chunkLoadRecovery.d.ts +6 -0
  26. package/dist/client/chunkLoadRecovery.d.ts.map +1 -1
  27. package/dist/client/index.js +4 -3
  28. package/dist/client/index.js.map +1 -1
  29. package/dist/facades/index.js +1 -1
  30. package/dist/http/HttpRequest.d.ts +6 -0
  31. package/dist/http/HttpRequest.d.ts.map +1 -1
  32. package/dist/http/index.js +1 -1
  33. package/dist/i18n/index.js +1 -1
  34. package/dist/kernel/index.js +1 -1
  35. package/dist/server/index.js +1 -1
  36. package/dist/services/index.js +1 -1
  37. package/dist/services/router/serverQueryFetcher.d.ts.map +1 -1
  38. package/dist/testing/index.js +2 -2
  39. package/package.json +1 -1
  40. package/dist/chunk-ty9s0z7q.js +0 -15
  41. /package/dist/{chunk-xafdc093.js.map → chunk-mcavkjh4.js.map} +0 -0
  42. /package/dist/{chunk-8yxjrjef.js.map → chunk-ndj94vde.js.map} +0 -0
  43. /package/dist/{chunk-qeayzybn.js.map → chunk-z316fasf.js.map} +0 -0
package/dist/ai/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{$b as e$,$c as d0,Ac as n9,Bc as o9,Cc as N8,Ec as U8,Fc as S8,Gc as C8,Hc as _8,Ic as M8,Jc as A8,Kc as R8,Lc as T8,Mc as E8,Nc as j8,Oc as k8,Pc as x8,Rc as w,Sc as t8,Tc as s,Uc as E,Vc as $8,Wc as u0,Xc as c0,Yb as r$,Yc as m0,Zb as DQ,Zc as p0,_b as FQ,_c as l0,ad as i0,bd as n0,cc as jJ,cd as o0,dc as S,dd as s0,ec as A,ed as a0,fd as DJ,gc as n8,gd as t0,hc as c8,hd as CQ,ic as KJ,id as r0,jc as g0,jd as _Q,kc as g,kd as e0,lc as J8,ld as AJ,mc as BQ,md as z$,nc as PQ,nd as J6,oc as NQ,od as $6,pc as m,pd as Q6,qc as UQ,qd as Z6,rc as iJ,rd as W6,sc as LQ,sd as V$,tc as OQ,uc as nJ,vc as F8,wc as B8,yc as P8,zc as v}from"../chunk-qeayzybn.js";import{Kd as G8}from"../chunk-y1ks8ahw.js";import"../chunk-wjff0d08.js";import{$h as h0,Fh as YQ,Gi as HQ,Ih as VQ,Ji as c$,Ni as zQ,Yh as U9,Zh as v0,_h as y0,ai as q}from"../chunk-ty9s0z7q.js";import{Oi as GQ,Qi as lJ,Ri as dJ}from"../chunk-efjk5aq7.js";import{_i as h}from"../chunk-w4at2d5d.js";import"../chunk-1ap3vcrr.js";import"../chunk-6tbs7yc1.js";import"../chunk-c0dvdfm0.js";import{bk as n,ck as o,qk as _J}from"../chunk-2ewe42dq.js";import"../chunk-hgvt5084.js";import{dl as y9}from"../chunk-kcgnjzqr.js";import"../chunk-eyv6hss6.js";import"../chunk-xw5d66ec.js";import"../chunk-23670kw5.js";import"../chunk-m5hd632w.js";import{readFileSync as jQ}from"fs";import{isAbsolute as kQ,join as sJ}from"path";var xQ=/\{\{>\s*([\w./-]+)\s*\}\}/g,W8=/\{\{(\w+)\}\}/g,qQ=/^[\w-]+(\/[\w-]+)*$/,K8={dir:"app/agents",shared:"prompts"},UJ={},aJ=new Map;function X8(){return UJ.cache??Bun.env.NODE_ENV==="production"}function IQ(J){if(!qQ.test(J))throw Error(`"${J}" is not a prompt name. Use letters, digits, "-" and "_", with "/" between folders.`);let $=UJ.dir??K8.dir,Q=kQ($)?$:sJ(process.cwd(),$),Z=J.includes("/")?`${J}.md`:sJ(UJ.shared??K8.shared,`${J}.md`);return sJ(Q,Z)}function wQ(J){let $=IQ(J),Q=X8()?aJ.get($):void 0;if(Q!==void 0)return Q;let Z;try{Z=jQ($,"utf8").replace(/\r?\n$/,"")}catch(W){if(W.code==="ENOENT")throw Error(`The prompt "${J}" does not exist (looked for ${$}).`);throw W}if(X8())aJ.set($,Z);return Z}function tJ(J,$){if($.includes(J))throw Error(`The prompt "${J}" includes itself: ${[...$,J].join(" > ")}.`);return wQ(J).replace(xQ,(Q,Z)=>tJ(Z,[...$,J]))}class Y8{static configure(J){UJ={...J},aJ.clear()}static render(J,$={}){return tJ(J,[]).replace(W8,(Q,Z)=>{if(!Object.hasOwn($,Z))throw Error(`The prompt "${J}" has no value for {{${Z}}}.`);return String($[Z])})}static placeholders(J){let $=[...tJ(J,[]).matchAll(W8)].map((Q)=>Q[1]);return[...new Set($)]}}class rJ extends G8{name="AgentJobDeadlineSweep";cron="* * * * *";async callback(){while(await v.sweep({limit:100})===100);}}var LJ=20;function H8(J,$){if($<=0||J.length===0)return null;let Q=(K,X)=>X.createdAt-K.createdAt||(K.id<X.id?1:-1);return["<jobs>","Background jobs that tools started in this conversation, running ones first. A running job's result replaces its tool result when it finishes. Do not start the same work again while a job for it is running.",...[...J.filter((K)=>K.state==="running").sort(Q),...J.filter((K)=>K.state!=="running").sort(Q)].slice(0,$).map((K)=>{let X=[`- ${K.id} (${K.toolName})`];if(K.state==="running")X.push(`running since ${eJ(K.createdAt)}`);else if(K.state==="ok")X.push(`finished at ${eJ(K.settledAt??K.updatedAt)}`);else{let G=K.error?`${K.error.code}: ${V8(K.error.message,200)}`:"failed";X.push(`failed at ${eJ(K.settledAt??K.updatedAt)} (${G})`)}if(K.summary!==void 0)X.push(`summary: ${V8(JSON.stringify(K.summary),300)}`);if(K.orphaned)X.push("its tool call was lost when the turn that started it was cut short");return X.join("; ")}),"</jobs>"].join(`
2
+ import{$b as e$,$c as d0,Ac as n9,Bc as o9,Cc as N8,Ec as U8,Fc as S8,Gc as C8,Hc as _8,Ic as M8,Jc as A8,Kc as R8,Lc as T8,Mc as E8,Nc as j8,Oc as k8,Pc as x8,Rc as w,Sc as t8,Tc as s,Uc as E,Vc as $8,Wc as u0,Xc as c0,Yb as r$,Yc as m0,Zb as DQ,Zc as p0,_b as FQ,_c as l0,ad as i0,bd as n0,cc as jJ,cd as o0,dc as S,dd as s0,ec as A,ed as a0,fd as DJ,gc as n8,gd as t0,hc as c8,hd as CQ,ic as KJ,id as r0,jc as g0,jd as _Q,kc as g,kd as e0,lc as J8,ld as AJ,mc as BQ,md as z$,nc as PQ,nd as J6,oc as NQ,od as $6,pc as m,pd as Q6,qc as UQ,qd as Z6,rc as iJ,rd as W6,sc as LQ,sd as V$,tc as OQ,uc as nJ,vc as F8,wc as B8,yc as P8,zc as v}from"../chunk-z316fasf.js";import{Kd as G8}from"../chunk-y1ks8ahw.js";import"../chunk-wjff0d08.js";import{$h as h0,Fh as YQ,Gi as HQ,Ih as VQ,Ji as c$,Ni as zQ,Yh as U9,Zh as v0,_h as y0,ai as q}from"../chunk-ndawdgtt.js";import{Oi as GQ,Qi as lJ,Ri as dJ}from"../chunk-efjk5aq7.js";import{_i as h}from"../chunk-w4at2d5d.js";import"../chunk-1ap3vcrr.js";import"../chunk-6tbs7yc1.js";import"../chunk-c0dvdfm0.js";import{bk as n,ck as o,qk as _J}from"../chunk-2ewe42dq.js";import"../chunk-hgvt5084.js";import"../chunk-71prz4rp.js";import{dl as y9}from"../chunk-kcgnjzqr.js";import"../chunk-eyv6hss6.js";import"../chunk-xw5d66ec.js";import"../chunk-23670kw5.js";import"../chunk-m5hd632w.js";import{readFileSync as jQ}from"fs";import{isAbsolute as kQ,join as sJ}from"path";var xQ=/\{\{>\s*([\w./-]+)\s*\}\}/g,W8=/\{\{(\w+)\}\}/g,qQ=/^[\w-]+(\/[\w-]+)*$/,K8={dir:"app/agents",shared:"prompts"},UJ={},aJ=new Map;function X8(){return UJ.cache??Bun.env.NODE_ENV==="production"}function IQ(J){if(!qQ.test(J))throw Error(`"${J}" is not a prompt name. Use letters, digits, "-" and "_", with "/" between folders.`);let $=UJ.dir??K8.dir,Q=kQ($)?$:sJ(process.cwd(),$),Z=J.includes("/")?`${J}.md`:sJ(UJ.shared??K8.shared,`${J}.md`);return sJ(Q,Z)}function wQ(J){let $=IQ(J),Q=X8()?aJ.get($):void 0;if(Q!==void 0)return Q;let Z;try{Z=jQ($,"utf8").replace(/\r?\n$/,"")}catch(W){if(W.code==="ENOENT")throw Error(`The prompt "${J}" does not exist (looked for ${$}).`);throw W}if(X8())aJ.set($,Z);return Z}function tJ(J,$){if($.includes(J))throw Error(`The prompt "${J}" includes itself: ${[...$,J].join(" > ")}.`);return wQ(J).replace(xQ,(Q,Z)=>tJ(Z,[...$,J]))}class Y8{static configure(J){UJ={...J},aJ.clear()}static render(J,$={}){return tJ(J,[]).replace(W8,(Q,Z)=>{if(!Object.hasOwn($,Z))throw Error(`The prompt "${J}" has no value for {{${Z}}}.`);return String($[Z])})}static placeholders(J){let $=[...tJ(J,[]).matchAll(W8)].map((Q)=>Q[1]);return[...new Set($)]}}class rJ extends G8{name="AgentJobDeadlineSweep";cron="* * * * *";async callback(){while(await v.sweep({limit:100})===100);}}var LJ=20;function H8(J,$){if($<=0||J.length===0)return null;let Q=(K,X)=>X.createdAt-K.createdAt||(K.id<X.id?1:-1);return["<jobs>","Background jobs that tools started in this conversation, running ones first. A running job's result replaces its tool result when it finishes. Do not start the same work again while a job for it is running.",...[...J.filter((K)=>K.state==="running").sort(Q),...J.filter((K)=>K.state!=="running").sort(Q)].slice(0,$).map((K)=>{let X=[`- ${K.id} (${K.toolName})`];if(K.state==="running")X.push(`running since ${eJ(K.createdAt)}`);else if(K.state==="ok")X.push(`finished at ${eJ(K.settledAt??K.updatedAt)}`);else{let G=K.error?`${K.error.code}: ${V8(K.error.message,200)}`:"failed";X.push(`failed at ${eJ(K.settledAt??K.updatedAt)} (${G})`)}if(K.summary!==void 0)X.push(`summary: ${V8(JSON.stringify(K.summary),300)}`);if(K.orphaned)X.push("its tool call was lost when the turn that started it was cut short");return X.join("; ")}),"</jobs>"].join(`
3
3
  `)}function eJ(J){return new Date(J).toISOString().replace(/\.\d{3}Z$/,"Z")}function V8(J,$){return J.length<=$?J:`${J.slice(0,$-1)}\u2026`}class $${table;sql;dialect;connection;constructor(J,$={}){let Q=$.table??"gemi_agent_jobs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(Q))throw Error(`The agent jobs table name "${Q}" is not a plain identifier. Use letters, digits and underscores.`);this.table=Q,this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name}async createTable(){for(let J of bQ(this.dialect,this.table))await this.sql.unsafe(J)}async transaction(J){if(this.connection===void 0||this.joinable())return J();return _J(this.sql,()=>J(),{connection:this.connection})}async create(J){let $=this.q(),Q=this.clock($);await $`
4
4
  INSERT INTO ${this.name($)}
5
5
  (id, thread_id, run_id, tool_call_id, tool_name, owner, job, summary, state,
@@ -241,4 +241,4 @@ return 0`;class p${injectedClient;prefix;constructor(J={}){this.injectedClient=J
241
241
 
242
242
  `)||void 0,L=await this.context(J,{body:V}),O=await this.reasoning(J,{body:V})||void 0,j=await this.skills(J,{body:V})||void 0,k=await this.attachmentsFor(J,Z,{body:V}),I=this.agent.memory?await this.memoryScopes(J,{body:V}):void 0;if(H?.cancelled)return WQ();let x=Z?new i$(this.store,Z,N,(T)=>this.reportHookFailure(T)):null,d=`run_${crypto.randomUUID()}`,_={req:J,runId:d,threadId:Z},R={id:null,notified:Promise.resolve()},C=this.agent.stream({runId:d,messages:N,turn:K,threadId:Z,...x?{onMessage:(T)=>x.finish(T)}:{},onTurn:(T)=>{if(R.id!==null)return;R.id=T.id;let i=x?x.settled():Promise.resolve();R.notified=i.then(()=>this.safely(()=>this.onMessage(T,_)))},instructions:P,...O?{reasoning:O}:{},...j&&j.length>0?{skills:j}:{},context:L,attachments:k,body:V,redactError:(T,i)=>this.redactError(T,i,_),nonces:this.nonces,receipts:this.receipts,subject:Y,...I?{memory:{scopes:I,...this.memoryMaxTokens!==void 0?{maxTokens:this.memoryMaxTokens}:{}}}:{},...Z?{jobs:{owner:Y}}:{},...this.contextWindow!==void 0?{contextWindow:this.contextWindow}:{},...Z&&CQ(this.store)?{summaryStore:this.store}:{},...this.prepareStep!==Q8.prototype.prepareStep||this.hooks?.prepareStep?{prepareStep:(T)=>this.prepareStep(T,_)}:{}}),RQ=this.liveRuns.register(C,{threadId:Z,owner:Y,clientRunId:G,onEvent:(T)=>this.dispatchEvent(T,_),onInternalError:(T)=>this.reportHookFailure(T),maxRunDurationMs:this.agent.maxRunDurationMs});if(D=C,x)this.follow(C,x);let{stored:TQ,hooks:Z8}=this.persistRun(C,_,RQ,x,R);if(t9.set(C,TQ),BJ.has(J))BJ.set(J,{run:C,hooks:Z8});return J.ctx?.()?.waitUntil(Z8),C.toResponse()};try{await this.authorizeRequest(J,{route:"stream",threadId:Z,body:V});let N=await this.foreignFile([...K?.files??[],...Z?[]:j0(Q.messages)],Y);if(N)return N;if(H?.cancelled)return WQ();let B=await this.runLimitKey(J,{owner:Y,threadId:Z}),P=B===null?mJ:F0(this.liveRuns).take(B,Z?`thread:${Z}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!P)return t$(429,"too_many_runs",`You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`);try{return Z?await this.withThread(Z,Y,F):await F()}finally{let L=D;if(L)L.result().then(P,P);else P()}}finally{if(H&&uJ.get(G)===H)uJ.delete(G)}}async withThread(J,$,Q){let Z=gJ.get(J)??Promise.resolve(),W,K=new Promise((G)=>{W=G}),X=Z.then(()=>K);gJ.set(J,X),await Z;try{let G=await this.liveRuns.find({threadId:J});if(G&&this.liveRuns.isRunning(G.runId)&&!this.liveRuns.mayAccess(G.runId,$))return NJ();let V=G?this.liveRuns.get(G.runId):null;if(V)V.stop({reason:"superseded by a later turn on this thread"}),await t9.get(V);return await Q()}finally{if(W(),gJ.get(J)===X)gJ.delete(J)}}async attach(J=new q){let $=await PJ(J,cJ);if($.error)return JJ($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:R0(J,"threadId");if(!Z)return M(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});await this.authorizeRequest(J,{route:"attach",threadId:Z});let W=await this.liveRuns.find({threadId:Z});if(W&&!this.liveRuns.mayAccess(W.runId,await this.runOwner(J)))return NJ();if(!W)return M(404,{code:"no_live_run",message:`No run in progress for thread ${Z} in this process.`});let K=typeof Q.runId==="string"?Q.runId:void 0,X=K&&K!==W.runId?void 0:A0(J,Q);try{return zQ(this.liveRuns.replay(W.runId,X))}catch(G){if(G instanceof e)return M(410,{code:G.code,message:G.message,oldestSeq:G.oldest});if(G instanceof FJ)return M(404,{code:G.code,message:G.message});throw G}}async stop(J=new q){let $=await PJ(J,cJ);if($.error)return JJ($);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=uJ.get(Q.clientRunId);if(X){if(X.owner!==null&&X.owner!==Z)return NJ();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 NJ();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 iJ(this.attachments,this.attachmentStorage,Z)}async voiceStart(J=new q){let $=this.voice;if(!$)return n$();let Q=await PJ(J,cJ);if(Q.error)return JJ(Q);let{sdp:Z,threadId:W,pushToTalk:K}=Q.body;if(typeof Z!=="string"||!Z.trimStart().startsWith("v="))return M(400,{code:"invalid_request",message:"`sdp` must be the browser's SDP offer."});let X=pJ(Q.body,k0),G=typeof W==="string"&&W!==""?W:void 0;await this.authorizeRequest(J,{route:"stream",threadId:G,body:X});let V=J.ctx?.()?.user??null,Y=await $.start({req:J,body:X,threadId:G,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((O)=>{console.error("[gemi/ai] a voice call that failed to start could not be hung up.",O)});try{await Y.onEnd?.({sessionId:"",...D?{callId:D}:{},threadId:Y.threadId??G??"",reason:"start_failed",startedAt:H,endedAt:Date.now(),durationMs:0,seconds:0,usage:S(),transcription:{usage:S(),seconds:0},transcript:[],requests:[],toolCalls:[],errors:[]})}catch(O){console.error("[gemi/ai] a voice session's onEnd threw.",O)}},F=Y.threadId??G;if(!F)return await z(void 0),M(400,{code:"invalid_request",message:"A voice session needs a thread: send `threadId`, or answer one from `voice.start`."});try{if(F!==G)await this.authorizeRequest(J,{route:"stream",threadId:F,body:X})}catch(L){throw await z(void 0),L}let U=crypto.randomUUID(),N=Y.tools??[];try{if(Y.mcp)N=[...N,...await b$(Y.mcp,{user:V,sessionId:U})]}catch(L){return await z(L),M(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}let B={...Y.session,tools:[...HJ($.delegate),...Y.session?.tools??[],...N.map((L)=>L.tool)],...K===!0?{turnDetection:null}:{}},P;try{P=await $.realtime.createCall({sdp:Z,session:B,safetyIdentifier:Y.safetyIdentifier})}catch(L){await z(L);let O=L instanceof f&&L.code==="rate_limited";return M(O?429:502,{code:"voice_unavailable",message:"Voice isn't available right now."})}D=P.callId;try{await this.voiceStore.create({id:U,callId:P.callId,threadId:F,owner:await this.runOwner(J),body:X,startedAt:H});let{threadId:L,session:O,safetyIdentifier:j,mcp:k,tools:I,...x}=Y;return{sessionId:p.start({...x,tools:N,controller:this.constructor,threadId:F,user:V,body:X,call:{realtime:$.realtime,callId:P.callId},sessionId:U,store:this.voiceStore,liveRuns:this.liveRuns,delegate:$.delegate,session:B}).sessionId,sdp:P.sdpAnswer,threadId:F,delegate:$.delegate?.name??zJ,endsAt:H+(Y.limits?.maxDurationMs??900000)}}catch(L){return await z(L),M(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}}async voiceUpdate(J=new q){if(!this.voice)return n$();let $=await this.voiceSession(J);if($ instanceof Response)return $;let Q=await PJ(J,cJ);if(Q.error)return JJ(Q);let Z=pJ(Q.body,[]);if(await this.authorizeRequest(J,{route:"stream",threadId:$.threadId,body:Z}),$.endedAt!==void 0)return M(409,{code:"voice_ended",message:"This voice session has ended."});return await this.voiceStore.update($.id,{body:Z}),p.get($.id)?.setBody(Z),{updated:!0}}async voiceEnd(J=new q){let $=this.voice;if(!$)return n$();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=p.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 M(404,{code:"voice_not_found",message:"No such voice session."});if(Q.owner!==null&&Q.owner!==await this.runOwner(J))return NJ();return Q}async upload(J=new q){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 G=L0(await this.attachmentLimits(J),Q,Z,W);if(G)throw new a$(G.code,G.message);let V=typeof X==="string"&&X.length>0&&await this.store.loadThread(X)!==null?X:void 0,Y=await this.runOwner(J),H=(k)=>this.fileOwners.record(k,{owner:Y,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 a$(z.code||"upload_refused",z.message);let F=await this.attachmentDestination(Q,J,D),U=x0(F,$.get("destination")),N=await this.attachmentScope(J,V,{body:K}),B=U!=="provider"&&!N;if(B){if(U==="storage")throw Error('This upload was routed to storage, but `attachmentScope()` returned null for the request, so there is no subject to file the attachment under. Guard the route (`this.agent(Chat).middleware({ upload: "auth" })`), send a `threadId` with the upload, or override `attachmentScope()`.');q0()}if(U==="provider"||!N){let k=await JQ(this.agent.provider,Q);await H(k);let I={fileId:k,name:Z,mimeType:W,size:Q.size,destination:"provider"};if(B)I.downgraded="no_scope";return I}let P=UQ(),L=await this.attachmentStorage.put({name:LQ(P,Z),body:Q,contentType:W}),O=U==="both"?await JQ(this.agent.provider,Q):void 0;if(O)await H(O);let j={id:P,scopeKey:N.key,fileId:O,objectName:L,name:Z,mimeType:W,size:Q.size,createdAt:new Date().toISOString(),destination:U};return await this.attachments.put(N,j),{fileId:O,attachmentId:P,name:Z,mimeType:W,size:Q.size,destination:U}}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 E0()}return null}onMessage(J,$){return this.hooks?.onMessage?.(J,$)}onToolCall(J,$){return this.hooks?.onToolCall?.(J,$)}onToolResult(J,$){return this.hooks?.onToolResult?.(J,$)}onAwaitingInput(J,$){return this.hooks?.onAwaitingInput?.(J,$)}redactError(J,$,Q){let Z=this.hooks?.redactError;if(Z)return Z(J,$,Q);return J8(J,$)}onError(J,$){return this.hooks?.onError?.(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":await this.onToolResult(J.part,$);return;case"awaiting-input":await this.onAwaitingInput(J.pending,$);return;case"error":await this.onError(BQ(J.error),$);return;default:return}}async readThread(J){let $=await this.store.loadThread(J);return $?(await this.settleThread(J,$,{write:!1})).messages:null}isRunLive(J,$){return this.liveRuns.get(J)!==null}async settleThread(J,$,{write:Q}){let Z=(V)=>this.isRunLive(V,J),W=await d9($,Z),K=W.messages,X=[],G=new Map(W.settled.map((V)=>[V.id,V]));if(f0(K)||Q)try{let V=await s9(K,{threadId:J,store:v.store,isRunLive:Z,outputSchemaFor:(Y)=>this.toolNamed(Y)?.outputSchema,modelOutputFor:(Y,H)=>_Q(this.toolNamed(Y),H,(D)=>this.reportHookFailure(D)),scan:this.jobsBlockMax()});K=V.messages,X=V.jobs;for(let Y of V.settled)G.set(Y.id,Y);if(Q&&V.orphans.length>0){await a9(v.store,V.orphans,(H)=>this.reportHookFailure(H));let Y=new Set(V.orphans.map((H)=>H.id));X=X.map((H)=>Y.has(H.id)?{...H,orphaned:!0}:H)}}catch(V){this.reportHookFailure(V)}if(Q&&G.size>0)try{await this.store.appendMessages(J,[...G.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??LJ}jobsBlock(J){return H8(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 Y=V.messages;if(Z?.close(Y),await Z?.settled(),$.threadId&&Y.length>0)try{await this.store.appendMessages($.threadId,Y)}catch(H){this.reportHookFailure(H)}K=this.notifyRun(V,Y,$,W)})(),G=X.then(()=>w0(Promise.all([K,Q]).then(()=>{}),this.hookHoldMs));return{stored:X,hooks:G}}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 o$=["turn","clientRunId","threadId","messages","regenerate"],P0=["text","files","toolResults"];function pJ(J,$=AQ(J)?o$:[...o$,...P0]){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 s$("The upload's `body` field is not valid JSON.")}if($===null||typeof $!=="object"||Array.isArray($))throw new s$("The upload's `body` field must be a JSON object.");return pJ($,o$)}class s$ extends lJ{constructor(J){super(J);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:J}}},view:{}}}}async function JQ(J,$){try{return await J.upload($)}catch(Q){if(Q instanceof w&&U0.has(Q.status))throw new SQ(E(Q).message);throw Q}}var U0=new Set([400,413,415,422]);class a$ extends lJ{constructor(J,$){super($);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:J,message:$}}},view:{}}}}function L0(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 ${$Q($.size)}; the limit is ${$Q(W)}.`};if(K&&K.length>0&&!K.some((X)=>O0(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 O0(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 $Q(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 SQ extends lJ{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 PJ(J,$){let Q=J?.rawRequest;if(!Q||Q.method==="GET"||Q.method==="HEAD"||!Q.body)return{body:{}};if(!C0(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 QQ($);let W;try{let X=await _0(Q,$);if(X===null)return QQ($);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 C0(J){return VQ(J)==="application/json"}async function _0(J,$){if(!Number.isFinite($)||!J.body)return await J.text();let Q=J.body.getReader(),Z=[],W=0;for(;;){let{done:G,value:V}=await Q.read();if(G)break;if(W+=V.byteLength,W>$)return await Q.cancel().catch(mJ),null;Z.push(V)}let K=new Uint8Array(W),X=0;for(let G of Z)K.set(G,X),X+=G.byteLength;return new TextDecoder().decode(K)}function QQ(J){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${J} bytes).`}}function t$(J,$,Q){return M(J,{...dJ(GQ(J),Q,J),code:$})}function JJ(J){if(J.status===413)return t$(413,J.code??"body_too_large",J.error??"");return M(J.status??400,{code:J.code??"invalid_request",message:J.error})}function AQ(J){return Boolean(J.turn)&&typeof J.turn==="object"}function M0(J){let $=AQ(J)?J.turn:J,Q={};if(typeof $.text==="string")Q.text=$.text;if(Array.isArray($.files)){let Z=S0($.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>ZQ)return{error:`turn.localId is longer than ${ZQ} characters.`};Q.localId=Z}return{turn:Q}}var ZQ=200;function S0(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:G,name:V,mimeType:Y}=K;if(X?.startsWith(m))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(G!==void 0&&!G.startsWith(m))return`${W}.attachmentId is not a gemi attachment id: it must start with "${m}".`;if(!X&&!G)return`${W} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;$.push({...X?{fileId:X}:{},...G?{attachmentId:G}:{},...V!==void 0?{name:V}:{},...Y!==void 0?{mimeType:Y}:{}})}return $}function A0(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 R0(J,$){let Q=J?.search?.get($);return typeof Q==="string"?Q:void 0}function T0(J){let $=$8(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 WQ(){return M(409,{code:"stopped",message:"The turn was stopped before it started."})}function NJ(){return M(403,dJ("permission","This run belongs to someone else.",403))}function E0(){return M(403,dJ("permission","A file in this turn was uploaded by someone else.",403))}function j0(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 k0=["sdp","threadId","pushToTalk"];function n$(){return M(404,{code:"voice_not_enabled",message:"This agent has no voice: set `voice` on its controller."})}function M(J,$){return new Response(JSON.stringify({error:$}),{status:J,headers:{"Content-Type":"application/json"}})}function x0(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 KQ=!1;function q0(){if(KQ)return;KQ=!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 I0=2147483647;function w0(J,$){let Q=J.then(()=>{},()=>{});if(!($<=I0))return Q;let Z,W=new Promise((K)=>{Z=setTimeout(K,$)});return Promise.race([Q,W]).finally(()=>clearTimeout(Z))}var XQ=!1;function b0(J){if(XQ||Bun.env.NODE_ENV!=="production")return;if(!(J instanceof r$))return;XQ=!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 f0(J){return J.some(($)=>$.content.some((Q)=>Q.type==="tool-result"&&Q.status==="running"))}export{d0 as windowMessages,HJ as voiceTools,u0 as turnStarts,kJ as toRealtimeUsage,lQ as toAgentTools,h0 as supportsStrict,c0 as splitTurns,r0 as settleSummaries,y0 as s,J8 as redactError,m0 as messageSize,KJ as measureUsage,b$ as mcpVoiceTools,h$ as liveRuns,DJ as keepSummary,C9 as isCallNotFound,$8 as injectedMessageIds,V$ as generate,hZ as evalChain,B0 as defineAgentHooks,v$ as defaultVoiceStore,t0 as defaultSummaryStore,e$ as defaultNonceStore,g$ as defaultFileOwners,nJ as defaultAttachmentStore,l$ as defaultAgentStore,fJ as VoiceHangup,p as VoiceBridge,g0 as Usage,z$ as ToolNamespace,g as ToolError,J6 as Skill,iJ as ScopedAttachments,$6 as SKILLS_NAMESPACE,p$ as RedisReceiptStore,DQ as RedisNonceStore,xJ as RealtimeSideband,f as RealtimeRequestError,GJ as RealtimeClient,Y8 as Prompt,FQ as PrismaNonceStore,e0 as PendingEscalation,x$ as OpenAIProvider,N$ as OpenAIImageProvider,f$ as MemoryVoiceSessionStore,a0 as MemorySummaryStore,m$ as MemoryReceiptStore,r$ as MemoryNonceStore,vJ as MemoryLiveRuns,yJ as MemoryFileOwners,wJ as MemoryCircuitStore,OQ as MemoryAttachmentStore,hJ as MemoryAgentStore,F8 as MemoryAgentJobStore,x8 as MEMORY_NAMESPACE,FJ as LiveRunNotFoundError,P8 as JobsRequireThreadError,B8 as JobHandle,v0 as JSONSchemaError,NQ as InvalidAttachmentScopeError,A8 as InMemoryAgentMemoryStore,TJ as ImageRequestError,EJ as ImageProvider,D$ as ImageModel,e as FrameCursorEvictedError,VJ as FallbackProvider,j8 as FakeAgentMemoryStore,SJ as Eval,b9 as DatabaseAgentStore,Z$ as DatabaseAgentMemoryStore,$$ as DatabaseAgentJobStore,L9 as DEFAULT_TRANSCRIPTION_MODEL,S8 as DEFAULT_MEMORY_MAX_TOKENS,k8 as DEFAULT_MEMORY_LIMITS,i0 as DEFAULT_MAX_SUMMARY_TOKENS,Q6 as DEFAULT_MAX_RUN_DURATION_MS,N8 as DEFAULT_JOB_DEADLINE_MS,LJ as DEFAULT_JOBS_CONTEXT_MAX,zJ as DEFAULT_DELEGATE_NAME,p0 as DEFAULT_CONTEXT_WINDOW_STEP,l0 as DEFAULT_CONTEXT_WINDOW_NOTE,n0 as DEFAULT_COMPACT_TRIGGER_TOKENS,o0 as DEFAULT_COMPACT_INSTRUCTIONS,s0 as COMPACT_SUMMARY_HEADER,q$ as AzureOpenAIProvider,U$ as AzureOpenAIImageProvider,PQ as AttachmentNotFoundError,oJ as AgentTurnError,AJ as AgentTool,Z6 as AgentRunError,r as AgentProvider,R8 as AgentMemoryRefusedError,T8 as AgentMemoryConflictError,E8 as AgentMemories,v as AgentJobs,rJ as AgentJobDeadlineSweep,U8 as AgentJob,Q8 as AgentController,W6 as Agent};
243
243
 
244
- //# debugId=EB443228B416D44864756E2164756E21
244
+ //# debugId=A84483C0012D360464756E2164756E21