UNPKG

eve

Version:

Filesystem-first framework for durable backend AI agents that run anywhere.

1 lines 9.41 kB
import{createSubagentCalledEvent}from"#protocol/message.js";import{workflowEntryReference}from"#execution/workflow-runtime.js";import{getWorkflowMetadata}from"#compiled/@workflow/core/index.js";import{deriveAgentOperationId}from"#subagents/handles/operation-id.js";import{readDurableSession,replaceDurableSessionSnapshot}from"#execution/durable-session-store.js";import{getAgentHandleStore,writeHandles}from"#subagents/handles/store.js";import{projectToDurableSession}from"#execution/session.js";import{findSessionTaskEntry}from"#tasks/session-index.js";import{AGENT_BUSY,AGENT_MISMATCH,AGENT_UNREACHABLE,formatAgentBusyMessage}from"#subagents/agent-handle-errors.js";import{clearProxyInputRequestsForChild,clearProxyInputRequestsForTask}from"#harness/proxy-input-requests.js";import{readLatestTaskView}from"#execution/tasks/parent/run-parent.js";import{abandonAgentInvocationOwners,applyTaskAgentHandleCommand}from"#subagents/handles/transitions.js";import{accumulateSessionUsage,getTurnUsageState,setTurnUsageState}from"#harness/turn-tag-state.js";import{isTerminalTaskStatus}from"#tasks/types.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{createSubagentReceiptIdentity}from"#execution/tools/subagent/receipt-identity.js";import{createAgentErrorResult,dispatchToClaimedAgentAddress}from"#subagents/handle-dispatch.js";import{createAgentContinuationBundle}from"#subagents/continuation-bundle.js";import{startSubagent}from"#execution/tools/subagent/start.js";import{prepareOwnerAgentInvocation}from"#execution/tools/subagent/invoke-preparation.js";import{prepareAgentInvocationTrace}from"#tracing/agent-invocation-coordinator.js";import{flushAgentInvocationTraces,settleAgentInvocationTrace}from"#tracing/agent-invocation-terminal.js";async function dispatchAgentInvocation(e){let t=await readDurableSession(e.sessionState),n=getAgentHandleStore(t.state)?.handles??[],r=await prepareOwnerAgentInvocation({invocation:e.request.input,invocationId:e.request.invocationId,knownAgentIds:n.map(e=>e.identity.id),serializedContext:e.serializedContext,sessionState:e.sessionState}),i=r.plan[0];if(i===void 0)throw Error(`Agent invocation produced no executable plan entry.`);if(i.kind===`reject`)return{kind:`failed`,result:i.result,serializedContext:r.serializedContext,sessionState:e.sessionState};let a=i.kind===`start`?i.target.action:i.action,o=prepareAgentInvocationTrace({channelMetadata:r.channelMetadata,invocation:a,ownerId:e.ownerId,serializedContext:r.serializedContext,sessionId:r.session.sessionId,sessionState:t.state,startTimeMs:Date.now(),taskId:e.taskId,turnId:r.batch.event.turnId}),s=r.session,currentAgentHandles=()=>getAgentHandleStore(s.state)?.handles??[],sessionState=()=>replaceDurableSessionSnapshot({session:projectToDurableSession(s),state:e.sessionState}),failed=async e=>({kind:`failed`,result:e,serializedContext:await flushAgentInvocationTraces(o.fail(e)),sessionState:sessionState()}),applyHandleCommand=e=>{let t=applyTaskAgentHandleCommand(s,e);return s=t.session,t.result},c,l;if(i.kind===`resume`){let t=currentAgentHandles().filter(t=>t.phase===`claimed`&&t.ownerId===e.ownerId&&t.callId===i.action.callId&&t.identity.id===i.agentId);if(t.length>1)throw Error(`Invocation owner "${e.ownerId}" has multiple claims for "${i.action.callId}".`);let n=t[0];if(n===void 0){let t=deriveAgentOperationId({callId:i.action.callId,parentSessionId:r.session.sessionId,parentTurnId:r.batch.event.turnId}),a=applyHandleCommand({agentId:i.agentId,callId:i.action.callId,expectedTarget:i.action.kind===`remote-agent-call`?`remote`:`local`,invokedName:i.action.kind===`remote-agent-call`?i.action.remoteAgentName:i.action.subagentName,kind:`claim`,operationId:t,ownerId:e.ownerId});if(n=readClaimedHandle(a),n===void 0)return failed(createTaskClaimError(i.action,i.agentId,a))}let a=createAgentContinuationBundle({action:i.action,bundle:r.bundle,dynamicRemoteAgent:i.dynamicRemoteAgent});c=await dispatchToClaimedAgentAddress({action:i.action,auth:r.auth,bundle:a,currentSession:s,parentToken:e.replyTo,handle:n,taskId:e.taskId}),c.kind===`error`&&c.deliveryPermanent===!0&&applyHandleCommand({agentId:i.agentId,kind:`remove`,ownerId:e.ownerId}),l=n.identity.id}else{let t=i.target.action,n=currentAgentHandles().filter(n=>n.phase===`reserved`&&n.ownerId===e.ownerId&&n.callId===t.callId&&n.identity.name===t.name&&n.identity.nodeId===t.nodeId),a=n.length===1?{identity:n[0].identity,operation:{id:n[0].operationId}}:createSubagentReceiptIdentity({callId:t.callId,subagentName:t.kind===`remote-agent-call`?t.remoteAgentName:t.subagentName,nodeId:t.nodeId,parentSessionId:r.session.sessionId,parentTurnId:r.batch.event.turnId});if(n.length>1)throw Error(`Invocation owner "${e.ownerId}" has multiple reservations for "${t.callId}".`);if(n.length===0&&applyHandleCommand({identity:a.identity,callId:t.callId,kind:`reserve`,operationId:a.operation.id,ownerId:e.ownerId}).kind!==`ready`)throw Error(`Agent handle store rejected start operation "${a.operation.id}".`);if(c=await startSubagent({auth:r.auth,batchEvent:r.batch.event,bundle:r.bundle,callbackBaseUrl:e.callbackBaseUrl,capabilities:r.capabilities,channelMetadata:r.channelMetadata,currentSession:s,fanoutSize:r.fanoutSize,initiatorAuth:r.initiatorAuth,localDevRequest:r.localDevRequest,parentContinuationToken:e.replyTo,activityObserver:r.activityObserver,sandboxSessionId:r.sandboxSessionId,session:s,taskId:e.taskId,target:i.target,trace:o.dispatch}),l=a.identity.id,c.kind===`error`)applyHandleCommand({agentId:l,kind:`remove`,ownerId:e.ownerId});else if(readClaimedHandle(applyHandleCommand({address:c.address,kind:`confirm`,operationId:a.operation.id,ownerId:e.ownerId}))===void 0)throw Error(`Agent handle store could not confirm start operation "${a.operation.id}".`)}if(c.kind===`error`)return failed(c.result);let u=i.kind===`resume`?i.action:i.target.action,d=i.kind===`resume`?i.dynamicRemoteAgent:i.target.kind===`remote`?i.target.dynamicRemoteAgent:void 0,f=createSubagentCalledEvent({agentId:l,callId:c.callId,childSessionId:c.address.sessionId,name:c.name,remote:c.address.kind===`agent/remote`?{resolverId:d===void 0?u.nodeId:d.credentialsStepId,url:c.address.url}:void 0,sequence:r.batch.event.sequence,sessionId:r.session.sessionId,toolName:c.toolName,turnId:r.batch.event.turnId,workflowId:workflowEntryReference.workflowId});return e.emit!==void 0&&await e.emit(f),{kind:`dispatched`,agentId:l,event:f,serializedContext:o.serializedContext,sessionState:sessionState()}}async function dispatchTaskAgentInvocationStep(e){"use step";if(e.taskId!==void 0){let t=await readDurableSession(e.sessionState),n=findSessionTaskEntry(t.state,e.taskId);if(n===void 0)return{kind:`not-admitted`,sessionState:e.sessionState};let r=await readLatestTaskView({taskRunId:n.taskRunId});if(r===void 0||isTerminalTaskStatus(r.status))return{kind:`not-admitted`,sessionState:e.sessionState}}return await dispatchAgentInvocation({...e,callbackBaseUrl:resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url)})}async function settleTaskAgentInvocationStep(e){"use step";let t=await readDurableSession(e.sessionState),n=await flushAgentInvocationTraces(settleAgentInvocationTrace({acceptedAtMs:Date.now(),result:e.result,serializedContext:e.serializedContext,sessionId:t.sessionId})),r=getAgentHandleStore(t.state)?.handles??[],i=r.filter(t=>t.phase===`claimed`&&t.ownerId===e.ownerId),a=i.find(t=>t.phase===`claimed`&&t.callId===e.result.callId)??(i.length===1?i[0]:void 0);if(a?.phase!==`claimed`)return{serializedContext:n,sessionState:e.sessionState};let o=e.result.outcome.kind===`terminal`?r.filter(e=>e!==a):r.map(t=>t===a?e.result.outcome.result.kind===`cancelled`?{address:a.address,identity:a.identity,lastStatus:`(cancelled)`,phase:`parked`}:{address:a.address,identity:a.identity,phase:`available`}:t),s=writeHandles(t,o);return e.result.outcome.kind===`terminal`&&(s=e.taskId===void 0?`continuationToken`in a.address?clearProxyInputRequestsForChild(s,a.address.continuationToken):s:clearProxyInputRequestsForTask(s,e.taskId)),e.accumulateUsage!==!1&&(s=setTurnUsageState(s,accumulateSessionUsage({previous:getTurnUsageState(s.state),usage:e.result.outcome.usageDelta}))),{serializedContext:n,sessionState:replaceDurableSessionSnapshot({session:s,state:e.sessionState})}}async function releaseAgentInvocationOwnerStep(e){"use step";let t=await readDurableSession(e.sessionState),n=e.cancelled?abandonAgentInvocationOwners(t,new Set([e.ownerId])):applyTaskAgentHandleCommand(t,{kind:`release-owner`,ownerId:e.ownerId}).session;return{sessionState:n===t?e.sessionState:replaceDurableSessionSnapshot({session:n,state:e.sessionState})}}function readClaimedHandle(e){let t=e.kind===`ready`?e.handle:void 0;return t?.phase===`claimed`?t:void 0}function createTaskClaimError(e,t,n){return n.kind===`mismatch`?createAgentErrorResult({action:e,code:AGENT_MISMATCH,message:`Agent "${t}" no longer matches this subagent definition. Start a new agent instead.`}):n.kind===`busy`?createAgentErrorResult({action:e,code:AGENT_BUSY,message:formatAgentBusyMessage({agentId:t,agentName:n.handle.identity.name,ownerId:`ownerId`in n.handle?n.handle.ownerId:void 0})}):createAgentErrorResult({action:e,code:AGENT_UNREACHABLE,message:`Agent with id "${t}" is no longer reachable.`})}export{dispatchAgentInvocation,dispatchTaskAgentInvocationStep,releaseAgentInvocationOwnerStep,settleTaskAgentInvocationStep};