import{createLogger}from"#internal/logging.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{deserializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{setPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{hydrateDurableSession}from"#execution/session.js";import{getSubagentDelegationName,isSubagentDelegationAction}from"#harness/subagent-depth.js";import{dispatchRuntimeActionsStep}from"#execution/dispatch-runtime-actions-step.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{buildRuntimeActionsFromWorkflowInterrupt}from"#harness/workflow-runtime-action-state.js";import{planWorkflowSubagentDispatch}from"#harness/workflow-subagent-limit.js";const log=createLogger(`execution.dispatch-workflow-runtime-actions`);async function dispatchWorkflowRuntimeActionsStep(e){"use step";let n=await readDurableSession(e.sessionState),r=getPendingWorkflowInterrupt(n.state);if(r===void 0)return{results:[],sessionState:e.sessionState};let i=buildRuntimeActionsFromWorkflowInterrupt(r.interrupt);if(i.length===0)return{results:[],sessionState:e.sessionState};let a=(await deserializeContext(e.serializedContext)).require(BundleKey),o=planWorkflowSubagentDispatch({actions:i,interrupt:r.interrupt,maxSubagents:n.workflowMaxSubagents}),s=o.blocked.map(e=>(log.warn(`workflow subagent limit reached; blocking delegated call`,{callId:e.callId,maxSubagents:o.maxSubagents,subagentName:isSubagentDelegationAction(e)?getSubagentDelegationName(e):e.kind,usedCalls:o.usedCalls}),createWorkflowSubagentLimitResult({action:e,plan:o})));if(o.allowed.length===0)return{results:s,sessionState:e.sessionState};let c=hydrateDurableSession({compactionOverrides:{thresholdPercent:a.resolvedAgent.config.compaction?.thresholdPercent},durable:n,turnAgent:a.turnAgent}),l=setPendingRuntimeActionBatch({actions:o.allowed,event:{sequence:0,stepIndex:0,turnId:`workflow-dispatch`},responseMessages:[],session:c}),u=await dispatchRuntimeActionsStep({callbackBaseUrl:e.callbackBaseUrl,parentContinuationToken:e.parentContinuationToken,parentWritable:e.parentWritable,serializedContext:e.serializedContext,sessionState:createDurableSessionState({session:l})});return s.length===0?u:{results:[...u.results,...s],sessionState:u.sessionState}}function createWorkflowSubagentLimitResult(e){let t=isSubagentDelegationAction(e.action)?getSubagentDelegationName(e.action):e.action.kind;return{callId:e.action.callId,isError:!0,kind:`subagent-result`,output:{code:`WORKFLOW_SUBAGENT_LIMIT_REACHED`,maxSubagents:e.plan.maxSubagents,message:`Workflow subagent limit reached (${String(e.plan.maxSubagents)}); "${t}" was not called.`},subagentName:t}}export{dispatchWorkflowRuntimeActionsStep};