eve
Version:
Filesystem-first framework for durable backend AI agents that run anywhere.
1 lines • 2.15 kB
JavaScript
import{createLogger}from"#internal/logging.js";import{callAdapterEventHandler}from"#channel/adapter.js";import{contextStorage}from"#context/container.js";import{ParentSessionKey}from"#context/keys.js";import{encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{deserializeContext}from"#context/serialize.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{bindSessionInstrumentation}from"#instrumentation/runtime.js";const log=createLogger(`execution.workflow-entry`);async function emitTerminalSessionEvent(e){let t=e.serializedContext[`eve.sessionId`]??``,n;try{n=await deserializeContext(e.serializedContext)}catch(n){log.error(`failed to restore context for terminal ${e.event.type} event`,{error:n,errorId:e.errorId,sessionId:t})}let handleEvent=async r=>{if(n!==void 0){let i=n.get(ChannelKey);if(i!==void 0)try{await callAdapterEventHandler(i,r,buildAdapterContext(i,n))}catch(n){log.error(`adapter failed to handle terminal ${r.type} event`,{error:n,errorId:e.errorId,sessionId:t})}}try{let t=e.parentWritable.getWriter();try{await t.write(encodeMessageStreamEvent(stampMessageStreamEvent(r)))}finally{t.releaseLock()}}catch(n){log.error(`failed to write terminal ${r.type} event to durable stream`,{error:n,errorId:e.errorId,sessionId:t})}},r;if(n!==void 0)try{let e=n.require(BundleKey);r=bindSessionInstrumentation({agentName:e.turnAgent.id,ctx:n,rootSessionId:n.get(ParentSessionKey)?.rootSessionId??t,sessionId:t})}catch(n){log.error(`failed to bind instrumentation for terminal ${e.event.type} event`,{error:n,errorId:e.errorId,sessionId:t})}let i=r?.createHandleEvent({handleEvent,turnId:e.turnId})??handleEvent;try{n===void 0?await i(e.event):await contextStorage.run(n,()=>i(e.event))}catch(n){log.error(`instrumentation failed to handle terminal ${e.event.type} event`,{error:n,errorId:e.errorId,sessionId:t})}finally{try{await r?.flush()}catch(n){log.error(`failed to flush instrumentation after terminal ${e.event.type} event`,{error:n,errorId:e.errorId,sessionId:t})}}}export{emitTerminalSessionEvent};