UNPKG

eve

Version:

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

1 lines • 8.28 kB
import{sessionCommandHookToken,sessionInboxHookToken}from"#execution/session-inbox/address.js";import{coalesceDeliveries}from"#harness/messages.js";import{getWorkflowMetadata}from"#compiled/@workflow/core/index.js";import{isInboxToolResultFromRecordedWorkflowToolRun}from"#harness/workflow-tool-runs.js";import{activeTurnId}from"#harness/active-turn-id.js";import{decodeSessionInboxPayload}from"#execution/session-inbox/protocol.js";import{isInboxSubagentResultFromRunningHandle}from"#subagents/handles/query.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";import{routeSelectedDelivery}from"#execution/session/route-selected-delivery.js";import{admitSessionInboxPayload,applySessionCancellation}from"#execution/session/admission.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{isSteeringDelivery}from"#execution/session/input-queue.js";import{TurnCancelledError}from"#harness/turn-cancellation.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{dispatchCoordinationStep}from"#execution/coordination-dispatch-step.js";import{acknowledgeDelegatedTasksStep}from"#execution/tasks/parent/delegate.js";import{handleWorkflowToolRunMessage}from"#execution/session-workflow-tool-run.js";import{turnStep}from"#execution/session/turn-step.js";import{resolveRuntimeActionResultsForCallIds}from"#runtime/actions/results.js";var SessionExecution=class{input;constructor(e){this.input=e}get cursor(){return this.input.cursor}async runTurn(e){let t=new ActiveTurn(this.input,e?.delivery?.caller?.callId);try{return await this.runTurnSteps(t,e)}finally{t.dispose()}}async runTurnSteps(e,t){let n=t;for(;;){let{cursor:t}=this.input,r=t.serializedContext,i=await turnStep(t.createStepInput(n,{abortSignal:e.signal,steeringSignal:e.steeringSignal})),a=i.action===`park`?i.pendingCoordinationCallIds:void 0,o=(i.backgroundTasks?.length??0)>0,s=i.action===`park`&&i.settled!==void 0;if(o){if(i.backgroundTaskState===void 0)throw Error(`Background tasks were returned without their committed session state.`);await t.apply({serializedContext:i.backgroundTaskContext??r,sessionState:i.backgroundTaskState}),await acknowledgeDelegatedTasksStep({tasks:i.backgroundTasks??[]})}if(await t.apply({serializedContext:i.serializedContext,sessionState:i.action===`cancelled`||!s&&e.signal.aborted?i.backgroundTaskState??i.sessionState:i.sessionState}),await e.admitBoundary(),e.resetSteering(),i.action===`cancelled`||!s&&e.signal.aborted&&(a===void 0||o))return await this.finishCancelledTurn();if(i.action===`done`)return{isError:i.isError,kind:`done`,output:i.output??``,usage:i.usage,usageDelta:i.usageDelta};if(a!==void 0&&i.action===`park`){let r=await dispatchCoordinationStep({action:i.action,callbackBaseUrl:resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url),workflowToolRunOwner:{inbox:sessionInboxHookToken(sessionCommandHookToken(this.input.sessionId))},sessionWritable:t.sessionWritable,serializedContext:t.serializedContext,sessionState:t.sessionState}),o=r.results.length===0?void 0:Date.now();await t.apply(r);let s=await this.waitForRuntimeActionResults({initialAcceptedAtMs:o,initialResults:r.results,pendingCallIds:a,turn:e});if(s===`cancelled`)return await this.finishCancelledTurn();n={delivery:await e.takeSteering(),runtimeResults:s};continue}if(i.action===`park`){if(!(i.hasPendingAuthorization||i.hasPendingInputBatch&&this.input.capabilities?.requestInput===!0||this.input.mode===`conversation`))throw Error("Task mode cannot wait for follow-up input (`next: null`).");return{authorizationAttemptIds:i.authorizationAttemptIds,kind:`park`,settled:i.settled}}let c=await e.takeSteering();n=c===void 0?void 0:{delivery:c}}}async handleWorkflowMessage(e){return await handleWorkflowToolRunMessage({callbackMetadataUrl:getWorkflowMetadata().url,cursor:this.input.cursor,message:e})}async finishCancelledTurn(){let{cursor:e}=this.input;return await cancelDescendantTurnsStep({serializedContext:e.serializedContext,sessionState:e.sessionState}),{cancelled:!0,kind:`park`}}async waitForRuntimeActionResults(e){let t=[...e.initialResults],n=new Map;if(e.initialAcceptedAtMs!==void 0)for(let r of t)n.set(r.callId,e.initialAcceptedAtMs);for(;;){let r=resolveRuntimeActionResultsForCallIds({pendingCallIds:e.pendingCallIds,results:t});if(r!==void 0)return{acceptedAtMsByCallId:Object.fromEntries(r.map(e=>[e.callId,n.get(e.callId)])),results:r};let i=await e.turn.nextRuntimeEvent();if(i===`cancelled`)return i;if(i.kind===`runtime-action-result`){let e=this.input.cursor.sessionState.snapshot.session.state,r=i.results.filter(t=>t.kind===`tool-result`?isInboxToolResultFromRecordedWorkflowToolRun(e,t):t.kind===`subagent-result`&&t.origin===`child`&&isInboxSubagentResultFromRunningHandle(e,t));if(r.length>0){let e=Date.now();t.push(...r);for(let t of r)n.set(t.callId,e)}continue}let a=await this.handleWorkflowMessage(i.message);a!==void 0&&(t.push(a),n.set(a.callId,Date.now()))}}},ActiveTurn=class{admitted=new Set;routedToChildren=new Set;runtimeResults=[];controller=new AbortController;expectedTurnId;input;callerCallId;unsubscribe;unsubscribeDelivery;steeringController=new AbortController;constructor(e,t){this.input=e,this.callerCallId=t,this.expectedTurnId=activeTurnId(e.cursor.sessionState.emissionState),this.unsubscribe=e.inbox.onInterrupt(e=>{this.cancelsThisTurn(e)&&this.abort()}),this.unsubscribeDelivery=e.inbox.onDelivery(this.signalSteering)}signalSteering=e=>{let t;try{t=decodeSessionInboxPayload(e)}catch{return}t.kind===`deliver`&&isSteeringDelivery(t,this.callerCallId)&&!this.input.cursor.sessionState.hasProxyInputRequests&&t.payloads.some(e=>e.message!==void 0&&e.inputResponses===void 0&&e.task===void 0)&&this.steeringController.abort()};get signal(){return this.controller.signal}dispose(){this.unsubscribe(),this.unsubscribeDelivery()}get steeringSignal(){return this.steeringController.signal}resetSteering(){this.steeringController.signal.aborted&&(this.unsubscribeDelivery(),this.steeringController=new AbortController,this.unsubscribeDelivery=this.input.inbox.onDelivery(this.signalSteering))}async admitBoundary(){let e=this.input.inbox.drain();for(let t of e)await this.admit(t)}async takeSteering(){let e=[];for(;;){let t=this.input.queue.takeSteering(this.admitted,this.callerCallId);if(t===void 0)break;for(let e of t.sequences)this.admitted.delete(e);let n=await routeSelectedDelivery(t,this.input.cursor);if(n.kind===`cancel-turn`){this.abort();break}n.kind===`turn`&&e.push(n.delivery)}if(e.length!==0)return e.length===1?e[0]:coalesceDeliveries(e)}async nextRuntimeEvent(){for(;;){if(this.signal.aborted)return`cancelled`;let e=this.runtimeResults.shift();if(e!==void 0)return e;let t=await this.input.inbox.next();if(t===void 0)throw Error(`Session inbox closed before runtime actions completed.`);await this.admit(t),await this.routeAdmittedToChildren()}}cancelsThisTurn(e){return e.kind===`reset`?!0:e.kind===`cancel`?e.turnId===void 0||e.turnId===this.expectedTurnId:!1}async admit(e){let t=await admitSessionInboxPayload(e,this.input);switch(t.kind){case`delivery`:this.admitted.add(t.admission.sequence);return;case`runtime-action-result`:this.runtimeResults.push({kind:`runtime-action-result`,results:t.payload.results});return;case`workflow`:this.runtimeResults.push({kind:`workflow`,message:t.message});return;case`cancel`:if(!this.cancelsThisTurn(e))return;await applySessionCancellation(t.command,this.input),this.abort();return;case`consumed`:return}}async routeAdmittedToChildren(){for(let e of this.admitted){if(this.routedToChildren.has(e))continue;let t=this.input.queue.delivery(e);if(t===void 0){this.admitted.delete(e);continue}this.routedToChildren.add(e);let n=await routeDeliverToChildren({delivery:t,sessionWritable:this.input.cursor.sessionWritable,serializedContext:this.input.cursor.serializedContext,sessionState:this.input.cursor.sessionState});if(await this.input.cursor.apply(n),n.kind===`cancel-turn`){this.input.queue.replaceDelivery(e,void 0),this.admitted.delete(e),this.abort();return}this.input.queue.replaceDelivery(e,n.remainder),n.remainder===void 0&&this.admitted.delete(e)}}abort(){this.controller.signal.aborted||this.controller.abort(new TurnCancelledError)}};export{SessionExecution};