import{createHook}from"#compiled/@workflow/core/index.js";import{claimHookOwnership,disposeHook,isHookConflictError}from"#execution/hook-ownership.js";import{sessionCancelHookToken}from"#execution/turn-cancellation-token.js";import{TurnCancelledError}from"#harness/turn-cancellation.js";async function createTurnCancellationControl(r){let i=createHook({token:sessionCancelHookToken(r.sessionId)}),a=i[Symbol.asyncIterator]();try{await claimHookOwnership(i)}catch(e){if(isHookConflictError(e))return;throw e}let o=new AbortController,s=consumeMatchingCancel(a,r.expectedTurnId).then(()=>(o.abort(new TurnCancelledError),`cancel`)),c=!1;return{signal:o.signal,requested:s,async dispose(){c||(c=!0,await disposeHook(i))}}}async function consumeMatchingCancel(e,t){for(;;){let n=await e.next();if(n.done)return await new Promise(()=>{});if(matchesActiveTurn(n.value,t))return}}function matchesActiveTurn(e,t){if(typeof e!=`object`||!e)return!0;let n=e.turnId;return n===void 0||n===t}export{createTurnCancellationControl};