import{createLogger,formatError}from"#internal/logging.js";import{callAdapterEventHandler}from"#channel/adapter.js";import{createSessionFailedEvent,encodeMessageStreamEvent,timestampHandleMessageStreamEvent}from"#protocol/message.js";import{summarizeKnownError}from"#harness/semantic-errors/index.js";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{deserializeContext}from"#context/serialize.js";import{buildAdapterContext}from"#channel/adapter-context.js";const log=createLogger(`execution.workflow-entry`);async function emitTerminalSessionFailureStep(e){"use step";let r=formatError(e.error),i=summarizeKnownError(e.error),a=r;if(i!==null){let e={...r,message:i.message,name:i.name,semanticErrorId:i.id};a=i.hint===void 0?e:{...e,hint:i.hint}}let o=typeof a.name==`string`?a.name:`WORKFLOW_EXECUTION_FAILED`,s=typeof a.message==`string`?a.message:String(e.error),c=e.serializedContext[`eve.sessionId`]??``;log.error(`workflow loop threw — emitting terminal session.failed`,{sessionId:c,errorId:typeof a.errorId==`string`?a.errorId:void 0,code:o,message:s,hint:i?.hint,detail:typeof a.detail==`string`?a.detail:void 0});let l=createSessionFailedEvent({code:o,details:a,message:s,sessionId:c});try{let t=await deserializeContext(e.serializedContext),n=t.get(ChannelKey);n!==void 0&&await callAdapterEventHandler(n,l,buildAdapterContext(n,t))}catch(e){log.error(`adapter failed to handle terminal session.failed event`,{errorId:typeof a.errorId==`string`?a.errorId:void 0,sessionId:c,error:e})}try{let t=e.parentWritable.getWriter();try{await t.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(l)))}finally{t.releaseLock()}}catch(e){log.error(`failed to write terminal session.failed event to durable stream`,{errorId:typeof a.errorId==`string`?a.errorId:void 0,sessionId:c,error:e})}}export{emitTerminalSessionFailureStep};