import{toErrorMessage}from"#shared/errors.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{createBundledRuntimeCompiledArtifactsSource}from"#runtime/compiled-artifacts-source.js";import{createRuntimeSandboxTemplateKey}from"#runtime/sandbox/keys.js";import{createRuntimeSandboxTemplatePlan}from"#runtime/sandbox/template-plan.js";import{loadCompiledModuleMapFromAuthoredSource}from"#internal/authored-module-map-loader.js";import{createAuthoredSourceRuntimeCompiledArtifactsSource}from"#internal/application/runtime-compiled-artifacts-source.js";import{loadCompileMetadata}from"#runtime/loaders/compile-metadata.js";import{withBundledCompiledArtifacts}from"#runtime/loaders/bundled-artifacts.js";import{loadCompiledManifest}from"#runtime/loaders/manifest.js";import{resolveRuntimeCompilerArtifactPaths}from"#runtime/loaders/artifact-paths.js";import{resolveRuntimeAgentGraph}from"#runtime/resolve-agent-graph.js";import{materializeWorkspaceDirectory}from"#runtime/workspace/seed-files.js";async function prewarmSandboxes(t){let n=await collectPrewarmTargets(t);if(n.length===0)return;t.log?.(`Eve: initializing ${n.length} sandbox ${pluralize(n.length,`template`)}...`);let r=t.dispatch??(async({backend:e,input:t})=>await e.prewarm(t)),i=0;await Promise.all(n.map(async({backend:n,label:a,input:o})=>{t.log?.(`Eve: initializing sandbox template "${a}"...`);let s;try{s=await r({backend:n,input:o})}catch(r){throw t.log?.(`Eve: failed to initialize sandbox template "${a}" on backend "${n.name}": ${toErrorMessage(r)}`),r}s.reused?(i+=1,t.log?.(`Eve: reused cached sandbox template "${a}".`)):t.log?.(`Eve: built sandbox template "${a}".`)})),t.log?.(`Eve: initialized ${n.length} sandbox ${pluralize(n.length,`template`)} (${i} reused, ${n.length-i} built).`)}async function prewarmAppSandboxes(e){let t=e.compiledArtifactsSource??createAuthoredSourceRuntimeCompiledArtifactsSource(e.appRoot);if(t.kind!==`disk`)throw Error(`prewarmAppSandboxes requires disk-backed compiled artifacts.`);let n=await(e.loadAgentGraph??loadGraphFromArtifacts)({compiledArtifactsSource:t});await prewarmSandboxes({appRoot:t.appRoot,compiledArtifactsSource:t,dispatch:e.dispatch,graph:n,log:e.log})}async function prewarmBuiltAppSandboxes(e){let t=createAuthoredSourceRuntimeCompiledArtifactsSource(e.appRoot),[r,i,u]=await Promise.all([loadCompileMetadata({compiledArtifactsSource:t}),loadCompiledManifest({compiledArtifactsSource:t}),loadCompiledModuleMapFromAuthoredSource({compiledArtifactsSource:t})]);await withBundledCompiledArtifacts({manifest:i,metadata:r??void 0,moduleMap:u,sessionId:`built-app-prewarm`},async()=>{let t=createBundledRuntimeCompiledArtifactsSource(),r=await resolveRuntimeAgentGraph({manifest:i,moduleMap:u});await prewarmSandboxes({appRoot:e.appRoot,compiledArtifactsSource:t,dispatch:e.dispatch,graph:r,log:e.log})})}async function collectPrewarmTargets(e){let t=resolveRuntimeCompilerArtifactPaths(e.appRoot).compileDirectoryPath,n={appRoot:e.appRoot},a=[];return await Promise.all(collectNodeSandboxes(e.graph).map(async({definition:o,nodeId:s,workspaceResourceRoot:c})=>{let l=createRuntimeSandboxTemplatePlan({definition:o,workspaceResourceRoot:c}),u=await createRuntimeSandboxTemplateKey({backendName:o.backend.name,compiledArtifactsSource:e.compiledArtifactsSource,nodeId:s,sourceId:o.sourceId,templatePlan:l});u!==null&&a.push({backend:o.backend,label:formatLabel(s),input:{bootstrap:o.bootstrap,seedFiles:await loadResourceRootSeedFiles({compileDirectoryPath:t,workspaceResourceRoot:c}),runtimeContext:n,templateKey:u}})})),a.sort((e,t)=>e.label.localeCompare(t.label))}async function loadResourceRootSeedFiles(e){return e.workspaceResourceRoot.rootEntries.length===0?[]:(await materializeWorkspaceDirectory(`${e.compileDirectoryPath}/${e.workspaceResourceRoot.logicalPath}`)).map(e=>({content:e.content,path:e.path}))}async function loadGraphFromArtifacts(e){let[t,n]=await Promise.all([loadCompiledManifest({compiledArtifactsSource:e.compiledArtifactsSource}),loadCompiledModuleMapFromAuthoredSource({compiledArtifactsSource:e.compiledArtifactsSource})]);return await resolveRuntimeAgentGraph({manifest:t,moduleMap:n})}function collectNodeSandboxes(e){return[...e.nodesByNodeId.entries()].flatMap(([e,t])=>{let n=t.sandboxRegistry.sandbox;return n===null?[]:[{...n,nodeId:e}]})}function pluralize(e,t){return e===1?t:`${t}s`}function formatLabel(e){return e===ROOT_RUNTIME_AGENT_NODE_ID?`root`:e}export{prewarmAppSandboxes,prewarmBuiltAppSandboxes,prewarmSandboxes};