"use strict";exports.id=5193,exports.ids=[5193],exports.modules={15193:(a,b,c)=>{c.d(b,{n6:()=>S,sE:()=>B,G_:()=>w,WM:()=>y,EO:()=>U,tE:()=>x,RJ:()=>z,rD:()=>ae,Ql:()=>aa,Wm:()=>ad});var d=c(73024),e=c(76760);function f(a,b,c){let d=e.relative(a,b);if(d.startsWith("..")||e.isAbsolute(d))throw Error(c)}function g(a,...b){let c=e.resolve(a,...b);return f(e.resolve(a),c,"Path escapes archive root"),c}function h(a,b){let c=e.resolve(a),d=e.resolve(b);return f(c,d,"Path escapes archive root"),e.relative(c,d).split(e.sep).join("/")}function i(a,b){let c=a.normalize("NFKD").replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,96);return c.length>0?c:b}function j(a){return e.resolve(a,".pi","kernel-lite")}async function k(a){await d.promises.mkdir(a,{recursive:!0});let b=await d.promises.lstat(a);if(b.isSymbolicLink()||!b.isDirectory())throw Error(`Archive path is not a real directory: ${a}`)}async function l(a){let b=e.resolve(a.cwd),c=e.resolve(a.archiveRoot??j(a.cwd));f(b,c,"Archive root must stay inside cwd");let h=i(a.ownerId,"owner"),l=i(a.runId,"run");if(l!==a.runId)throw Error("Invalid run id");let m=g(c,"sessions",h,"runs",l),n=g(m,"artifacts"),o=g(m,"r"===a.language?"script.R":"script.py"),p=g(m,"stdout.txt"),q=g(m,"stderr.txt"),r=g(m,"manifest.json");await k(n);let[s,t]=await Promise.all([d.promises.realpath(b),d.promises.realpath(c)]);return f(s,t,"Archive root must stay inside cwd"),await d.promises.writeFile(o,a.code,{encoding:"utf8",flag:"wx",mode:384}),{archiveRoot:c,ownerId:a.ownerId,safeOwnerId:h,runId:l,runDir:m,scriptPath:o,stdoutPath:p,stderrPath:q,outputDir:n,manifestPath:r}}async function m(a){await Promise.all([d.promises.writeFile(a.stdoutPath,a.stdout,{encoding:"utf8",flag:"w",mode:384}),d.promises.writeFile(a.stderrPath,a.stderr,{encoding:"utf8",flag:"w",mode:384})])}async function n(a){let b={schema:"kernel-plot.run.v1",runId:a.archive.runId,ownerId:a.archive.ownerId,language:a.language,runtime:a.runtime,status:a.status,title:a.title,scriptPath:a.archive.scriptPath,stdoutPath:a.archive.stdoutPath,stderrPath:a.archive.stderrPath,outputDir:a.archive.outputDir,artifacts:a.artifacts,stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode,error:a.error,cancelled:a.cancelled,timedOut:a.timedOut,createdAt:a.createdAt,completedAt:a.completedAt};return await d.promises.writeFile(a.archive.manifestPath,`${JSON.stringify(b,null,2)}
`,{encoding:"utf8",flag:"w",mode:384}),b}async function o(a){let b=g(e.resolve(a.archiveRoot??j(a.cwd)),"sessions",i(a.ownerId,"owner"),"runs"),c=await d.promises.readdir(b,{withFileTypes:!0}).catch(()=>[]),f=[];for(let a of c){if(!a.isDirectory()||a.isSymbolicLink())continue;let c=g(b,a.name,"manifest.json"),e=await d.promises.readFile(c,"utf8").catch(()=>null);if(e)try{let a=JSON.parse(e);"kernel-plot.run.v1"===a.schema&&f.push(a)}catch{}}return f.sort((a,b)=>b.completedAt.localeCompare(a.completedAt,"en"))}let p=new Set([".png",".jpg",".jpeg",".gif",".webp",".svg",".html",".htm",".pdf",".txt",".tsv",".csv",".json",".jsonl",".md",".parquet",".feather",".rds",".rda",".h5",".h5ad",".xlsx"]);async function q(a){if(a.depth>8)return[];let b=await d.promises.readdir(a.currentDir,{withFileTypes:!0}).catch(()=>[]),c=[];for(let f of b){if(c.length>=a.maxArtifactsPerRun)break;let b=e.join(a.currentDir,f.name);if(f.isSymbolicLink())continue;if(f.isDirectory()){c.push(...await q({...a,currentDir:b,depth:a.depth+1,maxArtifactsPerRun:a.maxArtifactsPerRun-c.length}));continue}if(!f.isFile())continue;let g=e.extname(f.name).toLowerCase();if(!p.has(g))continue;let i=await d.promises.lstat(b);i.isSymbolicLink()||!i.isFile()||i.size>a.maxArtifactBytes||c.push({path:b,relativePath:h(a.outputDir,b),archivePath:h(a.archiveRoot,b),name:f.name,mimeType:function(a){switch(a.toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";case".html":case".htm":return"text/html; charset=utf-8";case".pdf":return"application/pdf";case".txt":case".md":return"text/plain; charset=utf-8";case".csv":return"text/csv; charset=utf-8";case".tsv":return"text/tab-separated-values; charset=utf-8";case".json":case".jsonl":return"application/json; charset=utf-8";case".parquet":return"application/vnd.apache.parquet";case".feather":return"application/vnd.apache.arrow.file";case".rds":case".rda":return"application/x-r-data";case".h5":case".h5ad":return"application/x-hdf5";case".xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";default:return"application/octet-stream"}}(g),kind:function(a){let b=a.toLowerCase();return[".png",".jpg",".jpeg",".gif",".webp",".svg"].includes(b)?"image":[".html",".htm"].includes(b)?"html":[".pdf",".xlsx"].includes(b)?"document":[".txt",".md"].includes(b)?"text":[".csv",".tsv",".json",".jsonl",".parquet",".feather",".rds",".rda",".h5",".h5ad"].includes(b)?"data":"other"}(g),size:i.size})}return c}async function r(a){let b=await d.promises.lstat(a.outputDir).catch(()=>null);return!b||b.isSymbolicLink()||!b.isDirectory()?[]:(await q({...a,currentDir:a.outputDir,depth:0})).sort((a,b)=>a.archivePath.localeCompare(b.archivePath,"en"))}var s=c(48161),t=c(51455);function u(){return(0,e.join)((0,s.homedir)(),".config","warmplot.json")}function v(a){return(0,e.join)(a,".pi","warmplot.json")}async function w(){let a=u();try{let b=await (0,t.readFile)(a,"utf-8"),c=JSON.parse(b);return"1.0"!==c.version&&console.warn(`Config version mismatch: expected 1.0, got ${c.version}`),c}catch(a){return"ENOENT"===a.code||console.warn("Failed to load global config, using defaults:",a),{version:"1.0",kernels:{"default-python":{language:"python",command:"python3",args:["-u"],displayName:"Python 3 (System)",env:{}},"default-r":{language:"r",command:"R",args:["--slave","--vanilla"],displayName:"R (System)",env:{}}},defaultKernel:{python:"default-python",r:"default-r"},scanCache:{lastScan:new Date().toISOString(),scannedKernels:["default-python","default-r"]}}}}async function x(a){let b=u(),c=(0,e.join)((0,s.homedir)(),".config");try{await (0,t.mkdir)(c,{recursive:!0}),await (0,t.writeFile)(b,JSON.stringify(a,null,2),"utf-8")}catch(a){throw Error(`Failed to save global config: ${a instanceof Error?a.message:String(a)}`)}}async function y(a){let b=v(a);try{let a=await (0,t.readFile)(b,"utf-8"),c=JSON.parse(a);return"1.0"!==c.version&&console.warn(`Project config version mismatch: expected 1.0, got ${c.version}`),c}catch(a){return"ENOENT"===a.code||console.warn("Failed to load project config:",a),null}}async function z(a,b){let c=v(a),d=(0,e.join)(a,".pi");try{await (0,t.mkdir)(d,{recursive:!0}),await (0,t.writeFile)(c,JSON.stringify(b,null,2),"utf-8")}catch(a){throw Error(`Failed to save project config: ${a instanceof Error?a.message:String(a)}`)}}var A=c(77598);let B={enabled:!0,defaultRuntime:"kernel-lite",timeoutMs:6e4,idleTimeoutMs:9e5,maxLogChars:2e5,maxArtifactBytes:262144e3,maxArtifactsPerRun:200,pythonCommand:"python3",pythonArgs:[],rCommand:"R",rArgs:["--slave","--vanilla"],rscriptCommand:"Rscript",rscriptArgs:[]};var C=c(31421);function D(a,b){return a.length<=b?a:`${a.slice(0,b)}
[Warmplot truncated log at ${b} characters]`}function E(a,b){return{...process.env,...b,WARMPLOT_OUTPUT_DIR:a,PI_KERNEL_PLOT_OUTPUT_DIR:a,OPENANNO_PLOT_OUTPUT_DIR:a}}function F(a,b){a.kill("SIGTERM"),setTimeout(()=>{b()||a.kill("SIGKILL")},1500).unref()}class G{activeRuns=new Map;register(a){let b=new AbortController,c={...a,abortController:b};return this.activeRuns.set(a.runId,c),{signal:b.signal,unregister:()=>{this.activeRuns.get(a.runId)===c&&this.activeRuns.delete(a.runId)}}}cancel(a,b="Plot run cancelled"){let c=this.activeRuns.get(a);return!!c&&(c.abortController.abort(b),!0)}isActive(a){return this.activeRuns.has(a)}count(){return this.activeRuns.size}}function H(a,b,c){if("r"===b)return{command:a.rCommand,args:a.rArgs};if(!c)throw Error("Python kernel driver required");return{command:a.pythonCommand,args:[...a.pythonArgs,"-u","-c",c]}}let I="WARMPLOT_KERNEL_RESPONSE ",J=String.raw`
import contextlib
import io
import json
import os
import sys
import traceback

globals_ns = {"__name__": "__main__"}

def trim_log(value, limit):
    if len(value) <= limit:
        return value
    return value[:limit] + "\n[Warmplot truncated log at %d characters]" % limit

for line in sys.stdin:
    try:
        request = json.loads(line)
        if request.get("type") == "shutdown":
            break

        output_dir = request["outputDir"]
        os.environ["WARMPLOT_OUTPUT_DIR"] = output_dir
        os.environ["PI_KERNEL_PLOT_OUTPUT_DIR"] = output_dir
        os.environ["OPENANNO_PLOT_OUTPUT_DIR"] = output_dir
        for key, value in request.get("env", {}).items():
            os.environ[str(key)] = str(value)
        os.chdir(request["cwd"])
        stdout = io.StringIO()
        stderr = io.StringIO()
        status = "ok"
        error = None

        try:
            with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr):
                exec(request["code"], globals_ns, globals_ns)
        except BaseException as exc:
            status = "error"
            error = str(exc)
            stderr.write(traceback.format_exc())

        response = {
            "id": request["id"],
            "status": status,
            "stdout": trim_log(stdout.getvalue(), int(request.get("maxLogChars", 200000))),
            "stderr": trim_log(stderr.getvalue(), int(request.get("maxLogChars", 200000))),
            "error": error,
        }
    except BaseException as exc:
        response = {
            "id": None,
            "status": "error",
            "stdout": "",
            "stderr": traceback.format_exc(),
            "error": str(exc),
        }

    sys.stdout.write("WARMPLOT_KERNEL_RESPONSE " + json.dumps(response) + "\n")
    sys.stdout.flush()
`;class K{cwd;policy;process;pending=null;stdoutBuffer="";stderr="";stopped=!1;constructor(a,b){this.cwd=a,this.policy=b;const c=H(b,"python",J);this.process=(0,C.spawn)(c.command,c.args,{cwd:a,env:E(a),shell:!1,stdio:["pipe","pipe","pipe"]}),this.process.stdout.setEncoding("utf8"),this.process.stderr.setEncoding("utf8"),this.process.stdout.on("data",a=>this.handleStdout(a)),this.process.stderr.on("data",a=>{this.stderr=D(`${this.stderr}${a}`,this.policy.maxLogChars)}),this.process.on("error",a=>this.failPending(a.message)),this.process.on("exit",()=>{this.stopped=!0,this.failPending("Python plot kernel stopped")})}execute(a){return this.stopped||this.process.killed?Promise.resolve({stdout:"",stderr:this.stderr,exitCode:null,timedOut:!1,cancelled:!1,error:"Python plot kernel is not running"}):this.pending?Promise.resolve({stdout:"",stderr:"",exitCode:null,timedOut:!1,cancelled:!1,error:"Python plot kernel is busy"}):new Promise(b=>{this.pending={id:a.id,resolve:b},this.process.stdin.write(`${JSON.stringify({id:a.id,code:a.code,cwd:a.cwd,outputDir:a.outputDir,env:a.env,maxLogChars:this.policy.maxLogChars})}
`,a=>{a&&this.failPending(a.message)})})}async shutdown(){this.stopped=!0,this.process.stdin.write(`${JSON.stringify({type:"shutdown"})}
`,()=>{}),this.process.kill("SIGTERM"),setTimeout(()=>{this.process.killed||this.process.kill("SIGKILL")},1500).unref(),this.failPending("Python plot kernel stopped")}handleStdout(a){this.stdoutBuffer+=a;let b=this.stdoutBuffer.split(/\r?\n/);for(let a of(this.stdoutBuffer=b.pop()??"",b)){if(!a.startsWith(I))continue;let b=this.pending;if(b)try{let c=JSON.parse(a.slice(I.length));if(c.id!==b.id)continue;this.pending=null,b.resolve({stdout:c.stdout??"",stderr:c.stderr??"",exitCode:+("ok"!==c.status),timedOut:!1,cancelled:!1,error:"ok"===c.status?null:c.error??"Python plot kernel execution failed"})}catch(a){this.failPending(a instanceof Error?a.message:"Failed to parse Python kernel response")}}}failPending(a){let b=this.pending;b&&(this.pending=null,b.resolve({stdout:"",stderr:this.stderr,exitCode:null,timedOut:!1,cancelled:!1,error:a}))}}let L="WARMPLOT_KERNEL_RESPONSE ";function M(a){return`"${a.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\r/g,"\\r").replace(/\n/g,"\\n")}"`}class N{cwd;policy;process;pending=null;stdoutBuffer="";stderr="";stopped=!1;constructor(a,b){this.cwd=a,this.policy=b;const c=H(b,"r");this.process=(0,C.spawn)(c.command,c.args,{cwd:a,env:E(a),shell:!1,stdio:["pipe","pipe","pipe"]}),this.process.stdout.setEncoding("utf8"),this.process.stderr.setEncoding("utf8"),this.process.stdout.on("data",a=>this.handleStdout(a)),this.process.stderr.on("data",a=>{this.stderr=D(`${this.stderr}${a}`,this.policy.maxLogChars)}),this.process.on("error",a=>this.failPending(a.message)),this.process.on("exit",()=>{this.stopped=!0,this.failPending("R plot kernel stopped")})}async execute(a){if(this.stopped||this.process.killed)return{stdout:"",stderr:this.stderr,exitCode:null,timedOut:!1,cancelled:!1,error:"R plot kernel is not running"};if(this.pending)return{stdout:"",stderr:"",exitCode:null,timedOut:!1,cancelled:!1,error:"R plot kernel is busy"};let b=`${a.stdoutPath}.kernel.tmp`,c=`${a.stderrPath}.kernel.tmp`,e=`${a.scriptPath}.kernel-control.R`,f={...a.env,WARMPLOT_OUTPUT_DIR:a.outputDir,PI_KERNEL_PLOT_OUTPUT_DIR:a.outputDir,OPENANNO_PLOT_OUTPUT_DIR:a.outputDir};return await d.promises.writeFile(e,['.warmplot_run_status <- "ok"','.warmplot_run_error <- ""',`.warmplot_run_stdout <- file(${M(b)}, open = "wt")`,`.warmplot_run_stderr <- file(${M(c)}, open = "wt")`,'.warmplot_old_output_sinks <- sink.number(type = "output")','.warmplot_old_message_sinks <- sink.number(type = "message")',".warmplot_old_wd <- getwd()","tryCatch({",`  setwd(${M(a.cwd)})`,`  do.call(Sys.setenv, list(
${Object.entries(f).map(([a,b])=>`  ${a} = ${M(b)}`).join(`,
`)}
  ))`,'  sink(.warmplot_run_stdout, type = "output")','  sink(.warmplot_run_stderr, type = "message")',`  source(${M(a.scriptPath)}, local = .GlobalEnv, echo = FALSE)`,"}, error = function(e) {",'  .warmplot_run_status <<- "error"',"  .warmplot_run_error <<- conditionMessage(e)","  message(conditionMessage(e))","}, finally = {",'  while (sink.number(type = "output") > .warmplot_old_output_sinks) sink(type = "output")','  while (sink.number(type = "message") > .warmplot_old_message_sinks) sink(type = "message")',"  try(setwd(.warmplot_old_wd), silent = TRUE)","  try(close(.warmplot_run_stdout), silent = TRUE)","  try(close(.warmplot_run_stderr), silent = TRUE)","})",`cat(${M(`${L}${a.id} `)}, .warmplot_run_status, "\\n", sep = "")`,"flush.console()",""].join(`
`),{encoding:"utf8",flag:"wx",mode:384}),new Promise(f=>{this.pending={id:a.id,resolve:async a=>{let[g,h]=await Promise.all([d.promises.readFile(b,"utf8").catch(()=>""),d.promises.readFile(c,"utf8").catch(()=>"")]);await Promise.all([d.promises.rm(b,{force:!0}),d.promises.rm(c,{force:!0}),d.promises.rm(e,{force:!0})]),f({...a,stdout:D(g,this.policy.maxLogChars),stderr:D(h||a.stderr,this.policy.maxLogChars),error:a.error??(0===a.exitCode?null:D(h,this.policy.maxLogChars).trim()||"R plot kernel execution failed")})}},this.process.stdin.write(`source(${M(e)}, local = .GlobalEnv)
`,a=>{a&&this.failPending(a.message)})})}async shutdown(){this.stopped=!0,this.process.stdin.write(`quit(save = "no", status = 0)
`,()=>{}),this.process.kill("SIGTERM"),setTimeout(()=>{this.process.killed||this.process.kill("SIGKILL")},1500).unref(),this.failPending("R plot kernel stopped")}handleStdout(a){this.stdoutBuffer+=a;let b=this.stdoutBuffer.split(/\r?\n/);for(let a of(this.stdoutBuffer=b.pop()??"",b)){if(!a.startsWith(L))continue;let[,b,c]=a.match(/^WARMPLOT_KERNEL_RESPONSE\s+(\S+)\s+(\S+)/)??[],d=this.pending;d&&b===d.id&&(this.pending=null,d.resolve({stdout:"",stderr:"",exitCode:+("ok"!==c),timedOut:!1,cancelled:!1,error:null}))}}failPending(a){let b=this.pending;b&&(this.pending=null,b.resolve({stdout:"",stderr:this.stderr,exitCode:null,timedOut:!1,cancelled:!1,error:a}))}}class O{driver;idleTimeoutMs;onIdle;tail=Promise.resolve();idleTimer=null;constructor(a,b,c){this.driver=a,this.idleTimeoutMs=b,this.onIdle=c}execute(a){this.clearIdleTimer();let b=this.tail.then(()=>this.driver.execute(a));return this.tail=b.catch(()=>{}).finally(()=>this.armIdleTimer()),b}async shutdown(){this.clearIdleTimer(),await this.driver.shutdown()}armIdleTimer(){this.clearIdleTimer(),this.idleTimer=setTimeout(()=>{this.onIdle()},this.idleTimeoutMs),this.idleTimer.unref()}clearIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}}class P{policy;kernels=new Map;constructor(a){this.policy=a}execute(a){let b=this.createRuntimeKey(a.ownerId,a.language),c=this.getOrCreateKernel({key:b,language:a.language,cwd:a.run.cwd});return this.executeWithTimeout({key:b,kernel:c,run:a.run})}async stopSession(a){let b=a.language?[a.language]:["python","r"];await Promise.all(b.map(b=>this.stopKernelByKey(this.createRuntimeKey(a.ownerId,b))))}async dispose(){await Promise.all([...this.kernels.keys()].map(a=>this.stopKernelByKey(a)))}getActiveKernelCount(){return this.kernels.size}createRuntimeKey(a,b){return`${a}:${b}`}getOrCreateKernel(a){var b;let c=this.kernels.get(a.key);if(c)return c;let d=new O("r"===(b={language:a.language,cwd:a.cwd,policy:this.policy}).language?new N(b.cwd,b.policy):new K(b.cwd,b.policy),this.policy.idleTimeoutMs,()=>{this.stopKernelByKey(a.key)});return this.kernels.set(a.key,d),d}async stopKernelByKey(a){let b=this.kernels.get(a);b&&(this.kernels.delete(a),await b.shutdown())}executeWithTimeout(a){let b=null;return new Promise(c=>{let d=!1,e=()=>{d||(d=!0,b&&clearTimeout(b),this.stopKernelByKey(a.key),c({stdout:"",stderr:"",exitCode:null,timedOut:!1,cancelled:!0,error:"Plot run cancelled"}))};((b=setTimeout(()=>{d||(d=!0,a.run.signal?.removeEventListener("abort",e),this.stopKernelByKey(a.key),c({stdout:"",stderr:"",exitCode:null,timedOut:!0,cancelled:!1,error:`Plot kernel timed out after ${Math.round(a.run.timeoutMs/1e3)}s`}))},a.run.timeoutMs)).unref(),a.run.signal?.addEventListener("abort",e,{once:!0}),a.run.signal?.aborted)?e():a.kernel.execute(a.run).then(f=>{d||(d=!0,b&&clearTimeout(b),a.run.signal?.removeEventListener("abort",e),c(f))})})}}async function Q(a){var b,c,d,e;let f=(b=a.policy,c=a.run.language,d=a.run.scriptPath,"r"===c?{command:b.rscriptCommand,args:[...b.rscriptArgs,d]}:{command:b.pythonCommand,args:[...b.pythonArgs,d]});return e={command:f.command,args:f.args,cwd:a.run.cwd,env:E(a.run.outputDir,a.run.env),timeoutMs:a.run.timeoutMs,maxLogChars:a.policy.maxLogChars,signal:a.run.signal,label:`${"r"===a.run.language?"R":"Python"} plot worker`},new Promise(a=>{let b="",c="",d=!1,f=!1,g=!1,h=(0,C.spawn)(e.command,e.args,{cwd:e.cwd,env:e.env,shell:!1,stdio:["ignore","pipe","pipe"]}),i=b=>{d||(d=!0,clearTimeout(j),e.signal?.removeEventListener("abort",k),a(b))},j=setTimeout(()=>{f=!0,F(h,()=>d)},e.timeoutMs);j.unref();let k=()=>{d||(g=!0,F(h,()=>d))};e.signal?.addEventListener("abort",k,{once:!0}),e.signal?.aborted&&k(),h.stdout.on("data",a=>{b=D(`${b}${a.toString("utf8")}`,e.maxLogChars)}),h.stderr.on("data",a=>{c=D(`${c}${a.toString("utf8")}`,e.maxLogChars)}),h.on("error",a=>{i({stdout:b,stderr:c,exitCode:null,timedOut:f,cancelled:g,error:a.message})}),h.on("close",(a,d)=>{let h=g?`${e.label} cancelled`:null,j=f?`${e.label} timed out after ${Math.round(e.timeoutMs/1e3)}s`:null,k=!d||j||h?null:`${e.label} exited via signal ${d}`,l="number"==typeof a&&0!==a?`${e.label} exited with code ${a}`:null;i({stdout:b,stderr:c,exitCode:g||f?null:a,timedOut:f,cancelled:g,error:h??j??k??l})})})}class R{policy;runController=new G;kernelRuntime;constructor(a={}){this.policy=function(a){return{...B,...a,pythonArgs:a?.pythonArgs??B.pythonArgs,rArgs:a?.rArgs??B.rArgs,rscriptArgs:a?.rscriptArgs??B.rscriptArgs}}(a.policy),this.kernelRuntime=new P(this.policy)}async run(a){let b;if(!this.policy.enabled)throw Error("Kernel plotting is disabled");var c,d,e,f=a.language;if("python"!==f&&"r"!==f)throw Error("language must be python or r");let g=a.runtime??this.policy.defaultRuntime;if(function(a){if("kernel-lite"!==a&&"worker"!==a)throw Error("runtime must be kernel-lite or worker")}(g),"string"!=typeof a.code||0===a.code.length)throw Error("code required");let h=(0,A.randomUUID)().replace(/-/g,"").slice(0,16),i=new Date().toISOString(),j=await l({cwd:a.cwd,archiveRoot:a.archiveRoot,ownerId:a.ownerId,runId:h,language:a.language,code:a.code}),k=this.runController.register({runId:h,ownerId:a.ownerId,language:a.language,runtime:g}),o=function(a,b){if(!a)return b;if(!b)return a;let c=new AbortController,d=()=>{c.signal.aborted||c.abort(a.reason??b.reason)};return a.addEventListener("abort",d,{once:!0}),b.addEventListener("abort",d,{once:!0}),(a.aborted||b.aborted)&&d(),c.signal}(a.signal,k.signal);try{let c={id:h,language:a.language,code:a.code,cwd:a.cwd,outputDir:j.outputDir,scriptPath:j.scriptPath,stdoutPath:j.stdoutPath,stderrPath:j.stderrPath,timeoutMs:a.timeoutMs??this.policy.timeoutMs,env:a.env??{},signal:o};b="worker"===g?await Q({run:c,policy:this.policy}):await this.kernelRuntime.execute({ownerId:a.ownerId,language:a.language,run:c})}catch(e){let d=e instanceof Error?e.message:"Plot run failed";b={stdout:"",stderr:"",exitCode:null,timedOut:!1,cancelled:!1,error:(c=Error(d)).message.includes("ENOENT")||c.message.includes("not found")?`Missing ${"r"===a.language?"R":"Python"} runtime`:d}}finally{k.unregister()}await m({stdoutPath:j.stdoutPath,stderrPath:j.stderrPath,stdout:b.stdout,stderr:b.stderr});let p=await r({archiveRoot:j.archiveRoot,outputDir:j.outputDir,maxArtifactBytes:this.policy.maxArtifactBytes,maxArtifactsPerRun:this.policy.maxArtifactsPerRun}),q=(d=b).cancelled?"cancelled":d.timedOut?"timed_out":0!==d.exitCode||d.error?"failed":"succeeded",s=new Date().toISOString();return{runId:(e=await n({archive:j,language:a.language,runtime:g,status:q,title:a.title,stdout:b.stdout,stderr:b.stderr,exitCode:b.exitCode,error:b.error,cancelled:b.cancelled,timedOut:b.timedOut,artifacts:p,createdAt:i,completedAt:s})).runId,ownerId:e.ownerId,language:e.language,runtime:e.runtime,status:e.status,title:e.title,stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode,error:e.error,cancelled:e.cancelled,timedOut:e.timedOut,scriptPath:e.scriptPath,stdoutPath:e.stdoutPath,stderrPath:e.stderrPath,outputDir:e.outputDir,artifacts:e.artifacts,createdAt:e.createdAt,completedAt:e.completedAt}}async stopSession(a){await this.kernelRuntime.stopSession(a)}async cancelRun(a,b){return this.runController.cancel(a,b)}async listArtifacts(a){return(await o(a)).flatMap(a=>a.artifacts).slice(0,a.limit??100)}async dispose(){await this.kernelRuntime.dispose()}getActiveRunCount(){return this.runController.count()}getActiveKernelCount(){return this.kernelRuntime.getActiveKernelCount()}}function S(a){return new R(a)}function T(a,b){return b.kernels[a]||null}async function U(a){var b,c,d;let e=await w(),f=await y(a.cwd);if(a.sessionKernelId){let b=T(a.sessionKernelId,e);if(b)return{command:b.command,args:b.args,env:b.env,source:"session",kernelId:a.sessionKernelId}}if(f?.selectedKernels[a.language]){let b=f.selectedKernels[a.language],c=T(b,e);if(c)return{command:c.command,args:c.args,env:c.env,source:"project",kernelId:b}}let g=e.defaultKernel[a.language];if(g){let a=T(g,e);if(a)return{command:a.command,args:a.args,env:a.env,source:"global",kernelId:g}}let h="python"===a.language?a.policy.pythonCommand:a.policy.rCommand;return"python3"!==h&&"R"!==h?(b=a.language,c=a.policy,"python"===b?{command:c.pythonCommand,args:c.pythonArgs,env:{},source:"policy"}:{command:c.rCommand,args:c.rArgs,env:{},source:"policy"}):{command:"python"===(d=a.language)?"python3":"R",args:"python"===d?["-u"]:["--slave","--vanilla"],env:{},source:"path"}}let V=(0,c(57975).promisify)(C.exec);async function W(a){try{return await (0,t.access)(a,t.constants.X_OK),!0}catch{return!1}}async function X(){let a=[],b=[];try{let{stdout:b}=await V("conda env list");for(let c of b.split(`
`)){if(c.startsWith("#")||!c.trim())continue;let b=c.trim().split(/\s+/);if(b.length<2)continue;let d=b[0],f=b[b.length-1],g=(0,e.join)(f,"bin","python");await W(g)&&a.push({language:"python",command:g,args:["-u"],displayName:`Python 3 (Conda ${d})`,env:{CONDA_DEFAULT_ENV:d}})}}catch(a){b.push(`Conda scan failed: ${a instanceof Error?a.message:String(a)}`)}return{kernels:a,errors:b}}async function Y(a){let b=[];for(let c of[".venv","venv","env"])try{let d=(0,e.join)(a,c,"bin","python");if(await W(d)){let c=(0,e.basename)(a);b.push({language:"python",command:d,args:["-u"],displayName:`Python 3 (Venv ${c})`,env:{}})}}catch{}return{kernels:b,errors:[]}}async function Z(){let a=[],b=[];try{let{stdout:b}=await V("pyenv versions --bare");for(let c of b.trim().split(`
`)){if(!c.trim())continue;let b=(0,e.join)(process.env.HOME||"~",".pyenv","versions",c,"bin","python");await W(b)&&a.push({language:"python",command:b,args:["-u"],displayName:`Python ${c} (Pyenv)`,env:{}})}}catch(a){b.push(`Pyenv scan failed: ${a instanceof Error?a.message:String(a)}`)}return{kernels:a,errors:b}}async function $(){let a=[],b=[];try{let{stdout:b}=await V("poetry env list --full-path");for(let c of b.trim().split(`
`)){let b=c.split(" ")[0];if(!b)continue;let d=(0,e.join)(b,"bin","python");if(await W(d)){let c=(0,e.basename)(b);a.push({language:"python",command:d,args:["-u"],displayName:`Python 3 (Poetry ${c})`,env:{}})}}}catch(a){b.push(`Poetry scan failed: ${a instanceof Error?a.message:String(a)}`)}return{kernels:a,errors:b}}async function _(){let a=[],b=[];try{let{stdout:b}=await V("which python3"),c=b.trim();if(c&&await W(c))try{let{stdout:b}=await V(`${c} --version`),d=b.trim().replace("Python ","");a.push({language:"python",command:"python3",args:["-u"],displayName:`Python ${d} (System)`,env:{}})}catch{a.push({language:"python",command:"python3",args:["-u"],displayName:"Python 3 (System)",env:{}})}}catch(a){b.push(`System Python scan failed: ${a instanceof Error?a.message:String(a)}`)}return{kernels:a,errors:b}}async function aa(a){let b=[],c=[],d=[X(),Z(),$(),_()];for(let{kernels:e,errors:f}of(a&&d.push(Y(a)),await Promise.all(d)))b.push(...e),c.push(...f);return{newKernels:b,errors:c}}async function ab(){let a=[],b=[];try{let{stdout:b}=await V("which R"),c=b.trim();if(c&&await W(c))try{let{stdout:b}=await V("R --version | head -1"),c=b.match(/R version ([\d.]+)/),d=c?c[1]:"";a.push({language:"r",command:"R",args:["--slave","--vanilla"],displayName:d?`R ${d} (System)`:"R (System)",env:{}})}catch{a.push({language:"r",command:"R",args:["--slave","--vanilla"],displayName:"R (System)",env:{}})}}catch(a){b.push(`System R scan failed: ${a instanceof Error?a.message:String(a)}`)}return{kernels:a,errors:b}}async function ac(a){let b=[];try{let c=(0,e.join)(a,"renv"),d=(0,e.join)(a,"renv.lock"),f=await W(c).catch(()=>!1),g=await (0,t.access)(d).then(()=>!0).catch(()=>!1);if(f||g){let c=(0,e.basename)(a);b.push({language:"r",command:"R",args:["--slave","--vanilla"],displayName:`R (Renv ${c})`,env:{RENV_PROJECT:a}})}}catch{}return{kernels:b,errors:[]}}async function ad(a){let b=[],c=[],d=[ab()];for(let{kernels:e,errors:f}of(a&&d.push(ac(a)),await Promise.all(d)))b.push(...e),c.push(...f);return{newKernels:b,errors:c}}async function ae(a){let b=await aa(a),c=await ad(a);return{newKernels:[...b.newKernels,...c.newKernels],errors:[...b.errors,...c.errors]}}}};