import{callAdapterEventHandler}from"#channel/adapter.js";import{ModeKey}from"#context/keys.js";import{encodeMessageStreamEvent,timestampHandleMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession}from"#execution/session.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{upsertProxyInputRequests}from"#harness/proxy-input-requests.js";import{setChannelContext}from"#execution/channel-context.js";import{withContextScope}from"#context/run-step.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{emitProxiedInputRequest}from"#execution/subagent-hitl-proxy.js";async function runProxySubagentEventStep(e){"use step";let t=await readDurableSession(e.sessionState);return emitProxiedSubagentEvent({ctx:await deserializeContext(e.serializedContext),durableSession:t,hookPayload:e.hookPayload,parentWritable:e.parentWritable})}async function emitProxiedSubagentEvent(i){let{ctx:a}=i,o=a.require(ChannelKey),s=a.require(BundleKey),c=hydrateDurableSession({compactionOverrides:{thresholdPercent:s.resolvedAgent.config.compaction?.thresholdPercent},durable:i.durableSession,turnAgent:s.turnAgent}),l=buildAdapterContext(o,a),u=i.parentWritable.getWriter(),d,f;try{let emit=async t=>{let r=await callAdapterEventHandler(o,t,l);await u.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(r)))},r=await withContextScope(a,c,async e=>{if(i.hookPayload.kind===`subagent-authorization-event`)return await emit(i.hookPayload.event),{result:void 0,session:e};let n=await emitProxiedInputRequest({emit,hookPayload:i.hookPayload,mode:a.require(ModeKey),session:e});return{result:n.entries,session:n.session}});d=r.result,f=r.session}finally{u.releaseLock()}setChannelContext(a,{...o,state:{...l.state}}),d!==void 0&&i.hookPayload.kind===`subagent-input-request`&&(f=upsertProxyInputRequests({entries:d,forChildContinuationToken:i.hookPayload.childContinuationToken,session:f}));let p=reconcileSessionContinuationToken(a,f);return{serializedContext:serializeContext(a),sessionState:createDurableSessionState({session:p})}}export{emitProxiedSubagentEvent,runProxySubagentEventStep};