gemi 0.235.0 → 0.236.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/client/conformance.d.ts +4 -2
- package/dist/ai/client/conformance.d.ts.map +1 -1
- package/dist/ai/client/index.js +72 -6
- package/dist/ai/client/index.js.map +1 -1
- package/dist/ai/client/reducer.d.ts.map +1 -1
- package/dist/ai/index.js +3 -3
- package/dist/ai/index.js.map +3 -3
- package/dist/ai/providers/call.d.ts +1 -1
- package/dist/ai/types.d.ts +5 -0
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/ai/useChat.d.ts +35 -0
- package/dist/ai/useChat.d.ts.map +1 -1
- package/dist/auth/AuthController.d.ts.map +1 -1
- package/dist/{chunk-adfkz2kf.js → chunk-0e5sq42y.js} +1 -1
- package/dist/chunk-4800w7qx.js.map +2 -2
- package/dist/{chunk-cb7mgx75.js → chunk-73541m4t.js} +6 -6
- package/dist/{chunk-cb7mgx75.js.map → chunk-73541m4t.js.map} +3 -3
- package/dist/{chunk-t5gbp0yr.js → chunk-dav7mv8t.js} +2 -2
- package/dist/{chunk-t5gbp0yr.js.map → chunk-dav7mv8t.js.map} +3 -3
- package/dist/{chunk-1yws1nvb.js → chunk-hy54f691.js} +2 -2
- package/dist/{chunk-1yws1nvb.js.map → chunk-hy54f691.js.map} +1 -1
- package/dist/{chunk-2hw8sr4d.js → chunk-wbj4jh1h.js} +1 -1
- package/dist/{chunk-2hw8sr4d.js.map → chunk-wbj4jh1h.js.map} +1 -1
- package/dist/{chunk-9359fg6r.js → chunk-yknc5rgh.js} +1 -1
- package/dist/{chunk-9359fg6r.js.map → chunk-yknc5rgh.js.map} +1 -1
- package/dist/chunks/{RealtimeClient-C5Zh3fD6.js → RealtimeClient-DRVodyn1.js} +2 -2
- package/dist/chunks/{RealtimeClient-C5Zh3fD6.js.map → RealtimeClient-DRVodyn1.js.map} +1 -1
- package/dist/chunks/{ThemeProvider-bbbE-N3t.js → ThemeProvider-1WtAS7dH.js} +4 -4
- package/dist/chunks/{ThemeProvider-bbbE-N3t.js.map → ThemeProvider-1WtAS7dH.js.map} +1 -1
- package/dist/chunks/{fetchFileRequest-JXhnEi-R.js → fetchFileRequest-CVCelZqS.js} +2 -2
- package/dist/chunks/{fetchFileRequest-JXhnEi-R.js.map → fetchFileRequest-CVCelZqS.js.map} +1 -1
- package/dist/chunks/{live-CApTRvmK.js → live-twEh9Qwt.js} +3 -3
- package/dist/chunks/{live-CApTRvmK.js.map → live-twEh9Qwt.js.map} +1 -1
- package/dist/chunks/{mutationExtras-C2qSSZ2Q.js → mutationExtras-CM77Ur-9.js} +2 -2
- package/dist/chunks/{mutationExtras-C2qSSZ2Q.js.map → mutationExtras-CM77Ur-9.js.map} +1 -1
- package/dist/chunks/{subscriptionStream-DQLW7dTW.js → subscriptionStream-DQp1Krwi.js} +2 -2
- package/dist/chunks/{subscriptionStream-DQLW7dTW.js.map → subscriptionStream-DQp1Krwi.js.map} +1 -1
- package/dist/client/chunkLoadRecovery.d.ts +1 -1
- package/dist/client/index.js +4 -4
- package/dist/client/index.js.map +1 -1
- package/dist/facades/index.js +1 -1
- package/dist/http/index.js +1 -1
- package/dist/i18n/index.js +1 -1
- package/dist/kernel/index.js +1 -1
- package/dist/orm/index.js.map +1 -1
- package/dist/server/index.js +1 -1
- package/dist/services/index.js +1 -1
- package/dist/services/mcp/http/callers.d.ts +1 -1
- package/dist/testing/index.js +2 -2
- package/package.json +1 -1
- /package/dist/{chunk-adfkz2kf.js.map → chunk-0e5sq42y.js.map} +0 -0
|
@@ -20,7 +20,7 @@ ${await W$(X)}`);return Q.join(`
|
|
|
20
20
|
`)}})}async function W$(Z){try{return await Bun.file(Z).text()}catch($){return`(could not be read: ${$.message})`}}function V$(Z){return typeof Z==="object"&&Z!==null&&typeof Z.next==="function"&&Symbol.asyncIterator in Z}function s4(Z,$){let Q=[...Z],X=new Map(Q.map((B,G)=>[B.id,G]));for(let B of $){let G=X.get(B.id);if(G===void 0)X.set(B.id,Q.length),Q.push(B);else Q[G]=B}return Q}function MZ(Z){let $=new Set;for(let X of Z)for(let B of X.content)if(B.type==="tool-result")$.add(B.toolCallId);let Q=new Set;for(let X of Z)for(let B of X.content)if(B.type==="tool-call"&&!$.has(B.toolCallId))Q.add(B.toolCallId);return Q}function a4(Z){for(let $=Z.length-1;$>=0;$--){let Q=Z[$].content;for(let X=Q.length-1;X>=0;X--){let B=Q[X];if(B.type==="output"&&B.partial!==!0)return B.value}}return}function r4(Z,$){return $===void 0?`"${Z}"`:`"${Z}" labelled "${$}"`}function O7(Z){return Z.content.map(($)=>$.type==="text"?$.text:`<${$.type}>`).join("")}function J$(Z){if(Z.prompt!==void 0)return`user:${Z.prompt}`;let $=Z.messages?.[0];return $?`${$.role}:${O7($)}`:null}var e4=1;function H$(Z,$,Q){let X=Q.mimeType||$.type||"";if(X&&Z.attachment.mimeType!==X)return`was ${JSON.stringify(Z.attachment.mimeType)} on the turn that escalated and is ${JSON.stringify(X)} on the replay`;let B=Boolean(Q.showModel);if(B!==Boolean(Z.shown))return B?"was stored without showModel on the turn that escalated and asks for showModel on the replay":"was stored with showModel on the turn that escalated and asks for a plain put on the replay";return null}function Y$(Z,$,Q){if(Z.agent!==$.name||Z.label!==Q.label)return`was ${r4(Z.agent,Z.label)} on the turn that escalated and is ${r4($.name,Q.label)} on the replay`;let X=J$(Q),B=Z.messages[0],G=B?`${B.role}:${O7(B)}`:null;if(X!==null&&G!==null&&X!==G)return`was started with ${JSON.stringify(G)} on the turn that escalated and with ${JSON.stringify(X)} on the replay`;return null}function O0(Z,$){let Q=Z??[];if(Q.length<$.length)return null;for(let X=0;X<$.length;X++)if(Q[X]!==$[X])return null;return Q.slice($.length)}class R0{read;create;fill;index=0;replayable;constructor(Z,$,Q){this.read=Z;this.create=$;this.fill=Q;this.replayable=Z()?.length??0}next(){let Z=this.index++;return{at:Z,recorded:Z<this.replayable?this.read()?.[Z]:void 0,write:($)=>{let Q=this.read()??this.create();if(this.fill)for(let X=Q.length;X<Z;X++)Q[X]=this.fill();Q[Z]=$}}}}function Z7(Z,$,Q){return{id:`msg_${crypto.randomUUID()}`,role:"user",content:[...Z?[{type:"text",text:Z}]:[],...($??[]).map((X)=>({type:"file",...X.fileId?{fileId:X.fileId}:{},name:X.name,mimeType:X.mimeType,...X.attachmentId?{attachmentId:X.attachmentId}:{}}))],createdAt:new Date().toISOString(),finishReason:"stop",...Q?{event:{name:Q.name,...Q.data!==void 0?{data:Q.data}:{}}}:{}}}class C7{runId;config;params;context;controller=new AbortController;buffer=[];waiters=new Set;seq=0;ended=!1;history=[];compactMemo=new Map;lastStep;forceAgain;stepOffered;produced=[];current=null;outputTruncated=!1;amended=new Map;unreported=new Set;usage=x();modelSteps=0;toolCallCount=0;limiter;limitHit=null;approvals=new Map;denials=[];turn;finishReason="stop";cutCalls=0;failure;output;stopReason;timedOutAfter;cancelDeadline=()=>{};settled;meter;depth;maxDepth;chain;signingRunId;pathPrefix;onPending;openedWith=0;answeredOpen=!1;joins=[];joinable=!0;step=0;nestedSettling=new Set;shownQueue=new Map;memory;memoryBlock=null;constructor(Z,$){this.config=Z,this.params=$,this.context=$.context??{},this.runId=$.runId??`run_${crypto.randomUUID()}`,this.history=[...$.messages],this.limiter=$.usageLimits?new j0($.usageLimits,{runId:this.runId,agent:Z.name,...$.threadId?{threadId:$.threadId}:{}},(G)=>this.writeLog(`[gemi/ai] agent "${Z.name}" usageLimits.onUsage threw`,{error:G})):null;let Q=$.nesting;if(this.depth=Q?.depth??0,this.maxDepth=Q?.maxDepth??Z.maxDepth,this.chain=Q?.chain??[Z.name],this.signingRunId=Q?.signingRunId??this.runId,this.pathPrefix=Q?.signingPath??[],this.onPending=Q?.onPending??"escalate",this.memory=new LZ({options:Z.memory,scopes:$.memory?.scopes,agent:Z.name,runId:this.runId,threadId:$.threadId,writes:Q?.memoryWrites}),$.signal)if($.signal.aborted)this.controller.abort();else $.signal.addEventListener("abort",()=>this.stop(),{once:!0});let X=Z.maxRunDurationMs!==void 0?Z.maxRunDurationMs:Q?null:U7;this.cancelDeadline=L0(X,()=>this.expire(X));let B=tZ();this.meter=B.meter,this.settled=B.run(()=>this.execute()),this.settled.then(B.close,B.close),X7.getStore()?.waitUntil(this.settled)}emit(Z){if(this.ended)return;this.buffer.push({seq:++this.seq,event:Z}),this.wake()}wake(){let Z=[...this.waiters];this.waiters.clear();for(let $ of Z)$()}nextFrame(){return new Promise((Z)=>this.waiters.add(Z))}async*frames(Z=0){let $=Z>0?Z-1:0;for(;;){while($<this.buffer.length)yield this.buffer[$++];if(this.ended)return;await this.nextFrame()}}async*[Symbol.asyncIterator](){for await(let Z of this.frames())yield Z.event}toResponse(Z){let $=this.frames(Z?.from),Q=new TextEncoder,X=!1,B,G=new ReadableStream({start:async(W)=>{B=G7(W);try{for await(let V of $){if(X)break;W.enqueue(Q.encode(`id: ${V.seq}
|
|
21
21
|
data: ${JSON.stringify(V.event)}
|
|
22
22
|
|
|
23
|
-
`)),B.touch()}}catch{}B.stop();try{W.close()}catch{}},cancel:()=>{X=!0,B.stop()}});return new Response(G,{headers:{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})}result(Z){if(!Z?.throwOnError)return this.settled;return this.settled.then(($)=>{let Q=$.error;if(Q?.toolArgumentsTooLong)throw new P7({...$,error:{...Q,toolArgumentsTooLong:Q.toolArgumentsTooLong}});if(Q)throw new YZ({...$,error:Q});return $})}stop(Z){if(this.ended||this.controller.signal.aborted)return;this.stopReason=Z?.reason,this.controller.abort()}join(Z){if(this.depth>0||this.ended||!this.joinable||this.controller.signal.aborted)return null;if(this.step>=Math.max(1,this.config.maxSteps))return null;let $=Z.event?Z.event.text:Z.text;if(!Z.event&&!$&&!(Z.files&&Z.files.length>0))return null;let Q,X=new Promise((B)=>{Q=B});return this.joins.push({turn:Z,resolve:Q}),{taken:X}}expire(Z){if(this.ended||this.controller.signal.aborted)return;this.timedOutAfter=Z,this.stopReason=`The run reached its time limit of ${N0(Z)} and was stopped.`,this.controller.abort(new DOMException(this.stopReason,"TimeoutError"))}async execute(){this.emit({type:"run-start",runId:this.runId,threadId:this.params.threadId});try{await this.prepareMemory();let $=await this.resolveToolSchemas(),Q=$?[]:await this.ingestTurn();if($)this.fail($),this.finishReason="error";else if(Q.length>0)this.finishReason="awaiting-input",this.emit({type:"awaiting-input",runId:this.runId,pending:this.withTurn(Q)});else if(this.answersOnlyStale())this.fail({code:"invalid_tool_result",message:"The tool calls this turn answers are no longer waiting for an answer: an earlier turn answered or refused them.",retryable:!1}),this.finishReason="error";else await this.loop()}catch($){if($ instanceof S||this.controller.signal.aborted)await this.finalizeAborted();else if($ instanceof VZ)this.fail({code:"unknown",message:$.message,retryable:!0}),await this.finalizeMessage("error"),this.finishReason="error",this.writeLog(`[gemi/ai] agent "${this.config.name}" could not read its usage limits`,{error:$.cause});else this.fail(this.config.provider.normalizeError($),o($)),await this.finalizeMessage("error"),this.finishReason="error"}this.cancelDeadline(),this.joinable=!1;for(let $ of this.joins.splice(0))$.resolve(null);if(this.limiter)try{await this.limiter.report(this.spent(),!0)}catch($){this.writeLog(`[gemi/ai] agent "${this.config.name}" could not record its usage`,{error:$})}this.emit({type:"usage",usage:this.usage}),this.emit({type:"run-end",runId:this.runId,finishReason:this.finishReason}),this.ended=!0,this.wake(),this.precompact();let Z=this.finishReason==="error"?this.failure:void 0;if(Z&&this.config.logErrors)this.logFailure(Z);return{runId:this.runId,messages:this.produced,finishReason:this.finishReason,usage:this.usage,metered:this.meter.totals(),output:this.output,...Z?{error:Z}:{}}}async resolveToolSchemas(){let Z=[...this.config.registry.values()].filter((z)=>!z.inputSchema);if(Z.length===0)return;let $={context:this.context,body:this.params.body??{},runId:this.runId,threadId:this.params.threadId,signal:this.controller.signal},Q=new Map,X=await Promise.all(Z.map(async(z)=>{try{let J=z.tool.inputSchema,Y=await J($);M0(Y,`The tool "${z.tool.name}"`,"inputSchema"),Q.set(z.tool.name,Y);return}catch(J){return`"${z.tool.name}": ${J instanceof Error?J.message:String(J)}`}}));if(this.controller.signal.aborted)throw new S;let B=X.filter((z)=>z!==void 0);if(B.length>0)return{code:"tool_error",message:`Could not resolve the input schema of ${B.join("; ")}`,retryable:!1};let G=new Map;for(let[z,J]of this.config.registry)G.set(z,Q.has(z)?{...J,inputSchema:Q.get(z)}:J);let W=(z)=>Q.has(z.name)?HZ(G.get(z.name)):z,V=this.config.providerTools.map((z)=>("tools"in z)?{...z,tools:z.tools.map(W)}:W(z));this.config={...this.config,registry:G,providerTools:V};return}async prepareMemory(){let Z=this.config.memory;if(!Z)return;let $=this.memory,Q=$.writableLabels(),X=$.toolKinds(),B=(z)=>z==="recall"?$.labels.length>0:Q.length>0&&X.length>0,G=new Map;for(let[z,J]of this.config.registry){if(J.namespace!==f){G.set(z,J);continue}if(!B(z))continue;let Y=z==="recall"?$.labels:Q,K=XZ(z,{scopes:Y,descriptions:$.describeScopes(Y),kinds:X});G.set(z,{...J,inputSchema:K})}let W=this.config.providerTools.flatMap((z)=>{if(!("tools"in z)||z.name!==f)return[z];let J=z.tools.filter((Y)=>G.has(Y.name)).map((Y)=>HZ(G.get(Y.name)));return J.length>0?[{...z,tools:J}]:[]});this.config={...this.config,registry:G,providerTools:W};let V=this.params.memory?.maxTokens??Z.maxTokens??o0;try{this.memoryBlock=await $.block({maxTokens:V,recall:G.has("recall"),tools:G.has("remember")||G.has("forget")})}catch(z){let J=z instanceof Error?z.message:String(z);this.writeLog(`[gemi/ai] agent "${this.config.name}": the memory store could not be read, so this run has no <memory> block: ${J}`,{error:z})}if(this.controller.signal.aborted)throw new S}spent(){return{tokens:this.usage.totalTokens,steps:this.modelSteps,toolCalls:this.toolCallCount}}failOverLimit(Z){this.fail({code:"usage_limit",message:P0(Z),retryable:!1},{usageLimit:Z}),this.finishReason="error"}fail(Z,$={}){let Q={...Z,...$};this.failure=Q,this.emit({type:"error",error:this.redact(Q,{source:"run",failure:Q})})}redact(Z,$){let Q=z7(this.params.redactError,Z,$,(X)=>this.writeLog(`[gemi/ai] agent "${this.config.name}" redactError threw`,{error:X}));return W7(Q,Z),Q}logFailure(Z){let $=`[gemi/ai] agent "${this.config.name}" run failed (${Z.code}${Z.status!==void 0?` ${Z.status}`:""}): ${Z.message}`;this.writeLog($,{error:Z})}logToolFailure(Z,$){let Q=$ instanceof Error?$.message:String($);this.writeLog(`[gemi/ai] agent "${this.config.name}" tool "${String(Z.name)}" threw: ${Q}`,{toolCallId:Z.toolCallId,error:$})}writeLog(Z,$){let Q={agent:this.config.name,runId:this.runId,...this.params.threadId?{threadId:this.params.threadId}:{},...this.depth>0?{chain:this.chain}:{},...$},X=!1;try{a.error(Z,Q),X=!0}catch{}if(!X||Bun.env.NODE_ENV==="development")console.error(Z,Q)}async loop(){let Z=Math.max(1,this.config.maxSteps);for(let $=1;$<=Z;$++){if(this.step=$,this.limiter){let z=await this.limiter.check(this.spent(),{steps:1,tokens:1});if(z){this.failOverLimit(z);return}}await this.takeInbox(),await this.takeJoins();let Q=this.startMessage(),X=await this.runStep(Q,$);this.modelSteps++,this.lastStep={reason:X.reason,usage:Q.usage},await this.limiter?.report(this.spent());let B=X.error?this.cutCallToModel(Q,X.detail):void 0;if(X.error&&!B){this.fail(X.error,X.detail),await this.finalizeMessage("error"),this.finishReason="error";return}let G=Q.content.filter((z)=>z.type==="tool-call"&&z!==B);if(G.length===0&&!B&&X.emulated&&$<Z){this.forceAgain=X.emulated,await this.finalizeMessage(X.reason);continue}if(G.length===0&&!B){if(this.joins.length>0&&$<Z&&X.reason==="stop"){await this.finalizeMessage(X.reason);continue}this.joinable=!1,this.finishReason=X.reason,await this.finalizeMessage(X.reason);return}let W=G.length>0?await this.runTools(Q,G,$):[];if(await this.limiter?.report(this.spent()),this.limitHit&&W.length===0){let z=this.limitHit;await this.finalizeMessage(X.reason),this.failOverLimit(z);return}if(W.length>0){this.finishReason="awaiting-input";let z=this.withTurn(W);if(this.depth===0)Q.pending=z;await this.finalizeMessage("awaiting-input"),this.emit({type:"awaiting-input",runId:this.runId,pending:z});return}let V=B?null:await this.closingText(Q,G,$);if(V!==null){if(await this.finalizeMessage(X.reason),V){let z=this.startMessage();r(z,"text",V),this.emit({type:"text-delta",messageId:z.id,delta:V}),await this.finalizeMessage("stop")}if(this.joins.length>0&&$<Z)continue;this.finishReason="stop";return}if($===Z){this.finishReason="max-steps",await this.finalizeMessage("max-steps");return}await this.finalizeMessage(B?"stop":X.reason)}}cutCallToModel(Z,$){let Q=$?.toolArgumentsTooLong;if(!Q||!Q.toolCallId||this.cutCalls>=this.config.cutCallsToModel)return;let X=Z.content.find((B)=>B.type==="tool-call"&&B.toolCallId===Q.toolCallId);if(!X)X={type:"tool-call",toolCallId:Q.toolCallId,name:Q.tool,input:{}},Z.content.push(X);return this.cutCalls++,X.input={},this.emit({type:"tool-call",messageId:Z.id,part:X}),this.addResult(Z,{type:"tool-result",toolCallId:X.toolCallId,name:X.name,status:"error",error:{code:"invalid_tool_input",message:Q.whitespace!==void 0?`The arguments for "${Q.tool}" ran into more than ${Q.limit} characters of white space before they were complete, so the call did not run. Write the arguments again as compact JSON.`:`The arguments for "${Q.tool}" were cut off after more than ${Q.limit} characters, so the call did not run. Split the work over smaller calls.`,toolCallId:X.toolCallId,retryable:!0}}),X}async takeInbox(){let Z=this.depth===0?this.params.inbox:void 0;if(!Z)return;let $;try{$=await Z.take()}catch(Q){this.writeLog(`[gemi/ai] agent "${this.config.name}" could not read its inbox`,{error:Q});return}for(let Q of $){if(typeof Q!=="string"||Q.length===0)continue;let X={id:`msg_${crypto.randomUUID()}`,role:"user",content:[{type:"text",text:Q}],createdAt:new Date().toISOString(),finishReason:"stop",...this.turnField()};this.history.push(X),this.produced.push(X),this.emit({type:"message",message:X}),await this.report(X)}}async takeJoins(){while(this.joins.length>0){let{turn:Z,resolve:$}=this.joins.shift(),Q=this.turnStartId(),X={...Z7(Z.event?Z.event.text:Z.text,Z.files,Z.event),turn:Q,joined:Q};if(this.history.push(X),this.produced.push(X),Z.localId&&!Z.event)this.emit({type:"message-id",localId:Z.localId,messageId:X.id,message:X});else this.emit({type:"message",message:X});await this.report(X),$(X)}}continuedTurn(Z){let $=Z?this.history.indexOf(Z):this.history.length-1,Q=this.history[$];if(Q?.turn!==void 0)return Q.turn;let X=JZ(this.history);for(let B=$;B>=0;B--){let G=this.history[B];if(G.turn!==void 0)return G.turn;if(G.role==="user"&&!G.joined&&!X.has(G.id))return G.id}return this.history[0]?.id??""}withTurn(Z,$){let Q=this.depth===0?$??this.turn?.id:void 0;return Q?Z.map((X)=>X.turn===Q?X:{...X,turn:Q}):Z}othersTurn(Z){if(!this.turn||this.depth>0)return!1;let $=this.continuedTurn(Z);return $!==""&&$!==this.turn.id}turnStartId(){if(this.turn)return this.turn.id;let Z=JZ(this.history);for(let $=this.history.length-1;$>=0;$--){let Q=this.history[$];if(Q.role==="user"&&!Q.joined&&!Z.has(Q.id))return Q.id}return this.history[0]?.id??""}turnField(){return this.turn?{turn:this.turn.id}:{}}startMessage(){let Z={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString(),...this.turnField()};return this.current=Z,this.history.push(Z),this.produced.push(Z),this.emit({type:"message-start",messageId:Z.id,role:"assistant"}),Z}async finalizeMessage(Z){let $=this.current;if(!$)return;this.current=null;let Q=this.outputTruncated;if(this.outputTruncated=!1,$.finishReason=Z,Q)$.outputTruncated=!0;for(let X of $.content)if(X.type==="text"||X.type==="reasoning"){if(typeof X.text==="string")X.text=EZ(X.text)}this.emit({type:"message-end",messageId:$.id,finishReason:Z,...Q?{outputTruncated:!0}:{},...$.usage?{usage:$.usage}:{}}),await this.report($),await this.reportDeferred()}async report(Z){if(!this.params.onMessage)return;try{await this.params.onMessage(Z)}catch{}}async runStep(Z,$){let Q=this.controller.signal,X=this.config.provider;this.stepOffered=void 0;let B=await this.prepareRequest(Z,$);if("error"in B)return{reason:"error",error:B.error};this.stepOffered=B.offered;let W=(B.toolChoice==="required"||typeof B.toolChoice==="object")&&X.capabilities.supportsForcedToolChoice===!1,V=this.forceAgain!==void 0;this.forceAgain=void 0;let z=B.instructions,J={reason:"stop"},Y=new Map,K=[],q=()=>{if(K.length===0)return{};let _=K;return K=[],{toolSearches:_}},H="",D=[B.trailingContext,W?$$(B.toolChoice):void 0].filter(Boolean).join(`
|
|
23
|
+
`)),B.touch()}}catch{}B.stop();try{W.close()}catch{}},cancel:()=>{X=!0,B.stop()}});return new Response(G,{headers:{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})}result(Z){if(!Z?.throwOnError)return this.settled;return this.settled.then(($)=>{let Q=$.error;if(Q?.toolArgumentsTooLong)throw new P7({...$,error:{...Q,toolArgumentsTooLong:Q.toolArgumentsTooLong}});if(Q)throw new YZ({...$,error:Q});return $})}stop(Z){if(this.ended||this.controller.signal.aborted)return;this.stopReason=Z?.reason,this.controller.abort()}join(Z){if(this.depth>0||this.ended||!this.joinable||this.controller.signal.aborted)return null;if(this.step>=Math.max(1,this.config.maxSteps))return null;let $=Z.event?Z.event.text:Z.text;if(!Z.event&&!$&&!(Z.files&&Z.files.length>0))return null;let Q,X=new Promise((B)=>{Q=B});return this.joins.push({turn:Z,resolve:Q}),{taken:X}}expire(Z){if(this.ended||this.controller.signal.aborted)return;this.timedOutAfter=Z,this.stopReason=`The run reached its time limit of ${N0(Z)} and was stopped.`,this.controller.abort(new DOMException(this.stopReason,"TimeoutError"))}async execute(){this.emit({type:"run-start",runId:this.runId,threadId:this.params.threadId});try{await this.prepareMemory();let $=await this.resolveToolSchemas(),Q=$?[]:await this.ingestTurn();if($)this.fail($),this.finishReason="error";else if(Q.length>0)this.finishReason="awaiting-input",this.emit({type:"awaiting-input",runId:this.runId,pending:this.withTurn(Q)});else if(this.answersOnlyStale())this.fail({code:"invalid_tool_result",message:"The tool calls this turn answers are no longer waiting for an answer: an earlier turn answered or refused them.",retryable:!1}),this.finishReason="error";else await this.loop()}catch($){if($ instanceof S||this.controller.signal.aborted)await this.finalizeAborted();else if($ instanceof VZ)this.fail({code:"unknown",message:$.message,retryable:!0}),await this.finalizeMessage("error"),this.finishReason="error",this.writeLog(`[gemi/ai] agent "${this.config.name}" could not read its usage limits`,{error:$.cause});else this.fail(this.config.provider.normalizeError($),o($)),await this.finalizeMessage("error"),this.finishReason="error"}this.cancelDeadline(),this.joinable=!1;for(let $ of this.joins.splice(0))$.resolve(null);if(this.limiter)try{await this.limiter.report(this.spent(),!0)}catch($){this.writeLog(`[gemi/ai] agent "${this.config.name}" could not record its usage`,{error:$})}this.emit({type:"usage",usage:this.usage}),this.emit({type:"run-end",runId:this.runId,finishReason:this.finishReason}),this.ended=!0,this.wake(),this.precompact();let Z=this.finishReason==="error"?this.failure:void 0;if(Z&&this.config.logErrors)this.logFailure(Z);return{runId:this.runId,messages:this.produced,finishReason:this.finishReason,usage:this.usage,metered:this.meter.totals(),output:this.output,...Z?{error:Z}:{}}}async resolveToolSchemas(){let Z=[...this.config.registry.values()].filter((z)=>!z.inputSchema);if(Z.length===0)return;let $={context:this.context,body:this.params.body??{},runId:this.runId,threadId:this.params.threadId,signal:this.controller.signal},Q=new Map,X=await Promise.all(Z.map(async(z)=>{try{let J=z.tool.inputSchema,Y=await J($);M0(Y,`The tool "${z.tool.name}"`,"inputSchema"),Q.set(z.tool.name,Y);return}catch(J){return`"${z.tool.name}": ${J instanceof Error?J.message:String(J)}`}}));if(this.controller.signal.aborted)throw new S;let B=X.filter((z)=>z!==void 0);if(B.length>0)return{code:"tool_error",message:`Could not resolve the input schema of ${B.join("; ")}`,retryable:!1};let G=new Map;for(let[z,J]of this.config.registry)G.set(z,Q.has(z)?{...J,inputSchema:Q.get(z)}:J);let W=(z)=>Q.has(z.name)?HZ(G.get(z.name)):z,V=this.config.providerTools.map((z)=>("tools"in z)?{...z,tools:z.tools.map(W)}:W(z));this.config={...this.config,registry:G,providerTools:V};return}async prepareMemory(){let Z=this.config.memory;if(!Z)return;let $=this.memory,Q=$.writableLabels(),X=$.toolKinds(),B=(z)=>z==="recall"?$.labels.length>0:Q.length>0&&X.length>0,G=new Map;for(let[z,J]of this.config.registry){if(J.namespace!==f){G.set(z,J);continue}if(!B(z))continue;let Y=z==="recall"?$.labels:Q,K=XZ(z,{scopes:Y,descriptions:$.describeScopes(Y),kinds:X});G.set(z,{...J,inputSchema:K})}let W=this.config.providerTools.flatMap((z)=>{if(!("tools"in z)||z.name!==f)return[z];let J=z.tools.filter((Y)=>G.has(Y.name)).map((Y)=>HZ(G.get(Y.name)));return J.length>0?[{...z,tools:J}]:[]});this.config={...this.config,registry:G,providerTools:W};let V=this.params.memory?.maxTokens??Z.maxTokens??o0;try{this.memoryBlock=await $.block({maxTokens:V,recall:G.has("recall"),tools:G.has("remember")||G.has("forget")})}catch(z){let J=z instanceof Error?z.message:String(z);this.writeLog(`[gemi/ai] agent "${this.config.name}": the memory store could not be read, so this run has no <memory> block: ${J}`,{error:z})}if(this.controller.signal.aborted)throw new S}spent(){return{tokens:this.usage.totalTokens,steps:this.modelSteps,toolCalls:this.toolCallCount}}failOverLimit(Z){this.fail({code:"usage_limit",message:P0(Z),retryable:!1},{usageLimit:Z}),this.finishReason="error"}fail(Z,$={}){let Q={...Z,...$};this.failure=Q,this.emit({type:"error",error:this.redact(Q,{source:"run",failure:Q})})}redact(Z,$){let Q=z7(this.params.redactError,Z,$,(X)=>this.writeLog(`[gemi/ai] agent "${this.config.name}" redactError threw`,{error:X}));return W7(Q,Z),Q}logFailure(Z){let $=`[gemi/ai] agent "${this.config.name}" run failed (${Z.code}${Z.status!==void 0?` ${Z.status}`:""}): ${Z.message}`;this.writeLog($,{error:Z})}logToolFailure(Z,$){let Q=$ instanceof Error?$.message:String($);this.writeLog(`[gemi/ai] agent "${this.config.name}" tool "${String(Z.name)}" threw: ${Q}`,{toolCallId:Z.toolCallId,error:$})}writeLog(Z,$){let Q={agent:this.config.name,runId:this.runId,...this.params.threadId?{threadId:this.params.threadId}:{},...this.depth>0?{chain:this.chain}:{},...$},X=!1;try{a.error(Z,Q),X=!0}catch{}if(!X||Bun.env.NODE_ENV==="development")console.error(Z,Q)}async loop(){let Z=Math.max(1,this.config.maxSteps);for(let $=1;$<=Z;$++){if(this.step=$,this.limiter){let z=await this.limiter.check(this.spent(),{steps:1,tokens:1});if(z){this.failOverLimit(z);return}}await this.takeInbox(),await this.takeJoins();let Q=this.startMessage(),X=await this.runStep(Q,$);this.modelSteps++,this.lastStep={reason:X.reason,usage:Q.usage},await this.limiter?.report(this.spent());let B=X.error?this.cutCallToModel(Q,X.detail):void 0;if(X.error&&!B){this.fail(X.error,X.detail),await this.finalizeMessage("error"),this.finishReason="error";return}let G=Q.content.filter((z)=>z.type==="tool-call"&&z!==B);if(G.length===0&&!B&&X.emulated&&$<Z){this.forceAgain=X.emulated,await this.finalizeMessage(X.reason);continue}if(G.length===0&&!B){if(this.joins.length>0&&$<Z&&X.reason==="stop"){await this.finalizeMessage(X.reason);continue}this.joinable=!1,this.finishReason=X.reason,await this.finalizeMessage(X.reason);return}let W=G.length>0?await this.runTools(Q,G,$):[];if(await this.limiter?.report(this.spent()),this.limitHit&&W.length===0){let z=this.limitHit;await this.finalizeMessage(X.reason),this.failOverLimit(z);return}if(W.length>0){this.finishReason="awaiting-input";let z=this.withTurn(W);if(this.depth===0)Q.pending=z;await this.finalizeMessage("awaiting-input"),this.emit({type:"awaiting-input",runId:this.runId,pending:z});return}let V=B?null:await this.closingText(Q,G,$);if(V!==null){if(await this.finalizeMessage(X.reason),V){let z=this.startMessage();r(z,"text",V),this.emit({type:"text-delta",messageId:z.id,delta:V}),await this.finalizeMessage("stop")}if(this.joins.length>0&&$<Z)continue;this.finishReason="stop";return}if($===Z){this.finishReason="max-steps",await this.finalizeMessage("max-steps");return}await this.finalizeMessage(B?"stop":X.reason)}}cutCallToModel(Z,$){let Q=$?.toolArgumentsTooLong;if(!Q||!Q.toolCallId||this.cutCalls>=this.config.cutCallsToModel)return;let X=Z.content.find((B)=>B.type==="tool-call"&&B.toolCallId===Q.toolCallId);if(!X)X={type:"tool-call",toolCallId:Q.toolCallId,name:Q.tool,input:{}},Z.content.push(X);return this.cutCalls++,X.input={},this.emit({type:"tool-call",messageId:Z.id,part:X}),this.addResult(Z,{type:"tool-result",toolCallId:X.toolCallId,name:X.name,status:"error",error:{code:"invalid_tool_input",message:Q.whitespace!==void 0?`The arguments for "${Q.tool}" ran into more than ${Q.limit} characters of white space before they were complete, so the call did not run. Write the arguments again as compact JSON.`:`The arguments for "${Q.tool}" were cut off after more than ${Q.limit} characters, so the call did not run. Split the work over smaller calls.`,toolCallId:X.toolCallId,retryable:!0}}),X}async takeInbox(){let Z=this.depth===0?this.params.inbox:void 0;if(!Z)return;let $;try{$=await Z.take()}catch(Q){this.writeLog(`[gemi/ai] agent "${this.config.name}" could not read its inbox`,{error:Q});return}for(let Q of $){if(typeof Q!=="string"||Q.length===0)continue;let X={id:`msg_${crypto.randomUUID()}`,role:"user",content:[{type:"text",text:Q}],createdAt:new Date().toISOString(),finishReason:"stop",...this.turnField()};this.history.push(X),this.produced.push(X),this.emit({type:"message",message:X}),await this.report(X)}}async takeJoins(){while(this.joins.length>0){let{turn:Z,resolve:$}=this.joins.shift(),Q=this.turnStartId(),X={...Z7(Z.event?Z.event.text:Z.text,Z.files,Z.event),turn:Q,joined:Q};if(this.history.push(X),this.produced.push(X),Z.localId&&!Z.event)this.emit({type:"message-id",localId:Z.localId,messageId:X.id,message:X});else this.emit({type:"message",message:X});await this.report(X),$(X)}}continuedTurn(Z){let $=Z?this.history.indexOf(Z):this.history.length-1,Q=this.history[$];if(Q?.turn!==void 0)return Q.turn;let X=JZ(this.history);for(let B=$;B>=0;B--){let G=this.history[B];if(G.turn!==void 0)return G.turn;if(G.role==="user"&&!G.joined&&!X.has(G.id))return G.id}return this.history[0]?.id??""}withTurn(Z,$){let Q=this.depth===0?$??this.turn?.id:void 0;return Q?Z.map((X)=>X.turn===Q?X:{...X,turn:Q}):Z}othersTurn(Z){if(!this.turn||this.depth>0)return!1;let $=this.continuedTurn(Z);return $!==""&&$!==this.turn.id}turnStartId(){if(this.turn)return this.turn.id;let Z=JZ(this.history);for(let $=this.history.length-1;$>=0;$--){let Q=this.history[$];if(Q.role==="user"&&!Q.joined&&!Z.has(Q.id))return Q.id}return this.history[0]?.id??""}turnField(){return this.turn?{turn:this.turn.id}:{}}startMessage(){let Z={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString(),...this.turnField()};return this.current=Z,this.history.push(Z),this.produced.push(Z),this.emit({type:"message-start",messageId:Z.id,role:"assistant",...Z.turn?{turn:Z.turn}:{}}),Z}async finalizeMessage(Z){let $=this.current;if(!$)return;this.current=null;let Q=this.outputTruncated;if(this.outputTruncated=!1,$.finishReason=Z,Q)$.outputTruncated=!0;for(let X of $.content)if(X.type==="text"||X.type==="reasoning"){if(typeof X.text==="string")X.text=EZ(X.text)}this.emit({type:"message-end",messageId:$.id,finishReason:Z,...Q?{outputTruncated:!0}:{},...$.usage?{usage:$.usage}:{}}),await this.report($),await this.reportDeferred()}async report(Z){if(!this.params.onMessage)return;try{await this.params.onMessage(Z)}catch{}}async runStep(Z,$){let Q=this.controller.signal,X=this.config.provider;this.stepOffered=void 0;let B=await this.prepareRequest(Z,$);if("error"in B)return{reason:"error",error:B.error};this.stepOffered=B.offered;let W=(B.toolChoice==="required"||typeof B.toolChoice==="object")&&X.capabilities.supportsForcedToolChoice===!1,V=this.forceAgain!==void 0;this.forceAgain=void 0;let z=B.instructions,J={reason:"stop"},Y=new Map,K=[],q=()=>{if(K.length===0)return{};let _=K;return K=[],{toolSearches:_}},H="",D=[B.trailingContext,W?$$(B.toolChoice):void 0].filter(Boolean).join(`
|
|
24
24
|
|
|
25
25
|
`)||void 0,F=X.capabilities.trailingContext===!0,j=X.stream({messages:D&&!F?[...B.messages,Z$(D,this.turn?.id)]:B.messages,...D&&F?{trailingContext:D}:{},...B.allowedTools?{allowedTools:B.allowedTools}:{},systemPrompt:z,tools:B.tools.length>0?B.tools:void 0,...G$(this.config,this.config.instructions,this.config.providerTools),...B.toolChoice!==void 0?{toolChoice:B.toolChoice}:{},output:this.config.output?TZ(this.config.output):void 0,reasoning:B.reasoning,maxOutputTokens:B.maxOutputTokens,temperature:this.config.temperature,...this.cutCalls<this.config.cutCallsToModel?{retryToolArgumentsTooLong:!1}:{},agent:{name:this.config.name,depth:this.depth},signal:Q})[Symbol.asyncIterator](),L;for(;;){let _=await h(Promise.resolve(j.next()),Q).catch((O)=>{if(L&&O instanceof S)this.usage=M(this.usage,L.usage),DZ(L,X.model),Z.usage=M(Z.usage??x(),L.usage),L=void 0;throw O});if(_.done)break;let U=_.value;switch(U.type){case"usage":{L=U;break}case"text-delta":{r(Z,"text",U.delta),this.emit({type:"text-delta",messageId:Z.id,delta:U.delta});break}case"reasoning-delta":{kZ(Z,U.id,U.delta,U.providerMetadata),this.emit({type:"reasoning-delta",messageId:Z.id,delta:U.delta,id:U.id,...U.providerMetadata?{providerMetadata:U.providerMetadata}:{}});break}case"output-delta":{H+=U.delta,this.emit({type:"output-delta",messageId:Z.id,delta:U.delta,snapshot:C0(H)});break}case"tool-search":{K.push({namespaces:U.namespaces,loaded:U.loaded,...U.arguments!==void 0?{arguments:U.arguments}:{}}),this.emit({type:"tool-search",loaded:U.loaded});break}case"tool-call-delta":{let O=Y.get(U.toolCallId)??{name:U.name,args:""};O.args+=U.argsDelta,O.name=U.name||O.name,O.namespace=U.namespace||O.namespace,Y.set(U.toolCallId,O),this.emit({type:"tool-call",messageId:Z.id,part:{type:"tool-call",toolCallId:U.toolCallId,name:O.name,input:C0(O.args),partial:!0,...O.namespace?{namespace:O.namespace}:{}}});break}case"tool-call-discard":{for(let O of U.toolCallIds)Y.delete(O);this.emit({type:"tool-call-discard",messageId:Z.id,toolCallIds:U.toolCallIds});break}case"tool-call":{let O=U.namespace||Y.get(U.toolCallId)?.namespace||(this.config.registry.get(U.name)?.namespace===w?w:void 0);Y.delete(U.toolCallId);let I={type:"tool-call",toolCallId:U.toolCallId,name:U.name,input:Q7(U.args),...O?{namespace:O}:{},...q()};Z.content.push(I),this.emit({type:"tool-call",messageId:Z.id,part:I});break}case"finish":{if(L=void 0,this.usage=M(this.usage,U.usage),c(U.model??X.model,U.usage),Z.usage=M(Z.usage??x(),U.usage),!J.error)J={reason:U.reason};break}case"error":{J={reason:"error",error:U.error,detail:{...o(U),...U.toolArgumentsTooLong?{toolArgumentsTooLong:U.toolArgumentsTooLong}:{}}};break}case"file-rejected":{this.markFileRejected(U.fileId,U.message,o(U));break}case"retry":{this.emit({type:"retry",messageId:Z.id,attempt:U.attempt,maxRetries:U.maxRetries,code:U.error.code,delayMs:U.delayMs,...U.remainingMs!==void 0?{remainingMs:U.remainingMs}:{}});let O=this.params.onProviderRetry;if(O){let{type:I,...R}=U,k=(b)=>this.writeLog(`[gemi/ai] agent "${this.config.name}" onProviderRetry threw`,{error:b});try{let b=O({...R,runId:this.runId,agent:this.config.name,step:$});if(b instanceof Promise)b.catch(k)}catch(b){k(b)}}break}}}for(let[_,U]of Y){let O={type:"tool-call",toolCallId:_,name:U.name,input:Q7(U.args),...U.namespace?{namespace:U.namespace}:{},...q()};Z.content.push(O),this.emit({type:"tool-call",messageId:Z.id,part:O})}let N=J.reason==="length";if(N)this.outputTruncated=!0;if(this.config.output&&H&&!J.error&&!N){let _=SZ(this.config.output,H);if(_.ok===!0)this.output=_.value,Z.content.push({type:"output",value:_.value,text:H});else this.emit({type:"error",error:_.error})}if(W&&!V&&!J.error)J.emulated=B.toolChoice;return J}compactJobParams(Z,$){let Q=this.config.contextWindow;if(!Q?.compact||!this.params.threadId||this.depth!==0)return;let X=Q.compact===!0?{}:Q.compact;return{history:Z,stored:this.history.filter((B)=>B!==$),window:Q,compact:X,threadId:this.params.threadId,provider:this.config.provider,store:X.store||this.params.summaryStore||v4,skills:this.skillNames()}}skillNames(){let Z=new Set;for(let[$,Q]of this.config.registry)if(Q.namespace===w)Z.add($);return Z}precompact(){let Z=this.config.contextWindow;if(!Z?.compact||Z.compact!==!0&&Z.compact.background===!1)return;try{let $=this.compactJobParams(this.historyForProvider(void 0),void 0);if($)h4($)}catch{}}async prepareRequest(Z,$){let Q=this.historyForProvider(Z),X=this.config.contextWindow,B=this.compactJobParams(Q,Z),G=!X?Q:B?await w4({...B,signal:this.controller.signal,onUsage:(F)=>{this.usage=M(this.usage,F)},memo:this.compactMemo}):WZ(Q,X).messages,W=await this.systemPrompt(),V=this.config.reasoning,z=this.config.maxOutputTokens,J,Y,K=(this.depth===0?this.params.trailingContext:void 0)||void 0;for(let F of this.config.prepareStep){let P;try{P=await F({step:$,messages:[...G],history:[...Q],instructions:W,reasoning:V,maxOutputTokens:z,activeTools:J,toolChoice:Y,trailingContext:K,body:this.params.body??{},usage:this.usage,...this.lastStep?.usage?{lastStepUsage:this.lastStep.usage}:{},...this.lastStep?{lastFinishReason:this.lastStep.reason}:{},runId:this.runId,threadId:this.params.threadId,agent:this.config.name,depth:this.depth,context:this.context,signal:this.controller.signal})}catch(j){if(j instanceof S||this.controller.signal.aborted)throw j;return{error:{code:"unknown",message:`prepareStep threw: ${j instanceof Error?j.message:String(j)}`,retryable:!1}}}if(!P)continue;if(P.messages!==void 0){if(!Array.isArray(P.messages))return{error:{code:"unknown",message:"prepareStep answered `messages` that is not an array.",retryable:!1}};G=P.messages}if(P.instructions!==void 0)W=P.instructions||void 0;if(P.reasoning!==void 0)V=P.reasoning;if(P.maxOutputTokens!==void 0)z=P.maxOutputTokens;if(P.activeTools!==void 0)J=P.activeTools;if(P.toolChoice!==void 0)Y=P.toolChoice;if(P.trailingContext!==void 0)K=P.trailingContext||void 0}if(this.forceAgain&&Y===void 0)Y=this.forceAgain;let q=this.config.providerTools,H=this.config.offered;if(J)try{({providerTools:q,offered:H}=N7(this.config,J,`prepareStep (step ${$})`))}catch(F){return{error:{code:"unknown",message:F instanceof Error?F.message:String(F),retryable:!1}}}if(Y!==void 0){let F=Q$(Y,q,H,this.config.registry);if(F)return{error:{code:"unknown",message:`prepareStep ${F}`,retryable:!1}}}let D=J&&H&&this.config.provider.capabilities.allowedTools===!0?[...H]:void 0;return{messages:G,instructions:W,reasoning:V,maxOutputTokens:z,tools:D?this.config.providerTools:q,offered:J?H:void 0,toolChoice:Y,allowedTools:D,trailingContext:K}}async systemPrompt(){let Z=[this.config.instructions,this.params.instructions,this.memoryBlock].filter(($)=>Boolean($&&$.trim()));return Z.length>0?Z.join(`
|
|
26
26
|
|
|
@@ -45,4 +45,4 @@ ${wZ(Z)}
|
|
|
45
45
|
Correct these problems and give the whole answer again.`}function C$(Z,$,Q){let X=`[gemi/ai] generate() failed (${$.code}${$.status!==void 0?` ${$.status}`:""}): ${$.message}`,B={...Q,generateId:Z,error:$},G=!1;try{a.error(X,B),G=!0}catch{}if(!G||Bun.env.NODE_ENV==="development")console.error(X,B)}async function _$(Z,$){let Q=Z.messages??[];if(Q.length===0&&!Z.prompt)throw Error("generate() was given neither a `prompt` nor `messages`, so there is nothing to send the model.");let X=[...Q];if(Z.prompt)X.push({id:`msg_${crypto.randomUUID()}`,role:"user",content:[{type:"text",text:Z.prompt}],createdAt:new Date().toISOString()});let B={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString()},G=Z.signal??new AbortController().signal,W=x(),V="stop",z,J={},Y="",K=Z.onPartial?new fZ:void 0;try{let F=Z.provider.stream({messages:[...X],systemPrompt:Z.instructions?.trim()?Z.instructions:void 0,output:TZ(Z.output),reasoning:Z.reasoning,maxOutputTokens:Z.maxOutputTokens,temperature:Z.temperature,signal:Z.signal})[Symbol.asyncIterator](),P;try{for(;;){let j=await h(Promise.resolve(F.next()),G).catch((N)=>{if(P&&N instanceof S)W=M(W,P.usage),DZ(P,Z.provider.model),P=void 0;throw N});if(j.done)break;let L=j.value;switch(L.type){case"usage":P=L;break;case"output-delta":if(Y+=L.delta,K){let N=K.push(L.delta);if(K.changed||N.length>0)R$(Z.onPartial,K.snapshot(),{attempt:$,closed:N})}break;case"text-delta":r(B,"text",L.delta);break;case"reasoning-delta":kZ(B,L.id,L.delta,L.providerMetadata);break;case"finish":if(P=void 0,W=M(W,L.usage),c(L.model??Z.provider.model,L.usage),!z)V=L.reason;break;case"error":V="error",z=L.error,J=o(L);break;case"retry":{let{type:N,..._}=L;try{let U=Z.onProviderRetry?.(_);if(U instanceof Promise)U.catch(()=>{})}catch{}break}}}}finally{if(G.aborted)Promise.resolve(F.return?.()).catch(()=>{})}}catch(D){if(D instanceof S||G.aborted)V="aborted",z=x7(G);else V="error",z=Z.provider.normalizeError(D),J=o(D)}let q=!1,H;if(!z)if(V==="length")z={code:"invalid_output",message:"The model ran out of output tokens before finishing its structured answer, so it was cut off. Raise maxOutputTokens, or ask for a shorter answer.",retryable:!0};else if(!Y.trim())z={code:"invalid_output",message:"The model finished without giving a structured answer.",retryable:!0};else{let D=SZ(Z.output,Y);if(D.ok===!0)q=!0,H=D.value;else z=D.error}if(q)B.content.push({type:"output",value:H,text:Y});else if(Y)r(B,"text",Y);for(let D of B.content)if((D.type==="text"||D.type==="reasoning")&&typeof D.text==="string")D.text=EZ(D.text);if(B.finishReason=V,B.usage=W,X.push(B),q)return{ok:!0,output:H,messages:X,usage:W,finishReason:V};return{ok:!1,error:{...z,...J},messages:X,usage:W,finishReason:V}}function R$(Z,$,Q){let X=(B)=>{let G=`[gemi/ai] generate() onPartial threw: ${B instanceof Error?B.message:String(B)}`;try{a.warning(G,{error:B})}catch{console.error(G,B)}};try{let B=Z($,Q);if(B instanceof Promise)B.catch(X)}catch(B){X(B)}}function x7(Z){return Z.reason?.name==="TimeoutError"?{code:"timeout",message:"The generation timed out.",retryable:!0}:{code:"aborted",message:"The generation was stopped.",retryable:!1}}var f7=Symbol.for("gemi.ai.JobHandle");class w7{id;toolCallId;summary;deadlineAt;[f7]=!0;constructor(Z,$,Q,X){this.id=Z;this.toolCallId=$;this.summary=Q;this.deadlineAt=X}}function J7(Z){return typeof Z==="object"&&Z!==null&&Z[f7]===!0}class k0 extends C{code="jobs_require_thread";constructor(Z){super(Z,{retryable:!1});this.name="JobsRequireThreadError"}}var u=new rZ,yZ=new Set,I$=["waiting","running","ok","error"],KZ=new Set,hZ=new Map,d={get store(){return u},use(Z){u=Z},get(Z){return u.get(Z)},onSettled(Z){return yZ.add(Z),()=>{yZ.delete(Z)}},async settle(Z,$){return e(u,Z,$)},async fail(Z,$){return e(u,Z,{error:$})},async sweep(Z={}){let $=u,Q=Z.limit??100,X=await M$($),B=0;for(let G of await $.overdue(X,Q))if(await x$($,G))B++;if($.waiting)for(let G of await $.waiting(Q))try{await f0($,G)}catch(W){console.error(`Could not advance waiting background job ${G.id}.`,W)}return B},async start(Z,$,Q={}){let X=await b0(A7(Q,Z.name),{job:Z,args:$,options:Q});return uZ(X)},async track(Z={}){let $=await b0(A7(Z,"job"),{job:null,args:void 0,options:Z});return uZ($)},async cancel(Z,$={}){let Q=u,X=await Q.get(Z);if(!X||p(X.state))return!1;if($.silent)KZ.add(Z);if(!await Q.transition(Z,["waiting","running"],{state:"error",error:{code:"cancelled",message:$.reason??`The background job for "${X.toolName}" was cancelled.`,...X.toolCallId?{toolCallId:X.toolCallId}:{},retryable:!1}}))return KZ.delete(Z),!1;return await dZ(Q,Z),!0},async message(Z,$){let Q=u;if(!Q.appendInbox)throw Error("AgentJobs.message needs a job store with an inbox (appendInbox and takeInbox).");return Q.appendInbox(Z,$)},onSettledBatch(Z,$={}){let Q=new u7(Z,$),X=d.onSettled((G)=>Q.add(G)),B=()=>{X(),Q.stop()};return B.flush=(G,W)=>Q.flush(G,W?.now===!0),B}};function A7(Z,$){return{threadId:Z.threadId??"",runId:"",toolCallId:"",toolName:Z.name??$,owner:Z.owner??null,attachmentScope:Z.attachmentScope??null,deadlineMs:Z.deadlineMs??h7}}async function b0(Z,$){let Q=d.store,{job:X,args:B,options:G}=$,W=Z.deadlineMs;if(!Number.isFinite(W)||W<=0)throw new C(`A job's deadlineMs must be a positive number; got ${W}.`);let V=G.after?[...new Set(G.after)]:[],z=!1;if(V.length>0){if(!X)throw new C("A tracked job cannot wait for others: `after` is only for `start`.",{retryable:!1});if(!Q.waitingOn)throw Error("`after` needs a job store that can list waiting jobs (waitingOn).");for(let K of V){let q=await Q.get(K);if(!q)throw new C(`The job waits for ${K}, which does not exist.`,{retryable:!1});if(q.state==="error")throw new C(`The job waits for ${K}, which did not finish (${q.error?.code??"error"}). Leave it out, or start that work again.`,{retryable:!1});if(q.state!=="ok")z=!0}}if(X&&(X.name==="unset"||!X.name))throw Error("Cannot start an AgentJob with no `static name`.");let J=async()=>{let K=await Q.create({id:`ajob_${crypto.randomUUID()}`,threadId:Z.threadId,runId:Z.runId,toolCallId:Z.toolCallId,toolName:Z.toolName,owner:Z.owner,job:X?X.name:null,...G.summary!==void 0?{summary:gZ(G.summary,Z)}:{},attachmentScope:Z.attachmentScope,deadlineMs:W,...V.length>0?{after:V}:{},...G.batch!==void 0?{batch:G.batch}:{},...z?{state:"waiting",queued:{args:gZ(B,Z),deadlineMs:W}}:{}});if(X&&!z)try{await y7(X,{jobId:K.id,args:B})}catch(q){if(Q.transaction)throw q;throw await Q.transition(K.id,["running"],{state:"error",error:{code:"tool_error",message:`The background job for "${Z.toolName}" could not be queued.`,...Z.toolCallId?{toolCallId:Z.toolCallId}:{},retryable:!0}}).catch(()=>{}),q}return K},Y=Q.transaction?await Q.transaction(J):await J();if(z)await f0(Q,Y);return await Q.get(Y.id)??Y}async function M$(Z){return Z.now?await Z.now():Date.now()}async function x$(Z,$){let Q=await Z.transition($.id,["running"],{state:"error",error:{code:"timeout",message:`The background job for "${$.toolName}" did not finish before its deadline, so it was given up on. Its result, if it ever arrives, is ignored.`,toolCallId:$.toolCallId,retryable:!0}});if(Q)await dZ(Z,$.id);return Q}async function dZ(Z,$){hZ.get($)?.abort(new C("The background job was settled while it ran."));try{await A$(Z,$)}catch(Q){console.error(`Could not start or cancel the jobs waiting for background job ${$}.`,Q)}S$(Z,$)}async function A$(Z,$){if(!Z.waitingOn)return;for(let Q of await Z.waitingOn($))await f0(Z,Q)}async function f0(Z,$){let Q=$.after??[],X=await Promise.all(Q.map((z)=>Z.get(z))),B=Q.find((z,J)=>X[J]===null),G=X.find((z)=>z?.state==="error");if(B!==void 0||G){let z=G?.error?.code==="cancelled",J=G?.id??B;if(await Z.transition($.id,["waiting"],{state:"error",error:{code:z?"cancelled":"dependency_failed",message:G?`It waited for ${J}, which ${z?"was cancelled":"failed"}, so it did not start.`:`It waited for ${J}, which can no longer be found, so it did not start.`,...$.toolCallId?{toolCallId:$.toolCallId}:{},retryable:!1}})){if(KZ.has(J))KZ.add($.id);await dZ(Z,$.id)}return}if(X.some((z)=>z.state!=="ok"))return;if(!await Z.transition($.id,["waiting"],{state:"running",...$.queued?{deadlineMs:$.queued.deadlineMs}:{}}))return;let V=$.job?T$($.job):void 0;if(!V){if($.job===null)return;await e(Z,$.id,{error:{code:"tool_error",message:`The background job ${$.job} is not registered with the queue, so it could not start.`,retryable:!1}});return}try{await y7(V,{jobId:$.id,args:$.queued?.args})}catch(z){console.error(`Could not queue background job ${$.id} after its dependencies.`,z),await e(Z,$.id,{error:{code:"tool_error",message:`The background job for "${$.toolName}" could not be queued.`,retryable:!0}})}}function T$(Z){try{return ZZ(v0).jobs[Z]}catch{return}}function S$(Z,$){if(KZ.delete($))return;if(yZ.size===0)return;let Q=[...yZ];(async()=>{let X=await Z.get($);if(!X||!p(X.state))return;for(let B of Q)try{await B(X)}catch(G){console.error(`An AgentJobs.onSettled listener failed for background job ${$}.`,G)}})().catch((X)=>{console.error(`Could not read background job ${$} for its onSettled listeners.`,X)})}async function e(Z,$,Q){let X=await Z.get($);if(!X||X.state!=="running")return!1;let B=Q.usage?M(X.usage??x(),Q.usage):void 0,G="error"in Q?await Z.transition($,["running"],{state:"error",error:E$(X,Q.error),...B?{usage:B}:{}}):await Z.transition($,["running"],{state:"ok",output:gZ(Q.output,X),...B?{usage:B}:{}});if(G)await dZ(Z,$);return G}function E$(Z,$){if(typeof $==="string")return{code:"tool_error",message:$,toolCallId:Z.toolCallId,retryable:!0};if($ instanceof Error){let Q={code:"tool_error",message:$.message,toolCallId:Z.toolCallId,retryable:$ instanceof C?$.retryable:!0};if(!($ instanceof C))console.error(`The background job ${Z.job??"(tracked)"} for "${Z.toolName}" failed.`,$);return E7(Q,{source:"tool",toolName:Z.toolName,cause:$})}return{code:$.code??"tool_error",message:String($.message),toolCallId:Z.toolCallId,retryable:$.retryable??!0}}function gZ(Z,$){if(Z===void 0)return null;try{return JSON.parse(JSON.stringify(Z))}catch(Q){throw Error(`The output of the background job for "${$.toolName}" is not JSON: ${String(Q)}`)}}var h7=3600000;function H7(Z){let $=null,Q=(X,B,G={})=>{if(Z.async===void 0)throw new C(`"${Z.toolName}" called ctx.jobs, but the tool does not declare \`async\`. Add \`async: { deadlineMs }\` to its definition.`,{retryable:!1});if(!Z.jobs||!Z.threadId)throw new k0(`"${Z.toolName}" can only run in the background on a conversation the server keeps (a turn with a threadId), and this one has none.`);if(Z.depth>0)throw new k0(`"${Z.toolName}" can only run in the background from the top-level agent, not from a sub-agent.`);if($)throw new C(`"${Z.toolName}" started a background job already: a tool call has at most one.`,{retryable:!1});let W=G.deadlineMs??Z.async.deadlineMs??h7;if(!Number.isFinite(W)||W<=0)throw new C(`A job's deadlineMs must be a positive number; got ${W}.`);let{jobs:V,threadId:z}=Z;return $=(async()=>{let J=(await d.store.listForThread(z,{limit:50})).find((K)=>K.toolCallId===Z.toolCallId);if(J)return uZ(J);let Y=await b0({threadId:z,runId:Z.runId,toolCallId:Z.toolCallId,toolName:Z.toolName,owner:V.owner,attachmentScope:Z.attachments?.scopeKey??null,deadlineMs:W},{job:X,args:B,options:G});return uZ(Y)})(),$};return{start:(X,B,G)=>Q(X,B,G),track:(X)=>Q(null,void 0,X)}}function uZ(Z){return new w7(Z.id,Z.toolCallId,Z.summary,Z.deadlineAt)}function y7(Z,$){return ZZ(v0).push(Z,JSON.stringify([$]))}class k$ extends k7{attachments=v7;attachmentStorage=S7;cancelCheckMs=5000;constructor(){super();let Z=this.run;this.run=($)=>this.$runEnvelope($,Z)}onDeadletter(Z,...$){let Q=$[0];if(!Q?.jobId)return;e(d.store,Q.jobId,{error:Z}).catch((X)=>{console.error(`Could not record the failure of background job ${Q.jobId}.`,X)})}async $runEnvelope(Z,$){let Q=d.store,X=await Q.get(Z.jobId);if(!X||X.state!=="running")return;let B=new AbortController;hZ.set(X.id,B);let G=this.cancelCheckMs>0?setInterval(()=>{Q.get(X.id).then((z)=>{if(z&&z.state!=="running"&&!B.signal.aborted)B.abort(new C("The background job was cancelled."))}).catch(()=>{})},this.cancelCheckMs):void 0;G?.unref?.();let W=new g7(X,this,B.signal),V;try{V=await $.call(this,Z.args,W)}catch(z){await T7(Q,X.id,W.usage);let J=await Q.get(X.id).catch(()=>null);if(B.signal.aborted||J&&J.state!=="running")return;throw z}finally{if(clearInterval(G),hZ.get(X.id)===B)hZ.delete(X.id)}if(this.$outcome)return await T7(Q,X.id,W.usage),V;return await e(Q,X.id,{output:V,usage:W.usage}),V}}async function T7(Z,$,Q){if(Q.totalTokens===0&&Q.inputTokens===0&&Q.outputTokens===0)return;let X=await Z.get($);if(!X)return;await Z.transition($,I$,{usage:M(X.usage??x(),Q)}).catch(()=>{})}class g7{signal;id;threadId;toolCallId;toolName;owner;summary;after;batch;checkpointed;inbox;usage=x();attachments;constructor(Z,$,Q){this.signal=Q;this.id=Z.id,this.after=Z.after??[],this.batch=Z.batch,this.checkpointed=Z.checkpoint;let X=d.store;this.inbox={take:async()=>X.takeInbox?await X.takeInbox(Z.id):[]},this.threadId=Z.threadId,this.toolCallId=Z.toolCallId,this.toolName=Z.toolName,this.owner=Z.owner,this.summary=Z.summary;let B=Z.attachmentScope?new b7($.attachments,$.attachmentStorage,{key:Z.attachmentScope}):null,G=()=>{if(!B)throw new bZ("The run that started this job had no attachment scope, so the job cannot store or read files. See `attachmentScope()` on the controller.");return B};this.attachments={put:(W,V={})=>G().put(W,V),get:(W)=>G().get(W),read:(W)=>G().read(W),file:(W)=>G().file(W)}}async checkpoint(Z){return d.store.transition(this.id,["running"],{checkpoint:gZ(Z,this)})}generate(Z){return qZ(Z,{origin:{threadId:this.threadId,toolCallId:this.toolCallId,jobId:this.id},settled:($)=>{this.usage=M(this.usage,$.usage)}})}async generateImage(Z,$){let{name:Q,...X}=$,B=await Z.generate({...X,signal:this.signal});return this.park(Z,B,Q)}async editImage(Z,$){let{name:Q,images:X,mask:B,...G}=$,W=async(z)=>typeof z==="string"?await this.attachments.file(z):z,V=await Z.edit({...G,images:await Promise.all(X.map(W)),...B?{mask:await W(B)}:{},signal:this.signal});return this.park(Z,V,Q)}async park(Z,$,Q){this.usage=M(this.usage,$.usage);let X=$.mimeType==="image/jpeg"?"jpg":"png";return{attachment:await this.attachments.put($.image,{name:Q??`${Z.name}.${X}`,mimeType:$.mimeType}),size:$.size,mimeType:$.mimeType,usage:$.usage}}}class u7{listener;options;groups=new Map;stopped=!1;delayMs;maxDelayMs;keyOf;constructor(Z,$){this.listener=Z;this.options=$;this.delayMs=Math.max(0,$.delayMs??1000),this.maxDelayMs=Math.max(this.delayMs,$.maxDelayMs??this.delayMs*10),this.keyOf=$.key??((Q)=>Q.threadId)}add(Z){if(this.stopped)return;let $=this.keyOf(Z),Q=this.groups.get($);if(!Q)Q={jobs:new Map,first:void 0,timer:void 0,busy:!1,again:!1},this.groups.set($,Q);Q.jobs.set(Z.id,Z),Q.first??=Date.now(),this.schedule($,!1)}flush(Z,$){for(let Q of Z===void 0?[...this.groups.keys()]:[Z])if(this.groups.has(Q))this.schedule(Q,$)}stop(){this.stopped=!0;for(let Z of this.groups.values())clearTimeout(Z.timer);this.groups.clear()}schedule(Z,$){let Q=this.groups.get(Z);if(!Q)return;if(Q.busy){Q.again=!0;return}clearTimeout(Q.timer);let X=Q.first===void 0?this.delayMs:Q.first+this.maxDelayMs-Date.now(),B=$?0:Math.max(0,Math.min(this.delayMs,X));Q.timer=setTimeout(()=>void this.run(Z),B),Q.timer.unref?.()}async run(Z){let $=this.groups.get(Z);if(!$||this.stopped)return;$.timer=void 0,$.busy=!0;try{for(;;){$.again=!1;let Q=await this.ready([...$.jobs.values()]);if(Q.length===0)break;let X=this.options.hold?await this.options.hold(Q,Z):!1;if(X===!0)break;if(typeof X==="number"&&X>0){setTimeout(()=>this.flush(Z,!0),X).unref?.();break}for(let B of Q)$.jobs.delete(B.id);try{await this.listener(Q,Z)}catch(B){console.error(`An AgentJobs.onSettledBatch listener failed for ${Z}.`,B)}if(this.stopped)return}}catch(Q){console.error(`Could not report the settled background jobs of ${Z}.`,Q)}finally{if($.busy=!1,$.jobs.size===0){if(this.groups.get(Z)===$)this.groups.delete(Z)}else if($.first=void 0,$.again)this.schedule(Z,!1)}}async ready(Z){let $=d.store,Q=new Map,X=[];for(let B of Z){if(B.batch===void 0||!$.listBatch){X.push(B);continue}let G=Q.get(B.batch);if(!G)G=new Map((await $.listBatch(B.batch)).map((J)=>[J.id,J])),Q.set(B.batch,G);let W=G,V=(J,Y,K=new Set)=>{if(K.has(J.id))return!1;K.add(J.id);let q=J.after??[];return q.includes(Y)||q.some((H)=>{let D=W.get(H);return D!==void 0&&V(D,Y,K)})};if(![...W.values()].some((J)=>J.id!==B.id&&!p(J.state)&&!V(J,B.id)))X.push(B)}return X}}
|
|
46
46
|
export{u0 as jc,d7 as kc,c7 as lc,iZ as mc,BZ as nc,E as oc,tZ as pc,c as qc,l7 as rc,g$ as sc,u$ as tc,p as uc,rZ as vc,w7 as wc,J7 as xc,k0 as yc,d as zc,M$ as Ac,x$ as Bc,h7 as Cc,H7 as Dc,k$ as Ec,o0 as Fc,a0 as Gc,X9 as Hc,B9 as Ic,UZ as Jc,t as Kc,G0 as Lc,i as Mc,z0 as Nc,V9 as Oc,f as Pc,X1 as Qc,O9 as Rc,R9 as Sc,M9 as Tc,x9 as Uc,b4 as Vc,T9 as Wc,v4 as Xc,q1 as Yc,K1 as Zc,d4 as _c,p4 as $c,p9 as ad,s as bd,y as cd,vZ as dd,q7 as ed,w as fd,y1 as gd,U7 as hd,YZ as id,P7 as jd,A0 as kd,X$ as ld,Z7 as md,u1 as nd,u4 as od,qZ as pd};
|
|
47
47
|
|
|
48
|
-
//# debugId=
|
|
48
|
+
//# debugId=94B3472CA8088C5864756E2164756E21
|