import{buildCallbackContext}from"#context/build-callback-context.js";import{getRuntimeCompiledArtifactsAppRoot}from"#runtime/compiled-artifacts-source.js";import{createRuntimeSandboxKeys}from"#runtime/sandbox/keys.js";import{createRuntimeSandboxTemplatePlan}from"#runtime/sandbox/template-plan.js";async function ensureSandboxAccess(n){let r=n.state?.initialized??!1,i=n.state?.session??null,a=getRuntimeCompiledArtifactsAppRoot(n.compiledArtifactsSource)??process.cwd(),o=n.registry.sandbox,s;function getHandle(){return s===void 0&&(s=createHandle().catch(e=>{throw s=void 0,e})),s}async function createHandle(){if(o===null)return null;let t=o.definition,s=t.backend,c=createRuntimeSandboxTemplatePlan({definition:t,workspaceResourceRoot:o.workspaceResourceRoot}),l=await createRuntimeSandboxKeys({backendName:s.name,compiledArtifactsSource:n.compiledArtifactsSource,nodeId:n.nodeId,sessionId:n.sessionId,sourceId:t.sourceId,templatePlan:c}),u=await s.create({existingMetadata:i?.backendName===s.name&&i.sessionKey===l.sessionKey?i.metadata:void 0,runtimeContext:{appRoot:a},sessionKey:l.sessionKey,tags:n.tags,templateKey:l.templateKey});return r||=(await runOnSession(async()=>{await t.onSession?.({ctx:buildCallbackContext(),use:u.useSessionFn})}),!0),u}async function runOnSession(e){if(n.runOnSession!==void 0){await n.runOnSession(e);return}await e()}return{async captureState(){if(s!==void 0){let e=await s;e!==null&&(i=await e.captureState())}return{initialized:r,session:i}},async dispose(){s!==void 0&&await(await s)?.dispose()},async get(){return(await getHandle())?.session??null}}}export{ensureSandboxAccess};