eve
Version:
Filesystem-first framework for durable backend AI agents that run anywhere.
1 lines • 9.36 kB
JavaScript
import{randomBytes}from"node:crypto";import{createEveActivityRoutePath}from"#protocol/routes.js";import{createLogger,logError}from"#internal/logging.js";import{getChannelActivityPresentation}from"#channel/activity-renderer.js";import{sessionCommandHookToken}from"#execution/session-command-token.js";import{ActivityObserverKey}from"#context/keys.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{walkCauseChain}from"#shared/errors.js";import{normalizePersistedMessageStreamEvent}from"#protocol/message-version.js";import{cancelRun,getRawHookByToken,getRun,getWorld,start}from"#internal/workflow/runtime.js";import{serializeContext}from"#context/serialize.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{EntityConflictError,HookNotFoundError,RunExpiredError,WorkflowRunNotFoundError}from"#compiled/@workflow/errors/index.js";import{resumeSessionInbox}from"#execution/wire/session-inbox-resume.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{buildSessionAttributes,buildSubagentRootAttributes,readParentLineage}from"#execution/eve-workflow-attributes.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{initializeSessionInstrumentation}from"#instrumentation/runtime.js";import{createWorkflowCallbackUrl,resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{context,trace}from"#compiled/@opentelemetry/api/index.js";import{buildRunContext}from"#execution/runtime-context.js";import{parseNdjsonStream}from"#execution/ndjson-stream.js";import{buildInvocationAttributes}from"#internal/invocation/metadata.js";import{isAgentTraceContext}from"#tracing/agent-trace-context.js";import{ACTIVITY_COLLECTOR_WORKFLOW_NAME,SESSION_TIMEOUT_WORKFLOW_NAME,TASK_RUN_WORKFLOW_NAME,TURN_WORKFLOW_NAME,WORKFLOW_ENTRY_NAME,WORKFLOW_TOOL_RUN_WORKFLOW_NAME}from"#execution/stable-workflow-names.js";const EVE_PACKAGE_INFO=resolveInstalledPackageInfo(),COMMAND_HOOK_READY_TIMEOUT_MS=3e4,STABLE_ID_BASE=EVE_PACKAGE_INFO.name,log=createLogger(`execution.workflow-runtime`),workflowEntryReference={workflowId:`workflow//${STABLE_ID_BASE}//${WORKFLOW_ENTRY_NAME}`},turnWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${TURN_WORKFLOW_NAME}`},sessionTimeoutWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${SESSION_TIMEOUT_WORKFLOW_NAME}`},taskRunWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${TASK_RUN_WORKFLOW_NAME}`},activityCollectorWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${ACTIVITY_COLLECTOR_WORKFLOW_NAME}`},workflowToolRunWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${WORKFLOW_TOOL_RUN_WORKFLOW_NAME}`};function createWorkflowRuntime(e){return{async createSession(t){let n=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:e.nodeId}),r=buildRunContext({bundle:n,dynamicSubagentAgentConfig:e.dynamicSubagentAgentConfig,run:t}),i=resolveEffectiveAgentRuntime(n,r);initializeSessionInstrumentation({agentName:i.turnAgent.id,ctx:r});let a=i.limits?.sessionTimeoutMs,o=n.resolvedAgent.config?.experimental?.workflow?.retention,s,c=t.activityObserver;if(t.parent===void 0&&c===void 0&&(getChannelActivityPresentation(t.adapter)?.renderers.length??0)>0){let e=serializeContext(r),t=randomBytes(32).toString(`base64url`),n={expiresAt:new Date(Date.now()+(typeof a==`number`?a:864e5)).toISOString(),serializedContext:e,token:t};try{s=(await startWorkflowOnCurrentDeployment(activityCollectorWorkflowReference,[n],{experimental_retention:o})).runId;let e=process.env.VERCEL_URL?`https://${process.env.VERCEL_URL}`:`http://localhost:3000`,i=resolveWorkflowCallbackBaseUrl(e);c={sink:{url:createWorkflowCallbackUrl(i,createEveActivityRoutePath(t)),version:1}},r.set(ActivityObserverKey,c)}catch{await cancelActivityCollector(s),s=void 0,log.warn(`failed to start activity collector`)}}let l=serializeContext(r),u=readParentLineage(l),d={input:t.input,limits:t.limits,serializedContext:l},f=t.taskId??t.callback?.taskId;f!==void 0&&(d.taskId=f),s!==void 0&&(d.activityCollectorRunId=s),t.continuationConflictCommand!==void 0&&(d.continuationConflictCommand=t.continuationConflictCommand),a!==void 0&&(d.sessionTimeoutMs=a),o!==void 0&&(d.retention=o);let p={...u.sessionId===void 0?buildSessionAttributes({inputMessage:t.title??t.input.message,serializedContext:l}):buildSubagentRootAttributes({identity:{nodeId:n.nodeId??ROOT_RUNTIME_AGENT_NODE_ID},parentCallId:u.callId,parentSessionId:u.sessionId,parentTurnId:u.turnId,rootSessionId:u.rootSessionId??u.sessionId,serializedContext:l}),...t.externalInvocation===void 0?{}:buildInvocationAttributes(t.externalInvocation)},m;try{m=await startWorkflowOnCurrentDeployment(workflowEntryReference,[d],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(p),experimental_retention:o})}catch(e){throw await cancelActivityCollector(s),logError(log,`failed to start workflow run`,e,{continuationToken:t.continuationToken}),e}let h,getEvents=()=>(h??=parseNdjsonStream(()=>getRun(m.runId).getReadable(),normalizePersistedEvent),h);return{get events(){return getEvents()},sessionId:m.runId}},async dispatchContinuation(e){return await dispatchWorkflowCommand(e.continuationToken,e.command)},async dispatchSession(e){return await dispatchWorkflowCommand(sessionCommandHookToken(e.sessionId),e.command)},async getEventStream(e,t){return parseNdjsonStream(()=>getRun(e).getReadable({startIndex:t?.startIndex}),normalizePersistedEvent)},async getStreamTailIndex(e){let t=getRun(e).getReadable();try{return await t.getTailIndex()}finally{await t.cancel().catch(()=>{})}},async resolveContinuation(e){try{return{sessionId:(await getRawHookByToken(e)).runId}}catch(t){if(HookNotFoundError.is(t))return;throw logError(log,`failed to resolve session by continuation token`,t,{continuationToken:e}),t}}}}function normalizePersistedEvent(e){return normalizePersistedMessageStreamEvent(e)}async function cancelActivityCollector(e){if(e!==void 0)try{await cancelRun(await getWorld(),e,{cancelReason:`Root session creation did not complete`})}catch{log.warn(`failed to cancel unowned activity collector`)}}async function dispatchWorkflowCommand(e,t){let n;try{n=normalizeWorkflowHook(await resumeSessionInbox(e,t))}catch(n){if(isInactiveCommandTarget(n))return inactiveCommandResult(t);throw logError(log,`failed to dispatch session command`,n,{command:t.kind,token:e}),n}return t.kind===`reset`&&await waitForCommandHookRelease(sessionCommandHookToken(n.runId),n.runId),activeCommandResult(t,n.runId)}function activeCommandResult(e,t){return e.kind===`reset`?{previousSessionId:t,status:`reset`}:e.kind===`send`&&e.delivery!==void 0?{sessionId:t,status:`accepted`,deliveryId:e.delivery.deliveryId}:{sessionId:t,status:`accepted`}}function inactiveCommandResult(e){return e.kind===`send`?{status:`session_not_active`}:e.kind===`cancel`?{status:`no_active_turn`}:{status:`no_active_session`}}async function requestWorkflowTurnCancellation(e){let t={kind:`cancel`};return e.taskId!==void 0&&(t.taskId=e.taskId),e.tasks!==void 0&&(t.tasks=e.tasks),e.turnId!==void 0&&(t.turnId=e.turnId),await dispatchWorkflowCommand(sessionCommandHookToken(e.sessionId),t)}function isInactiveCommandTarget(e){if(HookNotFoundError.is(e))return!0;for(let t of walkCauseChain(e))if(WorkflowRunNotFoundError.is(t)||RunExpiredError.is(t)||EntityConflictError.is(t))return!0;return!1}async function waitForCommandHookOwner(e){let t=Date.now()+COMMAND_HOOK_READY_TIMEOUT_MS;for(;;)try{return normalizeWorkflowHook(await getRawHookByToken(e))}catch(e){if(!HookNotFoundError.is(e)||Date.now()>=t)throw e;await new Promise(e=>setTimeout(e,20))}}async function waitForCommandHookRelease(e,t){let n=Date.now()+COMMAND_HOOK_READY_TIMEOUT_MS;for(;;){try{if(normalizeWorkflowHook(await getRawHookByToken(e)).runId!==t)return}catch(e){if(HookNotFoundError.is(e))return;throw e}if(Date.now()>=n)throw Error(`Timed out waiting for session "${t}" to release its command inbox.`);await new Promise(e=>setTimeout(e,20))}}async function startWorkflowOnCurrentDeployment(e,t,n){return await startWorkflowOnDeployment(e,t,process.env.VERCEL_DEPLOYMENT_ID?.trim()||void 0,n)}async function startWorkflowOnAcceptedDeployment(e,t,n,r){return n===void 0?await startWorkflowOnCurrentDeployment(e,t,r):await startWorkflowOnDeployment(e,t,n,r)}async function startWorkflowOnDeployment(e,t,n,r){return await withWorkflowStartContext(async()=>n===void 0?r===void 0?await start(e,t):await start(e,t,r):await start(e,t,{...r,deploymentId:n}))}async function withWorkflowStartContext(e){let t=context.active(),n=isAgentTraceContext(t)?trace.deleteSpan(t):t;return await context.with(n,e)}function normalizeWorkflowHook(e){if(typeof e!=`object`||!e||!(`runId`in e))throw Error(`Workflow hook did not include a run id.`);let t=e.runId;if(typeof t!=`string`||t.length===0)throw Error(`Workflow hook did not include a run id.`);return{runId:t}}export{activityCollectorWorkflowReference,createWorkflowRuntime,requestWorkflowTurnCancellation,sessionTimeoutWorkflowReference,startWorkflowOnAcceptedDeployment,startWorkflowOnCurrentDeployment,taskRunWorkflowReference,turnWorkflowReference,waitForCommandHookOwner,workflowEntryReference,workflowToolRunWorkflowReference};