gemi 0.211.0 → 0.213.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 (36) hide show
  1. package/dist/ai/Agent.d.ts +3 -1
  2. package/dist/ai/Agent.d.ts.map +1 -1
  3. package/dist/ai/AgentProvider.d.ts +13 -1
  4. package/dist/ai/AgentProvider.d.ts.map +1 -1
  5. package/dist/ai/index.d.ts +1 -1
  6. package/dist/ai/index.d.ts.map +1 -1
  7. package/dist/ai/index.js +1 -1
  8. package/dist/ai/providers/call.d.ts +2 -0
  9. package/dist/ai/providers/call.d.ts.map +1 -1
  10. package/dist/ai/providers/http.d.ts +27 -0
  11. package/dist/ai/providers/http.d.ts.map +1 -1
  12. package/dist/ai/testing/index.js +1 -1
  13. package/dist/{chunk-th8cagtz.js → chunk-1tvg25na.js} +1 -1
  14. package/dist/chunk-3ejv7fs4.js +11 -0
  15. package/dist/{chunk-2swfxn2c.js.map → chunk-3ejv7fs4.js.map} +5 -5
  16. package/dist/{chunk-t3vgqv9a.js → chunk-8r7w8s60.js} +2 -2
  17. package/dist/{chunk-t3vgqv9a.js.map → chunk-8r7w8s60.js.map} +3 -3
  18. package/dist/{chunk-nvszx92e.js → chunk-gzda2jzb.js} +2 -2
  19. package/dist/{chunk-nvszx92e.js.map → chunk-gzda2jzb.js.map} +1 -1
  20. package/dist/chunk-m1grhk90.js +10 -0
  21. package/dist/chunk-m1grhk90.js.map +44 -0
  22. package/dist/{chunk-2p5anpf5.js → chunk-rme358mr.js} +1 -1
  23. package/dist/kernel/index.js +1 -1
  24. package/dist/server/index.js +1 -1
  25. package/dist/services/index.d.ts +1 -1
  26. package/dist/services/index.d.ts.map +1 -1
  27. package/dist/services/index.js +1 -1
  28. package/dist/services/mcp/McpRegistry.d.ts +14 -0
  29. package/dist/services/mcp/McpRegistry.d.ts.map +1 -1
  30. package/dist/services/mcp/http/McpHttpServer.d.ts.map +1 -1
  31. package/package.json +1 -1
  32. package/dist/chunk-2swfxn2c.js +0 -11
  33. package/dist/chunk-31xknhg0.js +0 -10
  34. package/dist/chunk-31xknhg0.js.map +0 -44
  35. /package/dist/{chunk-th8cagtz.js.map → chunk-1tvg25na.js.map} +0 -0
  36. /package/dist/{chunk-2p5anpf5.js.map → chunk-rme358mr.js.map} +0 -0
@@ -22,7 +22,7 @@ data: ${JSON.stringify(W.event)}
22
22
 
