import{scopeEvalTargetHandle}from"#evals/target.js";import{EvalSessionManager}from"#evals/session.js";import{createEmptyDerivedFacts}from"#evals/runner/derive-run-facts.js";async function executeCase(n){let{client:r,target:i,testCase:a,task:o,timeoutMs:s}=n,c=s===void 0?neverAbortSignal():AbortSignal.timeout(s),l=new EvalSessionManager({client:r,signal:c}),u=resolveRun(a,o),d=scopeEvalTargetHandle(i,{requirements:n.requirements??[],sessions:l}),f=[];return buildTaskResult({logs:f,output:await u({case:a,get session(){return l.primary},log:e=>{f.push(e),n.onLog?.(e)},newSession:()=>l.newSession(),signal:c,target:d}),parseOutput:o?.parseOutput,sessions:l.snapshots(),turn:l.lastTurnSession()?.lastTurn})}function resolveRun(e,t){let n=e.id;return`run`in e&&e.run!==void 0?e.run:t?.run===void 0?t?.messages===void 0?t?.prompt===void 0?`input`in e?async t=>(await t.session.send(formatCaseInput(e.input))).message:()=>{throw Error(`Eval case "${n}" must provide \`run\` or \`input\`.`)}:async n=>(await n.session.send(t.prompt(e))).message:async n=>{let r;for(let i of t.messages(e))r=await n.session.send(i);return r?.message}:t.run}function buildTaskResult(e){let t=e.sessions.flatMap(e=>e.events),n=e.turn?.message??null,r={output:e.output===void 0?n:e.output,finalMessage:n,sessionId:selectPrimarySessionId(e.sessions),status:e.turn?.status??`completed`,events:t,logs:e.logs,derived:combineDerivedFacts(e.sessions),sessions:e.sessions,runtimeIdentity:extractRuntimeIdentity(t)};return e.parseOutput!==void 0&&(r.output=e.parseOutput(r)),r}function combineDerivedFacts(e){if(e.length===0)return createEmptyDerivedFacts();let t=e.flatMap(e=>e.derived.toolCalls),r=e.flatMap(e=>e.derived.subagentCalls),i=e.flatMap(e=>e.derived.inputRequests),a=e.find(e=>e.derived.failureCode!==void 0)?.derived.failureCode;return{toolCalls:t,toolCallCount:t.length,subagentCalls:r,subagentCallCount:r.length,inputRequests:i,parked:e.some(e=>e.derived.parked),messageCount:sum(e,e=>e.derived.messageCount),reasoningBlockCount:sum(e,e=>e.derived.reasoningBlockCount),failureCode:a}}function selectPrimarySessionId(e){return e.find(e=>e.primary)?.sessionId??e[0]?.sessionId}function formatCaseInput(e){return typeof e==`string`?e:JSON.stringify(e)}function extractRuntimeIdentity(e){for(let t of e)if(t.type===`session.started`&&t.data.runtime!==void 0)return t.data.runtime}function sum(e,t){return e.reduce((e,n)=>e+t(n),0)}function neverAbortSignal(){return new AbortController().signal}export{executeCase};