import{callAdapterEventHandler}from"#channel/adapter.js";import{encodeMessageStreamEvent,timestampHandleMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{clearPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{hydrateDurableSession}from"#execution/session.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{clearPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{clearAllProxyInputRequests,hasProxyInputRequests}from"#harness/proxy-input-requests.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{withContextScope}from"#context/run-step.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{emitCancelledTurn}from"#harness/cancelled-turn-emission.js";async function settleCancelledTurnStep(r){"use step";let i=await readDurableSession(r.sessionState),a=await deserializeContext(r.serializedContext),o=a.require(ChannelKey),s=buildAdapterContext(o,a),c=a.require(BundleKey),l=hydrateDurableSession({compactionOverrides:{thresholdPercent:c.resolvedAgent.config.compaction?.thresholdPercent},durable:i,turnAgent:c.turnAgent}),u=getHarnessEmissionState(i.state);if(!(isHarnessBetweenTurns(l)&&hasProxyInputRequests(i.state))){let e=r.parentWritable.getWriter();try{let t=await withContextScope(a,l,async t=>({result:await emitCancelledTurn(async t=>{let n=await callAdapterEventHandler(o,t,s);setChannelContext(a,{...o,state:{...s.state}}),await e.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(n))),await dispatchStreamEventHooks({ctx:a,event:n,registry:c.hookRegistry})},u,t.continuationToken),session:t}));u=t.result,l=t.session}finally{e.releaseLock()}}let d=reconcileSessionContinuationToken(a,setHarnessEmissionState(clearAllProxyInputRequests(clearPendingWorkflowInterrupt(clearPendingRuntimeActionBatch(l))),u));return{serializedContext:serializeContext(a),sessionState:createDurableSessionState({session:d})}}export{settleCancelledTurnStep};