23
23
  `)),X.touch()}}catch{}X.stop();try{V.close()}catch{}},cancel:()=>{B=!0,X.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 j7({...$,error:{...Q,toolArgumentsTooLong:Q.toolArgumentsTooLong}});if(Q)throw new HZ({...$,error:Q});return $})}stop(Z){if(this.ended||this.controller.signal.aborted)return;this.stopReason=Z?.reason,this.controller.abort()}expire(Z){if(this.ended||this.controller.signal.aborted)return;this.timedOutAfter=Z,this.stopReason=`The run reached its time limit of ${O0(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: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 WZ)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($),i($)),await this.finalizeMessage("error"),this.finishReason="error"}if(this.cancelDeadline(),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,B=await Promise.all(Z.map(async(z)=>{try{let J=z.tool.inputSchema,H=await J($);x0(H,`The tool "${z.tool.name}"`,"inputSchema"),Q.set(z.tool.name,H);return}catch(J){return`"${z.tool.name}": ${J instanceof Error?J.message:String(J)}`}}));if(this.controller.signal.aborted)throw new S;let X=B.filter((z)=>z!==void 0);if(X.length>0)return{code:"tool_error",message:`Could not resolve the input schema of ${X.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 V=(z)=>Q.has(z.name)?JZ(G.get(z.name)):z,W=this.config.providerTools.map((z)=>("tools"in z)?{...z,tools:z.tools.map(V)}:V(z));this.config={...this.config,registry:G,providerTools:W};return}async prepareMemory(){let Z=this.config.memory;if(!Z)return;let $=this.memory,Q=$.writableLabels(),B=$.toolKinds(),X=(z)=>z==="recall"?$.labels.length>0:Q.length>0&&B.length>0,G=new Map;for(let[z,J]of this.config.registry){if(J.namespace!==v){G.set(z,J);continue}if(!X(z))continue;let H=z==="recall"?$.labels:Q,q=BZ(z,{scopes:H,descriptions:$.describeScopes(H),kinds:B});G.set(z,{...J,inputSchema:q})}let V=this.config.providerTools.flatMap((z)=>{if(!("tools"in z)||z.name!==v)return[z];let J=z.tools.filter((H)=>G.has(H.name)).map((H)=>JZ(G.get(H.name)));return J.length>0?[{...z,tools:J}]:[]});this.config={...this.config,registry:G,providerTools:V};let W=this.params.memory?.maxTokens??Z.maxTokens??t0;try{this.memoryBlock=await $.block({maxTokens:W,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:L0(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=V7(this.params.redactError,Z,$,(B)=>this.writeLog(`[gemi/ai] agent "${this.config.name}" redactError threw`,{error:B}));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}:{},...$},B=!1;try{t.error(Z,Q),B=!0}catch{}if(!B||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.limiter){let z=await this.limiter.check(this.spent(),{steps:1,tokens:1});if(z){this.failOverLimit(z);return}}await this.takeInbox();let Q=this.startMessage(),B=await this.runStep(Q,$);this.modelSteps++,this.lastStep={reason:B.reason,usage:Q.usage},await this.limiter?.report(this.spent());let X=B.error?this.cutCallToModel(Q,B.detail):void 0;if(B.error&&!X){this.fail(B.error,B.detail),await this.finalizeMessage("error"),this.finishReason="error";return}let G=Q.content.filter((z)=>z.type==="tool-call"&&z!==X);if(G.length===0&&!X&&B.emulated&&$<Z){this.forceAgain=B.emulated,await this.finalizeMessage(B.reason);continue}if(G.length===0&&!X){this.finishReason=B.reason,await this.finalizeMessage(B.reason);return}let V=G.length>0?await this.runTools(Q,G,$):[];if(await this.limiter?.report(this.spent()),this.limitHit&&V.length===0){let z=this.limitHit;await this.finalizeMessage(B.reason),this.failOverLimit(z);return}if(V.length>0){if(this.finishReason="awaiting-input",this.depth===0)Q.pending=V;await this.finalizeMessage("awaiting-input"),this.emit({type:"awaiting-input",runId:this.runId,pending:V});return}let W=X?null:await this.closingText(Q,G,$);if(W!==null){if(this.finishReason="stop",await this.finalizeMessage(B.reason),W){let z=this.startMessage();s(z,"text",W),this.emit({type:"text-delta",messageId:z.id,delta:W}),await this.finalizeMessage("stop")}return}if($===Z){this.finishReason="max-steps",await this.finalizeMessage("max-steps");return}await this.finalizeMessage(X?"stop":B.reason)}}cutCallToModel(Z,$){let Q=$?.toolArgumentsTooLong;if(!Q||this.cutCalls>=this.config.cutCallsToModel)return;let B=Z.content.find((X)=>X.type==="tool-call"&&X.toolCallId===Q.toolCallId);if(!B)return;return this.cutCalls++,B.input={},this.emit({type:"tool-call",messageId:Z.id,part:B}),this.addResult(Z,{type:"tool-result",toolCallId:B.toolCallId,name:B.name,status:"error",error:{code:"invalid_tool_input",message:`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:B.toolCallId,retryable:!0}}),B}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 B={id:`msg_${crypto.randomUUID()}`,role:"user",content:[{type:"text",text:Q}],createdAt:new Date().toISOString(),finishReason:"stop"};this.history.push(B),this.produced.push(B),this.emit({type:"message",message:B}),await this.report(B)}}startMessage(){let Z={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString()};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 B of $.content)if(B.type==="text"||B.type==="reasoning"){if(typeof B.text==="string")B.text=kZ(B.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,B=this.config.provider;this.stepOffered=void 0;let X=await this.prepareRequest(Z,$);if("error"in X)return{reason:"error",error:X.error};this.stepOffered=X.offered;let V=(X.toolChoice==="required"||typeof X.toolChoice==="object")&&B.capabilities.supportsForcedToolChoice===!1,W=this.forceAgain!==void 0;this.forceAgain=void 0;let z=V?[X.instructions,V$(X.toolChoice)].filter(Boolean).join(`
24
24
 
25
- `):X.instructions,J={reason:"stop"},H=new Map,q=[],K=()=>{if(q.length===0)return{};let P=q;return q=[],{toolSearches:P}},Y="",D=B.stream({messages:X.messages,systemPrompt:z,tools:X.tools.length>0?X.tools:void 0,...Y$(this.config,X.instructions,X.tools),...X.toolChoice!==void 0?{toolChoice:X.toolChoice}:{},output:this.config.output?TZ(this.config.output):void 0,reasoning:X.reasoning,maxOutputTokens:X.maxOutputTokens,temperature:this.config.temperature,signal:Q})[Symbol.asyncIterator]();for(;;){let P=await f(Promise.resolve(D.next()),Q);if(P.done)break;let U=P.value;switch(U.type){case"text-delta":{s(Z,"text",U.delta),this.emit({type:"text-delta",messageId:Z.id,delta:U.delta});break}case"reasoning-delta":{bZ(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":{Y+=U.delta,this.emit({type:"output-delta",messageId:Z.id,delta:U.delta,snapshot:R0(Y)});break}case"tool-search":{q.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 L=H.get(U.toolCallId)??{name:U.name,args:""};L.args+=U.argsDelta,L.name=U.name||L.name,L.namespace=U.namespace||L.namespace,H.set(U.toolCallId,L),this.emit({type:"tool-call",messageId:Z.id,part:{type:"tool-call",toolCallId:U.toolCallId,name:L.name,input:R0(L.args),partial:!0,...L.namespace?{namespace:L.namespace}:{}}});break}case"tool-call-discard":{for(let L of U.toolCallIds)H.delete(L);this.emit({type:"tool-call-discard",messageId:Z.id,toolCallIds:U.toolCallIds});break}case"tool-call":{let L=U.namespace||H.get(U.toolCallId)?.namespace||(this.config.registry.get(U.name)?.namespace===w?w:void 0);H.delete(U.toolCallId);let O={type:"tool-call",toolCallId:U.toolCallId,name:U.name,input:B7(U.args),...L?{namespace:L}:{},...K()};Z.content.push(O),this.emit({type:"tool-call",messageId:Z.id,part:O});break}case"finish":{if(this.usage=I(this.usage,U.usage),ZZ(U.model??B.model,U.usage),Z.usage=I(Z.usage??x(),U.usage),!J.error)J={reason:U.reason};break}case"error":{J={reason:"error",error:U.error,detail:{...i(U),...U.toolArgumentsTooLong?{toolArgumentsTooLong:U.toolArgumentsTooLong}:{}}};break}case"file-rejected":{this.markFileRejected(U.fileId,U.message,i(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 L=this.params.onProviderRetry;if(L){let{type:O,...R}=U,E=(_)=>this.writeLog(`[gemi/ai] agent "${this.config.name}" onProviderRetry threw`,{error:_});try{let _=L({...R,runId:this.runId,agent:this.config.name,step:$});if(_ instanceof Promise)_.catch(E)}catch(_){E(_)}}break}}}for(let[P,U]of H){let L={type:"tool-call",toolCallId:P,name:U.name,input:B7(U.args),...U.namespace?{namespace:U.namespace}:{},...K()};Z.content.push(L),this.emit({type:"tool-call",messageId:Z.id,part:L})}let j=J.reason==="length";if(j)this.outputTruncated=!0;if(this.config.output&&Y&&!J.error&&!j){let P=EZ(this.config.output,Y);if(P.ok===!0)this.output=P.value,Z.content.push({type:"output",value:P.value,text:Y});else this.emit({type:"error",error:P.error})}if(V&&!W&&!J.error)J.emulated=X.toolChoice;return J}compactJobParams(Z,$){let Q=this.config.contextWindow;if(!Q?.compact||!this.params.threadId||this.depth!==0)return;let B=Q.compact===!0?{}:Q.compact;return{history:Z,stored:this.history.filter((X)=>X!==$),window:Q,compact:B,threadId:this.params.threadId,provider:this.config.provider,store:B.store||this.params.summaryStore||w4,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($)y4($)}catch{}}async prepareRequest(Z,$){let Q=this.historyForProvider(Z),B=this.config.contextWindow,X=this.compactJobParams(Q,Z),G=!B?Q:X?await h4({...X,signal:this.controller.signal,onUsage:(Y)=>{this.usage=I(this.usage,Y)},memo:this.compactMemo}):GZ(Q,B).messages,V=await this.systemPrompt(),W=this.config.reasoning,z=this.config.maxOutputTokens,J,H;for(let Y of this.config.prepareStep){let F;try{F=await Y({step:$,messages:[...G],history:[...Q],instructions:V,reasoning:W,maxOutputTokens:z,activeTools:J,toolChoice:H,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(D){if(D instanceof S||this.controller.signal.aborted)throw D;return{error:{code:"unknown",message:`prepareStep threw: ${D instanceof Error?D.message:String(D)}`,retryable:!1}}}if(!F)continue;if(F.messages!==void 0){if(!Array.isArray(F.messages))return{error:{code:"unknown",message:"prepareStep answered `messages` that is not an array.",retryable:!1}};G=F.messages}if(F.instructions!==void 0)V=F.instructions||void 0;if(F.reasoning!==void 0)W=F.reasoning;if(F.maxOutputTokens!==void 0)z=F.maxOutputTokens;if(F.activeTools!==void 0)J=F.activeTools;if(F.toolChoice!==void 0)H=F.toolChoice}if(this.forceAgain&&H===void 0)H=this.forceAgain;let q=this.config.providerTools,K=this.config.offered;if(J)try{({providerTools:q,offered:K}=N7(this.config,J,`prepareStep (step ${$})`))}catch(Y){return{error:{code:"unknown",message:Y instanceof Error?Y.message:String(Y),retryable:!1}}}if(H!==void 0){let Y=W$(H,q,K,this.config.registry);if(Y)return{error:{code:"unknown",message:`prepareStep ${Y}`,retryable:!1}}}return{messages:G,instructions:V,reasoning:W,maxOutputTokens:z,tools:q,offered:J?K:void 0,toolChoice:H}}async systemPrompt(){let Z=[this.config.instructions,this.params.instructions,this.memoryBlock].filter(($)=>Boolean($&&$.trim()));return Z.length>0?Z.join(`
25
+ `):X.instructions,J={reason:"stop"},H=new Map,q=[],K=()=>{if(q.length===0)return{};let P=q;return q=[],{toolSearches:P}},Y="",D=B.stream({messages:X.messages,systemPrompt:z,tools:X.tools.length>0?X.tools:void 0,...Y$(this.config,X.instructions,X.tools),...X.toolChoice!==void 0?{toolChoice:X.toolChoice}:{},output:this.config.output?TZ(this.config.output):void 0,reasoning:X.reasoning,maxOutputTokens:X.maxOutputTokens,temperature:this.config.temperature,...this.cutCalls<this.config.cutCallsToModel?{retryToolArgumentsTooLong:!1}:{},signal:Q})[Symbol.asyncIterator]();for(;;){let P=await f(Promise.resolve(D.next()),Q);if(P.done)break;let U=P.value;switch(U.type){case"text-delta":{s(Z,"text",U.delta),this.emit({type:"text-delta",messageId:Z.id,delta:U.delta});break}case"reasoning-delta":{bZ(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":{Y+=U.delta,this.emit({type:"output-delta",messageId:Z.id,delta:U.delta,snapshot:R0(Y)});break}case"tool-search":{q.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 L=H.get(U.toolCallId)??{name:U.name,args:""};L.args+=U.argsDelta,L.name=U.name||L.name,L.namespace=U.namespace||L.namespace,H.set(U.toolCallId,L),this.emit({type:"tool-call",messageId:Z.id,part:{type:"tool-call",toolCallId:U.toolCallId,name:L.name,input:R0(L.args),partial:!0,...L.namespace?{namespace:L.namespace}:{}}});break}case"tool-call-discard":{for(let L of U.toolCallIds)H.delete(L);this.emit({type:"tool-call-discard",messageId:Z.id,toolCallIds:U.toolCallIds});break}case"tool-call":{let L=U.namespace||H.get(U.toolCallId)?.namespace||(this.config.registry.get(U.name)?.namespace===w?w:void 0);H.delete(U.toolCallId);let O={type:"tool-call",toolCallId:U.toolCallId,name:U.name,input:B7(U.args),...L?{namespace:L}:{},...K()};Z.content.push(O),this.emit({type:"tool-call",messageId:Z.id,part:O});break}case"finish":{if(this.usage=I(this.usage,U.usage),ZZ(U.model??B.model,U.usage),Z.usage=I(Z.usage??x(),U.usage),!J.error)J={reason:U.reason};break}case"error":{J={reason:"error",error:U.error,detail:{...i(U),...U.toolArgumentsTooLong?{toolArgumentsTooLong:U.toolArgumentsTooLong}:{}}};break}case"file-rejected":{this.markFileRejected(U.fileId,U.message,i(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 L=this.params.onProviderRetry;if(L){let{type:O,...R}=U,E=(_)=>this.writeLog(`[gemi/ai] agent "${this.config.name}" onProviderRetry threw`,{error:_});try{let _=L({...R,runId:this.runId,agent:this.config.name,step:$});if(_ instanceof Promise)_.catch(E)}catch(_){E(_)}}break}}}for(let[P,U]of H){let L={type:"tool-call",toolCallId:P,name:U.name,input:B7(U.args),...U.namespace?{namespace:U.namespace}:{},...K()};Z.content.push(L),this.emit({type:"tool-call",messageId:Z.id,part:L})}let j=J.reason==="length";if(j)this.outputTruncated=!0;if(this.config.output&&Y&&!J.error&&!j){let P=EZ(this.config.output,Y);if(P.ok===!0)this.output=P.value,Z.content.push({type:"output",value:P.value,text:Y});else this.emit({type:"error",error:P.error})}if(V&&!W&&!J.error)J.emulated=X.toolChoice;return J}compactJobParams(Z,$){let Q=this.config.contextWindow;if(!Q?.compact||!this.params.threadId||this.depth!==0)return;let B=Q.compact===!0?{}:Q.compact;return{history:Z,stored:this.history.filter((X)=>X!==$),window:Q,compact:B,threadId:this.params.threadId,provider:this.config.provider,store:B.store||this.params.summaryStore||w4,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($)y4($)}catch{}}async prepareRequest(Z,$){let Q=this.historyForProvider(Z),B=this.config.contextWindow,X=this.compactJobParams(Q,Z),G=!B?Q:X?await h4({...X,signal:this.controller.signal,onUsage:(Y)=>{this.usage=I(this.usage,Y)},memo:this.compactMemo}):GZ(Q,B).messages,V=await this.systemPrompt(),W=this.config.reasoning,z=this.config.maxOutputTokens,J,H;for(let Y of this.config.prepareStep){let F;try{F=await Y({step:$,messages:[...G],history:[...Q],instructions:V,reasoning:W,maxOutputTokens:z,activeTools:J,toolChoice:H,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(D){if(D instanceof S||this.controller.signal.aborted)throw D;return{error:{code:"unknown",message:`prepareStep threw: ${D instanceof Error?D.message:String(D)}`,retryable:!1}}}if(!F)continue;if(F.messages!==void 0){if(!Array.isArray(F.messages))return{error:{code:"unknown",message:"prepareStep answered `messages` that is not an array.",retryable:!1}};G=F.messages}if(F.instructions!==void 0)V=F.instructions||void 0;if(F.reasoning!==void 0)W=F.reasoning;if(F.maxOutputTokens!==void 0)z=F.maxOutputTokens;if(F.activeTools!==void 0)J=F.activeTools;if(F.toolChoice!==void 0)H=F.toolChoice}if(this.forceAgain&&H===void 0)H=this.forceAgain;let q=this.config.providerTools,K=this.config.offered;if(J)try{({providerTools:q,offered:K}=N7(this.config,J,`prepareStep (step ${$})`))}catch(Y){return{error:{code:"unknown",message:Y instanceof Error?Y.message:String(Y),retryable:!1}}}if(H!==void 0){let Y=W$(H,q,K,this.config.registry);if(Y)return{error:{code:"unknown",message:`prepareStep ${Y}`,retryable:!1}}}return{messages:G,instructions:V,reasoning:W,maxOutputTokens:z,tools:q,offered:J?K:void 0,toolChoice:H}}async systemPrompt(){let Z=[this.config.instructions,this.params.instructions,this.memoryBlock].filter(($)=>Boolean($&&$.trim()));return Z.length>0?Z.join(`
26
26
 
27
27
  `):void 0}async runTools(Z,$,Q){let B=[],X=[],G=this.config.toolExecution==="sequential",V=Promise.resolve(),W=null;for(let z of $){let J=String(z.name),H=this.stepOffered??this.config.offered,K=!H||H.has(J)?this.config.registry.get(J):void 0;if(!K){this.addResult(Z,{type:"tool-result",toolCallId:z.toolCallId,name:z.name,status:"error",error:{code:"tool_error",message:`There is no tool named "${String(z.name)}".`,toolCallId:z.toolCallId,retryable:!0}});continue}let Y=K.inputSchema.safeParse(z.input);if(Y.ok===!1){this.addResult(Z,{type:"tool-result",toolCallId:z.toolCallId,name:z.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${String(z.name)}": ${Y.errors.join(", ")}`,toolCallId:z.toolCallId,retryable:!0}});continue}z.input=Y.value;let F=Q7(K.tool);if(F==="approval"&&K.tool.approvalPredicate&&!await this.asksApproval(K.tool,z,Y.value,Q))F=null;if(F){let P=F==="approval"?this.deniedEarlier(K.tool,z):void 0;if(P){this.addResult(Z,{type:"tool-result",toolCallId:z.toolCallId,name:z.name,status:"denied",cause:"denied-earlier",...P.approval.reason!==void 0?{reason:P.approval.reason}:{}});continue}if(this.onPending==="deny"){this.addResult(Z,this.deniedByPolicy(z));continue}let U=F==="approval"&&K.tool.approvalPreview?await this.previewApproval(K.tool,z,Y.value,Q):void 0;B.push({toolCallId:z.toolCallId,name:z.name,input:Y.value,kind:F,signature:L4(this.claimsFor(z.toolCallId,String(z.name),F,Y.value)),...this.pathPrefix.length>0?{path:[...this.pathPrefix]}:{},...U!==void 0?{preview:U}:{}});continue}if(this.limiter){let P=this.limitHit;if(!P&&!W)try{P=await this.limiter.check(this.spent(),{toolCalls:1})}catch(U){if(!(U instanceof WZ))throw U;W=U}if(W){this.addResult(Z,{type:"tool-result",toolCallId:z.toolCallId,name:z.name,status:"error",error:{code:"unknown",message:W.message,toolCallId:z.toolCallId,retryable:!0}});continue}if(P){this.limitHit=P,this.addResult(Z,{type:"tool-result",toolCallId:z.toolCallId,name:z.name,status:"error",error:{code:"usage_limit",message:L0(P),toolCallId:z.toolCallId,retryable:!1}});continue}}this.toolCallCount++;let D=()=>this.executeTool(K,Z.id,z,Y.value,Q),j=(G?V.then(()=>{if(this.controller.signal.aborted)throw new S;return D()}):D()).then(async(P)=>{this.addResult(Z,P),await this.settleShown(z.toolCallId)}).catch((P)=>{if(P instanceof o){if(this.onPending==="deny"){this.addResult(Z,this.deniedByPolicy(z));return}B.push(...P.pending);return}});if(G)V=j;X.push(j)}if(await f(Promise.all(X).then(()=>{return}),this.controller.signal),W)throw W;return B}async closingText(Z,$,Q){let B=[];for(let X of $){let G=this.config.registry.get(String(X.name))?.tool;if(!G?.endsRun)return null;let V=Z.content.find((z)=>z.type==="tool-result"&&z.toolCallId===X.toolCallId);if(V?.status!=="ok")return null;let W=!0;if(typeof G.endsRun==="function"){let z={input:X.input,context:this.context,body:this.params.body??{},runId:this.runId,threadId:this.params.threadId,toolCallId:X.toolCallId,step:Q,depth:this.depth,signal:this.controller.signal};try{W=await f(Promise.resolve().then(()=>G.endsRun(V.output,z)),this.controller.signal)}catch(J){if(J instanceof S)throw J;return this.writeLog(`[gemi/ai] agent "${this.config.name}": the endsRun of "${G.name}" threw, so the run carries on`,{error:J,toolCallId:X.toolCallId}),null}}if(typeof W==="string"){if(W)B.push(W)}else if(W!==!0)return null}return B.join(`
28
28
 
@@ -45,4 +45,4 @@ ${hZ(Z)}
45
45
  Correct these problems and give the whole answer again.`}function A$(Z,$,Q){let B=`[gemi/ai] generate() failed (${$.code}${$.status!==void 0?` ${$.status}`:""}): ${$.message}`,X={...Q,generateId:Z,error:$},G=!1;try{t.error(B,X),G=!0}catch{}if(!G||Bun.env.NODE_ENV==="development")console.error(B,X)}async function S$(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 B=[...Q];if(Z.prompt)B.push({id:`msg_${crypto.randomUUID()}`,role:"user",content:[{type:"text",text:Z.prompt}],createdAt:new Date().toISOString()});let X={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString()},G=Z.signal??new AbortController().signal,V=x(),W="stop",z,J={},H="",q=Z.onPartial?new fZ:void 0;try{let D=Z.provider.stream({messages:[...B],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]();try{for(;;){let j=await f(Promise.resolve(D.next()),G);if(j.done)break;let P=j.value;switch(P.type){case"output-delta":if(H+=P.delta,q){let U=q.push(P.delta);if(q.changed||U.length>0)T$(Z.onPartial,q.snapshot(),{attempt:$,closed:U})}break;case"text-delta":s(X,"text",P.delta);break;case"reasoning-delta":bZ(X,P.id,P.delta,P.providerMetadata);break;case"finish":if(V=I(V,P.usage),ZZ(P.model??Z.provider.model,P.usage),!z)W=P.reason;break;case"error":W="error",z=P.error,J=i(P);break;case"retry":{let{type:U,...L}=P;try{let O=Z.onProviderRetry?.(L);if(O instanceof Promise)O.catch(()=>{})}catch{}break}}}}finally{if(G.aborted)Promise.resolve(D.return?.()).catch(()=>{})}}catch(F){if(F instanceof S||G.aborted)W="aborted",z=A7(G);else W="error",z=Z.provider.normalizeError(F),J=i(F)}let K=!1,Y;if(!z)if(W==="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(!H.trim())z={code:"invalid_output",message:"The model finished without giving a structured answer.",retryable:!0};else{let F=EZ(Z.output,H);if(F.ok===!0)K=!0,Y=F.value;else z=F.error}if(K)X.content.push({type:"output",value:Y,text:H});else if(H)s(X,"text",H);for(let F of X.content)if((F.type==="text"||F.type==="reasoning")&&typeof F.text==="string")F.text=kZ(F.text);if(X.finishReason=W,X.usage=V,B.push(X),K)return{ok:!0,output:Y,messages:B,usage:V,finishReason:W};return{ok:!1,error:{...z,...J},messages:B,usage:V,finishReason:W}}function T$(Z,$,Q){let B=(X)=>{let G=`[gemi/ai] generate() onPartial threw: ${X instanceof Error?X.message:String(X)}`;try{t.warning(G,{error:X})}catch{console.error(G,X)}};try{let X=Z($,Q);if(X instanceof Promise)X.catch(B)}catch(X){B(X)}}function A7(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 h7{id;toolCallId;summary;deadlineAt;[f7]=!0;constructor(Z,$,Q,B){this.id=Z;this.toolCallId=$;this.summary=Q;this.deadlineAt=B}}function H7(Z){return typeof Z==="object"&&Z!==null&&Z[f7]===!0}class b0 extends C{code="jobs_require_thread";constructor(Z){super(Z,{retryable:!1});this.name="JobsRequireThreadError"}}var g=new eZ,gZ=new Set,E$=["waiting","running","ok","error"],qZ=new Set,yZ=new Map,u={get store(){return g},use(Z){g=Z},get(Z){return g.get(Z)},onSettled(Z){return gZ.add(Z),()=>{gZ.delete(Z)}},async settle(Z,$){return a(g,Z,$)},async fail(Z,$){return a(g,Z,{error:$})},async sweep(Z={}){let $=g,Q=Z.limit??100,B=await k$($),X=0;for(let G of await $.overdue(B,Q))if(await b$($,G))X++;if($.waiting)for(let G of await $.waiting(Q))try{await f0($,G)}catch(V){console.error(`Could not advance waiting background job ${G.id}.`,V)}return X},async start(Z,$,Q={}){let B=await v0(S7(Q,Z.name),{job:Z,args:$,options:Q});return dZ(B)},async track(Z={}){let $=await v0(S7(Z,"job"),{job:null,args:void 0,options:Z});return dZ($)},async cancel(Z,$={}){let Q=g,B=await Q.get(Z);if(!B||d(B.state))return!1;if($.silent)qZ.add(Z);if(!await Q.transition(Z,["waiting","running"],{state:"error",error:{code:"cancelled",message:$.reason??`The background job for "${B.toolName}" was cancelled.`,...B.toolCallId?{toolCallId:B.toolCallId}:{},retryable:!1}}))return qZ.delete(Z),!1;return await cZ(Q,Z),!0},async message(Z,$){let Q=g;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 d7(Z,$),B=u.onSettled((G)=>Q.add(G)),X=()=>{B(),Q.stop()};return X.flush=(G,V)=>Q.flush(G,V?.now===!0),X}};function S7(Z,$){return{threadId:Z.threadId??"",runId:"",toolCallId:"",toolName:Z.name??$,owner:Z.owner??null,attachmentScope:Z.attachmentScope??null,deadlineMs:Z.deadlineMs??y7}}async function v0(Z,$){let Q=u.store,{job:B,args:X,options:G}=$,V=Z.deadlineMs;if(!Number.isFinite(V)||V<=0)throw new C(`A job's deadlineMs must be a positive number; got ${V}.`);let W=G.after?[...new Set(G.after)]:[],z=!1;if(W.length>0){if(!B)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 q of W){let K=await Q.get(q);if(!K)throw new C(`The job waits for ${q}, which does not exist.`,{retryable:!1});if(K.state==="error")throw new C(`The job waits for ${q}, which did not finish (${K.error?.code??"error"}). Leave it out, or start that work again.`,{retryable:!1});if(K.state!=="ok")z=!0}}if(B&&(B.name==="unset"||!B.name))throw Error("Cannot start an AgentJob with no `static name`.");let J=async()=>{let q=await Q.create({id:`ajob_${crypto.randomUUID()}`,threadId:Z.threadId,runId:Z.runId,toolCallId:Z.toolCallId,toolName:Z.toolName,owner:Z.owner,job:B?B.name:null,...G.summary!==void 0?{summary:uZ(G.summary,Z)}:{},attachmentScope:Z.attachmentScope,deadlineMs:V,...W.length>0?{after:W}:{},...G.batch!==void 0?{batch:G.batch}:{},...z?{state:"waiting",queued:{args:uZ(X,Z),deadlineMs:V}}:{}});if(B&&!z)try{await g7(B,{jobId:q.id,args:X})}catch(K){if(Q.transaction)throw K;throw await Q.transition(q.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(()=>{}),K}return q},H=Q.transaction?await Q.transaction(J):await J();if(z)await f0(Q,H);return await Q.get(H.id)??H}async function k$(Z){return Z.now?await Z.now():Date.now()}async function b$(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 cZ(Z,$.id);return Q}async function cZ(Z,$){yZ.get($)?.abort(new C("The background job was settled while it ran."));try{await v$(Z,$)}catch(Q){console.error(`Could not start or cancel the jobs waiting for background job ${$}.`,Q)}f$(Z,$)}async function v$(Z,$){if(!Z.waitingOn)return;for(let Q of await Z.waitingOn($))await f0(Z,Q)}async function f0(Z,$){let Q=$.after??[],B=await Promise.all(Q.map((z)=>Z.get(z))),X=Q.find((z,J)=>B[J]===null),G=B.find((z)=>z?.state==="error");if(X!==void 0||G){let z=G?.error?.code==="cancelled",J=G?.id??X;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(qZ.has(J))qZ.add($.id);await cZ(Z,$.id)}return}if(B.some((z)=>z.state!=="ok"))return;if(!await Z.transition($.id,["waiting"],{state:"running",...$.queued?{deadlineMs:$.queued.deadlineMs}:{}}))return;let W=$.job?w$($.job):void 0;if(!W){if($.job===null)return;await a(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 g7(W,{jobId:$.id,args:$.queued?.args})}catch(z){console.error(`Could not queue background job ${$.id} after its dependencies.`,z),await a(Z,$.id,{error:{code:"tool_error",message:`The background job for "${$.toolName}" could not be queued.`,retryable:!0}})}}function w$(Z){try{return e(w0).jobs[Z]}catch{return}}function f$(Z,$){if(qZ.delete($))return;if(gZ.size===0)return;let Q=[...gZ];(async()=>{let B=await Z.get($);if(!B||!d(B.state))return;for(let X of Q)try{await X(B)}catch(G){console.error(`An AgentJobs.onSettled listener failed for background job ${$}.`,G)}})().catch((B)=>{console.error(`Could not read background job ${$} for its onSettled listeners.`,B)})}async function a(Z,$,Q){let B=await Z.get($);if(!B||B.state!=="running")return!1;let X=Q.usage?I(B.usage??x(),Q.usage):void 0,G="error"in Q?await Z.transition($,["running"],{state:"error",error:h$(B,Q.error),...X?{usage:X}:{}}):await Z.transition($,["running"],{state:"ok",output:uZ(Q.output,B),...X?{usage:X}:{}});if(G)await cZ(Z,$);return G}function h$(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 k7(Q,{source:"tool",toolName:Z.toolName,cause:$})}return{code:$.code??"tool_error",message:String($.message),toolCallId:Z.toolCallId,retryable:$.retryable??!0}}function uZ(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 y7=3600000;function Y7(Z){let $=null,Q=(B,X,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 b0(`"${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 b0(`"${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 V=G.deadlineMs??Z.async.deadlineMs??y7;if(!Number.isFinite(V)||V<=0)throw new C(`A job's deadlineMs must be a positive number; got ${V}.`);let{jobs:W,threadId:z}=Z;return $=(async()=>{let J=(await u.store.listForThread(z,{limit:50})).find((q)=>q.toolCallId===Z.toolCallId);if(J)return dZ(J);let H=await v0({threadId:z,runId:Z.runId,toolCallId:Z.toolCallId,toolName:Z.toolName,owner:W.owner,attachmentScope:Z.attachments?.scopeKey??null,deadlineMs:V},{job:B,args:X,options:G});return dZ(H)})(),$};return{start:(B,X,G)=>Q(B,X,G),track:(B)=>Q(null,void 0,B)}}function dZ(Z){return new h7(Z.id,Z.toolCallId,Z.summary,Z.deadlineAt)}function g7(Z,$){return e(w0).push(Z,JSON.stringify([$]))}class y$ extends b7{attachments=w7;attachmentStorage=E7;cancelCheckMs=5000;constructor(){super();let Z=this.run;this.run=($)=>this.$runEnvelope($,Z)}onDeadletter(Z,...$){let Q=$[0];if(!Q?.jobId)return;a(u.store,Q.jobId,{error:Z}).catch((B)=>{console.error(`Could not record the failure of background job ${Q.jobId}.`,B)})}async $runEnvelope(Z,$){let Q=u.store,B=await Q.get(Z.jobId);if(!B||B.state!=="running")return;let X=new AbortController;yZ.set(B.id,X);let G=this.cancelCheckMs>0?setInterval(()=>{Q.get(B.id).then((z)=>{if(z&&z.state!=="running"&&!X.signal.aborted)X.abort(new C("The background job was cancelled."))}).catch(()=>{})},this.cancelCheckMs):void 0;G?.unref?.();let V=new u7(B,this,X.signal),W;try{W=await $.call(this,Z.args,V)}catch(z){await T7(Q,B.id,V.usage);let J=await Q.get(B.id).catch(()=>null);if(X.signal.aborted||J&&J.state!=="running")return;throw z}finally{if(clearInterval(G),yZ.get(B.id)===X)yZ.delete(B.id)}if(this.$outcome)return await T7(Q,B.id,V.usage),W;return await a(Q,B.id,{output:W,usage:V.usage}),W}}async function T7(Z,$,Q){if(Q.totalTokens===0&&Q.inputTokens===0&&Q.outputTokens===0)return;let B=await Z.get($);if(!B)return;await Z.transition($,E$,{usage:I(B.usage??x(),Q)}).catch(()=>{})}class u7{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 B=u.store;this.inbox={take:async()=>B.takeInbox?await B.takeInbox(Z.id):[]},this.threadId=Z.threadId,this.toolCallId=Z.toolCallId,this.toolName=Z.toolName,this.owner=Z.owner,this.summary=Z.summary;let X=Z.attachmentScope?new v7($.attachments,$.attachmentStorage,{key:Z.attachmentScope}):null,G=()=>{if(!X)throw new vZ("The run that started this job had no attachment scope, so the job cannot store or read files. See `attachmentScope()` on the controller.");return X};this.attachments={put:(V,W={})=>G().put(V,W),get:(V)=>G().get(V),read:(V)=>G().read(V),file:(V)=>G().file(V)}}async checkpoint(Z){return u.store.transition(this.id,["running"],{checkpoint:uZ(Z,this)})}generate(Z){return YZ(Z,{origin:{threadId:this.threadId,toolCallId:this.toolCallId,jobId:this.id},settled:($)=>{this.usage=I(this.usage,$.usage)}})}async generateImage(Z,$){let{name:Q,...B}=$,X=await Z.generate({...B,signal:this.signal});return this.park(Z,X,Q)}async editImage(Z,$){let{name:Q,images:B,mask:X,...G}=$,V=async(z)=>typeof z==="string"?await this.attachments.file(z):z,W=await Z.edit({...G,images:await Promise.all(B.map(V)),...X?{mask:await V(X)}:{},signal:this.signal});return this.park(Z,W,Q)}async park(Z,$,Q){this.usage=I(this.usage,$.usage);let B=$.mimeType==="image/jpeg"?"jpg":"png";return{attachment:await this.attachments.put($.image,{name:Q??`${Z.name}.${B}`,mimeType:$.mimeType}),size:$.size,mimeType:$.mimeType,usage:$.usage}}}class d7{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 B=Q.first===void 0?this.delayMs:Q.first+this.maxDelayMs-Date.now(),X=$?0:Math.max(0,Math.min(this.delayMs,B));Q.timer=setTimeout(()=>void this.run(Z),X),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 B=this.options.hold?await this.options.hold(Q,Z):!1;if(B===!0)break;if(typeof B==="number"&&B>0){setTimeout(()=>this.flush(Z,!0),B).unref?.();break}for(let X of Q)$.jobs.delete(X.id);try{await this.listener(Q,Z)}catch(X){console.error(`An AgentJobs.onSettledBatch listener failed for ${Z}.`,X)}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 $=u.store,Q=new Map,B=[];for(let X of Z){if(X.batch===void 0||!$.listBatch){B.push(X);continue}let G=Q.get(X.batch);if(!G)G=new Map((await $.listBatch(X.batch)).map((J)=>[J.id,J])),Q.set(X.batch,G);let V=G,W=(J,H,q=new Set)=>{if(q.has(J.id))return!1;q.add(J.id);let K=J.after??[];return K.includes(H)||K.some((Y)=>{let F=V.get(Y);return F!==void 0&&W(F,H,q)})};if(![...V.values()].some((J)=>J.id!==X.id&&!d(J.state)&&!W(J,X.id)))B.push(X)}return B}}
46
46
  export{d0 as ic,c7 as jc,p7 as kc,iZ as lc,XZ as mc,T as nc,sZ as oc,ZZ as pc,n7 as qc,l$ as rc,i$ as sc,d as tc,eZ as uc,h7 as vc,H7 as wc,b0 as xc,u as yc,k$ as zc,b$ as Ac,y7 as Bc,Y7 as Cc,y$ as Dc,t0 as Ec,r0 as Fc,X9 as Gc,G9 as Hc,FZ as Ic,n as Jc,z0 as Kc,p as Lc,V0 as Mc,J9 as Nc,v as Oc,J1 as Pc,RZ as Qc,_Z as Rc,F1 as Sc,N9 as Tc,R9 as Uc,_9 as Vc,GZ as Wc,A9 as Xc,E9 as Yc,b9 as Zc,v9 as _c,v4 as $c,f9 as ad,w4 as bd,C1 as cd,N1 as dd,c4 as ed,m4 as fd,s9 as gd,o as hd,h as id,wZ as jd,K7 as kd,w as ld,i1 as md,P7 as nd,HZ as od,j7 as pd,S0 as qd,J$ as rd,o1 as sd,d4 as td,YZ as ud};
47
47
 
48
- //# debugId=5F615BE9C47767A064756E2164756E21
48
+ //# debugId=D911907159169D7164756E2164756E21