import{createInputRequestedEvent,createSessionCompletedEvent,createTurnCompletedEvent}from"#protocol/message.js";import{emitFailedStep,emitTurnEpilogue,setHarnessEmissionState}from"#harness/emission.js";import{setPendingInputBatch}from"#harness/input-requests.js";import{extendSessionTokenBudget,getSessionTokenLimitViolation,getSessionTokenUsage}from"#harness/turn-tag-state.js";import{createSessionLimitContinuationRequest}from"#harness/session-limit-continuation.js";async function applySessionLimitContinuation(e){if(e.limitContinuation===void 0)return{result:null,session:e.session};if(e.limitContinuation.granted)return{result:null,session:extendSessionTokenBudget(e.session)};let r=getSessionTokenLimitViolation(e.session);return r===null?{result:null,session:e.session}:e.config.mode===`task`?{result:await failSessionTokenLimit({...e,violation:r}),session:e.session}:(e.emit&&(await e.emit(createTurnCompletedEvent({sequence:e.emissionState.sequence,turnId:e.emissionState.turnId})),await e.emit(createSessionCompletedEvent())),{result:{next:{done:!0,output:``},session:e.session},session:e.session})}async function enforceSessionTokenLimit(e){let t=getSessionTokenLimitViolation(e.session);if(t===null)return null;let{emit:n}=e;return n!==void 0&&(e.config.mode===`conversation`||e.config.capabilities?.requestInput===!0)?parkOnSessionTokenLimit({...e,emit:n,violation:t}):failSessionTokenLimit({...e,violation:t})}async function parkOnSessionTokenLimit(t){let n=getSessionTokenUsage(t.session),r=createSessionLimitContinuationRequest({sessionId:t.session.sessionId,totalUsedTokens:t.violation.kind===`input`?n.inputTokens:n.outputTokens,violation:t.violation}),a=t.emissionState,o=setPendingInputBatch({event:{sequence:a.sequence,stepIndex:a.stepIndex,turnId:a.turnId},requests:[r],responseMessages:[],session:{...t.session,history:[...t.messages]}});return await t.emit(createInputRequestedEvent({requests:[r],sequence:a.sequence,stepIndex:a.stepIndex,turnId:a.turnId})),t.config.mode===`conversation`&&(a=await emitTurnEpilogue(t.emit,a,t.config.mode,o.continuationToken)),{next:null,session:setHarnessEmissionState(o,a)}}function formatSessionTokenLimitMessage(e){return`The session reached its configured ${e} token limit.`}async function failSessionTokenLimit(e){let t=getSessionTokenUsage(e.session),n=formatSessionTokenLimitMessage(e.violation.kind),i={inputTokens:t.inputTokens,kind:e.violation.kind,limit:e.violation.limit,outputTokens:t.outputTokens,usedTokens:e.violation.usedTokens};return e.emit&&await emitFailedStep(e.emit,e.emissionState,{code:`SESSION_TOKEN_LIMIT_REACHED`,details:i,message:n,sessionId:e.session.sessionId}),{next:{done:!0,isError:e.config.mode===`task`?!0:void 0,output:e.config.mode===`task`?n:``},session:e.session}}export{applySessionLimitContinuation,enforceSessionTokenLimit};