import{createLogger,logError}from"#internal/logging.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{deserializeContext}from"#context/serialize.js";import{readDurableSession}from"#execution/durable-session-store.js";import{cancelRemoteAgentTurn,isRetryableRemoteAgentCancelError,resolveRemoteAgentForAction}from"#execution/remote-agent-dispatch.js";import{requestWorkflowTurnCancellation}from"#execution/workflow-runtime.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";const log=createLogger(`execution.cancel-descendant-turns`);async function cancelDescendantTurnsStep(e){"use step";let r;try{r=getPendingRuntimeActionBatch((await readDurableSession(e.sessionState)).state)}catch(n){logError(log,`failed to read pending descendants during cancellation`,n,{sessionId:e.sessionState.sessionId});return}if(r===void 0)return;let i=r.childSessionIds;if(i===void 0)return;let a,getRemoteRegistry=()=>a??=deserializeContext(e.serializedContext).then(e=>e.require(BundleKey).subagentRegistry.subagentsByNodeId),o=r.actions.flatMap(e=>{let t=i[e.callId];return t===void 0?[]:e.kind===`subagent-call`?[cancelLocalDescendant({action:e,childSessionId:t})]:e.kind===`remote-agent-call`?[cancelRemoteDescendant({action:e,childSessionId:t,remoteRegistry:getRemoteRegistry()})]:[]});await Promise.all(o)}async function cancelLocalDescendant(e){try{await requestCancellationWithRetry({request:()=>requestWorkflowTurnCancellation({sessionId:e.childSessionId}),shouldRetryError:()=>!1})}catch(n){logError(log,`failed to cancel local descendant turn`,n,{callId:e.action.callId,childSessionId:e.childSessionId,subagentName:e.action.subagentName})}}async function cancelRemoteDescendant(e){try{let t=await e.remoteRegistry,n=resolveRemoteAgentForAction({nodeId:e.action.nodeId,remoteAgentName:e.action.remoteAgentName,registry:t});await requestCancellationWithRetry({request:()=>cancelRemoteAgentTurn({remote:n,sessionId:e.childSessionId}),shouldRetryError:isRetryableRemoteAgentCancelError})}catch(n){logError(log,`failed to cancel remote descendant turn`,n,{callId:e.action.callId,childSessionId:e.childSessionId,remoteAgentName:e.action.remoteAgentName})}}async function requestCancellationWithRetry(e){for(let t=1;t<=12;t+=1){try{if((await e.request()).status===`accepted`||t===12)return}catch(n){if(!e.shouldRetryError(n)||t===12)throw n}await new Promise(e=>setTimeout(e,250))}}export{cancelDescendantTurnsStep};