New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details
Socket
Book a DemoSign in
Socket

web-python-kernel

Package Overview
Dependencies
Maintainers
1
Versions
9
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

web-python-kernel - npm Package Compare versions

Comparing version
0.1.0
to
0.1.1
dist/kernel.worker.js

Sorry, the diff of this file is too big to display

+3
/*! For license information please see kernel.worker.min.js.LICENSE.txt */
var e={590:(e,t,r)=>{r.d(t,{LV:()=>d,p:()=>p});const n=Symbol("Comlink.proxy"),o=Symbol("Comlink.endpoint"),s=Symbol("Comlink.releaseProxy"),i=Symbol("Comlink.finalizer"),a=Symbol("Comlink.thrown"),l=e=>"object"==typeof e&&null!==e||"function"==typeof e,c=new Map([["proxy",{canHandle:e=>l(e)&&e[n],serialize(e){const{port1:t,port2:r}=new MessageChannel;return p(e,t),[r,[r]]},deserialize:e=>(e.start(),d(e))}],["throw",{canHandle:e=>l(e)&&a in e,serialize({value:e}){let t;return t=e instanceof Error?{isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:{isError:!1,value:e},[t,[]]},deserialize(e){if(e.isError)throw Object.assign(new Error(e.value.message),e.value);throw e.value}}]]);function p(e,t=globalThis,r=["*"]){t.addEventListener("message",function o(s){if(!s||!s.data)return;if(!function(e,t){for(const r of e){if(t===r||"*"===r)return!0;if(r instanceof RegExp&&r.test(t))return!0}return!1}(r,s.origin))return void console.warn(`Invalid origin '${s.origin}' for comlink proxy`);const{id:l,type:c,path:d}=Object.assign({path:[]},s.data),m=(s.data.argumentList||[]).map(w);let h;try{const t=d.slice(0,-1).reduce((e,t)=>e[t],e),r=d.reduce((e,t)=>e[t],e);switch(c){case"GET":h=r;break;case"SET":t[d.slice(-1)[0]]=w(s.data.value),h=!0;break;case"APPLY":h=r.apply(t,m);break;case"CONSTRUCT":h=function(e){return Object.assign(e,{[n]:!0})}(new r(...m));break;case"ENDPOINT":{const{port1:t,port2:r}=new MessageChannel;p(e,r),h=function(e,t){return R.set(e,t),e}(t,[t])}break;case"RELEASE":h=void 0;break;default:return}}catch(e){h={value:e,[a]:0}}Promise.resolve(h).catch(e=>({value:e,[a]:0})).then(r=>{const[n,s]=_(r);t.postMessage(Object.assign(Object.assign({},n),{id:l}),s),"RELEASE"===c&&(t.removeEventListener("message",o),u(t),i in e&&"function"==typeof e[i]&&e[i]())}).catch(e=>{const[r,n]=_({value:new TypeError("Unserializable return value"),[a]:0});t.postMessage(Object.assign(Object.assign({},r),{id:l}),n)})}),t.start&&t.start()}function u(e){(function(e){return"MessagePort"===e.constructor.name})(e)&&e.close()}function d(e,t){const r=new Map;return e.addEventListener("message",function(e){const{data:t}=e;if(!t||!t.id)return;const n=r.get(t.id);if(n)try{n(t)}finally{r.delete(t.id)}}),g(e,r,[],t)}function m(e){if(e)throw new Error("Proxy has been released and is not useable")}function h(e){return b(e,new Map,{type:"RELEASE"}).then(()=>{u(e)})}const y=new WeakMap,f="FinalizationRegistry"in globalThis&&new FinalizationRegistry(e=>{const t=(y.get(e)||0)-1;y.set(e,t),0===t&&h(e)});function g(e,t,r=[],n=function(){}){let i=!1;const a=new Proxy(n,{get(n,o){if(m(i),o===s)return()=>{!function(e){f&&f.unregister(e)}(a),h(e),t.clear(),i=!0};if("then"===o){if(0===r.length)return{then:()=>a};const n=b(e,t,{type:"GET",path:r.map(e=>e.toString())}).then(w);return n.then.bind(n)}return g(e,t,[...r,o])},set(n,o,s){m(i);const[a,l]=_(s);return b(e,t,{type:"SET",path:[...r,o].map(e=>e.toString()),value:a},l).then(w)},apply(n,s,a){m(i);const l=r[r.length-1];if(l===o)return b(e,t,{type:"ENDPOINT"}).then(w);if("bind"===l)return g(e,t,r.slice(0,-1));const[c,p]=E(a);return b(e,t,{type:"APPLY",path:r.map(e=>e.toString()),argumentList:c},p).then(w)},construct(n,o){m(i);const[s,a]=E(o);return b(e,t,{type:"CONSTRUCT",path:r.map(e=>e.toString()),argumentList:s},a).then(w)}});return function(e,t){const r=(y.get(t)||0)+1;y.set(t,r),f&&f.register(e,t,e)}(a,e),a}function E(e){const t=e.map(_);return[t.map(e=>e[0]),(r=t.map(e=>e[1]),Array.prototype.concat.apply([],r))];var r}const R=new WeakMap;function _(e){for(const[t,r]of c)if(r.canHandle(e)){const[n,o]=r.serialize(e);return[{type:"HANDLER",name:t,value:n},o]}return[{type:"RAW",value:e},R.get(e)||[]]}function w(e){switch(e.type){case"HANDLER":return c.get(e.name).deserialize(e.value);case"RAW":return e.value}}function b(e,t,r,n){return new Promise(o=>{const s=new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-");t.set(s,o),e.start&&e.start(),e.postMessage(Object.assign({id:s},r),n)})}},637:(e,t,r)=>{r.d(t,{MB:()=>p});const n="https://cdn.jsdelivr.net/pyodide/v0.28.0/full/pyodide.js";let o=!1,s=null;var i,a,l=r(696);r(590),function(e){e.MAIN_THREAD="main_thread",e.WORKER="worker"}(i||(i={})),function(e){e.PYTHON="python"}(a||(a={}));class c{constructor(){this.events={}}on(e,t){this.events[e]||(this.events[e]=[]),this.events[e].push(t)}off(e,t){if(!this.events[e])return;const r=this.events[e].indexOf(t);r>-1&&this.events[e].splice(r,1)}emit(e,...t){this.events[e]&&this.events[e].forEach(e=>e(...t))}setMaxListeners(e){}}class p extends c{constructor(){super(),this.initialized=!1,this.initPromise=null,this.filesystemOptions={enabled:!1,root:".",mountPoint:"/home/pyodide"},this._resolveInputReply=null,this._parent_header={},this.executionCount=0,this._status="unknown",this._interruptBuffer=null,this._interruptSupported=!1,this.environmentVariables={},super.setMaxListeners(20),this.kernelId=`kernel_${Math.random().toString(36).substring(2)}_${Date.now()}`}async getStatus(){return this._status}async initialize(e){if(!this.initialized)return this.initPromise||(e?.filesystem&&(this.filesystemOptions={...this.filesystemOptions,...e.filesystem}),e?.env&&(this.environmentVariables={...e.env}),e?.lockFileURL&&(this.lockFileURL=e.lockFileURL),this.initPromise=this._initializeInternal()),this.initPromise}async _initializeInternal(){const e=Date.now();console.log("🚀 Starting optimized kernel initialization...");try{const t=Date.now(),r={};this.lockFileURL&&(r.lockFileURL=this.lockFileURL,console.log(`🔒 Using lockFileURL: ${this.lockFileURL}`)),this.pyodide=await async function(e={}){return s||(s=(async()=>{try{"undefined"!=typeof importScripts?await new Promise((e,t)=>{try{if("undefined"==typeof importScripts)return void t(new Error("importScripts is not available - not in a worker context"));if(void 0!==globalThis.loadPyodide)return void e();importScripts(n),e()}catch(e){t(new Error(`Failed to import Pyodide in worker: ${e}`))}}):await new Promise((e,t)=>{if(void 0!==globalThis.loadPyodide)return void e();const r=document.createElement("script");r.src=n,r.onload=()=>e(),r.onerror=()=>t(new Error(`Failed to load Pyodide from ${n}`)),document.head.appendChild(r)});const t=globalThis.loadPyodide;if(!t)throw new Error("loadPyodide function not found after script load");const r={indexURL:"https://cdn.jsdelivr.net/pyodide/v0.28.0/full/",...e},s=await t(r);return o=!0,console.log("✅ Pyodide loaded successfully from CDN"),s}catch(e){throw s=null,e}})(),s)}(r);const i=Date.now()-t;if(console.log(`✅ Pyodide loaded in ${i}ms`),this.lockFileURL){console.log("🚀 Using lock file - skipping package installation");const[,]=await Promise.all([this.filesystemOptions.enabled?this.mountFilesystem():Promise.resolve(),this.setEnvironmentVariables()]);await this.initGlobals()}else{const[,,]=await Promise.all([this.filesystemOptions.enabled?this.mountFilesystem():Promise.resolve(),this.initPackageManager(),this.setEnvironmentVariables()]);await this.initKernel(),await this.initGlobals()}const a=Date.now()-e;console.log(`🎯 KERNEL INITIALIZATION COMPLETE in ${a}ms`),console.log(`⚡ Performance: Pyodide(${i}ms) + Setup(${a-i}ms)`),this.initialized=!0,this._status="active",console.log("🟢 Kernel is now ACTIVE and ready for execution!")}catch(e){throw console.error("❌ Kernel initialization failed:",e),this._status="unknown",e}}async mountFilesystem(){try{console.log(`Mounting filesystem from ${this.filesystemOptions.root} to ${this.filesystemOptions.mountPoint}`),await this.pyodide.FS.mount(this.pyodide.FS.filesystems.NODEFS,{root:this.filesystemOptions.root||"."},this.filesystemOptions.mountPoint||"/home/pyodide"),console.log("Filesystem mounted successfully");try{const e=this.pyodide.FS.readdir(this.filesystemOptions.mountPoint||"/home/pyodide");console.log(`Files in ${this.filesystemOptions.mountPoint} directory: ${e.join(", ")}`)}catch(e){console.error(`Error listing mounted directory: ${e}`)}}catch(e){throw console.error("Error mounting filesystem:",e),e}}async initPackageManager(){const e=Date.now();console.log("⚡ Initializing optimized package manager...");try{let t;console.log("📦 Loading micropip, packaging..."),await this.pyodide.loadPackage(["micropip","packaging"]),console.log("✅ Loaded micropip, packaging"),t="undefined"!=typeof window&&window.location?new URL(".",window.location.href).href:"undefined"!=typeof self&&self.location?new URL(".",self.location.href).href:"/";const r=new URL("pypi/all.json",t).href,n=[new URL("pypi/piplite-0.6.0a5-py3-none-any.whl",t).href,new URL("pypi/pyodide_kernel-0.6.0a5-py3-none-any.whl",t).href,new URL("pypi/ipykernel-6.9.2-py3-none-any.whl",t).href,new URL("pypi/widgetsnbextension-3.6.999-py3-none-any.whl",t).href,new URL("pypi/widgetsnbextension-4.0.999-py3-none-any.whl",t).href];console.log(`🚀 Installing ${n.length} wheel packages in parallel...`);const o=n.map(async(e,t)=>{const r=Date.now();try{await this.pyodide.runPythonAsync(`\nimport micropip\nawait micropip.install('${e}', keep_going=True)\nprint(f"✅ Wheel ${t+1}/${n.length} installed")\n`);const o=Date.now()-r;return console.log(`⚡ Wheel ${t+1} installed in ${o}ms`),{index:t,success:!0,time:o}}catch(e){const n=Date.now()-r;return console.warn(`⚠️ Wheel ${t+1} failed after ${n}ms:`,e),{index:t,success:!1,time:n,error:e}}}),s=await Promise.all(o),i=s.filter(e=>e.success),a=s.filter(e=>!e.success);console.log(`📊 Wheels: ${i.length}/${n.length} successful`),a.length>0&&console.warn(`⚠️ Failed wheels: ${a.map(e=>e.index+1).join(", ")}`);try{await this.pyodide.runPythonAsync(`\ntry:\n import piplite.piplite\n import json\n\n # Load package index for faster lookups\n try:\n piplite.piplite.PIPLITE_URL = "${r}"\n # Pre-load package index for faster installation\n print("📋 Package index configured")\n except Exception as e:\n print(f"⚠️ Package index setup warning: {e}")\n\n # Configure piplite for optimal performance\n piplite.piplite.REPODATA_INFO = {}\n print("⚡ Piplite optimized for performance")\nexcept ImportError:\n print("⚠️ Piplite not available, continuing without it")\nexcept Exception as e:\n print(f"⚠️ Piplite setup failed: {e}")\n`)}catch(e){console.warn("⚠️ Piplite configuration failed, continuing without it:",e)}const l=Date.now()-e;console.log(`🎯 Package manager initialized in ${l}ms`)}catch(e){throw console.error("❌ Package manager initialization failed:",e),e}}async initKernel(){const e=Date.now();console.log("🚀 Initializing kernel packages with maximum optimization...");const t=[{name:"pure-eval",priority:1,source:"pyodide"},{name:"stack-data",priority:1,source:"pyodide"},{name:"pygments",priority:1,source:"pyodide"},{name:"ssl",priority:1,source:"pyodide"},{name:"sqlite3",priority:1,source:"pyodide"},{name:"prompt_toolkit",priority:1,source:"pyodide"},{name:"jedi",priority:1,source:"pyodide"},{name:"ipython",priority:1,source:"pyodide"},{name:"comm",priority:2,source:"pip"},{name:"hypha-rpc",priority:2,source:"pip"},{name:"nbformat",priority:2,source:"pip"},{name:"ipykernel",priority:3,source:"pip"},{name:"pyodide_kernel",priority:3,source:"pip"}];try{console.log(`📦 Installing ${t.length} packages with intelligent optimization...`),await this.installPackagesWithIntelligentOptimization(t),console.log("📥 Importing pyodide_kernel...");const r=Date.now();await this.pyodide.runPythonAsync("import pyodide_kernel");const n=Date.now()-r;console.log(`✅ pyodide_kernel imported in ${n}ms`);const o=Date.now()-e;console.log(`🎯 Kernel packages initialized in ${o}ms`)}catch(e){throw console.error("❌ Kernel package initialization failed:",e),e}}async installPackagesWithIntelligentOptimization(e){console.log(`⚡ Starting intelligent parallel installation of ${e.length} packages...`);const t=e.map(async e=>{const t=Date.now();try{if(console.log(`🔄 Installing ${e.name} (priority: ${e.priority}, preferred: ${e.source})...`),"pyodide"!==e.source){await this.installViaPipWithOptimizations(e.name);const r=Date.now()-t;return console.log(`✅ ${e.name} installed via pip (${r}ms)`),{package:e.name,method:"pip",duration:r,success:!0,priority:e.priority}}try{await this.pyodide.loadPackage([e.name]);const r=Date.now()-t;return console.log(`✅ ${e.name} loaded from Pyodide CDN (${r}ms)`),{package:e.name,method:"pyodide",duration:r,success:!0,priority:e.priority}}catch(r){console.log(`📦 ${e.name} not available on CDN, trying pip...`),await this.installViaPipWithOptimizations(e.name);const n=Date.now()-t;return console.log(`✅ ${e.name} installed via pip fallback (${n}ms)`),{package:e.name,method:"pip-fallback",duration:n,success:!0,priority:e.priority}}}catch(r){const n=Date.now()-t;return console.warn(`❌ Failed to install ${e.name} after ${n}ms:`,r),{package:e.name,method:"failed",duration:n,success:!1,priority:e.priority,error:r}}}),r=await Promise.all(t);this.analyzeInstallationResults(r)}async installViaPipWithOptimizations(e){await this.pyodide.runPythonAsync(`\ntry:\n # Import piplite first\n import piplite\n # Use optimized pip installation with caching\n await piplite.install('${e}', keep_going=True, deps=True)\n print("✅ Successfully installed ${e} via optimized pip")\nexcept Exception as e:\n print("⚠️ Warning: Failed to install ${e}:", str(e))\n # Try alternative installation method\n try:\n import micropip\n await micropip.install('${e}', keep_going=True)\n print("✅ Successfully installed ${e} via micropip fallback")\n except Exception as e2:\n print("❌ Both pip methods failed for ${e}:", str(e2))\n raise e2\n`)}analyzeInstallationResults(e){const t=e.filter(e=>e.success),r=e.filter(e=>!e.success),n=t.filter(e=>"pyodide"===e.method),o=t.filter(e=>"pip"===e.method),s=t.filter(e=>"pip-fallback"===e.method),i=Math.max(...e.map(e=>e.duration)),a=e.reduce((e,t)=>e+t.duration,0)/e.length,l=e.reduce((e,t)=>e+t.duration,0);console.log("🎯 INTELLIGENT INSTALLATION COMPLETE!"),console.log(`📊 Results: ${t.length}/${e.length} successful`),console.log(`⚡ Pyodide CDN: ${n.length} packages`),console.log(`📦 Direct pip: ${o.length} packages`),console.log(`🔄 Pip fallback: ${s.length} packages`),console.log(`❌ Failed: ${r.length} packages`),console.log(`⏱️ Total time: ${i}ms (vs ~${l}ms sequential)`),console.log(`🚀 Speed improvement: ~${Math.round(l/i)}x faster`),console.log(`📈 Average per package: ${Math.round(a)}ms`),r.length>0&&(console.warn(`⚠️ Failed packages: ${r.map(e=>e.package).join(", ")}`),r.forEach(e=>{console.warn(` - ${e.package}: ${e.error?.message||"Unknown error"}`)}));const c=Math.min(...t.map(e=>e.duration)),p=Math.max(...t.map(e=>e.duration));console.log(`📊 Performance range: ${c}ms (fastest) to ${p}ms (slowest)`)}async initGlobals(){console.log("Initializing globals...");const{globals:e}=this.pyodide;this._kernel=e.get("pyodide_kernel").kernel_instance.copy(),this._stdout_stream=e.get("pyodide_kernel").stdout_stream.copy(),this._stderr_stream=e.get("pyodide_kernel").stderr_stream.copy(),this._interpreter=this._kernel.interpreter.copy(),this._interpreter.send_comm=this.sendComm.bind(this),this.setupCallbacks()}setupCallbacks(){const e=(e,t)=>{const r={name:this.formatResult(e),text:this.formatResult(t)};this._sendMessage({parentHeader:this.formatResult(this._parent_header).header,bundle:r,type:"stream"})};this._stdout_stream.publish_stream_callback=e,this._stderr_stream.publish_stream_callback=e,this._interpreter.display_pub.clear_output_callback=e=>{const t={wait:this.formatResult(e)};this._sendMessage({parentHeader:this.formatResult(this._parent_header).header,bundle:t,type:"clear_output"})},this._interpreter.display_pub.display_data_callback=(e,t,r)=>{const n={data:this.formatResult(e),metadata:this.formatResult(t),transient:this.formatResult(r)};this._sendMessage({parentHeader:this.formatResult(this._parent_header).header,bundle:n,type:"display_data"})},this._interpreter.display_pub.update_display_data_callback=(e,t,r)=>{const n={data:this.formatResult(e),metadata:this.formatResult(t),transient:this.formatResult(r)};this._sendMessage({parentHeader:this.formatResult(this._parent_header).header,bundle:n,type:"update_display_data"})},this._interpreter.displayhook.publish_execution_result=(e,t,r)=>{const n={execution_count:e,data:this.formatResult(t),metadata:this.formatResult(r)};this._sendMessage({parentHeader:this.formatResult(this._parent_header).header,bundle:n,type:"execute_result"})},this._interpreter.input=this.input.bind(this),this._interpreter.getpass=this.getpass.bind(this)}_sendMessage(e){this._processMessage(e)}_processMessage(e){if(!e.type)return;let t;switch(e.type){case"stream":{const r=e.bundle??{name:"stdout",text:""};super.emit(l.z.STREAM,r),t=r;break}case"input_request":{const r=e.content??{prompt:"",password:!1};super.emit(l.z.INPUT_REQUEST,r),t=r;break}case"display_data":{const r=e.bundle??{data:{},metadata:{},transient:{}};super.emit(l.z.DISPLAY_DATA,r),t=r;break}case"update_display_data":{const r=e.bundle??{data:{},metadata:{},transient:{}};super.emit(l.z.UPDATE_DISPLAY_DATA,r),t=r;break}case"clear_output":{const r=e.bundle??{wait:!1};super.emit(l.z.CLEAR_OUTPUT,r),t=r;break}case"execute_result":{const r=e.bundle??{execution_count:this.executionCount,data:{},metadata:{}};super.emit(l.z.EXECUTE_RESULT,r),t=r;break}case"execute_error":{const r=e.bundle??{ename:"",evalue:"",traceback:[]};super.emit(l.z.EXECUTE_ERROR,r),t=r;break}case"comm_open":case"comm_msg":case"comm_close":{const r=e.content??{};super.emit(e.type,r,e.metadata,e.buffers),t={content:r,metadata:e.metadata,buffers:e.buffers};break}}t&&super.emit(l.z.ALL,{type:e.type,data:t})}isInitialized(){return this.initialized}async setup(e){await this.initialize(),this._parent_header=this.pyodide.toPy(e||{})}async execute(e,t={}){this.initialized||await this.initialize();try{this._status="busy",super.emit(l.z.KERNEL_BUSY,{}),await this.setup(t);const r="\n# Kernel isolation - reset commonly conflicting variables to prevent cross-kernel state sharing\nfor _var in ['x', 'value', 'result', 'a', 'b', 'c', 'data', 'temp']:\n if _var in globals():\n del globals()[_var]\ndel _var\n";return this.pyodide.runPython(r),new Promise((t,r)=>{const n={allMessages:[],executionComplete:!1,executionResult:null,executionError:null,timeout:null},o=e=>{n.allMessages.push(e)},s=async e=>{if(n.executionComplete)return;console.log(`[KERNEL] Execution completed, processing ${n.allMessages.length} messages`),n.executionComplete=!0,super.off(l.z.ALL,o);let r,s=!1,i=null;const a=n.executionResult;a&&"error"===a.status&&(s=!0,i={ename:a.ename,evalue:a.evalue,traceback:a.traceback});for(const e of n.allMessages){if("execute_error"===e.type){s=!0,i=e.data;break}"execute_result"===e.type&&(r=e.data)}if(this._status="active",super.emit(l.z.KERNEL_IDLE,{}),s){console.log("[KERNEL] Execution failed with error:",i);const e=i.ename?i.ename.replace(/^<class '(.+)'>$/,"$1"):i.ename;super.emit(l.z.EXECUTE_ERROR,{ename:e,evalue:i.evalue,traceback:i.traceback});const r=`${i.ename||"Error"}: ${i.evalue||"Unknown error"}`;t({success:!1,error:new Error(r),result:n.executionResult})}else{console.log(`[KERNEL] Execution successful, captured ${n.allMessages.length} output messages`);let e=void 0!==r?r:n.executionResult;t({success:!0,result:e})}};super.on(l.z.ALL,o),this._kernel.run(e).then(e=>{console.log("[KERNEL] Python execution finished, waiting for messages to settle"),n.executionResult=this.formatResult(e),setTimeout(()=>{s()},100)}).catch(e=>{console.error("[KERNEL] Python execution error:",e),n.executionError=e instanceof Error?e:new Error(String(e)),setTimeout(()=>{s()},100)})})}catch(e){return console.error("[KERNEL] Execute setup error:",e),this._status="active",super.emit(l.z.KERNEL_IDLE,{}),{success:!1,error:e instanceof Error?e:new Error(String(e))}}}formatResult(e){if(!(e instanceof this.pyodide.ffi.PyProxy))return e;try{const t=e.toJs();return this.mapToObject(t)}catch(e){return console.error("Error formatting result:",e),{status:"error",error:String(e)}}}mapToObject(e){const t=e instanceof Array?[]:{};return e.forEach((e,r)=>{t[r]=e instanceof Map||e instanceof Array?this.mapToObject(e):e}),t}async inputReply(e){this._resolveInputReply&&(this._resolveInputReply(e),this._resolveInputReply=null)}async sendInputRequest(e,t){const r={prompt:e,password:t};this._sendMessage({type:"input_request",content:r,parentHeader:this.formatResult(this._parent_header).header})}async getpass(e){e=void 0===e?"":e,await this.sendInputRequest(e,!0);const t=new Promise(e=>{this._resolveInputReply=e});return(await t).value}async input(e){e=void 0===e?"":e,await this.sendInputRequest(e,!1);const t=new Promise(e=>{this._resolveInputReply=e});return(await t).value}async sendComm(e,t,r,n,o){this._sendMessage({type:e,content:this.formatResult(t),metadata:this.formatResult(r),ident:this.formatResult(n),buffers:this.formatResult(o),parentHeader:this.formatResult(this._parent_header).header})}async complete(e,t,r={}){await this.setup(r);const n=this._kernel.complete(e,t);return this.formatResult(n)}async inspect(e,t,r,n={}){await this.setup(n);const o=this._kernel.inspect(e,t,r);return this.formatResult(o)}async isComplete(e,t={}){await this.setup(t);const r=this._kernel.is_complete(e);return this.formatResult(r)}async commInfo(e,t={}){await this.setup(t);const r=this._kernel.comm_info(e);return{comms:this.formatResult(r),status:"ok"}}async commOpen(e,t={}){await this.setup(t);const r=this._kernel.comm_manager.comm_open(this.pyodide.toPy(null),this.pyodide.toPy(null),this.pyodide.toPy(e));return this.formatResult(r)}async commMsg(e,t={}){await this.setup(t);const r=this._kernel.comm_manager.comm_msg(this.pyodide.toPy(null),this.pyodide.toPy(null),this.pyodide.toPy(e));return this.formatResult(r)}async commClose(e,t={}){await this.setup(t);const r=this._kernel.comm_manager.comm_close(this.pyodide.toPy(null),this.pyodide.toPy(null),this.pyodide.toPy(e));return this.formatResult(r)}async*executeStream(e,t={}){try{await this.initialize();const r=[],n=e=>{r.push(e)};super.on(l.z.ALL,n);try{const n=this.execute(e,t);for(;;)if(r.length>0&&(yield r.shift()),await Promise.race([n.then(()=>!0),new Promise(e=>setTimeout(()=>e(!1),10))])){for(;r.length>0;)yield r.shift();return await n}}catch(e){throw console.error("Error in executeStream:",e),e}finally{super.off(l.z.ALL,n)}}catch(e){return console.error("Error in executeStream setup:",e),{success:!1,error:e instanceof Error?e:new Error(String(e))}}}async interrupt(){if(!this.initialized||!this.pyodide)return console.warn("[KERNEL] Cannot interrupt: kernel not initialized"),!1;console.log("[KERNEL] Attempting to interrupt execution...");try{if(this._interruptBuffer&&this._interruptSupported&&(console.log("[KERNEL] Using interrupt buffer method"),this._interruptBuffer[0]=2,await new Promise(e=>setTimeout(e,100)),0===this._interruptBuffer[0]))return console.log("[KERNEL] Interrupt processed successfully via buffer"),!0;try{return console.log("[KERNEL] Attempting Python-level interrupt"),await this.pyodide.runPythonAsync("\nimport sys\nimport _thread\n# Try to interrupt the main thread\n_thread.interrupt_main()\n"),console.log("[KERNEL] Python interrupt signal sent"),!0}catch(e){console.log("[KERNEL] Python interrupt attempt failed:",e)}return this._interpreter&&"function"==typeof this._interpreter.interrupt?(console.log("[KERNEL] Using interpreter interrupt method"),this._interpreter.interrupt(),!0):(console.log("[KERNEL] Sending interrupt messages for UI feedback"),this._sendMessage({type:"stream",bundle:{name:"stderr",text:"KeyboardInterrupt: Execution interrupted by user\n"}}),this._sendMessage({type:"execute_error",bundle:{ename:"KeyboardInterrupt",evalue:"Execution interrupted by user",traceback:["KeyboardInterrupt: Execution interrupted by user"]}}),!1)}catch(e){return console.error("[KERNEL] Error during interrupt:",e),!1}}setInterruptBuffer(e){this._interruptBuffer=e;try{this.pyodide&&"function"==typeof this.pyodide.setInterruptBuffer?(this.pyodide.setInterruptBuffer(e),this._interruptSupported=!0):(console.warn("[KERNEL] pyodide.setInterruptBuffer not available, interrupt support limited"),this._interruptSupported=!1)}catch(e){console.error("[KERNEL] Error setting interrupt buffer:",e),this._interruptSupported=!1}}async setEnvironmentVariables(){if(0===Object.keys(this.environmentVariables).length)return;const e=Date.now();console.log(`🌍 Setting ${Object.keys(this.environmentVariables).length} environment variables...`);try{for(const[e,t]of Object.entries(this.environmentVariables)){let r;r=null==t?"":String(t),await this.pyodide.runPythonAsync(`\nimport os\nos.environ[${JSON.stringify(e)}] = ${JSON.stringify(r)}\n`)}const t=Date.now()-e;console.log(`⚡ Environment variables set in ${t}ms`)}catch(e){throw console.error("❌ Failed to set environment variables:",e),e}}}},696:(e,t,r)=>{var n;r.d(t,{z:()=>n}),function(e){e.STREAM="stream",e.DISPLAY_DATA="display_data",e.UPDATE_DISPLAY_DATA="update_display_data",e.EXECUTE_RESULT="execute_result",e.EXECUTE_ERROR="execute_error",e.EXECUTE_REQUEST="execute_request",e.INPUT_REQUEST="input_request",e.CLEAR_OUTPUT="clear_output",e.COMM_OPEN="comm_open",e.COMM_MSG="comm_msg",e.COMM_CLOSE="comm_close",e.KERNEL_READY="kernel_ready",e.KERNEL_BUSY="kernel_busy",e.KERNEL_IDLE="kernel_idle",e.ALL="*",e.EXECUTION_STALLED="execution_stalled",e.KERNEL_UNRECOVERABLE="kernel_unrecoverable",e.EXECUTION_INTERRUPTED="execution_interrupted",e.KERNEL_RESTARTED="kernel_restarted",e.KERNEL_TERMINATED="kernel_terminated"}(n||(n={}))}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var s=t[n]={exports:{}};return e[n](s,s.exports,r),s.exports}r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var n=r(590),o=r(696);const s=new(r(637).MB);let i=null,a={},l=new Map,c=null;function p(e){return e&&"object"==typeof e&&("KeyboardInterrupt"===e.type||e.message&&e.message.includes("KeyboardInterrupt"))}function u(){i?Object.values(o.z).forEach(e=>{const t=t=>{i&&i.postMessage({type:e,data:t})};l.set(e,t),s.on(e,t)}):console.error("[WORKER] Cannot set up event forwarding: no event port available")}self.addEventListener("error",e=>{console.error("[WORKER] Global error caught:",e.error),e.preventDefault()}),self.addEventListener("unhandledrejection",e=>{p(e.reason)?(console.log("[WORKER] KeyboardInterrupt caught in unhandled rejection handler - this is expected during interrupts"),i&&i.postMessage({type:o.z.EXECUTE_ERROR,data:{ename:"KeyboardInterrupt",evalue:"Execution interrupted by user",traceback:["KeyboardInterrupt: Execution interrupted by user"]}})):console.error("[WORKER] Unhandled promise rejection:",e.reason),e.preventDefault()}),self.addEventListener("message",e=>{if("SET_EVENT_PORT"===e.data?.type&&e.data?.port)!function(){if(l.size>0){for(const[e,t]of l.entries())s.off(e,t);l.clear()}i&&(i.close(),i=null)}(),i=e.data.port,s.isInitialized()&&u();else if("INITIALIZE_KERNEL"===e.data?.type)a=e.data.options||{},async function(e){try{await s.initialize(e),c&&"function"==typeof s.setInterruptBuffer&&s.setInterruptBuffer(c),u(),i&&i.postMessage({type:"KERNEL_INITIALIZED",data:{success:!0}})}catch(e){throw console.error("Kernel initialization failed:",e),e}}(a).catch(e=>{console.error("[WORKER] Error initializing kernel in worker:",e),i&&i.postMessage({type:o.z.EXECUTE_ERROR,data:{ename:"WorkerInitError",evalue:`Failed to initialize kernel: ${e.message}`,traceback:[e.stack||""]}})});else if("SET_INTERRUPT_BUFFER"===e.data?.type){c=e.data.buffer,s.isInitialized()&&c&&"function"==typeof s.setInterruptBuffer?(s.setInterruptBuffer(c),console.log("[WORKER] Interrupt buffer set in pyodide kernel")):c&&console.log("[WORKER] Interrupt buffer stored, will be set when kernel initializes");const t={type:"INTERRUPT_BUFFER_SET",data:{success:!0}};i&&i.postMessage(t),self.postMessage(t)}else if("INTERRUPT_KERNEL"===e.data?.type)if(c){c[0]=2;const e={type:"INTERRUPT_TRIGGERED",data:{success:!0,method:"buffer"}};i&&i.postMessage(e),self.postMessage(e)}else if(console.log("[WORKER] No interrupt buffer available, trying kernel.interrupt()"),"function"==typeof s.interrupt)s.interrupt().then(e=>{const t={type:"INTERRUPT_TRIGGERED",data:{success:e,method:"kernel"}};i&&i.postMessage(t),self.postMessage(t)}).catch(e=>{console.error("[WORKER] Error during kernel interrupt:",e);const t={type:"INTERRUPT_TRIGGERED",data:{success:!1,error:e.message,method:"kernel"}};i&&i.postMessage(t),self.postMessage(t)});else{console.warn("[WORKER] No interrupt method available");const e={type:"INTERRUPT_TRIGGERED",data:{success:!1,error:"No interrupt method available",method:"none"}};i&&i.postMessage(e),self.postMessage(e)}}),self.addEventListener("beforeunload",async()=>{try{i&&i.postMessage({type:"WORKER_TERMINATING",data:{message:"Worker is shutting down"}})}catch(e){console.error("Error during worker cleanup:",e)}});const d={initialize:async e=>{try{return void await s.initialize(e)}catch(e){throw console.error("[WORKER] Initialize error:",e),e}},execute:async(e,t)=>{try{return await s.execute(e,t)}catch(e){return console.error("[WORKER] Execute error:",e),p(e)?(console.log("[WORKER] KeyboardInterrupt caught in execute method"),{success:!1,error:new Error("KeyboardInterrupt: Execution interrupted by user"),result:{payload:[],status:"error",ename:"KeyboardInterrupt",evalue:"Execution interrupted by user",traceback:["KeyboardInterrupt: Execution interrupted by user"]}}):{success:!1,error:e instanceof Error?e:new Error(String(e)),result:{payload:[],status:"error",ename:e instanceof Error?e.constructor.name:"Error",evalue:e instanceof Error?e.message:String(e),traceback:e instanceof Error&&e.stack?e.stack.split("\n"):[String(e)]}}}},isInitialized:()=>{try{return s.isInitialized()}catch(e){return console.error("[WORKER] IsInitialized error:",e),!1}},inputReply:async e=>{try{await s.inputReply(e)}catch(e){throw console.error("[WORKER] InputReply error:",e),e}},getStatus:async()=>{try{return await s.getStatus()}catch(e){return console.error("[WORKER] getStatus error:",e),"unknown"}},interrupt:async()=>{try{return"function"==typeof s.interrupt?await s.interrupt():(console.warn("[WORKER] Kernel does not support interrupt method"),!1)}catch(e){return console.error("[WORKER] Interrupt error:",e),!1}},setInterruptBuffer:e=>{try{return"function"==typeof s.setInterruptBuffer?(s.setInterruptBuffer(e),!0):(console.warn("[WORKER] Kernel does not support setInterruptBuffer method"),!1)}catch(e){return console.error("[WORKER] setInterruptBuffer error:",e),!1}},complete:async(e,t,r)=>{try{return"function"==typeof s.complete?await s.complete(e,t,r):(console.warn("[WORKER] Kernel does not support complete method"),{status:"error",error:"Completion not supported"})}catch(e){return console.error("[WORKER] Complete error:",e),{status:"error",error:String(e)}}},inspect:async(e,t,r,n)=>{try{return"function"==typeof s.inspect?await s.inspect(e,t,r,n):(console.warn("[WORKER] Kernel does not support inspect method"),{status:"error",error:"Inspection not supported"})}catch(e){return console.error("[WORKER] Inspect error:",e),{status:"error",error:String(e)}}},isComplete:async(e,t)=>{try{return"function"==typeof s.isComplete?await s.isComplete(e,t):(console.warn("[WORKER] Kernel does not support isComplete method"),{status:"unknown"})}catch(e){return console.error("[WORKER] IsComplete error:",e),{status:"error",error:String(e)}}},commInfo:async(e,t)=>{try{return"function"==typeof s.commInfo?await s.commInfo(e,t):(console.warn("[WORKER] Kernel does not support commInfo method"),{comms:{},status:"ok"})}catch(e){return console.error("[WORKER] CommInfo error:",e),{comms:{},status:"error",error:String(e)}}},commOpen:async(e,t)=>{try{return"function"==typeof s.commOpen?await s.commOpen(e,t):void console.warn("[WORKER] Kernel does not support commOpen method")}catch(e){return void console.error("[WORKER] CommOpen error:",e)}},commMsg:async(e,t)=>{try{return"function"==typeof s.commMsg?await s.commMsg(e,t):void console.warn("[WORKER] Kernel does not support commMsg method")}catch(e){return void console.error("[WORKER] CommMsg error:",e)}},commClose:async(e,t)=>{try{return"function"==typeof s.commClose?await s.commClose(e,t):void console.warn("[WORKER] Kernel does not support commClose method")}catch(e){return void console.error("[WORKER] CommClose error:",e)}}};try{n.p(d)}catch(e){console.error("Error exposing proxy:",e)}
//# sourceMappingURL=kernel.worker.min.js.map
/**
* @license
* Copyright 2019 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/

Sorry, the diff of this file is too big to display

export {};
//# sourceMappingURL=kernel.worker.d.ts.map
{"version":3,"file":"kernel.worker.d.ts","sourceRoot":"","sources":["../../src/kernel.worker.ts"],"names":[],"mappings":""}
+19
-27

@@ -1,4 +0,4 @@

PK��Zt��U}�piplite/__init__.pyM��
PKBPt��U}�piplite/__init__.pyM��
1E�|�eY����?� y�:�dB��{�XX]�=���p�^���p��]2�q�ر��nC�gv �]�…��Z�$L�"�NEj��M�Ji�
��d�q��q�́>b��y�_M{�_O7�PK��Z���F�=piplite/cli.py�Xmo�6��_A(&����P��nH���e0��dZ:�D$R%�8^���#)��r�d�aĢH��{�0 ߒ�ߓ��Dz�@�!�UŪՊd�,)�NU��r�>�l�2)pI¸Ҵ(V�$�*���+�%�r?;�+5���2���
��d�q��q�́>b��y�_M{�_O7�PKBP���F�=piplite/cli.py�Xmo�6��_A(&����P��nH���e0��dZ:�D$R%�8^���#)��r�d�aĢH��{�0 ߒ�ߓ��Dz�@�!�UŪՊd�,)�NU��r�>�l�2)pI¸Ҵ(V�$�*���+�%�r?;�+5���2���
��"g9\xA�B�/�.���e�2m�T��믾yI�F��H���3�Æ4�D���((6�v$�S�$������|&Sz��� }��T<9YT4��[P�V�-@�n��Y Q�9yG '�xY�;�k����z���M�On���bj��22 9���n��h~��6޴`�SIx�9z���v?�9ܧ�4V�.E[��� 3λ`5�j�����$�4�����N�"�M��)�p �h��I.@�/4�CtJ�G�e��p��%��R�`CYQK@��D]�h/n-DvK��Z3�� � `��

@@ -10,28 +10,20 @@ ��A�G}�"�F��P���T@���r[,~0/�[SQ�+��/��� ���%}���*�ps���x~�M������:�����<�ii�NHSܱ��S-)W��%�9k� ��dΞJ�j��tp@w��lXs<Q�tR⋢V���k�lN�h{4�d���ɜHt��5CGR��<-�-X�}���l�h�PF��!�.����

��͵�M =�&}5��E.��S\��w��f���{��Z؉��n�|j� �2��di�6u��wz ���]U�T�4!�{��D��Xnjmn*u3ְ�Hl�l#�9q)4�<U��*�n!�;ыp�H�nI�4ؙ���n�i��t�������I}�?rH�$�d[�������bk�[(�C�"8��(|uU��T��X��X��=��BgK]m���m�m!���j���� �� �������� z�J�'E�Y�{�y�#o}x�A�Ite-n~=( �Ǹ���̵b�No�0�£����)���s7^����57#� ��Z6��x���On�ܻ��x�o1On���M� SSL[q�b� �Ӓ�\��'v꽓��eVQ4�f>�=���`zHqC*$ʿj5�MA�Yu6m�$j����2C�UB��6�y�&밚ږx\a[��(��۫O��SZE=,[�ش4��}��#c����z ��X,��z���k��q����>��G*0ׇ�G����u��o�|;k�AT�H��0�Ǟ�gA�Ȉ�x�i�x�+���x� |6:�CH�jg��F�.��`�n�Jǁ��q'�:t����z�a�Da�\A���s�*�F���7�X^2lu�7իB(����U�D3
��xq��o��3s�R��=;��ߵ4���:ۙ$�1:��M���'�p۠`���UTje�Qx�C2‚��sy�Rb\���-ұ �#]���3٭��528�a�s�K��C������Ll9� <0�0��OͿ�8gT1�~-p�2�PK��Z��F�
piplite/piplite.py�Ym��6��_A((b�\�����M��w�ԗ�\P,2-�6����Ժ�t��� E���M�o�kK"���̫�(���j/S�JY�V�yY
���k�Ԇ}�ʣ:�V�T��R&���T�2؇/{�C6w�,��yޏ����=ߊh��ʣ�d&F�B"_1��d��U& �l�����f'�l�4�;�ˣݩ���Bٞoe��EQ��m��3{,e�e5?���Y��X�R�ۏF�{��[��T��V�Uz��ܦ�FJ�"���ŵl�,2�߹��H��ب߳��J�cR��Y�f��������r��濇�F����Jx�%;�3��'�z~�����������j�z=�[a��Y?I
�I��=��Mri,"� b�*#F��l�\0Qd���5 L����}�[9j����,˫��<y���N����<����9_�՛M�i������}z�}�*���@��a5�����Xi@��4�4�P�RUEPc>�^-�g�_͓�� ה�d�������}��H��ô0%�] ���Ԅ�ו�3��,z�����?����k��Ksn [:�Y��WҠ�Y��<��\k��� �>+��'���(nA�z�7誹x�/]�\��!z�/������ 0E.�ܰ ��Jd8A:��Q������p�C�=���ѷ��"�S�T� g�B��)Ġ�~�tW��T� n �e>� A0,%�b}:���S� ���?=����t��e����+��w�)s!�Ի���LCM��
�Ĝ> ����y��9'�akя^�
EHF��+3����@��^5h�m`�(Ӡ��LoU �D�Sp�đz��HTrm�%��Lm��O�];��AǦ���A [邽U�p�����&�Q)�1����8Ĩdn#���.~@5�AK7pm冧�$����f�m�%ȓښ���~G��z�N6��gk�p��F���}�_�=�?�P{�^s��wfǿ��_���LBX����Ƚ� o�`8�q��=�YB�JT�}8�*���R�ƦN�t�@2 p�FT�
3�-��c�������-�tB � C�&�N�6��&��|���^X�~�0r1��^��$0�Y�j��~f����;��e ��Mt�s�?#.�h�K�8��� $P.ZYT� H��IG?�p:T��}���PQ��vů�viaO. At� ~)�wN�D�P�GЏ�k�1T0�l�;V6T�>
� ���C���=ϛ��Z�4�1m���C�N��d�uG_��L�RI-��)�I�o����B��*�턭��}���f�4��]ՏS-2�>xސ=s�R�K��`��}<�V�� �ؖl[�-��pS���`�lT�RPP ��\����b �]����6����~܉|�}�P88�u���O��Zl� ;�Z�Mۯ�%h�)��>L7 �w�����}��f�֟��Iz�?8:1+m�?+���D�ΰg����\�"4��{ܾx��B�K�΃RKm��G (ƦLP�I�N�0���M E��
��k�J#=j���9�����X�M�%4,���.�b�U�Qs��#H���A��P� �F��,(�zn� �b�]WXu��
(�;)e8I+����=*���J==-F�8`E�
"g%4����;�j�
�ck!�\C���5ݎ�� �l���Y���{����K�l|u6���� CP��efG d�pHԀ�Zb*n�>P*,�F�$�#�eJ8D �'��;��0��Zhp,6� ܾ{t ��{��v�pE��h��-��N�����|G�.;��(XZ����l����54�#8��߀��4���j5d8!�{Π�YM��Q�.,�sɋ�Q`m9_�?�7\�c�v�l���Zk���p�K�B���3�0.!����@e� u3�*u�����T5���u6���J�7f�y]�ܝ�f޺?Y��{֯m�܄��x�9�><���`@�� �xИXu&Ck���|mT^��Eq@sQ8��Я ]�Eĉ M����B�w���xƜy0H8��\R#T��C � �<���.OSa )� �t[
'�{΂Ckqp;m�f|K�!#������iSk�npy�#d�T�8�(��芛��q�/�~%4�Ƭ:���@��,�`X�3b�IǠ�"���ƲՊ�,����\�� �0tl�6��8aP��. `g'`i��R��@�؆
w�A9( ��'�M&�U��
A��d,kB�tx�%mX#�6���7�٫������&��U+!f?a >`���z�vN�f)(��@�g���2(�jl�63Pr�:Xِ[Qw��10�٩*�ޫ���9�BQ��_�3����C_?����m����_.c�T�@�mf�v�̷�S�A͵���˱抃����'ִ
<aE��׌�h +�Z^�APU�}�}�ގW�mCi�E�w�ẏ#�f�����[�xB�2�`@o��pԄ#nB%�CK�_��}�<U�Te1�JE2{� ��/�O����{�M� o���a�v�"Su�SG�t<4��O�A���h�c�Ƽ���1t�AÞ8tϏ4>�u,s��<�w娑VG���㦬�:�Z�O�#o}t� AS�uʋ� /P��!��Xd�p�Yb���0����$��4�Yh/0���� �Q�d��u̮D�
;�b>�k���=�Rc��WZ�Lk u��!I Zabm ���Zi�a��1�֢V+��:ou�x^[�˽̹�mp��� ��?cQH}ɦ������?�,�����dۨ�@t��/PK��Zt޹��"piplite-0.6.0a5.dist-info/METADATA�PMo�0 ��W�eb��>�6 K: C�M���%6f-K�D7���9�0@A�=>��Y[ͺ��)S�5\��յH��:��˷�~����=��C��4�M
��xq��o��3s�R��=;��ߵ4���:ۙ$�1:��M���'�p۠`���UTje�Qx�C2‚��sy�Rb\���-ұ �#]���3٭��528�a�s�K��C������Ll9� <0�0��OͿ�8gT1�~-p�2�PKBP>IX,B �#piplite/piplite.py�Zm��6��_A8(b�\�����M������^Q,���5�����]�v��� I������@��D��������j���V��V+vм��f���`j�>���
]H+X�ʽ(�T�Iz=���� �����U"KcyQ �|\��߉���[UG��\��.E�b�0��2+�\��Z�����V��Fif��-�G�U%[}�<���Y����{��V;f��,��g^k��L�p�Ѩ2�.��lr�RZ+�Mv*�t*n�m#eP���/[*�\�v.��(2�(7�,�����G�3K�-�}�ݏ�r����z��^��`�ɵ-�A�-��f#4إ9��6h����i���7� pj���pZ�<B����n^�^�|�x�uO���ʲm��Ziw� ��} ��|�8�5���r�rU��l���ɳ�fc>��/�,��挳A����wN|gf�U)��=���4<�B�@w����;�K�Ȱ�r�����s^t�@Kn:G1i��F��W���c�����@/�8�h�v.�0>�T�ٛ��K�xE���["gVy����=4$ hmm��܈��cx�x�-o�n6YX>hWG���fv�,����l�K":
�z=�U�Y��Nطto��%߉4l齘��X�����6b\�{A&e^)YZ��1��܃*vua� ��H%��b�vqs�~���k8������lK����K�����M�i�����յ�5�s���� Ph%Jߡy����&ݨ��Y����7����o��� � C���A���T��m�� �C�Dy�G�T�Aj���Z9˶\���۷�?��}D��� ��^Vpc�ҡ��\������E-|�A|�K&�a�a+J�[P��oc�x���R��/_�٠�CY(��w��w0���
��"�HQ�)2�"�9p�������hb��c�nEp�����P�r#3H����]�#�(7��b�e!1"A0,%��p��6B�;���A��ǡއ=�l�A�82GQ�=�˧5�P�X� &0o�8� l-�ת�"O&���L�_��@ËtQ���h�60�i�Yt����Eb��4u��7U\���D�!�N�0!�}g�otl
���`����s�M�2^`��u!�a��Q����_�?${ Q3�r n��� �Г��l�5�}�(A6��`�1�'�aw=~N6�gk���F�����?��O?<NN�=Ʃ���f�?��_gѦ\,[��m�=|�D0�?0�A��z��*�c�����cy{!�.6u
<�$3eP�Z@5�Wa��'�/����/���a:%'� #,}?\Z�H ~z���S��yF��y�t�=��_Q�#�B򥼻�S�@NwF�`\y�Y
l.D̙ �������
��s��Þ v��8$�pB8�h�
�QHa���E&h��,k�"ܥ����C�W�Y��S%^"{R*:߽�����GWTm^���p�ex�D]#hQ�(�6M�ޖ �H8��K,J:�+]M��ˌ��Hp1� j;�sH�6n*�`����s�;I�sp֏ �J^�g�Do�]�]i��fs�m�<�� }� $f���N�_�N\��z_�N�GqN���a���0k�(�S-5�tf���TG�^�*��V�n��J��vOsQ������j��� �3����D�w��+�w�L � P�-ٶ�^�{ N��{e��wS ,b^\�Fe�+ �1H`|i m�/�
�N*�����r���{Z��⋮_�V��?�K�t3�:q��t��ww�n�~��z3��߮��{����y#b�4�e��rhp� 4�P�-�L
�-���s�1��Pj���T������ԵA�Fw'r�W�.�3/Vt���0C�1#���{X�C���g�3��Ё�gD�f���g�s�v�P����$3j:[�*R� ��\!O�v]cI��+��6�)ùlVk����wD* ����+���; |C@�V�`8� �l2]��ϙ�i[���'��0��l�*�D®���&��7��8pJ���l�`������d(�[c�$7�hʕp%�?A z؂F� �S a��7Q�w�N@�pMj���Ԯ x~� �2pzD�ĕ @���Qnl���(Xڞ���l����-�4�#:��߀�t����j5�pB��A#)sO���^�>XI��Y���Ւ�����r�������Z �6����(���$�I��_�O����f ]Ž��W�j"��kU'���m��Y�d�=��U�ds4V���� ����!8ur��9��$���܋ 4!V����~ل��*j{�(�h.J�d4�#�c��8qѴ)��(�}W_h�i`̙A�)/b��S�ZB����QՄ�X�C�-I!ź!<'�=��,:�󈛀��iC4/�H3dd ������6�ưu�˛�2Q&�eQ[������y�ĸ�e�1���5�2 ��;M�;Ư� RN�l��<���à��}��r�����vq������,-��Vj<Ȝ[�p��"☙�=\� h� �_ٟ�eMl����k�0Fpy�������f���M�ÏWB¾E >`��+?D='�Y�J�g�%����m(�jm�ת�3Pr�:Xِ[��<�s��J�d��J���=�Uf&?��d�\Lh'�`�N�B��2&0J�d�f�n�� ���Tu�p#hu���Xs�AF�y��'zZ��X����q�Ub���%
C��}y�ގׅm���E»�ļ��w0��0� 5m�> ne\���P��� GV��J�Sh�_��}<u�Te ��Fj��!��1y�M?&8dy,� ?���Pd�W=�;��C�jp��f�0z�<Z�D� �$��g�Ν�Ӱg��#���πU�3�Z���]9��y��F>n��J�S���D=�6F�4�Y������u��_��E.:KL���'0���C�O��B{��B6�Fu@�q>֝cv%*U��P�$x{}��ڞz����)-hȌ5��Xc@�����
Q��`�� �֢V��ƺhuUx^[�˝,��mpپъ���?_$�4���MM���\�ǚ��^/MAf����{ �?�� PKBPt޹��"piplite-0.6.0a5.dist-info/METADATA�PMo�0 ��W�eb��>�6 K: C�M���%6f-K�D7���9�0@A�=>��Y[ͺ��)S�5\��յH��:��˷�~����=��C��4�M
h��v���0$�3h�c��jO�MiB_= qdL��*���Ţ��ѩ��mH5|~����9Q3pHY�ɠ�X|"'��W����Z8�3�
��������cL����.��� �0�Q$�ֻW�����{)j��$�,��I=�cI��\��Ά�W��)u�Ry�d�^���������R�ϗ���érB��qE���gphɴ��!�NT}�(�m����qi�L=�J�����5 ��Q��A��I��� ��:��f�^ �e������� w�bDo��<�-��R֍ÿ"�ڹF�M�]#�!�w�PK��ZB�� VWpiplite-0.6.0a5.dist-info/WHEEL �HM�� K-*��ϳR0�3�rO�K-J,�/�R�H,I����KJ����Kt=�uJ�Rs2��J�JS�Bӭ
*�u���Ru�*�PK��Z��l�*piplite-0.6.0a5.dist-info/licenses/LICENSE�R�n�8��+=5 m��[�DS�ͅ,�$�GE��h�t��}��������#�̛���J���O6v�`�r���%�����=E��������R�h��9.���G�u��l�{B�\�9?C7��� �����G7w�+�2�^\|���d�;��Kt���]&���g7`���?A�ѿ���~\j
��������cL����.��� �0�Q$�ֻW�����{)j��$�,��I=�cI��\��Ά�W��)u�Ry�d�^���������R�ϗ���érB��qE���gphɴ��!�NT}�(�m����qi�L=�J�����5 ��Q��A��I��� ��:��f�^ �e������� w�bDo��<�-��R֍ÿ"�ڹF�M�]#�!�w�PKBPB�� VWpiplite-0.6.0a5.dist-info/WHEEL �HM�� K-*��ϳR0�3�rO�K-J,�/�R�H,I����KJ����Kt=�uJ�Rs2��J�JS�Bӭ
*�u���Ru�*�PKBP��l�*piplite-0.6.0a5.dist-info/licenses/LICENSE�R�n�8��+=5 m��[�DS�ͅ,�$�GE��h�t��}��������#�̛���J���O6v�`�r���%�����=E��������R�h��9.���G�u��l�{B�\�9?C7��� �����G7w�+�2�^\|���d�;��Kt���]&���g7`���?A�ѿ���~\j
�i��3!�������Xv�)&���?�ԛ ���L�9��X �v�<�� ���Mv���t���6����������������1;�X����1����]7�w��br� ����.7���M6�I�;�'?X0���l������p�+<�t&(���|��"�����.��!��;�#&���_�¯��d�t@���Y-�t���p�`�B��k���ƍ���%�`��lJl���*��@�_k�Ī5>P��HJ���k��� �]S CtEk#�.@ԬjKQo
@���J��2#�4��� �v\�-~ҕ��9d"ka�4k��(4T�ڊ*hZ�H�e�RhVQ���=Nlj�xm@oiU�Te����G�tUq�'��R(�L��1t�U�3������S�/-a��tG7���/,���V�]�>�v��0�ᰑ�LF�Ճ`\� ��٭V�Jjh�h�1^�Zd�Dm�Rmc���P�mQ�Ql-����R�!� 4y��/`�������)�,��37e硁�F#�|S� �OldB� ��pWB�q��8�͒ӎ�����y� �@��h_�q�Z\�$[ƶp���|PK��Z�j��[ piplite-0.6.0a5.dist-info/RECORD}�=s�0���ς
�@:� Z��,9�(��O����������U9k�1��` ����)������k2��<jd�k}KJGS&ra]gN����zPq�^dT6� ��M��E{=�kc�58�K稧��M�g3]��c_( �wsb�[�,Q����$����k}��t��$ウ+��#u$F`�0� Yq,�_�3L�3�t�F���]��t�8̖��{6�����������`o��
�7r`#�x��fz/]'��,�����S��:w$2�p[{gZd�S���F�Y�<����������-����ZP�H�dK
�uq+^®7������#I�آ�jk
��PK��Zt��U}���piplite/__init__.pyPK��Z���F�=���piplite/cli.pyPK��Z��F�
���piplite/piplite.pyPK��Zt޹��"��piplite-0.6.0a5.dist-info/METADATAPK��ZB�� VW��piplite-0.6.0a5.dist-info/WHEELPK��Z��l�*�Gpiplite-0.6.0a5.dist-info/licenses/LICENSEPK��Z�j��[ ��piplite-0.6.0a5.dist-info/RECORDPK?
@���J��2#�4��� �v\�-~ҕ��9d"ka�4k��(4T�ڊ*hZ�H�e�RhVQ���=Nlj�xm@oiU�Te����G�tUq�'��R(�L��1t�U�3������S�/-a��tG7���/,���V�]�>�v��0�ᰑ�LF�Ճ`\� ��٭V�Jjh�h�1^�Zd�Dm�Rmc���P�mQ�Ql-����R�!� 4y��/`�������)�,��37e硁�F#�|S� �OldB� ��pWB�q��8�͒ӎ�����y� �@��h_�q�Z\�$[ƶp���|PKBPZֳ�\ piplite-0.6.0a5.dist-info/RECORD}ѻr�@��>ς�0,�"�*��P`�.^V�E y�Lfb&��龿8-k+���������(�s*C�} e�dqz,��Q#V:�'��)�\�K™��6ց A������S��:�G$��nJڬ�� ^ =�Z��tIG�����ع�2�c~�eY� �Ѓ~F��L<{����a�I�|� I�����'�P����R(��V���B�6C�IA��Gc;�-8$�l���xd�=q�!^n[��B��*/��Ah�do���ntrJY
�e��s��r%�L� /�>m�㇠k/Ԋ凚�t�gh�g vs���ε.��Y��Oj;���0�JL������d�H�h��mAx�PKBPt��U}���piplite/__init__.pyPKBP���F�=���piplite/cli.pyPKBP>IX,B �#���piplite/piplite.pyPKBPt޹��"�piplite-0.6.0a5.dist-info/METADATAPKBPB�� VW��piplite-0.6.0a5.dist-info/WHEELPKBP��l�*��piplite-0.6.0a5.dist-info/licenses/LICENSEPKBPZֳ�\ ��piplite-0.6.0a5.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AE,MAAM,EAAE,YAAY,EAAE,CAAC,GAAG,CAAC,EAAE,MAAM,GAAE,GAAQ,GAAG,OAAO,CAAC,GAAG,CAAC;IAO3G;;OAEG;IACU,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,GAAE,GAAQ,GAAG,OAAO,CAAC,GAAG,CAAC;IAOrE;;OAEG;IACU,QAAQ,CAAC,WAAW,EAAE,MAAM,GAAG,IAAI,EAAE,MAAM,GAAE,GAAQ,GAAG,OAAO,CAAC,GAAG,CAAC;IAUjF;;OAEG;IACU,QAAQ,CAAC,OAAO,EAAE,GAAG,EAAE,MAAM,GAAE,GAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAYpE;;OAEG;IACU,OAAO,CAAC,OAAO,EAAE,GAAG,EAAE,MAAM,GAAE,GAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAYnE;;OAEG;IACU,SAAS,CAAC,OAAO,EAAE,GAAG,EAAE,MAAM,GAAE,GAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAYrE;;;;;OAKG;IACW,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,GAAE,GAAQ,GAAG,cAAc,CAAC,GAAG,EAAE;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,MAAM,CAAC,EAAE,GAAG,CAAC;QAAC,KAAK,CAAC,EAAE,KAAK,CAAA;KAAE,EAAE,IAAI,CAAC;IA0D5H,SAAS,IAAI,OAAO,CAAC,OAAO,CAAC;IA8EnC,kBAAkB,CAAC,MAAM,EAAE,UAAU,GAAG,IAAI;IAiBnD;;;OAGG;YACW,uBAAuB;CAkCtC;AAKD,OAAO,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC"}

@@ -33,2 +33,3 @@ declare class EventEmitter {

}>;
interruptionMode?: 'shared-array-buffer' | 'kernel-interrupt' | 'auto';
}

@@ -89,2 +90,3 @@ export interface IKernelInstance {

private interruptBuffers;
private interruptionMode;
/**

@@ -91,0 +93,0 @@ * Helper function to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D;;;;OAIG;IACU,eAAe,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAqB1D;;;;;;OAMG;YACW,yBAAyB;IAMvC;;;;;;OAMG;YACW,qBAAqB;IA2GnC;;;;;;OAMG;YACW,6BAA6B;IAgC3C;;;;;;;OAOG;YACW,oBAAoB;IAiFlC;;;OAGG;IACI,kBAAkB,IAAI,KAAK,CAAC;QACjC,QAAQ,EAAE,MAAM,CAAC;QACjB,WAAW,EAAE,MAAM,CAAC;QACpB,SAAS,EAAE,MAAM,CAAC;QAClB,OAAO,EAAE,MAAM,CAAC;QAChB,UAAU,EAAE,MAAM,CAAC;QACnB,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,UAAU,EAAE,UAAU,CAAC;QACvB,cAAc,EAAE,cAAc,CAAC;KAChC,CAAC;IA8DF;;;OAGG;IACU,wBAAwB,IAAI,OAAO,CAAC,KAAK,CAAC;QACrD,QAAQ,EAAE,MAAM,CAAC;QACjB,WAAW,EAAE,MAAM,CAAC;QACpB,MAAM,EAAE,aAAa,GAAG,WAAW,GAAG,YAAY,GAAG,QAAQ,CAAC;QAC9D,OAAO,EAAE,OAAO,CAAC;QACjB,KAAK,CAAC,EAAE,MAAM,CAAC;KAChB,CAAC,CAAC;IAkEH;;;;;OAKG;YACW,0BAA0B;CAmEzC"}
/*! For license information please see web-python-kernel.min.js.LICENSE.txt */
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.WebPythonKernel=t():e.WebPythonKernel=t()}(self,()=>(()=>{"use strict";var e={590:(e,t,r)=>{r.d(t,{LV:()=>d,p:()=>u});const n=Symbol("Comlink.proxy"),o=Symbol("Comlink.endpoint"),s=Symbol("Comlink.releaseProxy"),i=Symbol("Comlink.finalizer"),a=Symbol("Comlink.thrown"),l=e=>"object"==typeof e&&null!==e||"function"==typeof e,c=new Map([["proxy",{canHandle:e=>l(e)&&e[n],serialize(e){const{port1:t,port2:r}=new MessageChannel;return u(e,t),[r,[r]]},deserialize:e=>(e.start(),d(e))}],["throw",{canHandle:e=>l(e)&&a in e,serialize({value:e}){let t;return t=e instanceof Error?{isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:{isError:!1,value:e},[t,[]]},deserialize(e){if(e.isError)throw Object.assign(new Error(e.value.message),e.value);throw e.value}}]]);function u(e,t=globalThis,r=["*"]){t.addEventListener("message",function o(s){if(!s||!s.data)return;if(!function(e,t){for(const r of e){if(t===r||"*"===r)return!0;if(r instanceof RegExp&&r.test(t))return!0}return!1}(r,s.origin))return void console.warn(`Invalid origin '${s.origin}' for comlink proxy`);const{id:l,type:c,path:d}=Object.assign({path:[]},s.data),m=(s.data.argumentList||[]).map(R);let h;try{const t=d.slice(0,-1).reduce((e,t)=>e[t],e),r=d.reduce((e,t)=>e[t],e);switch(c){case"GET":h=r;break;case"SET":t[d.slice(-1)[0]]=R(s.data.value),h=!0;break;case"APPLY":h=r.apply(t,m);break;case"CONSTRUCT":h=function(e){return Object.assign(e,{[n]:!0})}(new r(...m));break;case"ENDPOINT":{const{port1:t,port2:r}=new MessageChannel;u(e,r),h=function(e,t){return w.set(e,t),e}(t,[t])}break;case"RELEASE":h=void 0;break;default:return}}catch(e){h={value:e,[a]:0}}Promise.resolve(h).catch(e=>({value:e,[a]:0})).then(r=>{const[n,s]=k(r);t.postMessage(Object.assign(Object.assign({},n),{id:l}),s),"RELEASE"===c&&(t.removeEventListener("message",o),p(t),i in e&&"function"==typeof e[i]&&e[i]())}).catch(e=>{const[r,n]=k({value:new TypeError("Unserializable return value"),[a]:0});t.postMessage(Object.assign(Object.assign({},r),{id:l}),n)})}),t.start&&t.start()}function p(e){(function(e){return"MessagePort"===e.constructor.name})(e)&&e.close()}function d(e,t){const r=new Map;return e.addEventListener("message",function(e){const{data:t}=e;if(!t||!t.id)return;const n=r.get(t.id);if(n)try{n(t)}finally{r.delete(t.id)}}),g(e,r,[],t)}function m(e){if(e)throw new Error("Proxy has been released and is not useable")}function h(e){return x(e,new Map,{type:"RELEASE"}).then(()=>{p(e)})}const f=new WeakMap,y="FinalizationRegistry"in globalThis&&new FinalizationRegistry(e=>{const t=(f.get(e)||0)-1;f.set(e,t),0===t&&h(e)});function g(e,t,r=[],n=function(){}){let i=!1;const a=new Proxy(n,{get(n,o){if(m(i),o===s)return()=>{!function(e){y&&y.unregister(e)}(a),h(e),t.clear(),i=!0};if("then"===o){if(0===r.length)return{then:()=>a};const n=x(e,t,{type:"GET",path:r.map(e=>e.toString())}).then(R);return n.then.bind(n)}return g(e,t,[...r,o])},set(n,o,s){m(i);const[a,l]=k(s);return x(e,t,{type:"SET",path:[...r,o].map(e=>e.toString()),value:a},l).then(R)},apply(n,s,a){m(i);const l=r[r.length-1];if(l===o)return x(e,t,{type:"ENDPOINT"}).then(R);if("bind"===l)return g(e,t,r.slice(0,-1));const[c,u]=E(a);return x(e,t,{type:"APPLY",path:r.map(e=>e.toString()),argumentList:c},u).then(R)},construct(n,o){m(i);const[s,a]=E(o);return x(e,t,{type:"CONSTRUCT",path:r.map(e=>e.toString()),argumentList:s},a).then(R)}});return function(e,t){const r=(f.get(t)||0)+1;f.set(t,r),y&&y.register(e,t,e)}(a,e),a}function E(e){const t=e.map(k);return[t.map(e=>e[0]),(r=t.map(e=>e[1]),Array.prototype.concat.apply([],r))];var r}const w=new WeakMap;function k(e){for(const[t,r]of c)if(r.canHandle(e)){const[n,o]=r.serialize(e);return[{type:"HANDLER",name:t,value:n},o]}return[{type:"RAW",value:e},w.get(e)||[]]}function R(e){switch(e.type){case"HANDLER":return c.get(e.name).deserialize(e.value);case"RAW":return e.value}}function x(e,t,r,n){return new Promise(o=>{const s=new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-");t.set(s,o),e.start&&e.start(),e.postMessage(Object.assign({id:s},r),n)})}},637:(e,t,r)=>{r.r(t),r.d(t,{Kernel:()=>m,KernelEvents:()=>l.z,KernelLanguage:()=>a,KernelManager:()=>p,KernelMode:()=>i});const n="https://cdn.jsdelivr.net/pyodide/v0.28.0/full/pyodide.js";let o=!1,s=null;var i,a,l=r(696),c=r(590);class u{constructor(){this.events={}}on(e,t){this.events[e]||(this.events[e]=[]),this.events[e].push(t)}off(e,t){if(!this.events[e])return;const r=this.events[e].indexOf(t);r>-1&&this.events[e].splice(r,1)}removeListener(e,t){this.off(e,t)}emit(e,...t){this.events[e]&&this.events[e].forEach(e=>e(...t))}setMaxListeners(e){}}!function(e){e.MAIN_THREAD="main_thread",e.WORKER="worker"}(i||(i={})),function(e){e.PYTHON="python"}(a||(a={}));class p extends u{isKeyboardInterrupt(e){return e&&"object"==typeof e&&("type"in e&&"KeyboardInterrupt"===e.type||"message"in e&&"string"==typeof e.message&&e.message.includes("KeyboardInterrupt"))}createKeyboardInterruptResult(){return{success:!1,error:new Error("KeyboardInterrupt: Execution interrupted by user"),result:{status:"error",ename:"KeyboardInterrupt",evalue:"Execution interrupted by user",traceback:["KeyboardInterrupt: Execution interrupted by user"]}}}storeAbortController(e,t,r){this.abortControllers.has(e)||this.abortControllers.set(e,new Map),this.abortControllers.get(e).set(t,r)}removeAbortController(e,t){const r=this.abortControllers.get(e);if(!r)return;const n=r.get(t);return n&&(r.delete(t),0===r.size&&this.abortControllers.delete(e)),n}abortAllKernelOperations(e){const t=this.abortControllers.get(e);if(t){for(const[r,n]of t)try{n.abort(),console.log(`🚫 Aborted execution ${r} for kernel ${e}`)}catch(e){console.warn(`⚠️ Error aborting execution ${r}:`,e)}this.abortControllers.delete(e)}}constructor(e={}){super(),this.kernels=new Map,this.listenerWrappers=new Map,this.lastActivityTime=new Map,this.inactivityTimers=new Map,this.ongoingExecutions=new Map,this.executionTimeouts=new Map,this.executionStartTimes=new Map,this.executionMetadata=new Map,this.abortControllers=new Map,this.pool=new Map,this.isPreloading=!1,this.prefillingInProgress=new Map,this.interruptBuffers=new Map,super.setMaxListeners(100),this.allowedKernelTypes=e.allowedKernelTypes||[{mode:i.WORKER,language:a.PYTHON}];const t=this.allowedKernelTypes.filter(e=>e.language===a.PYTHON);this.poolConfig={enabled:!1,poolSize:2,autoRefill:!0,preloadConfigs:t,...e.pool},this.poolConfig.preloadConfigs&&(this.poolConfig.preloadConfigs=this.poolConfig.preloadConfigs.filter(e=>{const t=this.isKernelTypeAllowed(e.mode,e.language);return t||console.warn(`Pool preload config ${e.mode}-${e.language} is not in allowedKernelTypes, skipping`),t})),this.poolConfig.enabled&&this.preloadPool().catch(e=>{console.error("Error preloading kernel pool:",e)})}getPoolKey(e,t){return`${e}-${t}`}getFromPool(e,t){if(!this.poolConfig.enabled)return null;const r=this.getPoolKey(e,t),n=this.pool.get(r);if(!n||0===n.length)return null;const o=n.shift();return this.poolConfig.autoRefill&&setTimeout(()=>{this.refillPoolSingle(e,t).catch(e=>{console.error(`Error refilling single kernel for ${r}:`,e)})},0),o}addToPool(e,t,r){if(!this.poolConfig.enabled)return;const n=this.getPoolKey(e,t);this.pool.has(n)||this.pool.set(n,[]);const o=this.pool.get(n);o.length<this.poolConfig.poolSize?(o.push(r),r.catch(e=>{console.error(`Pool kernel promise rejected for ${n}:`,e);const t=o.indexOf(r);-1!==t&&o.splice(t,1)})):r.then(e=>{e.destroy().catch(e=>{console.error("Error destroying excess pool kernel:",e)})}).catch(e=>{console.error("Excess pool kernel promise rejected:",e)})}async refillPoolSingle(e,t){if(!this.poolConfig.enabled)return;const r=this.getPoolKey(e,t);if((this.pool.get(r)||[]).length<this.poolConfig.poolSize){const r=this.createPoolKernelPromise(e,t);this.addToPool(e,t,r)}}async refillPool(e,t){if(!this.poolConfig.enabled)return;const r=this.getPoolKey(e,t);if(!this.prefillingInProgress.get(r)){this.prefillingInProgress.set(r,!0);try{const n=this.pool.get(r)||[],o=this.poolConfig.poolSize-n.length;if(o<=0)return;const s=Array.from({length:o},()=>this.createPoolKernelPromise(e,t));for(const r of s)this.addToPool(e,t,r)}catch(e){console.error(`Error refilling pool for ${r}:`,e)}finally{this.prefillingInProgress.set(r,!1)}}}createPoolKernelPromise(e,t){return new Promise(async(r,n)=>{try{const n=await this.createPoolKernel(e,t);n.isFromPool=!0,r(n)}catch(r){console.error(`Error creating pool kernel for ${e}-${t}:`,r),n(r)}})}async createPoolKernel(e,t){const r=`pool-${crypto.randomUUID()}`,n={mode:e,lang:t};let o;try{if(e===i.MAIN_THREAD){const s={id:r,options:n,mode:e,language:t};this.kernels.set(r,s);try{o=await this.createMainThreadKernel(r)}finally{this.kernels.delete(r)}}else{const s={id:r,options:n,mode:e,language:t};this.kernels.set(r,s);try{o=await this.createWorkerKernel(r)}finally{this.kernels.delete(r)}}}catch(e){throw this.kernels.delete(r),e}return o}async preloadPool(){if(this.poolConfig.enabled&&!this.isPreloading){this.isPreloading=!0;try{for(const e of this.poolConfig.preloadConfigs)try{await this.refillPool(e.mode,e.language)}catch(t){console.error(`Error preloading ${e.mode}-${e.language}:`,t)}}catch(e){console.error("Error during kernel pool preloading:",e)}finally{this.isPreloading=!1}}}canUsePool(e){return!!this.poolConfig.enabled&&!e.filesystem&&!e.deno?.permissions&&void 0===e.inactivityTimeout&&void 0===e.maxExecutionTime}reassignPoolKernel(e,t,r){const n={id:t,kernel:e.kernel,mode:e.mode,language:e.language,worker:e.worker,created:new Date,options:{...e.options,...r},isFromPool:!0,destroy:e.destroy};if("function"!=typeof n.destroy)throw console.error("Failed to preserve destroy function during pool kernel reassignment"),console.error("poolKernel.destroy type:",typeof e.destroy),console.error("updatedInstance.destroy type:",typeof n.destroy),new Error("Failed to preserve destroy function during pool kernel reassignment");return n}getPoolStats(){const e={};for(const[t,r]of this.pool.entries())e[t]={available:r.length,total:this.poolConfig.poolSize};return e}getPoolConfig(){return{enabled:this.poolConfig.enabled,poolSize:this.poolConfig.poolSize,autoRefill:this.poolConfig.autoRefill,preloadConfigs:[...this.poolConfig.preloadConfigs],isPreloading:this.isPreloading}}async createKernel(e={}){if(e.id&&e.id.includes(":"))throw new Error("Kernel ID cannot contain colons");const t=e.id||crypto.randomUUID(),r=e.mode||i.WORKER,n=e.lang||a.PYTHON;if(!this.isKernelTypeAllowed(r,n))throw new Error(`Kernel type ${r}-${n} is not allowed. Allowed types: ${this.allowedKernelTypes.map(e=>`${e.mode}-${e.language}`).join(", ")}`);const o=e.namespace?`${e.namespace}:${t}`:t;if(this.kernels.has(o))throw new Error(`Kernel with ID ${o} already exists`);if(this.canUsePool(e)){const t=this.getPoolKey(r,n);if(this.poolConfig.preloadConfigs.some(e=>e.mode===r&&e.language===n)){let s=this.getFromPool(r,n);if(s)return await this.setupPoolKernelFromPromise(s,o,e);try{const s=this.createPoolKernelPromise(r,n);return this.poolConfig.autoRefill&&setTimeout(()=>{this.refillPool(r,n).catch(e=>{console.error(`Error refilling exhausted pool for ${t}:`,e)})},0),await this.setupPoolKernelFromPromise(s,o,e)}catch(e){console.error(`Failed to create kernel promise for exhausted pool: ${e}`)}}else{const t=this.getFromPool(r,n);if(t)return await this.setupPoolKernelFromPromise(t,o,e)}}return this.createOnDemandKernel(o,r,n,e)}async setupPoolKernelFromPromise(e,t,r){try{const n=await e,o=this.reassignPoolKernel(n,t,r);if(o.mode===i.WORKER&&o.worker){const e=o.worker,{port1:r,port2:n}=new MessageChannel;e.postMessage({type:"SET_EVENT_PORT",port:n},[n]);const s=e=>{e.data&&e.data.type&&super.emit(e.data.type,{kernelId:t,data:e.data.data})};r.addEventListener("message",s),r.start();const i=o.destroy;o.destroy=async()=>(r.removeEventListener("message",s),r.close(),i())}return this.kernels.set(t,o),this.setupEventForwarding(o),this.updateKernelActivity(t),r.inactivityTimeout&&r.inactivityTimeout>0&&this.setupInactivityTimeout(t,r.inactivityTimeout),r.maxExecutionTime&&r.maxExecutionTime>0&&this.setupStalledExecutionHandler(t),t}catch(e){throw console.error(`Error setting up pool kernel ${t}:`,e),super.emit(l.z.EXECUTE_ERROR,{kernelId:t,data:{ename:"KernelSetupError",evalue:`Failed to setup kernel: ${e instanceof Error?e.message:String(e)}`,traceback:[e instanceof Error?e.stack||e.message:String(e)]}}),e}}setupPoolKernel(e,t,r){const n=this.reassignPoolKernel(e,t,r);if(n.mode===i.WORKER&&n.worker){const e=n.worker,{port1:r,port2:o}=new MessageChannel;e.postMessage({type:"SET_EVENT_PORT",port:o},[o]);const s=e=>{e.data&&e.data.type&&super.emit(e.data.type,{kernelId:t,data:e.data.data})};r.addEventListener("message",s),r.start();const i=n.destroy;n.destroy=async()=>(r.removeEventListener("message",s),r.close(),i())}return this.kernels.set(t,n),this.setupEventForwarding(n),this.updateKernelActivity(t),r.inactivityTimeout&&r.inactivityTimeout>0&&this.setupInactivityTimeout(t,r.inactivityTimeout),r.maxExecutionTime&&r.maxExecutionTime>0&&this.setupStalledExecutionHandler(t),t}async createOnDemandKernel(e,t,r,n){const o={id:e,options:{...n,lang:r},mode:t,language:r};let s;return this.kernels.set(e,o),s=t===i.MAIN_THREAD?await this.createMainThreadKernel(e):await this.createWorkerKernel(e),this.kernels.set(e,s),this.setupEventForwarding(s),this.updateKernelActivity(e),n.inactivityTimeout&&n.inactivityTimeout>0&&this.setupInactivityTimeout(e,n.inactivityTimeout),n.maxExecutionTime&&n.maxExecutionTime>0&&this.setupStalledExecutionHandler(e),e}async createMainThreadKernel(e){const t=this.kernels.get(e)?.options||{},r=t.lang||a.PYTHON,n=new m,o={id:e,kernel:n,mode:i.MAIN_THREAD,language:r,created:new Date,options:t,destroy:async()=>Promise.resolve()},s={};return t.filesystem&&(s.filesystem=t.filesystem),t.env&&(s.env=t.env),t.lockFileURL&&(s.lockFileURL=t.lockFileURL),await n.initialize(s),o}async createWorkerKernel(e){const t=this.kernels.get(e)?.options||{},n=t.lang||a.PYTHON;t.deno?.permissions&&t.deno.permissions;const o=r(757),s=o.default?new o.default:new o,{port1:l,port2:u}=new MessageChannel,p=new Promise((e,t)=>{const r=n=>{"KERNEL_INITIALIZED"===n.data?.type&&(n.data.data.success?(l.removeEventListener("message",r),e()):(l.removeEventListener("message",r),t(new Error("Kernel initialization failed"))))};l.addEventListener("message",r)});s.postMessage({type:"SET_EVENT_PORT",port:u},[u]);const d=c.LV(s),m=t=>{t.data&&t.data.type&&super.emit(t.data.type,{kernelId:e,data:t.data.data})};return l.addEventListener("message",m),l.start(),s.postMessage({type:"INITIALIZE_KERNEL",options:{filesystem:t.filesystem,env:t.env,lockFileURL:t.lockFileURL,lang:n}}),await p,await this.setupWorkerInterruptBuffer(e,s),{id:e,kernel:{initialize:async e=>d.initialize(e),execute:async(e,t)=>await d.execute(e,t),isInitialized:()=>d.isInitialized(),inputReply:async e=>d.inputReply(e),getStatus:async()=>{try{return"function"==typeof d.getStatus?await d.getStatus():"unknown"}catch(e){return"unknown"}},complete:async(e,t,r)=>{try{return"function"==typeof d.complete?await d.complete(e,t,r):{status:"error",error:"Completion not supported"}}catch(e){return{status:"error",error:String(e)}}},inspect:async(e,t,r,n)=>{try{return"function"==typeof d.inspect?await d.inspect(e,t,r,n):{status:"error",error:"Inspection not supported"}}catch(e){return{status:"error",error:String(e)}}},isComplete:async(e,t)=>{try{return"function"==typeof d.isComplete?await d.isComplete(e,t):{status:"unknown"}}catch(e){return{status:"error",error:String(e)}}},interrupt:async()=>{try{return"function"==typeof d.interrupt&&await d.interrupt()}catch(e){return!1}},setInterruptBuffer:e=>{try{"function"==typeof d.setInterruptBuffer&&d.setInterruptBuffer(e)}catch(e){console.warn("Failed to set interrupt buffer:",e)}},commInfo:async(e,t)=>{try{return"function"==typeof d.commInfo?await d.commInfo(e,t):{comms:{},status:"ok"}}catch(e){return{comms:{},status:"error",error:String(e)}}},commOpen:async(e,t)=>{try{if("function"==typeof d.commOpen)return await d.commOpen(e,t)}catch(e){console.warn("Failed to open comm:",e)}},commMsg:async(e,t)=>{try{if("function"==typeof d.commMsg)return await d.commMsg(e,t)}catch(e){console.warn("Failed to send comm message:",e)}},commClose:async(e,t)=>{try{if("function"==typeof d.commClose)return await d.commClose(e,t)}catch(e){console.warn("Failed to close comm:",e)}}},mode:i.WORKER,language:n,worker:s,created:new Date,options:t,destroy:async()=>(l.removeEventListener("message",m),l.close(),s.terminate(),Promise.resolve())}}setupEventForwarding(e){e.mode===i.MAIN_THREAD&&Object.values(l.z).forEach(t=>{e.kernel.on(t,r=>{super.emit(t,{kernelId:e.id,data:r})})})}getKernel(e){return this.kernels.get(e)}getKernelIds(){return Array.from(this.kernels.keys())}async listKernels(e){const t=Array.from(this.kernels.entries()).filter(([t])=>!t.startsWith("pool-")&&(!e||t.startsWith(`${e}:`)));return await Promise.all(t.map(async([e,t])=>{const r=e.match(/^([^:]+):/),n=r?r[1]:void 0;let o="unknown";try{t&&t.kernel&&"function"==typeof t.kernel.getStatus&&(o=await t.kernel.getStatus())}catch(t){console.warn(`Error getting status for kernel ${e}:`,t),o="unknown"}return{id:e,mode:t.mode,language:t.language,status:o,created:t.created||new Date,namespace:n,deno:t.options?.deno}}))}async destroyKernel(e){const t=this.kernels.get(e);if(t){if("function"!=typeof t.destroy)throw new Error(`Kernel ${e} is missing destroy function (type: ${typeof t.destroy})`);if(this.abortAllKernelOperations(e),this.clearInactivityTimeout(e),this.executionTimeouts.has(e)){const t=this.executionTimeouts.get(e);for(const e of t.values())clearTimeout(e);this.executionTimeouts.delete(e)}this.executionStartTimes.has(e)&&this.executionStartTimes.delete(e),this.executionMetadata.has(e)&&this.executionMetadata.delete(e),this.interruptBuffers.has(e)&&this.interruptBuffers.delete(e),this.ongoingExecutions.delete(e),this.lastActivityTime.delete(e),this.removeAllKernelListeners(e),await t.destroy(),this.kernels.delete(e)}}async destroyAll(e){const t=Array.from(this.kernels.keys()).filter(t=>!e||t.startsWith(`${e}:`)).map(async e=>{const t=this.kernels.get(e);return t&&"function"==typeof t.destroy?this.destroyKernel(e):(console.warn(`Skipping incomplete kernel instance ${e} during destroyAll`),void this.kernels.delete(e))});await Promise.all(t),e||await this.destroyPool()}async destroyPool(){const e=[];for(const[t,r]of this.pool.entries())for(const t of r){const r=t.then(e=>e.destroy()).catch(e=>{console.error("Error destroying pool kernel from promise:",e)});e.push(r)}await Promise.all(e),this.pool.clear(),this.prefillingInProgress.clear()}onKernelEvent(e,t,r){if(!this.kernels.has(e))throw new Error(`Kernel with ID ${e} not found`);const n={original:r,wrapped:t=>{t.kernelId===e&&r(t.data)}};this.storeListener(e,t,r,n),super.on(t,n.wrapped)}offKernelEvent(e,t,r){const n=this.getListener(e,t,r);n&&(super.removeListener(t,n.wrapped),this.removeStoredListener(e,t,r))}storeListener(e,t,r,n){this.listenerWrappers.has(e)||this.listenerWrappers.set(e,new Map);const o=this.listenerWrappers.get(e);o.has(t)||o.set(t,new Map),o.get(t).set(r,n)}getListener(e,t,r){const n=this.listenerWrappers.get(e);if(!n)return;const o=n.get(t);return o?o.get(r):void 0}removeStoredListener(e,t,r){const n=this.listenerWrappers.get(e);if(!n)return;const o=n.get(t);o&&(o.delete(r),0===o.size&&n.delete(t),0===n.size&&this.listenerWrappers.delete(e))}removeAllKernelListeners(e){const t=this.listenerWrappers.get(e);if(t){for(const[e,r]of t.entries())for(const t of r.values())super.removeListener(e,t.wrapped);this.listenerWrappers.delete(e)}}getListeners(e,t){const r=this.listenerWrappers.get(e);if(!r)return[];const n=r.get(t);return n?Array.from(n.keys()):[]}async*executeStream(e,t,r={}){const n=this.getKernel(e);if(!n)throw new Error(`Kernel with ID ${e} not found`);this.updateKernelActivity(e);const o=this.trackExecution(e,t),s=new AbortController;this.storeAbortController(e,o,s);try{if(n.mode===i.MAIN_THREAD){const s=n.kernel;if("function"==typeof s.executeStream)try{return yield*s.executeStream(t,r),this.updateKernelActivity(e),this.completeExecution(e,o),{success:!0}}catch(t){return console.error("Error in main thread executeStream:",t),this.updateKernelActivity(e),this.completeExecution(e,o),{success:!1,error:t instanceof Error?t:new Error(String(t))}}}try{const i=[];let a=!1,c={success:!0};const u=new Map,p=()=>{for(const[e,t]of u.entries())super.off(e,t);u.clear()},d=t=>{const r=r=>{r.kernelId!==e||a||(i.push({type:t,data:r.data,executionId:o}),this.updateKernelActivity(e))};return u.set(t,r),r},m=d("stream"),h=d("display_data"),f=d("update_display_data"),y=d("execute_result"),g=d("execute_error");super.on(l.z.STREAM,m),super.on(l.z.DISPLAY_DATA,h),super.on(l.z.UPDATE_DISPLAY_DATA,f),super.on(l.z.EXECUTE_RESULT,y),super.on(l.z.EXECUTE_ERROR,g);const E=new Promise((p,d)=>{const m=t=>{t.kernelId!==e||a||(a=!0,c={success:!1,error:new Error(`${t.data.ename}: ${t.data.evalue}`),result:t.data},this.updateKernelActivity(e),p(c))};if(u.set("execute_error_completion",m),super.on(l.z.EXECUTE_ERROR,m),s.signal.aborted)return a=!0,void p({success:!1,error:new Error("Execution was aborted")});s.signal.addEventListener("abort",()=>{a||(console.log(`🚫 Execution ${o} aborted`),a=!0,p({success:!1,error:new Error("Execution was aborted")}))});try{n.kernel.execute(t,r).then(t=>{if(!a){if(t.success&&t.result&&"error"===t.result.status){const e={status:t.result.status,ename:t.result.ename,evalue:t.result.evalue,traceback:t.result.traceback};i.push({type:"error",data:e,executionId:o}),c={success:!1,error:new Error(`${t.result.ename}: ${t.result.evalue}`),result:t.result}}else c=t;a=!0,this.updateKernelActivity(e),p(c)}}).catch(t=>{if(!a){let r;console.error(`Error in execute for kernel ${e}:`,t),this.isKeyboardInterrupt(t)?(console.log(`KeyboardInterrupt caught in executeStream for kernel ${e}`),r=this.createKeyboardInterruptResult(),i.push({type:"error",data:r.result,executionId:o})):r={success:!1,error:t instanceof Error?t:new Error(String(t))},a=!0,c=r,this.updateKernelActivity(e),p(r)}})}catch(t){if(!a){console.error(`Error calling execute for kernel ${e}:`,t);const r={success:!1,error:t instanceof Error?t:new Error(String(t))};a=!0,c=r,this.updateKernelActivity(e),p(r)}}});try{for(;(!a||i.length>0)&&!s.signal.aborted;){if(i.length>0){const e=i.shift();yield e;continue}if(!a)try{await new Promise((e,t)=>{const r=setTimeout(e,10);s.signal.addEventListener("abort",()=>{clearTimeout(r),t(new Error("Aborted"))})})}catch(e){if(s.signal.aborted)break}}if(s.signal.aborted&&!a)throw new Error("Execution was aborted during stream monitoring");return await E}finally{p(),this.removeAbortController(e,o),this.completeExecution(e,o)}}catch(t){return this.completeExecution(e,o),console.error("Unexpected error in executeStream:",t),{success:!1,error:t instanceof Error?t:new Error(String(t))}}}catch(t){return this.completeExecution(e,o),console.error("Unexpected error in executeStream:",t),{success:!1,error:t instanceof Error?t:new Error(String(t))}}}trackExecution(e,t){const r=`exec-${crypto.randomUUID()}`,n=Date.now(),o=this.kernels.get(e);if(o&&o.mode===i.WORKER&&this.interruptBuffers.has(e)&&(this.interruptBuffers.get(e)[0]=0),this.ongoingExecutions.has(e)||this.ongoingExecutions.set(e,new Set),this.ongoingExecutions.get(e).add(r),this.executionStartTimes.has(e)||this.executionStartTimes.set(e,new Map),this.executionStartTimes.get(e).set(r,n),this.executionMetadata.has(e)||this.executionMetadata.set(e,new Map),this.updateKernelActivity(e),o&&o.options.maxExecutionTime&&o.options.maxExecutionTime>0){this.executionTimeouts.has(e)||this.executionTimeouts.set(e,new Map);const s=setTimeout(()=>{console.warn(`Execution ${r} on kernel ${e} has been running for ${o.options.maxExecutionTime}ms and may be stuck/dead.`);const s=this.executionMetadata.get(e)?.get(r),i=Date.now()-(s?.startTime||n);super.emit("execution_stalled",{kernelId:e,executionId:r,maxExecutionTime:o.options.maxExecutionTime,actualRuntime:i,code:s?.code||t,startTime:s?.startTime||n}),this.handleStuckExecution(e,r,i,s?.code||t)},o.options.maxExecutionTime);this.executionTimeouts.get(e).set(r,s),this.executionMetadata.get(e).set(r,{startTime:n,code:t,timeoutId:s})}else this.executionMetadata.get(e).set(r,{startTime:n,code:t});return r}completeExecution(e,t){if(this.executionTimeouts.has(e)){const r=this.executionTimeouts.get(e);r.has(t)&&(clearTimeout(r.get(t)),r.delete(t)),0===r.size&&this.executionTimeouts.delete(e)}if(this.executionStartTimes.has(e)){const r=this.executionStartTimes.get(e);r.delete(t),0===r.size&&this.executionStartTimes.delete(e)}if(this.executionMetadata.has(e)){const r=this.executionMetadata.get(e);r.delete(t),0===r.size&&this.executionMetadata.delete(e)}if(this.ongoingExecutions.has(e)){const r=this.ongoingExecutions.get(e);r.delete(t),0===r.size&&(this.ongoingExecutions.delete(e),this.updateKernelActivity(e))}}hasOngoingExecutions(e){return this.ongoingExecutions.has(e)&&this.ongoingExecutions.get(e).size>0}getOngoingExecutionCount(e){return this.ongoingExecutions.has(e)?this.ongoingExecutions.get(e).size:0}setupInactivityTimeout(e,t){if(t<=0)return;this.clearInactivityTimeout(e);const r=this.lastActivityTime.get(e)||Date.now(),n=Date.now()-r,o=Math.max(0,t-n);if(0===o)return this.hasOngoingExecutions(e)?void this.setupInactivityTimeout(e,t):void this.destroyKernel(e).catch(t=>{console.error(`Error destroying inactive kernel ${e}:`,t)});const s=setTimeout(()=>{this.hasOngoingExecutions(e)?this.setupInactivityTimeout(e,t):this.destroyKernel(e).catch(t=>{console.error(`Error destroying inactive kernel ${e}:`,t)})},o);this.inactivityTimers.set(e,s)}clearInactivityTimeout(e){if(this.inactivityTimers.has(e)){const t=this.inactivityTimers.get(e);clearTimeout(t),this.inactivityTimers.delete(e)}}updateKernelActivity(e){this.lastActivityTime.set(e,Date.now());const t=this.kernels.get(e);if(!t)return;const r=t.options.inactivityTimeout;r&&r>0&&this.setupInactivityTimeout(e,r)}getLastActivityTime(e){return this.lastActivityTime.get(e)}getInactivityTimeout(e){const t=this.kernels.get(e);if(t)return t.options.inactivityTimeout}setInactivityTimeout(e,t){const r=this.kernels.get(e);return!!r&&(r.options.inactivityTimeout=t,this.clearInactivityTimeout(e),t>0&&this.setupInactivityTimeout(e,t),!0)}getTimeUntilShutdown(e){const t=this.kernels.get(e);if(!t)return;const r=t.options.inactivityTimeout;if(!r||r<=0)return;const n=this.lastActivityTime.get(e);if(!n)return;const o=r-(Date.now()-n);return Math.max(0,o)}getInactivityTimers(){const e={};return this.inactivityTimers.forEach((t,r)=>{e[r]=t}),e}setupStalledExecutionHandler(e){super.on(l.z.EXECUTION_STALLED,t=>{t.kernelId===e&&(console.warn(`Handling stalled execution ${t.executionId} on kernel ${e} (running longer than ${t.maxExecutionTime}ms)`),this.kernels.get(e)&&super.emit(l.z.EXECUTE_ERROR,{kernelId:e,data:{ename:"ExecutionStalledError",evalue:`Execution stalled or potentially deadlocked (running > ${t.maxExecutionTime}ms)`,traceback:["Execution may be stuck in an infinite loop or deadlocked."]}}))})}async forceTerminateKernel(e,t="Force terminated due to stalled execution"){if(!this.kernels.get(e))return!1;try{return console.warn(`Force terminating kernel ${e}: ${t}`),super.emit(l.z.EXECUTE_ERROR,{kernelId:e,data:{ename:"KernelForcedTermination",evalue:t,traceback:["Kernel was forcefully terminated by the system."]}}),await this.destroyKernel(e),!0}catch(t){return console.error(`Error during forced termination of kernel ${e}:`,t),!1}}getExecutionInfo(e){const t=this.kernels.get(e);if(!t)return{count:0,isStuck:!1,executionIds:[],executions:[]};if(!t.options)return{count:0,isStuck:!1,executionIds:[],executions:[]};const r=this.ongoingExecutions.get(e)?Array.from(this.ongoingExecutions.get(e)):[],n=r.length,o=Date.now(),s=t.options.maxExecutionTime,i=[];let a,l=!1;const c=this.executionStartTimes.get(e),u=this.executionMetadata.get(e);for(const t of r){const r=c?.get(t),n=u?.get(t);if(void 0!==r){const e=o-r,c=void 0!==s&&e>s;i.push({id:t,startTime:r,runtime:e,code:n?.code,isStuck:c}),(void 0===a||e>a)&&(a=e),c&&(l=!0)}else console.warn(`No start time found for execution ${t} on kernel ${e}`),i.push({id:t,startTime:0,runtime:0,code:n?.code,isStuck:!1})}return i.sort((e,t)=>e.startTime-t.startTime),{count:n,isStuck:l,executionIds:r,longestRunningTime:a,executions:i}}async execute(e,t,r={}){const n=this.getKernel(e);if(!n)throw new Error(`Kernel with ID ${e} not found`);this.updateKernelActivity(e);const o=this.trackExecution(e,t);try{const s=await n.kernel.execute(t,r);return this.updateKernelActivity(e),this.completeExecution(e,o),s}catch(t){return this.updateKernelActivity(e),this.completeExecution(e,o),{success:!1,error:t instanceof Error?t:new Error(String(t))}}}isKernelTypeAllowed(e,t){return this.allowedKernelTypes.some(r=>r.mode===e&&r.language===t)}getAllowedKernelTypes(){return[...this.allowedKernelTypes]}pingKernel(e){return!!this.kernels.get(e)&&(this.updateKernelActivity(e),!0)}async restartKernel(e){const t=this.kernels.get(e);if(!t)return console.warn(`Cannot restart kernel ${e}: kernel not found`),!1;try{const r={mode:t.mode,language:t.language,options:{...t.options}};let n,o;if(e.includes(":")){const t=e.split(":");n=t[0],o=t[1]}else o=e;await this.destroyKernel(e);const s={id:o,mode:r.mode,lang:r.language,namespace:n,deno:r.options.deno,filesystem:r.options.filesystem,inactivityTimeout:r.options.inactivityTimeout,maxExecutionTime:r.options.maxExecutionTime},i=await this.createKernel(s);return i===e||(console.error(`Kernel restart failed: expected ID ${e}, got ${i}`),!1)}catch(t){return console.error(`Error restarting kernel ${e}:`,t),!1}}async interruptKernel(e){const t=this.kernels.get(e);if(!t)return console.warn(`Cannot interrupt kernel ${e}: kernel not found`),!1;try{return t.mode===i.WORKER&&t.worker?await this.interruptWorkerKernel(e,t):await this.interruptMainThreadKernel(e,t)}catch(t){return console.error(`Error interrupting kernel ${e}:`,t instanceof Error?t.message:String(t)),!1}}async interruptMainThreadKernel(e,t){throw new Error(`Main thread kernel ${e} does not support reliable interruption. Use worker kernels for interruptible execution.`)}async interruptWorkerKernel(e,t){try{const r=t.worker;if(!r)return console.error(`Worker not found for kernel ${e}`),!1;let n=this.interruptBuffers.get(e);if(!n)try{const t=new SharedArrayBuffer(1);n=new Uint8Array(t),n[0]=0,this.interruptBuffers.set(e,n),r.postMessage({type:"SET_INTERRUPT_BUFFER",buffer:n}),await new Promise((e,t)=>{const n=setTimeout(()=>{t(new Error("Timeout waiting for interrupt buffer setup"))},2e3),o=t=>{"INTERRUPT_BUFFER_SET"===t.data?.type&&(r.removeEventListener("message",o),clearTimeout(n),e())};r.addEventListener("message",o)}),console.log(`Interrupt buffer set up for kernel ${e}`)}catch(t){return console.warn(`Failed to create SharedArrayBuffer for kernel ${e}, falling back to message-based interrupt:`,t),await this.interruptWorkerKernelFallback(e,r)}console.log(`Setting interrupt signal for kernel ${e}...`),n[0]=2;let o=0;const s=50;for(;o<s&&0!==n[0];)await new Promise(e=>setTimeout(e,100)),o++;return 0===n[0]?(console.log(`Interrupt processed successfully for kernel ${e} after ${100*o}ms`),!0):(console.warn(`Interrupt signal not processed for kernel ${e} after ${100*s}ms`),!0)}catch(t){return console.error(`Error interrupting worker kernel ${e}:`,t),!1}}async interruptWorkerKernelFallback(e,t){return new Promise(r=>{const n=e=>{if("INTERRUPT_TRIGGERED"===e.data?.type){t.removeEventListener("message",n);const o=e.data.data?.success||!1;r(o)}};t.addEventListener("message",n),t.postMessage({type:"INTERRUPT_KERNEL"}),setTimeout(()=>{t.removeEventListener("message",n),console.warn(`Timeout waiting for interrupt response from kernel ${e}`),r(!1)},5e3)})}async handleStuckExecution(e,t,r,n){const o=this.kernels.get(e);if(o){if(console.warn(`Handling stuck execution ${t} on kernel ${e} (runtime: ${r}ms)`),await this.interruptKernel(e))return console.log(`Successfully interrupted kernel ${e}`),void super.emit(l.z.EXECUTE_ERROR,{kernelId:e,data:{ename:"ExecutionInterrupted",evalue:`Execution automatically interrupted after ${r}ms (exceeded maxExecutionTime)`,traceback:["Execution was automatically interrupted due to timeout.",`Runtime: ${r}ms`,`Max allowed: ${o.options.maxExecutionTime}ms`,n?`Code: ${n.substring(0,200)}${n.length>200?"...":""}`:"Code: <unknown>"]}});if(console.warn(`Interrupt failed for kernel ${e}, attempting restart...`),await this.restartKernel(e))return console.log(`Successfully restarted kernel ${e}`),void super.emit(l.z.EXECUTE_ERROR,{kernelId:e,data:{ename:"KernelRestarted",evalue:`Kernel automatically restarted due to stuck execution (runtime: ${r}ms)`,traceback:["Kernel was automatically restarted due to stuck execution.",`Runtime: ${r}ms`,`Max allowed: ${o.options.maxExecutionTime}ms`,"Interrupt attempt failed, kernel was restarted instead.",n?`Code: ${n.substring(0,200)}${n.length>200?"...":""}`:"Code: <unknown>"]}});console.error(`Restart failed for kernel ${e}, force terminating...`),await this.forceTerminateKernel(e,`Stuck execution could not be interrupted or restarted (runtime: ${r}ms)`)?console.log(`Successfully terminated kernel ${e}`):(console.error(`Failed to terminate kernel ${e} - manual intervention may be required`),super.emit("kernel_unrecoverable",{kernelId:e,executionId:t,actualRuntime:r,code:n,message:"Kernel is stuck and could not be recovered through interrupt, restart, or termination"}))}}getStuckExecutions(){const e=[],t=Date.now();for(const[r,n]of this.kernels.entries()){if(r.startsWith("pool-"))continue;if(!n.options?.maxExecutionTime||n.options.maxExecutionTime<=0)continue;const o=n.options.maxExecutionTime,s=this.executionStartTimes.get(r),i=this.executionMetadata.get(r),a=this.ongoingExecutions.get(r);if(a&&0!==a.size)for(const l of a){const a=s?.get(l);if(void 0===a)continue;const c=t-a;if(c>o){const t=i?.get(l);e.push({kernelId:r,executionId:l,startTime:a,runtime:c,maxAllowed:o,code:t?.code,kernelMode:n.mode,kernelLanguage:n.language})}}}return e.sort((e,t)=>t.runtime-e.runtime),e}async handleAllStuckExecutions(){const e=this.getStuckExecutions(),t=[];console.log(`Found ${e.length} stuck executions to handle`);const r=new Map;for(const t of e)r.has(t.kernelId)||r.set(t.kernelId,[]),r.get(t.kernelId).push(t);for(const[e,n]of r)try{const r=n[0];console.log(`Handling stuck kernel ${e} with ${n.length} stuck executions (primary: ${r.runtime}ms)`),await this.handleStuckExecution(e,r.executionId,r.runtime,r.code);for(const e of n)t.push({kernelId:e.kernelId,executionId:e.executionId,action:"interrupted",success:!0})}catch(r){console.error(`Error handling stuck executions for kernel ${e}:`,r);for(const e of n)t.push({kernelId:e.kernelId,executionId:e.executionId,action:"failed",success:!1,error:r instanceof Error?r.message:String(r)})}return t}async setupWorkerInterruptBuffer(e,t){try{const r=new SharedArrayBuffer(1),n=new Uint8Array(r);n[0]=0,this.interruptBuffers.set(e,n),t.postMessage({type:"SET_INTERRUPT_BUFFER",buffer:n}),await new Promise((e,r)=>{const n=setTimeout(()=>{r(new Error("Timeout waiting for interrupt buffer setup"))},5e3),o=r=>{"INTERRUPT_BUFFER_SET"===r.data?.type&&(t.removeEventListener("message",o),clearTimeout(n),e())};t.addEventListener("message",o)})}catch(t){console.warn(`Failed to set up interrupt buffer for kernel ${e}:`,t)}}}class d{constructor(){this.events={}}on(e,t){this.events[e]||(this.events[e]=[]),this.events[e].push(t)}off(e,t){if(!this.events[e])return;const r=this.events[e].indexOf(t);r>-1&&this.events[e].splice(r,1)}emit(e,...t){this.events[e]&&this.events[e].forEach(e=>e(...t))}setMaxListeners(e){}}class m extends d{constructor(){super(),this.initialized=!1,this.initPromise=null,this.filesystemOptions={enabled:!1,root:".",mountPoint:"/home/pyodide"},this._resolveInputReply=null,this._parent_header={},this.executionCount=0,this._status="unknown",this._interruptBuffer=null,this._interruptSupported=!1,this.environmentVariables={},super.setMaxListeners(20),this.kernelId=`kernel_${Math.random().toString(36).substring(2)}_${Date.now()}`}async getStatus(){return this._status}async initialize(e){if(!this.initialized)return this.initPromise||(e?.filesystem&&(this.filesystemOptions={...this.filesystemOptions,...e.filesystem}),e?.env&&(this.environmentVariables={...e.env}),e?.lockFileURL&&(this.lockFileURL=e.lockFileURL),this.initPromise=this._initializeInternal()),this.initPromise}async _initializeInternal(){const e=Date.now();console.log("🚀 Starting optimized kernel initialization...");try{const t=Date.now(),r={};this.lockFileURL&&(r.lockFileURL=this.lockFileURL,console.log(`🔒 Using lockFileURL: ${this.lockFileURL}`)),this.pyodide=await async function(e={}){return s||(s=(async()=>{try{"undefined"!=typeof importScripts?await new Promise((e,t)=>{try{if("undefined"==typeof importScripts)return void t(new Error("importScripts is not available - not in a worker context"));if(void 0!==globalThis.loadPyodide)return void e();importScripts(n),e()}catch(e){t(new Error(`Failed to import Pyodide in worker: ${e}`))}}):await new Promise((e,t)=>{if(void 0!==globalThis.loadPyodide)return void e();const r=document.createElement("script");r.src=n,r.onload=()=>e(),r.onerror=()=>t(new Error(`Failed to load Pyodide from ${n}`)),document.head.appendChild(r)});const t=globalThis.loadPyodide;if(!t)throw new Error("loadPyodide function not found after script load");const r={indexURL:"https://cdn.jsdelivr.net/pyodide/v0.28.0/full/",...e},s=await t(r);return o=!0,console.log("✅ Pyodide loaded successfully from CDN"),s}catch(e){throw s=null,e}})(),s)}(r);const i=Date.now()-t;if(console.log(`✅ Pyodide loaded in ${i}ms`),this.lockFileURL){console.log("🚀 Using lock file - skipping package installation");const[,]=await Promise.all([this.filesystemOptions.enabled?this.mountFilesystem():Promise.resolve(),this.setEnvironmentVariables()]);await this.initGlobals()}else{const[,,]=await Promise.all([this.filesystemOptions.enabled?this.mountFilesystem():Promise.resolve(),this.initPackageManager(),this.setEnvironmentVariables()]);await this.initKernel(),await this.initGlobals()}const a=Date.now()-e;console.log(`🎯 KERNEL INITIALIZATION COMPLETE in ${a}ms`),console.log(`⚡ Performance: Pyodide(${i}ms) + Setup(${a-i}ms)`),this.initialized=!0,this._status="active",console.log("🟢 Kernel is now ACTIVE and ready for execution!")}catch(e){throw console.error("❌ Kernel initialization failed:",e),this._status="unknown",e}}async mountFilesystem(){try{console.log(`Mounting filesystem from ${this.filesystemOptions.root} to ${this.filesystemOptions.mountPoint}`),await this.pyodide.FS.mount(this.pyodide.FS.filesystems.NODEFS,{root:this.filesystemOptions.root||"."},this.filesystemOptions.mountPoint||"/home/pyodide"),console.log("Filesystem mounted successfully");try{const e=this.pyodide.FS.readdir(this.filesystemOptions.mountPoint||"/home/pyodide");console.log(`Files in ${this.filesystemOptions.mountPoint} directory: ${e.join(", ")}`)}catch(e){console.error(`Error listing mounted directory: ${e}`)}}catch(e){throw console.error("Error mounting filesystem:",e),e}}async initPackageManager(){const e=Date.now();console.log("⚡ Initializing optimized package manager...");try{let t;console.log("📦 Loading micropip, packaging..."),await this.pyodide.loadPackage(["micropip","packaging"]),console.log("✅ Loaded micropip, packaging"),t="undefined"!=typeof window&&window.location?new URL(".",window.location.href).href:"undefined"!=typeof self&&self.location?new URL(".",self.location.href).href:"/";const r=new URL("pypi/all.json",t).href,n=[new URL("pypi/piplite-0.6.0a5-py3-none-any.whl",t).href,new URL("pypi/pyodide_kernel-0.6.0a5-py3-none-any.whl",t).href,new URL("pypi/ipykernel-6.9.2-py3-none-any.whl",t).href,new URL("pypi/widgetsnbextension-3.6.999-py3-none-any.whl",t).href,new URL("pypi/widgetsnbextension-4.0.999-py3-none-any.whl",t).href];console.log(`🚀 Installing ${n.length} wheel packages in parallel...`);const o=n.map(async(e,t)=>{const r=Date.now();try{await this.pyodide.runPythonAsync(`\nimport micropip\nawait micropip.install('${e}', keep_going=True)\nprint(f"✅ Wheel ${t+1}/${n.length} installed")\n`);const o=Date.now()-r;return console.log(`⚡ Wheel ${t+1} installed in ${o}ms`),{index:t,success:!0,time:o}}catch(e){const n=Date.now()-r;return console.warn(`⚠️ Wheel ${t+1} failed after ${n}ms:`,e),{index:t,success:!1,time:n,error:e}}}),s=await Promise.all(o),i=s.filter(e=>e.success),a=s.filter(e=>!e.success);console.log(`📊 Wheels: ${i.length}/${n.length} successful`),a.length>0&&console.warn(`⚠️ Failed wheels: ${a.map(e=>e.index+1).join(", ")}`);try{await this.pyodide.runPythonAsync(`\ntry:\n import piplite.piplite\n import json\n\n # Load package index for faster lookups\n try:\n piplite.piplite.PIPLITE_URL = "${r}"\n # Pre-load package index for faster installation\n print("📋 Package index configured")\n except Exception as e:\n print(f"⚠️ Package index setup warning: {e}")\n\n # Configure piplite for optimal performance\n piplite.piplite.REPODATA_INFO = {}\n print("⚡ Piplite optimized for performance")\nexcept ImportError:\n print("⚠️ Piplite not available, continuing without it")\nexcept Exception as e:\n print(f"⚠️ Piplite setup failed: {e}")\n`)}catch(e){console.warn("⚠️ Piplite configuration failed, continuing without it:",e)}const l=Date.now()-e;console.log(`🎯 Package manager initialized in ${l}ms`)}catch(e){throw console.error("❌ Package manager initialization failed:",e),e}}async initKernel(){const e=Date.now();console.log("🚀 Initializing kernel packages with maximum optimization...");const t=[{name:"pure-eval",priority:1,source:"pyodide"},{name:"stack-data",priority:1,source:"pyodide"},{name:"pygments",priority:1,source:"pyodide"},{name:"ssl",priority:1,source:"pyodide"},{name:"sqlite3",priority:1,source:"pyodide"},{name:"prompt_toolkit",priority:1,source:"pyodide"},{name:"jedi",priority:1,source:"pyodide"},{name:"ipython",priority:1,source:"pyodide"},{name:"comm",priority:2,source:"pip"},{name:"hypha-rpc",priority:2,source:"pip"},{name:"nbformat",priority:2,source:"pip"},{name:"ipykernel",priority:3,source:"pip"},{name:"pyodide_kernel",priority:3,source:"pip"}];try{console.log(`📦 Installing ${t.length} packages with intelligent optimization...`),await this.installPackagesWithIntelligentOptimization(t),console.log("📥 Importing pyodide_kernel...");const r=Date.now();await this.pyodide.runPythonAsync("import pyodide_kernel");const n=Date.now()-r;console.log(`✅ pyodide_kernel imported in ${n}ms`);const o=Date.now()-e;console.log(`🎯 Kernel packages initialized in ${o}ms`)}catch(e){throw console.error("❌ Kernel package initialization failed:",e),e}}async installPackagesWithIntelligentOptimization(e){console.log(`⚡ Starting intelligent parallel installation of ${e.length} packages...`);const t=e.map(async e=>{const t=Date.now();try{if(console.log(`🔄 Installing ${e.name} (priority: ${e.priority}, preferred: ${e.source})...`),"pyodide"!==e.source){await this.installViaPipWithOptimizations(e.name);const r=Date.now()-t;return console.log(`✅ ${e.name} installed via pip (${r}ms)`),{package:e.name,method:"pip",duration:r,success:!0,priority:e.priority}}try{await this.pyodide.loadPackage([e.name]);const r=Date.now()-t;return console.log(`✅ ${e.name} loaded from Pyodide CDN (${r}ms)`),{package:e.name,method:"pyodide",duration:r,success:!0,priority:e.priority}}catch(r){console.log(`📦 ${e.name} not available on CDN, trying pip...`),await this.installViaPipWithOptimizations(e.name);const n=Date.now()-t;return console.log(`✅ ${e.name} installed via pip fallback (${n}ms)`),{package:e.name,method:"pip-fallback",duration:n,success:!0,priority:e.priority}}}catch(r){const n=Date.now()-t;return console.warn(`❌ Failed to install ${e.name} after ${n}ms:`,r),{package:e.name,method:"failed",duration:n,success:!1,priority:e.priority,error:r}}}),r=await Promise.all(t);this.analyzeInstallationResults(r)}async installViaPipWithOptimizations(e){await this.pyodide.runPythonAsync(`\ntry:\n # Use optimized pip installation with caching\n await piplite.install('${e}', keep_going=True, deps=True)\n print("✅ Successfully installed ${e} via optimized pip")\nexcept Exception as e:\n print("⚠️ Warning: Failed to install ${e}:", str(e))\n # Try alternative installation method\n try:\n import micropip\n await micropip.install('${e}', keep_going=True)\n print("✅ Successfully installed ${e} via micropip fallback")\n except Exception as e2:\n print("❌ Both pip methods failed for ${e}:", str(e2))\n raise e2\n`)}analyzeInstallationResults(e){const t=e.filter(e=>e.success),r=e.filter(e=>!e.success),n=t.filter(e=>"pyodide"===e.method),o=t.filter(e=>"pip"===e.method),s=t.filter(e=>"pip-fallback"===e.method),i=Math.max(...e.map(e=>e.duration)),a=e.reduce((e,t)=>e+t.duration,0)/e.length,l=e.reduce((e,t)=>e+t.duration,0);console.log("🎯 INTELLIGENT INSTALLATION COMPLETE!"),console.log(`📊 Results: ${t.length}/${e.length} successful`),console.log(`⚡ Pyodide CDN: ${n.length} packages`),console.log(`📦 Direct pip: ${o.length} packages`),console.log(`🔄 Pip fallback: ${s.length} packages`),console.log(`❌ Failed: ${r.length} packages`),console.log(`⏱️ Total time: ${i}ms (vs ~${l}ms sequential)`),console.log(`🚀 Speed improvement: ~${Math.round(l/i)}x faster`),console.log(`📈 Average per package: ${Math.round(a)}ms`),r.length>0&&(console.warn(`⚠️ Failed packages: ${r.map(e=>e.package).join(", ")}`),r.forEach(e=>{console.warn(` - ${e.package}: ${e.error?.message||"Unknown error"}`)}));const c=Math.min(...t.map(e=>e.duration)),u=Math.max(...t.map(e=>e.duration));console.log(`📊 Performance range: ${c}ms (fastest) to ${u}ms (slowest)`)}async initGlobals(){console.log("Initializing globals...");const{globals:e}=this.pyodide;this._kernel=e.get("pyodide_kernel").kernel_instance.copy(),this._stdout_stream=e.get("pyodide_kernel").stdout_stream.copy(),this._stderr_stream=e.get("pyodide_kernel").stderr_stream.copy(),this._interpreter=this._kernel.interpreter.copy(),this._interpreter.send_comm=this.sendComm.bind(this),this.setupCallbacks()}setupCallbacks(){const e=(e,t)=>{const r={name:this.formatResult(e),text:this.formatResult(t)};this._sendMessage({parentHeader:this.formatResult(this._parent_header).header,bundle:r,type:"stream"})};this._stdout_stream.publish_stream_callback=e,this._stderr_stream.publish_stream_callback=e,this._interpreter.display_pub.clear_output_callback=e=>{const t={wait:this.formatResult(e)};this._sendMessage({parentHeader:this.formatResult(this._parent_header).header,bundle:t,type:"clear_output"})},this._interpreter.display_pub.display_data_callback=(e,t,r)=>{const n={data:this.formatResult(e),metadata:this.formatResult(t),transient:this.formatResult(r)};this._sendMessage({parentHeader:this.formatResult(this._parent_header).header,bundle:n,type:"display_data"})},this._interpreter.display_pub.update_display_data_callback=(e,t,r)=>{const n={data:this.formatResult(e),metadata:this.formatResult(t),transient:this.formatResult(r)};this._sendMessage({parentHeader:this.formatResult(this._parent_header).header,bundle:n,type:"update_display_data"})},this._interpreter.displayhook.publish_execution_result=(e,t,r)=>{const n={execution_count:e,data:this.formatResult(t),metadata:this.formatResult(r)};this._sendMessage({parentHeader:this.formatResult(this._parent_header).header,bundle:n,type:"execute_result"})},this._interpreter.input=this.input.bind(this),this._interpreter.getpass=this.getpass.bind(this)}_sendMessage(e){this._processMessage(e)}_processMessage(e){if(!e.type)return;let t;switch(e.type){case"stream":{const r=e.bundle??{name:"stdout",text:""};super.emit(l.z.STREAM,r),t=r;break}case"input_request":{const r=e.content??{prompt:"",password:!1};super.emit(l.z.INPUT_REQUEST,r),t=r;break}case"display_data":{const r=e.bundle??{data:{},metadata:{},transient:{}};super.emit(l.z.DISPLAY_DATA,r),t=r;break}case"update_display_data":{const r=e.bundle??{data:{},metadata:{},transient:{}};super.emit(l.z.UPDATE_DISPLAY_DATA,r),t=r;break}case"clear_output":{const r=e.bundle??{wait:!1};super.emit(l.z.CLEAR_OUTPUT,r),t=r;break}case"execute_result":{const r=e.bundle??{execution_count:this.executionCount,data:{},metadata:{}};super.emit(l.z.EXECUTE_RESULT,r),t=r;break}case"execute_error":{const r=e.bundle??{ename:"",evalue:"",traceback:[]};super.emit(l.z.EXECUTE_ERROR,r),t=r;break}case"comm_open":case"comm_msg":case"comm_close":{const r=e.content??{};super.emit(e.type,r,e.metadata,e.buffers),t={content:r,metadata:e.metadata,buffers:e.buffers};break}}t&&super.emit(l.z.ALL,{type:e.type,data:t})}isInitialized(){return this.initialized}async setup(e){await this.initialize(),this._parent_header=this.pyodide.toPy(e||{})}async execute(e,t={}){this.initialized||await this.initialize();try{this._status="busy",super.emit(l.z.KERNEL_BUSY,{}),await this.setup(t);const r="\n# Kernel isolation - reset commonly conflicting variables to prevent cross-kernel state sharing\nfor _var in ['x', 'value', 'result', 'a', 'b', 'c', 'data', 'temp']:\n if _var in globals():\n del globals()[_var]\ndel _var\n";return this.pyodide.runPython(r),new Promise((t,r)=>{const n={allMessages:[],executionComplete:!1,executionResult:null,executionError:null,timeout:null},o=e=>{n.allMessages.push(e)},s=async e=>{if(n.executionComplete)return;console.log(`[KERNEL] Execution completed, processing ${n.allMessages.length} messages`),n.executionComplete=!0,super.off(l.z.ALL,o);let r,s=!1,i=null;const a=n.executionResult;a&&"error"===a.status&&(s=!0,i={ename:a.ename,evalue:a.evalue,traceback:a.traceback});for(const e of n.allMessages){if("execute_error"===e.type){s=!0,i=e.data;break}"execute_result"===e.type&&(r=e.data)}if(this._status="active",super.emit(l.z.KERNEL_IDLE,{}),s){console.log("[KERNEL] Execution failed with error:",i);const e=i.ename?i.ename.replace(/^<class '(.+)'>$/,"$1"):i.ename;super.emit(l.z.EXECUTE_ERROR,{ename:e,evalue:i.evalue,traceback:i.traceback});const r=`${i.ename||"Error"}: ${i.evalue||"Unknown error"}`;t({success:!1,error:new Error(r),result:n.executionResult})}else{console.log(`[KERNEL] Execution successful, captured ${n.allMessages.length} output messages`);let e=void 0!==r?r:n.executionResult;t({success:!0,result:e})}};super.on(l.z.ALL,o),this._kernel.run(e).then(e=>{console.log("[KERNEL] Python execution finished, waiting for messages to settle"),n.executionResult=this.formatResult(e),setTimeout(()=>{s()},100)}).catch(e=>{console.error("[KERNEL] Python execution error:",e),n.executionError=e instanceof Error?e:new Error(String(e)),setTimeout(()=>{s()},100)})})}catch(e){return console.error("[KERNEL] Execute setup error:",e),this._status="active",super.emit(l.z.KERNEL_IDLE,{}),{success:!1,error:e instanceof Error?e:new Error(String(e))}}}formatResult(e){if(!(e instanceof this.pyodide.ffi.PyProxy))return e;try{const t=e.toJs();return this.mapToObject(t)}catch(e){return console.error("Error formatting result:",e),{status:"error",error:String(e)}}}mapToObject(e){const t=e instanceof Array?[]:{};return e.forEach((e,r)=>{t[r]=e instanceof Map||e instanceof Array?this.mapToObject(e):e}),t}async inputReply(e){this._resolveInputReply&&(this._resolveInputReply(e),this._resolveInputReply=null)}async sendInputRequest(e,t){const r={prompt:e,password:t};this._sendMessage({type:"input_request",content:r,parentHeader:this.formatResult(this._parent_header).header})}async getpass(e){e=void 0===e?"":e,await this.sendInputRequest(e,!0);const t=new Promise(e=>{this._resolveInputReply=e});return(await t).value}async input(e){e=void 0===e?"":e,await this.sendInputRequest(e,!1);const t=new Promise(e=>{this._resolveInputReply=e});return(await t).value}async sendComm(e,t,r,n,o){this._sendMessage({type:e,content:this.formatResult(t),metadata:this.formatResult(r),ident:this.formatResult(n),buffers:this.formatResult(o),parentHeader:this.formatResult(this._parent_header).header})}async complete(e,t,r={}){await this.setup(r);const n=this._kernel.complete(e,t);return this.formatResult(n)}async inspect(e,t,r,n={}){await this.setup(n);const o=this._kernel.inspect(e,t,r);return this.formatResult(o)}async isComplete(e,t={}){await this.setup(t);const r=this._kernel.is_complete(e);return this.formatResult(r)}async commInfo(e,t={}){await this.setup(t);const r=this._kernel.comm_info(e);return{comms:this.formatResult(r),status:"ok"}}async commOpen(e,t={}){await this.setup(t);const r=this._kernel.comm_manager.comm_open(this.pyodide.toPy(null),this.pyodide.toPy(null),this.pyodide.toPy(e));return this.formatResult(r)}async commMsg(e,t={}){await this.setup(t);const r=this._kernel.comm_manager.comm_msg(this.pyodide.toPy(null),this.pyodide.toPy(null),this.pyodide.toPy(e));return this.formatResult(r)}async commClose(e,t={}){await this.setup(t);const r=this._kernel.comm_manager.comm_close(this.pyodide.toPy(null),this.pyodide.toPy(null),this.pyodide.toPy(e));return this.formatResult(r)}async*executeStream(e,t={}){try{await this.initialize();const r=[],n=e=>{r.push(e)};super.on(l.z.ALL,n);try{const n=this.execute(e,t);for(;;)if(r.length>0&&(yield r.shift()),await Promise.race([n.then(()=>!0),new Promise(e=>setTimeout(()=>e(!1),10))])){for(;r.length>0;)yield r.shift();return await n}}catch(e){throw console.error("Error in executeStream:",e),e}finally{super.off(l.z.ALL,n)}}catch(e){return console.error("Error in executeStream setup:",e),{success:!1,error:e instanceof Error?e:new Error(String(e))}}}async interrupt(){if(!this.initialized||!this.pyodide)return console.warn("[KERNEL] Cannot interrupt: kernel not initialized"),!1;console.warn("[KERNEL] Main thread kernels have limited interrupt support");try{return this._interruptBuffer&&this._interruptSupported?(this._interruptBuffer[0]=2,await new Promise(e=>setTimeout(e,100)),0===this._interruptBuffer[0]):this._interpreter&&"function"==typeof this._interpreter.interrupt?(this._interpreter.interrupt(),!0):(this._sendMessage({type:"stream",bundle:{name:"stderr",text:"KeyboardInterrupt: Execution interrupted by user\n"}}),this._sendMessage({type:"execute_error",bundle:{ename:"KeyboardInterrupt",evalue:"Execution interrupted by user",traceback:["KeyboardInterrupt: Execution interrupted by user"]}}),!0)}catch(e){return console.error("[KERNEL] Error during interrupt:",e),!1}}setInterruptBuffer(e){this._interruptBuffer=e;try{this.pyodide&&"function"==typeof this.pyodide.setInterruptBuffer?(this.pyodide.setInterruptBuffer(e),this._interruptSupported=!0):(console.warn("[KERNEL] pyodide.setInterruptBuffer not available, interrupt support limited"),this._interruptSupported=!1)}catch(e){console.error("[KERNEL] Error setting interrupt buffer:",e),this._interruptSupported=!1}}async setEnvironmentVariables(){if(0===Object.keys(this.environmentVariables).length)return;const e=Date.now();console.log(`🌍 Setting ${Object.keys(this.environmentVariables).length} environment variables...`);try{for(const[e,t]of Object.entries(this.environmentVariables)){let r;r=null==t?"":String(t),await this.pyodide.runPythonAsync(`\nimport os\nos.environ[${JSON.stringify(e)}] = ${JSON.stringify(r)}\n`)}const t=Date.now()-e;console.log(`⚡ Environment variables set in ${t}ms`)}catch(e){throw console.error("❌ Failed to set environment variables:",e),e}}}},696:(e,t,r)=>{var n;r.d(t,{z:()=>n}),function(e){e.STREAM="stream",e.DISPLAY_DATA="display_data",e.UPDATE_DISPLAY_DATA="update_display_data",e.EXECUTE_RESULT="execute_result",e.EXECUTE_ERROR="execute_error",e.EXECUTE_REQUEST="execute_request",e.INPUT_REQUEST="input_request",e.CLEAR_OUTPUT="clear_output",e.COMM_OPEN="comm_open",e.COMM_MSG="comm_msg",e.COMM_CLOSE="comm_close",e.KERNEL_READY="kernel_ready",e.KERNEL_BUSY="kernel_busy",e.KERNEL_IDLE="kernel_idle",e.ALL="*",e.EXECUTION_STALLED="execution_stalled",e.KERNEL_UNRECOVERABLE="kernel_unrecoverable",e.EXECUTION_INTERRUPTED="execution_interrupted",e.KERNEL_RESTARTED="kernel_restarted",e.KERNEL_TERMINATED="kernel_terminated"}(n||(n={}))},757:(e,t,r)=>{r.r(t);var n=r(590),o=r(696);const s=new(r(637).Kernel);let i=null,a={},l=new Map,c=null;function u(e){return e&&"object"==typeof e&&("KeyboardInterrupt"===e.type||e.message&&e.message.includes("KeyboardInterrupt"))}function p(){i?Object.values(o.z).forEach(e=>{const t=t=>{i&&i.postMessage({type:e,data:t})};l.set(e,t),s.on(e,t)}):console.error("[WORKER] Cannot set up event forwarding: no event port available")}self.addEventListener("error",e=>{console.error("[WORKER] Global error caught:",e.error),e.preventDefault()}),self.addEventListener("unhandledrejection",e=>{u(e.reason)?(console.log("[WORKER] KeyboardInterrupt caught in unhandled rejection handler - this is expected during interrupts"),i&&i.postMessage({type:o.z.EXECUTE_ERROR,data:{ename:"KeyboardInterrupt",evalue:"Execution interrupted by user",traceback:["KeyboardInterrupt: Execution interrupted by user"]}})):console.error("[WORKER] Unhandled promise rejection:",e.reason),e.preventDefault()}),self.addEventListener("message",e=>{if("SET_EVENT_PORT"===e.data?.type&&e.data?.port)!function(){if(l.size>0){for(const[e,t]of l.entries())s.off(e,t);l.clear()}i&&(i.close(),i=null)}(),i=e.data.port,s.isInitialized()&&p();else if("INITIALIZE_KERNEL"===e.data?.type)a=e.data.options||{},async function(e){try{await s.initialize(e),c&&"function"==typeof s.setInterruptBuffer&&s.setInterruptBuffer(c),p(),i&&i.postMessage({type:"KERNEL_INITIALIZED",data:{success:!0}})}catch(e){throw console.error("Kernel initialization failed:",e),e}}(a).catch(e=>{console.error("[WORKER] Error initializing kernel in worker:",e),i&&i.postMessage({type:o.z.EXECUTE_ERROR,data:{ename:"WorkerInitError",evalue:`Failed to initialize kernel: ${e.message}`,traceback:[e.stack||""]}})});else if("SET_INTERRUPT_BUFFER"===e.data?.type){c=e.data.buffer,s.isInitialized()&&c&&"function"==typeof s.setInterruptBuffer?(s.setInterruptBuffer(c),console.log("[WORKER] Interrupt buffer set in pyodide kernel")):c&&console.log("[WORKER] Interrupt buffer stored, will be set when kernel initializes");const t={type:"INTERRUPT_BUFFER_SET",data:{success:!0}};i&&i.postMessage(t),self.postMessage(t)}else if("INTERRUPT_KERNEL"===e.data?.type)if(c){c[0]=2;const e={type:"INTERRUPT_TRIGGERED",data:{success:!0,method:"buffer"}};i&&i.postMessage(e),self.postMessage(e)}else if(console.log("[WORKER] No interrupt buffer available, trying kernel.interrupt()"),"function"==typeof s.interrupt)s.interrupt().then(e=>{const t={type:"INTERRUPT_TRIGGERED",data:{success:e,method:"kernel"}};i&&i.postMessage(t),self.postMessage(t)}).catch(e=>{console.error("[WORKER] Error during kernel interrupt:",e);const t={type:"INTERRUPT_TRIGGERED",data:{success:!1,error:e.message,method:"kernel"}};i&&i.postMessage(t),self.postMessage(t)});else{console.warn("[WORKER] No interrupt method available");const e={type:"INTERRUPT_TRIGGERED",data:{success:!1,error:"No interrupt method available",method:"none"}};i&&i.postMessage(e),self.postMessage(e)}}),self.addEventListener("beforeunload",async()=>{try{i&&i.postMessage({type:"WORKER_TERMINATING",data:{message:"Worker is shutting down"}})}catch(e){console.error("Error during worker cleanup:",e)}});const d={initialize:async e=>{try{return void await s.initialize(e)}catch(e){throw console.error("[WORKER] Initialize error:",e),e}},execute:async(e,t)=>{try{return await s.execute(e,t)}catch(e){return console.error("[WORKER] Execute error:",e),u(e)?(console.log("[WORKER] KeyboardInterrupt caught in execute method"),{success:!1,error:new Error("KeyboardInterrupt: Execution interrupted by user"),result:{payload:[],status:"error",ename:"KeyboardInterrupt",evalue:"Execution interrupted by user",traceback:["KeyboardInterrupt: Execution interrupted by user"]}}):{success:!1,error:e instanceof Error?e:new Error(String(e)),result:{payload:[],status:"error",ename:e instanceof Error?e.constructor.name:"Error",evalue:e instanceof Error?e.message:String(e),traceback:e instanceof Error&&e.stack?e.stack.split("\n"):[String(e)]}}}},isInitialized:()=>{try{return s.isInitialized()}catch(e){return console.error("[WORKER] IsInitialized error:",e),!1}},inputReply:async e=>{try{await s.inputReply(e)}catch(e){throw console.error("[WORKER] InputReply error:",e),e}},getStatus:async()=>{try{return await s.getStatus()}catch(e){return console.error("[WORKER] getStatus error:",e),"unknown"}},interrupt:async()=>{try{return"function"==typeof s.interrupt?await s.interrupt():(console.warn("[WORKER] Kernel does not support interrupt method"),!1)}catch(e){return console.error("[WORKER] Interrupt error:",e),!1}},setInterruptBuffer:e=>{try{return"function"==typeof s.setInterruptBuffer?(s.setInterruptBuffer(e),!0):(console.warn("[WORKER] Kernel does not support setInterruptBuffer method"),!1)}catch(e){return console.error("[WORKER] setInterruptBuffer error:",e),!1}},complete:async(e,t,r)=>{try{return"function"==typeof s.complete?await s.complete(e,t,r):(console.warn("[WORKER] Kernel does not support complete method"),{status:"error",error:"Completion not supported"})}catch(e){return console.error("[WORKER] Complete error:",e),{status:"error",error:String(e)}}},inspect:async(e,t,r,n)=>{try{return"function"==typeof s.inspect?await s.inspect(e,t,r,n):(console.warn("[WORKER] Kernel does not support inspect method"),{status:"error",error:"Inspection not supported"})}catch(e){return console.error("[WORKER] Inspect error:",e),{status:"error",error:String(e)}}},isComplete:async(e,t)=>{try{return"function"==typeof s.isComplete?await s.isComplete(e,t):(console.warn("[WORKER] Kernel does not support isComplete method"),{status:"unknown"})}catch(e){return console.error("[WORKER] IsComplete error:",e),{status:"error",error:String(e)}}},commInfo:async(e,t)=>{try{return"function"==typeof s.commInfo?await s.commInfo(e,t):(console.warn("[WORKER] Kernel does not support commInfo method"),{comms:{},status:"ok"})}catch(e){return console.error("[WORKER] CommInfo error:",e),{comms:{},status:"error",error:String(e)}}},commOpen:async(e,t)=>{try{return"function"==typeof s.commOpen?await s.commOpen(e,t):void console.warn("[WORKER] Kernel does not support commOpen method")}catch(e){return void console.error("[WORKER] CommOpen error:",e)}},commMsg:async(e,t)=>{try{return"function"==typeof s.commMsg?await s.commMsg(e,t):void console.warn("[WORKER] Kernel does not support commMsg method")}catch(e){return void console.error("[WORKER] CommMsg error:",e)}},commClose:async(e,t)=>{try{return"function"==typeof s.commClose?await s.commClose(e,t):void console.warn("[WORKER] Kernel does not support commClose method")}catch(e){return void console.error("[WORKER] CommClose error:",e)}}};try{n.p(d)}catch(e){console.error("Error exposing proxy:",e)}}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var s=t[n]={exports:{}};return e[n](s,s.exports,r),s.exports}return r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r(637)})());
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.WebPythonKernel=t():e.WebPythonKernel=t()}(self,()=>(()=>{"use strict";var e={590:(e,t,r)=>{r.d(t,{LV:()=>d});const n=Symbol("Comlink.proxy"),o=Symbol("Comlink.endpoint"),i=Symbol("Comlink.releaseProxy"),s=Symbol("Comlink.finalizer"),a=Symbol("Comlink.thrown"),l=e=>"object"==typeof e&&null!==e||"function"==typeof e,c=new Map([["proxy",{canHandle:e=>l(e)&&e[n],serialize(e){const{port1:t,port2:r}=new MessageChannel;return u(e,t),[r,[r]]},deserialize:e=>(e.start(),d(e))}],["throw",{canHandle:e=>l(e)&&a in e,serialize({value:e}){let t;return t=e instanceof Error?{isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:{isError:!1,value:e},[t,[]]},deserialize(e){if(e.isError)throw Object.assign(new Error(e.value.message),e.value);throw e.value}}]]);function u(e,t=globalThis,r=["*"]){t.addEventListener("message",function o(i){if(!i||!i.data)return;if(!function(e,t){for(const r of e){if(t===r||"*"===r)return!0;if(r instanceof RegExp&&r.test(t))return!0}return!1}(r,i.origin))return void console.warn(`Invalid origin '${i.origin}' for comlink proxy`);const{id:l,type:c,path:d}=Object.assign({path:[]},i.data),h=(i.data.argumentList||[]).map(x);let m;try{const t=d.slice(0,-1).reduce((e,t)=>e[t],e),r=d.reduce((e,t)=>e[t],e);switch(c){case"GET":m=r;break;case"SET":t[d.slice(-1)[0]]=x(i.data.value),m=!0;break;case"APPLY":m=r.apply(t,h);break;case"CONSTRUCT":m=function(e){return Object.assign(e,{[n]:!0})}(new r(...h));break;case"ENDPOINT":{const{port1:t,port2:r}=new MessageChannel;u(e,r),m=function(e,t){return w.set(e,t),e}(t,[t])}break;case"RELEASE":m=void 0;break;default:return}}catch(e){m={value:e,[a]:0}}Promise.resolve(m).catch(e=>({value:e,[a]:0})).then(r=>{const[n,i]=k(r);t.postMessage(Object.assign(Object.assign({},n),{id:l}),i),"RELEASE"===c&&(t.removeEventListener("message",o),p(t),s in e&&"function"==typeof e[s]&&e[s]())}).catch(e=>{const[r,n]=k({value:new TypeError("Unserializable return value"),[a]:0});t.postMessage(Object.assign(Object.assign({},r),{id:l}),n)})}),t.start&&t.start()}function p(e){(function(e){return"MessagePort"===e.constructor.name})(e)&&e.close()}function d(e,t){const r=new Map;return e.addEventListener("message",function(e){const{data:t}=e;if(!t||!t.id)return;const n=r.get(t.id);if(n)try{n(t)}finally{r.delete(t.id)}}),y(e,r,[],t)}function h(e){if(e)throw new Error("Proxy has been released and is not useable")}function m(e){return v(e,new Map,{type:"RELEASE"}).then(()=>{p(e)})}const g=new WeakMap,f="FinalizationRegistry"in globalThis&&new FinalizationRegistry(e=>{const t=(g.get(e)||0)-1;g.set(e,t),0===t&&m(e)});function y(e,t,r=[],n=function(){}){let s=!1;const a=new Proxy(n,{get(n,o){if(h(s),o===i)return()=>{!function(e){f&&f.unregister(e)}(a),m(e),t.clear(),s=!0};if("then"===o){if(0===r.length)return{then:()=>a};const n=v(e,t,{type:"GET",path:r.map(e=>e.toString())}).then(x);return n.then.bind(n)}return y(e,t,[...r,o])},set(n,o,i){h(s);const[a,l]=k(i);return v(e,t,{type:"SET",path:[...r,o].map(e=>e.toString()),value:a},l).then(x)},apply(n,i,a){h(s);const l=r[r.length-1];if(l===o)return v(e,t,{type:"ENDPOINT"}).then(x);if("bind"===l)return y(e,t,r.slice(0,-1));const[c,u]=E(a);return v(e,t,{type:"APPLY",path:r.map(e=>e.toString()),argumentList:c},u).then(x)},construct(n,o){h(s);const[i,a]=E(o);return v(e,t,{type:"CONSTRUCT",path:r.map(e=>e.toString()),argumentList:i},a).then(x)}});return function(e,t){const r=(g.get(t)||0)+1;g.set(t,r),f&&f.register(e,t,e)}(a,e),a}function E(e){const t=e.map(k);return[t.map(e=>e[0]),(r=t.map(e=>e[1]),Array.prototype.concat.apply([],r))];var r}const w=new WeakMap;function k(e){for(const[t,r]of c)if(r.canHandle(e)){const[n,o]=r.serialize(e);return[{type:"HANDLER",name:t,value:n},o]}return[{type:"RAW",value:e},w.get(e)||[]]}function x(e){switch(e.type){case"HANDLER":return c.get(e.name).deserialize(e.value);case"RAW":return e.value}}function v(e,t,r,n){return new Promise(o=>{const i=new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-");t.set(i,o),e.start&&e.start(),e.postMessage(Object.assign({id:i},r),n)})}},696:(e,t,r)=>{var n;r.d(t,{z:()=>n}),function(e){e.STREAM="stream",e.DISPLAY_DATA="display_data",e.UPDATE_DISPLAY_DATA="update_display_data",e.EXECUTE_RESULT="execute_result",e.EXECUTE_ERROR="execute_error",e.EXECUTE_REQUEST="execute_request",e.INPUT_REQUEST="input_request",e.CLEAR_OUTPUT="clear_output",e.COMM_OPEN="comm_open",e.COMM_MSG="comm_msg",e.COMM_CLOSE="comm_close",e.KERNEL_READY="kernel_ready",e.KERNEL_BUSY="kernel_busy",e.KERNEL_IDLE="kernel_idle",e.ALL="*",e.EXECUTION_STALLED="execution_stalled",e.KERNEL_UNRECOVERABLE="kernel_unrecoverable",e.EXECUTION_INTERRUPTED="execution_interrupted",e.KERNEL_RESTARTED="kernel_restarted",e.KERNEL_TERMINATED="kernel_terminated"}(n||(n={}))}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var i=t[n]={exports:{}};return e[n](i,i.exports,r),i.exports}r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};r.r(n),r.d(n,{Kernel:()=>m,KernelEvents:()=>c.z,KernelLanguage:()=>l,KernelManager:()=>d,KernelMode:()=>a});const o="https://cdn.jsdelivr.net/pyodide/v0.28.0/full/pyodide.js";let i=!1,s=null;var a,l,c=r(696),u=r(590);class p{constructor(){this.events={}}on(e,t){this.events[e]||(this.events[e]=[]),this.events[e].push(t)}off(e,t){if(!this.events[e])return;const r=this.events[e].indexOf(t);r>-1&&this.events[e].splice(r,1)}removeListener(e,t){this.off(e,t)}emit(e,...t){this.events[e]&&this.events[e].forEach(e=>e(...t))}setMaxListeners(e){}}!function(e){e.MAIN_THREAD="main_thread",e.WORKER="worker"}(a||(a={})),function(e){e.PYTHON="python"}(l||(l={}));class d extends p{isKeyboardInterrupt(e){return e&&"object"==typeof e&&("type"in e&&"KeyboardInterrupt"===e.type||"message"in e&&"string"==typeof e.message&&e.message.includes("KeyboardInterrupt"))}createKeyboardInterruptResult(){return{success:!1,error:new Error("KeyboardInterrupt: Execution interrupted by user"),result:{status:"error",ename:"KeyboardInterrupt",evalue:"Execution interrupted by user",traceback:["KeyboardInterrupt: Execution interrupted by user"]}}}storeAbortController(e,t,r){this.abortControllers.has(e)||this.abortControllers.set(e,new Map),this.abortControllers.get(e).set(t,r)}removeAbortController(e,t){const r=this.abortControllers.get(e);if(!r)return;const n=r.get(t);return n&&(r.delete(t),0===r.size&&this.abortControllers.delete(e)),n}abortAllKernelOperations(e){const t=this.abortControllers.get(e);if(t){for(const[r,n]of t)try{n.abort(),console.log(`🚫 Aborted execution ${r} for kernel ${e}`)}catch(e){console.warn(`⚠️ Error aborting execution ${r}:`,e)}this.abortControllers.delete(e)}}constructor(e={}){super(),this.kernels=new Map,this.listenerWrappers=new Map,this.lastActivityTime=new Map,this.inactivityTimers=new Map,this.ongoingExecutions=new Map,this.executionTimeouts=new Map,this.executionStartTimes=new Map,this.executionMetadata=new Map,this.abortControllers=new Map,this.pool=new Map,this.isPreloading=!1,this.prefillingInProgress=new Map,this.interruptBuffers=new Map,super.setMaxListeners(100),this.interruptionMode=e.interruptionMode||"auto",this.allowedKernelTypes=e.allowedKernelTypes||[{mode:a.WORKER,language:l.PYTHON}];const t=this.allowedKernelTypes.filter(e=>e.language===l.PYTHON);this.poolConfig={enabled:!1,poolSize:2,autoRefill:!0,preloadConfigs:t,...e.pool},this.poolConfig.preloadConfigs&&(this.poolConfig.preloadConfigs=this.poolConfig.preloadConfigs.filter(e=>{const t=this.isKernelTypeAllowed(e.mode,e.language);return t||console.warn(`Pool preload config ${e.mode}-${e.language} is not in allowedKernelTypes, skipping`),t})),this.poolConfig.enabled&&this.preloadPool().catch(e=>{console.error("Error preloading kernel pool:",e)})}getPoolKey(e,t){return`${e}-${t}`}getFromPool(e,t){if(!this.poolConfig.enabled)return null;const r=this.getPoolKey(e,t),n=this.pool.get(r);if(!n||0===n.length)return null;const o=n.shift();return this.poolConfig.autoRefill&&setTimeout(()=>{this.refillPoolSingle(e,t).catch(e=>{console.error(`Error refilling single kernel for ${r}:`,e)})},0),o}addToPool(e,t,r){if(!this.poolConfig.enabled)return;const n=this.getPoolKey(e,t);this.pool.has(n)||this.pool.set(n,[]);const o=this.pool.get(n);o.length<this.poolConfig.poolSize?(o.push(r),r.catch(e=>{console.error(`Pool kernel promise rejected for ${n}:`,e);const t=o.indexOf(r);-1!==t&&o.splice(t,1)})):r.then(e=>{e.destroy().catch(e=>{console.error("Error destroying excess pool kernel:",e)})}).catch(e=>{console.error("Excess pool kernel promise rejected:",e)})}async refillPoolSingle(e,t){if(!this.poolConfig.enabled)return;const r=this.getPoolKey(e,t);if((this.pool.get(r)||[]).length<this.poolConfig.poolSize){const r=this.createPoolKernelPromise(e,t);this.addToPool(e,t,r)}}async refillPool(e,t){if(!this.poolConfig.enabled)return;const r=this.getPoolKey(e,t);if(!this.prefillingInProgress.get(r)){this.prefillingInProgress.set(r,!0);try{const n=this.pool.get(r)||[],o=this.poolConfig.poolSize-n.length;if(o<=0)return;const i=Array.from({length:o},()=>this.createPoolKernelPromise(e,t));for(const r of i)this.addToPool(e,t,r)}catch(e){console.error(`Error refilling pool for ${r}:`,e)}finally{this.prefillingInProgress.set(r,!1)}}}createPoolKernelPromise(e,t){return new Promise(async(r,n)=>{try{const n=await this.createPoolKernel(e,t);n.isFromPool=!0,r(n)}catch(r){console.error(`Error creating pool kernel for ${e}-${t}:`,r),n(r)}})}async createPoolKernel(e,t){const r=`pool-${crypto.randomUUID()}`,n={mode:e,lang:t};let o;try{if(e===a.MAIN_THREAD){const i={id:r,options:n,mode:e,language:t};this.kernels.set(r,i);try{o=await this.createMainThreadKernel(r)}finally{this.kernels.delete(r)}}else{const i={id:r,options:n,mode:e,language:t};this.kernels.set(r,i);try{o=await this.createWorkerKernel(r)}finally{this.kernels.delete(r)}}}catch(e){throw this.kernels.delete(r),e}return o}async preloadPool(){if(this.poolConfig.enabled&&!this.isPreloading){this.isPreloading=!0;try{for(const e of this.poolConfig.preloadConfigs)try{await this.refillPool(e.mode,e.language)}catch(t){console.error(`Error preloading ${e.mode}-${e.language}:`,t)}}catch(e){console.error("Error during kernel pool preloading:",e)}finally{this.isPreloading=!1}}}canUsePool(e){return!!this.poolConfig.enabled&&!e.filesystem&&!e.deno?.permissions&&void 0===e.inactivityTimeout&&void 0===e.maxExecutionTime}reassignPoolKernel(e,t,r){const n={id:t,kernel:e.kernel,mode:e.mode,language:e.language,worker:e.worker,created:new Date,options:{...e.options,...r},isFromPool:!0,destroy:e.destroy};if("function"!=typeof n.destroy)throw console.error("Failed to preserve destroy function during pool kernel reassignment"),console.error("poolKernel.destroy type:",typeof e.destroy),console.error("updatedInstance.destroy type:",typeof n.destroy),new Error("Failed to preserve destroy function during pool kernel reassignment");return n}getPoolStats(){const e={};for(const[t,r]of this.pool.entries())e[t]={available:r.length,total:this.poolConfig.poolSize};return e}getPoolConfig(){return{enabled:this.poolConfig.enabled,poolSize:this.poolConfig.poolSize,autoRefill:this.poolConfig.autoRefill,preloadConfigs:[...this.poolConfig.preloadConfigs],isPreloading:this.isPreloading}}async createKernel(e={}){if(e.id&&e.id.includes(":"))throw new Error("Kernel ID cannot contain colons");const t=e.id||crypto.randomUUID(),r=e.mode||a.WORKER,n=e.lang||l.PYTHON;if(!this.isKernelTypeAllowed(r,n))throw new Error(`Kernel type ${r}-${n} is not allowed. Allowed types: ${this.allowedKernelTypes.map(e=>`${e.mode}-${e.language}`).join(", ")}`);const o=e.namespace?`${e.namespace}:${t}`:t;if(this.kernels.has(o))throw new Error(`Kernel with ID ${o} already exists`);if(this.canUsePool(e)){const t=this.getPoolKey(r,n);if(this.poolConfig.preloadConfigs.some(e=>e.mode===r&&e.language===n)){let i=this.getFromPool(r,n);if(i)return await this.setupPoolKernelFromPromise(i,o,e);try{const i=this.createPoolKernelPromise(r,n);return this.poolConfig.autoRefill&&setTimeout(()=>{this.refillPool(r,n).catch(e=>{console.error(`Error refilling exhausted pool for ${t}:`,e)})},0),await this.setupPoolKernelFromPromise(i,o,e)}catch(e){console.error(`Failed to create kernel promise for exhausted pool: ${e}`)}}else{const t=this.getFromPool(r,n);if(t)return await this.setupPoolKernelFromPromise(t,o,e)}}return this.createOnDemandKernel(o,r,n,e)}async setupPoolKernelFromPromise(e,t,r){try{const n=await e,o=this.reassignPoolKernel(n,t,r);if(o.mode===a.WORKER&&o.worker){const e=o.worker,{port1:r,port2:n}=new MessageChannel;e.postMessage({type:"SET_EVENT_PORT",port:n},[n]);const i=e=>{e.data&&e.data.type&&super.emit(e.data.type,{kernelId:t,data:e.data.data})};r.addEventListener("message",i),r.start();const s=o.destroy;o.destroy=async()=>(r.removeEventListener("message",i),r.close(),s())}return this.kernels.set(t,o),this.setupEventForwarding(o),this.updateKernelActivity(t),r.inactivityTimeout&&r.inactivityTimeout>0&&this.setupInactivityTimeout(t,r.inactivityTimeout),r.maxExecutionTime&&r.maxExecutionTime>0&&this.setupStalledExecutionHandler(t),t}catch(e){throw console.error(`Error setting up pool kernel ${t}:`,e),super.emit(c.z.EXECUTE_ERROR,{kernelId:t,data:{ename:"KernelSetupError",evalue:`Failed to setup kernel: ${e instanceof Error?e.message:String(e)}`,traceback:[e instanceof Error?e.stack||e.message:String(e)]}}),e}}setupPoolKernel(e,t,r){const n=this.reassignPoolKernel(e,t,r);if(n.mode===a.WORKER&&n.worker){const e=n.worker,{port1:r,port2:o}=new MessageChannel;e.postMessage({type:"SET_EVENT_PORT",port:o},[o]);const i=e=>{e.data&&e.data.type&&super.emit(e.data.type,{kernelId:t,data:e.data.data})};r.addEventListener("message",i),r.start();const s=n.destroy;n.destroy=async()=>(r.removeEventListener("message",i),r.close(),s())}return this.kernels.set(t,n),this.setupEventForwarding(n),this.updateKernelActivity(t),r.inactivityTimeout&&r.inactivityTimeout>0&&this.setupInactivityTimeout(t,r.inactivityTimeout),r.maxExecutionTime&&r.maxExecutionTime>0&&this.setupStalledExecutionHandler(t),t}async createOnDemandKernel(e,t,r,n){const o={id:e,options:{...n,lang:r},mode:t,language:r};let i;return this.kernels.set(e,o),i=t===a.MAIN_THREAD?await this.createMainThreadKernel(e):await this.createWorkerKernel(e),this.kernels.set(e,i),this.setupEventForwarding(i),this.updateKernelActivity(e),n.inactivityTimeout&&n.inactivityTimeout>0&&this.setupInactivityTimeout(e,n.inactivityTimeout),n.maxExecutionTime&&n.maxExecutionTime>0&&this.setupStalledExecutionHandler(e),e}async createMainThreadKernel(e){const t=this.kernels.get(e)?.options||{},r=t.lang||l.PYTHON,n=new m,o={id:e,kernel:n,mode:a.MAIN_THREAD,language:r,created:new Date,options:t,destroy:async()=>Promise.resolve()},i={};return t.filesystem&&(i.filesystem=t.filesystem),t.env&&(i.env=t.env),t.lockFileURL&&(i.lockFileURL=t.lockFileURL),await n.initialize(i),o}async createWorkerKernel(e){const t=this.kernels.get(e)?.options||{},r=t.lang||l.PYTHON;t.deno?.permissions&&t.deno.permissions;const n=new Worker("./dist/kernel.worker.js",{type:"classic"}),{port1:o,port2:i}=new MessageChannel,s=new Promise((e,t)=>{const r=n=>{"KERNEL_INITIALIZED"===n.data?.type&&(n.data.data.success?(o.removeEventListener("message",r),e()):(o.removeEventListener("message",r),t(new Error("Kernel initialization failed"))))};o.addEventListener("message",r)});n.postMessage({type:"SET_EVENT_PORT",port:i},[i]);const c=u.LV(n),p=t=>{t.data&&t.data.type&&super.emit(t.data.type,{kernelId:e,data:t.data.data})};return o.addEventListener("message",p),o.start(),n.postMessage({type:"INITIALIZE_KERNEL",options:{filesystem:t.filesystem,env:t.env,lockFileURL:t.lockFileURL,lang:r}}),await s,await this.setupWorkerInterruptBuffer(e,n),{id:e,kernel:{initialize:async e=>c.initialize(e),execute:async(e,t)=>await c.execute(e,t),isInitialized:()=>c.isInitialized(),inputReply:async e=>c.inputReply(e),getStatus:async()=>{try{return"function"==typeof c.getStatus?await c.getStatus():"unknown"}catch(e){return"unknown"}},complete:async(e,t,r)=>{try{return"function"==typeof c.complete?await c.complete(e,t,r):{status:"error",error:"Completion not supported"}}catch(e){return{status:"error",error:String(e)}}},inspect:async(e,t,r,n)=>{try{return"function"==typeof c.inspect?await c.inspect(e,t,r,n):{status:"error",error:"Inspection not supported"}}catch(e){return{status:"error",error:String(e)}}},isComplete:async(e,t)=>{try{return"function"==typeof c.isComplete?await c.isComplete(e,t):{status:"unknown"}}catch(e){return{status:"error",error:String(e)}}},interrupt:async()=>{try{return"function"==typeof c.interrupt&&await c.interrupt()}catch(e){return!1}},setInterruptBuffer:e=>{try{"function"==typeof c.setInterruptBuffer&&c.setInterruptBuffer(e)}catch(e){console.warn("Failed to set interrupt buffer:",e)}},commInfo:async(e,t)=>{try{return"function"==typeof c.commInfo?await c.commInfo(e,t):{comms:{},status:"ok"}}catch(e){return{comms:{},status:"error",error:String(e)}}},commOpen:async(e,t)=>{try{if("function"==typeof c.commOpen)return await c.commOpen(e,t)}catch(e){console.warn("Failed to open comm:",e)}},commMsg:async(e,t)=>{try{if("function"==typeof c.commMsg)return await c.commMsg(e,t)}catch(e){console.warn("Failed to send comm message:",e)}},commClose:async(e,t)=>{try{if("function"==typeof c.commClose)return await c.commClose(e,t)}catch(e){console.warn("Failed to close comm:",e)}}},mode:a.WORKER,language:r,worker:n,created:new Date,options:t,destroy:async()=>(o.removeEventListener("message",p),o.close(),n.terminate(),Promise.resolve())}}setupEventForwarding(e){e.mode===a.MAIN_THREAD&&Object.values(c.z).forEach(t=>{e.kernel.on(t,r=>{super.emit(t,{kernelId:e.id,data:r})})})}getKernel(e){return this.kernels.get(e)}getKernelIds(){return Array.from(this.kernels.keys())}async listKernels(e){const t=Array.from(this.kernels.entries()).filter(([t])=>!t.startsWith("pool-")&&(!e||t.startsWith(`${e}:`)));return await Promise.all(t.map(async([e,t])=>{const r=e.match(/^([^:]+):/),n=r?r[1]:void 0;let o="unknown";try{t&&t.kernel&&"function"==typeof t.kernel.getStatus&&(o=await t.kernel.getStatus())}catch(t){console.warn(`Error getting status for kernel ${e}:`,t),o="unknown"}return{id:e,mode:t.mode,language:t.language,status:o,created:t.created||new Date,namespace:n,deno:t.options?.deno}}))}async destroyKernel(e){const t=this.kernels.get(e);if(t){if("function"!=typeof t.destroy)throw new Error(`Kernel ${e} is missing destroy function (type: ${typeof t.destroy})`);if(this.abortAllKernelOperations(e),this.clearInactivityTimeout(e),this.executionTimeouts.has(e)){const t=this.executionTimeouts.get(e);for(const e of t.values())clearTimeout(e);this.executionTimeouts.delete(e)}this.executionStartTimes.has(e)&&this.executionStartTimes.delete(e),this.executionMetadata.has(e)&&this.executionMetadata.delete(e),this.interruptBuffers.has(e)&&this.interruptBuffers.delete(e),this.ongoingExecutions.delete(e),this.lastActivityTime.delete(e),this.removeAllKernelListeners(e),await t.destroy(),this.kernels.delete(e)}}async destroyAll(e){const t=Array.from(this.kernels.keys()).filter(t=>!e||t.startsWith(`${e}:`)).map(async e=>{const t=this.kernels.get(e);return t&&"function"==typeof t.destroy?this.destroyKernel(e):(console.warn(`Skipping incomplete kernel instance ${e} during destroyAll`),void this.kernels.delete(e))});await Promise.all(t),e||await this.destroyPool()}async destroyPool(){const e=[];for(const[t,r]of this.pool.entries())for(const t of r){const r=t.then(e=>e.destroy()).catch(e=>{console.error("Error destroying pool kernel from promise:",e)});e.push(r)}await Promise.all(e),this.pool.clear(),this.prefillingInProgress.clear()}onKernelEvent(e,t,r){if(!this.kernels.has(e))throw new Error(`Kernel with ID ${e} not found`);const n={original:r,wrapped:t=>{t.kernelId===e&&r(t.data)}};this.storeListener(e,t,r,n),super.on(t,n.wrapped)}offKernelEvent(e,t,r){const n=this.getListener(e,t,r);n&&(super.removeListener(t,n.wrapped),this.removeStoredListener(e,t,r))}storeListener(e,t,r,n){this.listenerWrappers.has(e)||this.listenerWrappers.set(e,new Map);const o=this.listenerWrappers.get(e);o.has(t)||o.set(t,new Map),o.get(t).set(r,n)}getListener(e,t,r){const n=this.listenerWrappers.get(e);if(!n)return;const o=n.get(t);return o?o.get(r):void 0}removeStoredListener(e,t,r){const n=this.listenerWrappers.get(e);if(!n)return;const o=n.get(t);o&&(o.delete(r),0===o.size&&n.delete(t),0===n.size&&this.listenerWrappers.delete(e))}removeAllKernelListeners(e){const t=this.listenerWrappers.get(e);if(t){for(const[e,r]of t.entries())for(const t of r.values())super.removeListener(e,t.wrapped);this.listenerWrappers.delete(e)}}getListeners(e,t){const r=this.listenerWrappers.get(e);if(!r)return[];const n=r.get(t);return n?Array.from(n.keys()):[]}async*executeStream(e,t,r={}){const n=this.getKernel(e);if(!n)throw new Error(`Kernel with ID ${e} not found`);this.updateKernelActivity(e);const o=this.trackExecution(e,t),i=new AbortController;this.storeAbortController(e,o,i);try{if(n.mode===a.MAIN_THREAD){const i=n.kernel;if("function"==typeof i.executeStream)try{return yield*i.executeStream(t,r),this.updateKernelActivity(e),this.completeExecution(e,o),{success:!0}}catch(t){return console.error("Error in main thread executeStream:",t),this.updateKernelActivity(e),this.completeExecution(e,o),{success:!1,error:t instanceof Error?t:new Error(String(t))}}}try{const s=[];let a=!1,l={success:!0};const u=new Map,p=()=>{for(const[e,t]of u.entries())super.off(e,t);u.clear()},d=t=>{const r=r=>{r.kernelId!==e||a||(s.push({type:t,data:r.data,executionId:o}),this.updateKernelActivity(e))};return u.set(t,r),r},h=d("stream"),m=d("display_data"),g=d("update_display_data"),f=d("execute_result"),y=d("execute_error");super.on(c.z.STREAM,h),super.on(c.z.DISPLAY_DATA,m),super.on(c.z.UPDATE_DISPLAY_DATA,g),super.on(c.z.EXECUTE_RESULT,f),super.on(c.z.EXECUTE_ERROR,y);const E=new Promise((p,d)=>{const h=t=>{t.kernelId!==e||a||(a=!0,l={success:!1,error:new Error(`${t.data.ename}: ${t.data.evalue}`),result:t.data},this.updateKernelActivity(e),p(l))};if(u.set("execute_error_completion",h),super.on(c.z.EXECUTE_ERROR,h),i.signal.aborted)return a=!0,void p({success:!1,error:new Error("Execution was aborted")});i.signal.addEventListener("abort",()=>{a||(console.log(`🚫 Execution ${o} aborted`),a=!0,p({success:!1,error:new Error("Execution was aborted")}))});try{n.kernel.execute(t,r).then(t=>{if(!a){if(t.success&&t.result&&"error"===t.result.status){const e={status:t.result.status,ename:t.result.ename,evalue:t.result.evalue,traceback:t.result.traceback};s.push({type:"error",data:e,executionId:o}),l={success:!1,error:new Error(`${t.result.ename}: ${t.result.evalue}`),result:t.result}}else l=t;a=!0,this.updateKernelActivity(e),p(l)}}).catch(t=>{if(!a){let r;console.error(`Error in execute for kernel ${e}:`,t),this.isKeyboardInterrupt(t)?(console.log(`KeyboardInterrupt caught in executeStream for kernel ${e}`),r=this.createKeyboardInterruptResult(),s.push({type:"error",data:r.result,executionId:o})):r={success:!1,error:t instanceof Error?t:new Error(String(t))},a=!0,l=r,this.updateKernelActivity(e),p(r)}})}catch(t){if(!a){console.error(`Error calling execute for kernel ${e}:`,t);const r={success:!1,error:t instanceof Error?t:new Error(String(t))};a=!0,l=r,this.updateKernelActivity(e),p(r)}}});try{for(;(!a||s.length>0)&&!i.signal.aborted;){if(s.length>0){const e=s.shift();yield e;continue}if(!a)try{await new Promise((e,t)=>{const r=setTimeout(e,10);i.signal.addEventListener("abort",()=>{clearTimeout(r),t(new Error("Aborted"))})})}catch(e){if(i.signal.aborted)break}}if(i.signal.aborted&&!a)throw new Error("Execution was aborted during stream monitoring");return await E}finally{p(),this.removeAbortController(e,o),this.completeExecution(e,o)}}catch(t){return this.completeExecution(e,o),console.error("Unexpected error in executeStream:",t),{success:!1,error:t instanceof Error?t:new Error(String(t))}}}catch(t){return this.completeExecution(e,o),console.error("Unexpected error in executeStream:",t),{success:!1,error:t instanceof Error?t:new Error(String(t))}}}trackExecution(e,t){const r=`exec-${crypto.randomUUID()}`,n=Date.now(),o=this.kernels.get(e);if(o&&o.mode===a.WORKER&&this.interruptBuffers.has(e)&&(this.interruptBuffers.get(e)[0]=0),this.ongoingExecutions.has(e)||this.ongoingExecutions.set(e,new Set),this.ongoingExecutions.get(e).add(r),this.executionStartTimes.has(e)||this.executionStartTimes.set(e,new Map),this.executionStartTimes.get(e).set(r,n),this.executionMetadata.has(e)||this.executionMetadata.set(e,new Map),this.updateKernelActivity(e),o&&o.options.maxExecutionTime&&o.options.maxExecutionTime>0){this.executionTimeouts.has(e)||this.executionTimeouts.set(e,new Map);const i=setTimeout(()=>{console.warn(`Execution ${r} on kernel ${e} has been running for ${o.options.maxExecutionTime}ms and may be stuck/dead.`);const i=this.executionMetadata.get(e)?.get(r),s=Date.now()-(i?.startTime||n);super.emit("execution_stalled",{kernelId:e,executionId:r,maxExecutionTime:o.options.maxExecutionTime,actualRuntime:s,code:i?.code||t,startTime:i?.startTime||n}),this.handleStuckExecution(e,r,s,i?.code||t)},o.options.maxExecutionTime);this.executionTimeouts.get(e).set(r,i),this.executionMetadata.get(e).set(r,{startTime:n,code:t,timeoutId:i})}else this.executionMetadata.get(e).set(r,{startTime:n,code:t});return r}completeExecution(e,t){if(this.executionTimeouts.has(e)){const r=this.executionTimeouts.get(e);r.has(t)&&(clearTimeout(r.get(t)),r.delete(t)),0===r.size&&this.executionTimeouts.delete(e)}if(this.executionStartTimes.has(e)){const r=this.executionStartTimes.get(e);r.delete(t),0===r.size&&this.executionStartTimes.delete(e)}if(this.executionMetadata.has(e)){const r=this.executionMetadata.get(e);r.delete(t),0===r.size&&this.executionMetadata.delete(e)}if(this.ongoingExecutions.has(e)){const r=this.ongoingExecutions.get(e);r.delete(t),0===r.size&&(this.ongoingExecutions.delete(e),this.updateKernelActivity(e))}}hasOngoingExecutions(e){return this.ongoingExecutions.has(e)&&this.ongoingExecutions.get(e).size>0}getOngoingExecutionCount(e){return this.ongoingExecutions.has(e)?this.ongoingExecutions.get(e).size:0}setupInactivityTimeout(e,t){if(t<=0)return;this.clearInactivityTimeout(e);const r=this.lastActivityTime.get(e)||Date.now(),n=Date.now()-r,o=Math.max(0,t-n);if(0===o)return this.hasOngoingExecutions(e)?void this.setupInactivityTimeout(e,t):void this.destroyKernel(e).catch(t=>{console.error(`Error destroying inactive kernel ${e}:`,t)});const i=setTimeout(()=>{this.hasOngoingExecutions(e)?this.setupInactivityTimeout(e,t):this.destroyKernel(e).catch(t=>{console.error(`Error destroying inactive kernel ${e}:`,t)})},o);this.inactivityTimers.set(e,i)}clearInactivityTimeout(e){if(this.inactivityTimers.has(e)){const t=this.inactivityTimers.get(e);clearTimeout(t),this.inactivityTimers.delete(e)}}updateKernelActivity(e){this.lastActivityTime.set(e,Date.now());const t=this.kernels.get(e);if(!t)return;const r=t.options.inactivityTimeout;r&&r>0&&this.setupInactivityTimeout(e,r)}getLastActivityTime(e){return this.lastActivityTime.get(e)}getInactivityTimeout(e){const t=this.kernels.get(e);if(t)return t.options.inactivityTimeout}setInactivityTimeout(e,t){const r=this.kernels.get(e);return!!r&&(r.options.inactivityTimeout=t,this.clearInactivityTimeout(e),t>0&&this.setupInactivityTimeout(e,t),!0)}getTimeUntilShutdown(e){const t=this.kernels.get(e);if(!t)return;const r=t.options.inactivityTimeout;if(!r||r<=0)return;const n=this.lastActivityTime.get(e);if(!n)return;const o=r-(Date.now()-n);return Math.max(0,o)}getInactivityTimers(){const e={};return this.inactivityTimers.forEach((t,r)=>{e[r]=t}),e}setupStalledExecutionHandler(e){super.on(c.z.EXECUTION_STALLED,t=>{t.kernelId===e&&(console.warn(`Handling stalled execution ${t.executionId} on kernel ${e} (running longer than ${t.maxExecutionTime}ms)`),this.kernels.get(e)&&super.emit(c.z.EXECUTE_ERROR,{kernelId:e,data:{ename:"ExecutionStalledError",evalue:`Execution stalled or potentially deadlocked (running > ${t.maxExecutionTime}ms)`,traceback:["Execution may be stuck in an infinite loop or deadlocked."]}}))})}async forceTerminateKernel(e,t="Force terminated due to stalled execution"){if(!this.kernels.get(e))return!1;try{return console.warn(`Force terminating kernel ${e}: ${t}`),super.emit(c.z.EXECUTE_ERROR,{kernelId:e,data:{ename:"KernelForcedTermination",evalue:t,traceback:["Kernel was forcefully terminated by the system."]}}),await this.destroyKernel(e),!0}catch(t){return console.error(`Error during forced termination of kernel ${e}:`,t),!1}}getExecutionInfo(e){const t=this.kernels.get(e);if(!t)return{count:0,isStuck:!1,executionIds:[],executions:[]};if(!t.options)return{count:0,isStuck:!1,executionIds:[],executions:[]};const r=this.ongoingExecutions.get(e)?Array.from(this.ongoingExecutions.get(e)):[],n=r.length,o=Date.now(),i=t.options.maxExecutionTime,s=[];let a,l=!1;const c=this.executionStartTimes.get(e),u=this.executionMetadata.get(e);for(const t of r){const r=c?.get(t),n=u?.get(t);if(void 0!==r){const e=o-r,c=void 0!==i&&e>i;s.push({id:t,startTime:r,runtime:e,code:n?.code,isStuck:c}),(void 0===a||e>a)&&(a=e),c&&(l=!0)}else console.warn(`No start time found for execution ${t} on kernel ${e}`),s.push({id:t,startTime:0,runtime:0,code:n?.code,isStuck:!1})}return s.sort((e,t)=>e.startTime-t.startTime),{count:n,isStuck:l,executionIds:r,longestRunningTime:a,executions:s}}async execute(e,t,r={}){const n=this.getKernel(e);if(!n)throw new Error(`Kernel with ID ${e} not found`);this.updateKernelActivity(e);const o=this.trackExecution(e,t);try{const i=await n.kernel.execute(t,r);return this.updateKernelActivity(e),this.completeExecution(e,o),i}catch(t){return this.updateKernelActivity(e),this.completeExecution(e,o),{success:!1,error:t instanceof Error?t:new Error(String(t))}}}isKernelTypeAllowed(e,t){return this.allowedKernelTypes.some(r=>r.mode===e&&r.language===t)}getAllowedKernelTypes(){return[...this.allowedKernelTypes]}pingKernel(e){return!!this.kernels.get(e)&&(this.updateKernelActivity(e),!0)}async restartKernel(e){const t=this.kernels.get(e);if(!t)return console.warn(`Cannot restart kernel ${e}: kernel not found`),!1;try{const r={mode:t.mode,language:t.language,options:{...t.options}};let n,o;if(e.includes(":")){const t=e.split(":");n=t[0],o=t[1]}else o=e;await this.destroyKernel(e);const i={id:o,mode:r.mode,lang:r.language,namespace:n,deno:r.options.deno,filesystem:r.options.filesystem,inactivityTimeout:r.options.inactivityTimeout,maxExecutionTime:r.options.maxExecutionTime},s=await this.createKernel(i);return s===e||(console.error(`Kernel restart failed: expected ID ${e}, got ${s}`),!1)}catch(t){return console.error(`Error restarting kernel ${e}:`,t),!1}}async interruptKernel(e){const t=this.kernels.get(e);if(!t)return console.warn(`Cannot interrupt kernel ${e}: kernel not found`),!1;try{return t.mode===a.WORKER&&t.worker?await this.interruptWorkerKernel(e,t):await this.interruptMainThreadKernel(e,t)}catch(t){return console.error(`Error interrupting kernel ${e}:`,t instanceof Error?t.message:String(t)),!1}}async interruptMainThreadKernel(e,t){throw new Error(`Main thread kernel ${e} does not support reliable interruption. Use worker kernels for interruptible execution.`)}async interruptWorkerKernel(e,t){try{const r=t.worker;if(!r)return console.error(`Worker not found for kernel ${e}`),!1;if("kernel-interrupt"===this.interruptionMode)return await this.interruptWorkerKernelFallback(e,r);let n=this.interruptBuffers.get(e);if(!n)try{const t=new SharedArrayBuffer(1);n=new Uint8Array(t),n[0]=0,this.interruptBuffers.set(e,n),r.postMessage({type:"SET_INTERRUPT_BUFFER",buffer:n}),await new Promise((e,t)=>{const n=setTimeout(()=>{t(new Error("Timeout waiting for interrupt buffer setup"))},2e3),o=t=>{"INTERRUPT_BUFFER_SET"===t.data?.type&&(r.removeEventListener("message",o),clearTimeout(n),e())};r.addEventListener("message",o)}),console.log(`Interrupt buffer set up for kernel ${e}`)}catch(t){if("shared-array-buffer"===this.interruptionMode)throw console.error(`❌ Cannot create SharedArrayBuffer for interrupt handling in kernel ${e}`),new Error("SharedArrayBuffer is required for interruption mode 'shared-array-buffer' but is not available.\n\nTo fix this issue, either:\n1. Configure your web server with these headers:\n - Cross-Origin-Opener-Policy: same-origin\n - Cross-Origin-Embedder-Policy: require-corp\n\n2. Or change the interruption mode when creating KernelManager:\n new KernelManager({ interruptionMode: 'auto' })");return console.info(`ℹ️ Using message-based interrupt for kernel ${e} (SharedArrayBuffer not available)`),await this.interruptWorkerKernelFallback(e,r)}console.log(`Setting interrupt signal for kernel ${e}...`),n[0]=2;let o=0;const i=50;for(;o<i&&0!==n[0];)await new Promise(e=>setTimeout(e,100)),o++;return 0===n[0]?(console.log(`Interrupt processed successfully for kernel ${e} after ${100*o}ms`),!0):(console.warn(`Interrupt signal not processed for kernel ${e} after ${100*i}ms`),!0)}catch(t){return console.error(`Error interrupting worker kernel ${e}:`,t),!1}}async interruptWorkerKernelFallback(e,t){return new Promise(r=>{const n=e=>{if("INTERRUPT_TRIGGERED"===e.data?.type){t.removeEventListener("message",n);const o=e.data.data?.success||!1;r(o)}};t.addEventListener("message",n),t.postMessage({type:"INTERRUPT_KERNEL"}),setTimeout(()=>{t.removeEventListener("message",n),console.warn(`⏱️ Interrupt request timed out for kernel ${e} after 5 seconds.\nThis may happen if:\n- The kernel is running code that cannot be interrupted\n- The kernel is in an unresponsive state\nYou may need to restart the kernel if it remains unresponsive.`),r(!1)},5e3)})}async handleStuckExecution(e,t,r,n){const o=this.kernels.get(e);if(o){if(console.warn(`Handling stuck execution ${t} on kernel ${e} (runtime: ${r}ms)`),await this.interruptKernel(e))return console.log(`Successfully interrupted kernel ${e}`),void super.emit(c.z.EXECUTE_ERROR,{kernelId:e,data:{ename:"ExecutionInterrupted",evalue:`Execution automatically interrupted after ${r}ms (exceeded maxExecutionTime)`,traceback:["Execution was automatically interrupted due to timeout.",`Runtime: ${r}ms`,`Max allowed: ${o.options.maxExecutionTime}ms`,n?`Code: ${n.substring(0,200)}${n.length>200?"...":""}`:"Code: <unknown>"]}});if(console.warn(`Interrupt failed for kernel ${e}, attempting restart...`),await this.restartKernel(e))return console.log(`Successfully restarted kernel ${e}`),void super.emit(c.z.EXECUTE_ERROR,{kernelId:e,data:{ename:"KernelRestarted",evalue:`Kernel automatically restarted due to stuck execution (runtime: ${r}ms)`,traceback:["Kernel was automatically restarted due to stuck execution.",`Runtime: ${r}ms`,`Max allowed: ${o.options.maxExecutionTime}ms`,"Interrupt attempt failed, kernel was restarted instead.",n?`Code: ${n.substring(0,200)}${n.length>200?"...":""}`:"Code: <unknown>"]}});console.error(`Restart failed for kernel ${e}, force terminating...`),await this.forceTerminateKernel(e,`Stuck execution could not be interrupted or restarted (runtime: ${r}ms)`)?console.log(`Successfully terminated kernel ${e}`):(console.error(`Failed to terminate kernel ${e} - manual intervention may be required`),super.emit("kernel_unrecoverable",{kernelId:e,executionId:t,actualRuntime:r,code:n,message:"Kernel is stuck and could not be recovered through interrupt, restart, or termination"}))}}getStuckExecutions(){const e=[],t=Date.now();for(const[r,n]of this.kernels.entries()){if(r.startsWith("pool-"))continue;if(!n.options?.maxExecutionTime||n.options.maxExecutionTime<=0)continue;const o=n.options.maxExecutionTime,i=this.executionStartTimes.get(r),s=this.executionMetadata.get(r),a=this.ongoingExecutions.get(r);if(a&&0!==a.size)for(const l of a){const a=i?.get(l);if(void 0===a)continue;const c=t-a;if(c>o){const t=s?.get(l);e.push({kernelId:r,executionId:l,startTime:a,runtime:c,maxAllowed:o,code:t?.code,kernelMode:n.mode,kernelLanguage:n.language})}}}return e.sort((e,t)=>t.runtime-e.runtime),e}async handleAllStuckExecutions(){const e=this.getStuckExecutions(),t=[];console.log(`Found ${e.length} stuck executions to handle`);const r=new Map;for(const t of e)r.has(t.kernelId)||r.set(t.kernelId,[]),r.get(t.kernelId).push(t);for(const[e,n]of r)try{const r=n[0];console.log(`Handling stuck kernel ${e} with ${n.length} stuck executions (primary: ${r.runtime}ms)`),await this.handleStuckExecution(e,r.executionId,r.runtime,r.code);for(const e of n)t.push({kernelId:e.kernelId,executionId:e.executionId,action:"interrupted",success:!0})}catch(r){console.error(`Error handling stuck executions for kernel ${e}:`,r);for(const e of n)t.push({kernelId:e.kernelId,executionId:e.executionId,action:"failed",success:!1,error:r instanceof Error?r.message:String(r)})}return t}async setupWorkerInterruptBuffer(e,t){if("kernel-interrupt"!==this.interruptionMode)try{const r=new SharedArrayBuffer(1),n=new Uint8Array(r);n[0]=0,this.interruptBuffers.set(e,n),t.postMessage({type:"SET_INTERRUPT_BUFFER",buffer:n}),await new Promise((e,r)=>{const n=setTimeout(()=>{r(new Error("Timeout waiting for interrupt buffer setup"))},5e3),o=r=>{"INTERRUPT_BUFFER_SET"===r.data?.type&&(t.removeEventListener("message",o),clearTimeout(n),e())};t.addEventListener("message",o)})}catch(t){if("shared-array-buffer"===this.interruptionMode)throw console.error(`❌ SharedArrayBuffer required but not available for kernel ${e}`),new Error("SharedArrayBuffer is required but not available. To enable SharedArrayBuffer, your server must set these headers:\n- Cross-Origin-Opener-Policy: same-origin\n- Cross-Origin-Embedder-Policy: require-corp\n\nAlternatively, use interruptionMode: 'kernel-interrupt' or 'auto' in KernelManager options.");console.info(`ℹ️ SharedArrayBuffer not available for kernel ${e}. Using alternative interrupt method.\n\nTo enable faster interrupts, configure your server with these headers:\n- Cross-Origin-Opener-Policy: same-origin\n- Cross-Origin-Embedder-Policy: require-corp\n\nNote: Some development servers (e.g., Vite, webpack-dev-server) can be configured to add these headers.\nThe alternative interrupt method will still work but may be less responsive for long-running code.`)}else console.log(`Skipping SharedArrayBuffer setup for kernel ${e} - using kernel.interrupt() mode`)}}class h{constructor(){this.events={}}on(e,t){this.events[e]||(this.events[e]=[]),this.events[e].push(t)}off(e,t){if(!this.events[e])return;const r=this.events[e].indexOf(t);r>-1&&this.events[e].splice(r,1)}emit(e,...t){this.events[e]&&this.events[e].forEach(e=>e(...t))}setMaxListeners(e){}}class m extends h{constructor(){super(),this.initialized=!1,this.initPromise=null,this.filesystemOptions={enabled:!1,root:".",mountPoint:"/home/pyodide"},this._resolveInputReply=null,this._parent_header={},this.executionCount=0,this._status="unknown",this._interruptBuffer=null,this._interruptSupported=!1,this.environmentVariables={},super.setMaxListeners(20),this.kernelId=`kernel_${Math.random().toString(36).substring(2)}_${Date.now()}`}async getStatus(){return this._status}async initialize(e){if(!this.initialized)return this.initPromise||(e?.filesystem&&(this.filesystemOptions={...this.filesystemOptions,...e.filesystem}),e?.env&&(this.environmentVariables={...e.env}),e?.lockFileURL&&(this.lockFileURL=e.lockFileURL),this.initPromise=this._initializeInternal()),this.initPromise}async _initializeInternal(){const e=Date.now();console.log("🚀 Starting optimized kernel initialization...");try{const t=Date.now(),r={};this.lockFileURL&&(r.lockFileURL=this.lockFileURL,console.log(`🔒 Using lockFileURL: ${this.lockFileURL}`)),this.pyodide=await async function(e={}){return s||(s=(async()=>{try{"undefined"!=typeof importScripts?await new Promise((e,t)=>{try{if("undefined"==typeof importScripts)return void t(new Error("importScripts is not available - not in a worker context"));if(void 0!==globalThis.loadPyodide)return void e();importScripts(o),e()}catch(e){t(new Error(`Failed to import Pyodide in worker: ${e}`))}}):await new Promise((e,t)=>{if(void 0!==globalThis.loadPyodide)return void e();const r=document.createElement("script");r.src=o,r.onload=()=>e(),r.onerror=()=>t(new Error(`Failed to load Pyodide from ${o}`)),document.head.appendChild(r)});const t=globalThis.loadPyodide;if(!t)throw new Error("loadPyodide function not found after script load");const r={indexURL:"https://cdn.jsdelivr.net/pyodide/v0.28.0/full/",...e},n=await t(r);return i=!0,console.log("✅ Pyodide loaded successfully from CDN"),n}catch(e){throw s=null,e}})(),s)}(r);const n=Date.now()-t;if(console.log(`✅ Pyodide loaded in ${n}ms`),this.lockFileURL){console.log("🚀 Using lock file - skipping package installation");const[,]=await Promise.all([this.filesystemOptions.enabled?this.mountFilesystem():Promise.resolve(),this.setEnvironmentVariables()]);await this.initGlobals()}else{const[,,]=await Promise.all([this.filesystemOptions.enabled?this.mountFilesystem():Promise.resolve(),this.initPackageManager(),this.setEnvironmentVariables()]);await this.initKernel(),await this.initGlobals()}const a=Date.now()-e;console.log(`🎯 KERNEL INITIALIZATION COMPLETE in ${a}ms`),console.log(`⚡ Performance: Pyodide(${n}ms) + Setup(${a-n}ms)`),this.initialized=!0,this._status="active",console.log("🟢 Kernel is now ACTIVE and ready for execution!")}catch(e){throw console.error("❌ Kernel initialization failed:",e),this._status="unknown",e}}async mountFilesystem(){try{console.log(`Mounting filesystem from ${this.filesystemOptions.root} to ${this.filesystemOptions.mountPoint}`),await this.pyodide.FS.mount(this.pyodide.FS.filesystems.NODEFS,{root:this.filesystemOptions.root||"."},this.filesystemOptions.mountPoint||"/home/pyodide"),console.log("Filesystem mounted successfully");try{const e=this.pyodide.FS.readdir(this.filesystemOptions.mountPoint||"/home/pyodide");console.log(`Files in ${this.filesystemOptions.mountPoint} directory: ${e.join(", ")}`)}catch(e){console.error(`Error listing mounted directory: ${e}`)}}catch(e){throw console.error("Error mounting filesystem:",e),e}}async initPackageManager(){const e=Date.now();console.log("⚡ Initializing optimized package manager...");try{let t;console.log("📦 Loading micropip, packaging..."),await this.pyodide.loadPackage(["micropip","packaging"]),console.log("✅ Loaded micropip, packaging"),t="undefined"!=typeof window&&window.location?new URL(".",window.location.href).href:"undefined"!=typeof self&&self.location?new URL(".",self.location.href).href:"/";const r=new URL("pypi/all.json",t).href,n=[new URL("pypi/piplite-0.6.0a5-py3-none-any.whl",t).href,new URL("pypi/pyodide_kernel-0.6.0a5-py3-none-any.whl",t).href,new URL("pypi/ipykernel-6.9.2-py3-none-any.whl",t).href,new URL("pypi/widgetsnbextension-3.6.999-py3-none-any.whl",t).href,new URL("pypi/widgetsnbextension-4.0.999-py3-none-any.whl",t).href];console.log(`🚀 Installing ${n.length} wheel packages in parallel...`);const o=n.map(async(e,t)=>{const r=Date.now();try{await this.pyodide.runPythonAsync(`\nimport micropip\nawait micropip.install('${e}', keep_going=True)\nprint(f"✅ Wheel ${t+1}/${n.length} installed")\n`);const o=Date.now()-r;return console.log(`⚡ Wheel ${t+1} installed in ${o}ms`),{index:t,success:!0,time:o}}catch(e){const n=Date.now()-r;return console.warn(`⚠️ Wheel ${t+1} failed after ${n}ms:`,e),{index:t,success:!1,time:n,error:e}}}),i=await Promise.all(o),s=i.filter(e=>e.success),a=i.filter(e=>!e.success);console.log(`📊 Wheels: ${s.length}/${n.length} successful`),a.length>0&&console.warn(`⚠️ Failed wheels: ${a.map(e=>e.index+1).join(", ")}`);try{await this.pyodide.runPythonAsync(`\ntry:\n import piplite.piplite\n import json\n\n # Load package index for faster lookups\n try:\n piplite.piplite.PIPLITE_URL = "${r}"\n # Pre-load package index for faster installation\n print("📋 Package index configured")\n except Exception as e:\n print(f"⚠️ Package index setup warning: {e}")\n\n # Configure piplite for optimal performance\n piplite.piplite.REPODATA_INFO = {}\n print("⚡ Piplite optimized for performance")\nexcept ImportError:\n print("⚠️ Piplite not available, continuing without it")\nexcept Exception as e:\n print(f"⚠️ Piplite setup failed: {e}")\n`)}catch(e){console.warn("⚠️ Piplite configuration failed, continuing without it:",e)}const l=Date.now()-e;console.log(`🎯 Package manager initialized in ${l}ms`)}catch(e){throw console.error("❌ Package manager initialization failed:",e),e}}async initKernel(){const e=Date.now();console.log("🚀 Initializing kernel packages with maximum optimization...");const t=[{name:"pure-eval",priority:1,source:"pyodide"},{name:"stack-data",priority:1,source:"pyodide"},{name:"pygments",priority:1,source:"pyodide"},{name:"ssl",priority:1,source:"pyodide"},{name:"sqlite3",priority:1,source:"pyodide"},{name:"prompt_toolkit",priority:1,source:"pyodide"},{name:"jedi",priority:1,source:"pyodide"},{name:"ipython",priority:1,source:"pyodide"},{name:"comm",priority:2,source:"pip"},{name:"hypha-rpc",priority:2,source:"pip"},{name:"nbformat",priority:2,source:"pip"},{name:"ipykernel",priority:3,source:"pip"},{name:"pyodide_kernel",priority:3,source:"pip"}];try{console.log(`📦 Installing ${t.length} packages with intelligent optimization...`),await this.installPackagesWithIntelligentOptimization(t),console.log("📥 Importing pyodide_kernel...");const r=Date.now();await this.pyodide.runPythonAsync("import pyodide_kernel");const n=Date.now()-r;console.log(`✅ pyodide_kernel imported in ${n}ms`);const o=Date.now()-e;console.log(`🎯 Kernel packages initialized in ${o}ms`)}catch(e){throw console.error("❌ Kernel package initialization failed:",e),e}}async installPackagesWithIntelligentOptimization(e){console.log(`⚡ Starting intelligent parallel installation of ${e.length} packages...`);const t=e.map(async e=>{const t=Date.now();try{if(console.log(`🔄 Installing ${e.name} (priority: ${e.priority}, preferred: ${e.source})...`),"pyodide"!==e.source){await this.installViaPipWithOptimizations(e.name);const r=Date.now()-t;return console.log(`✅ ${e.name} installed via pip (${r}ms)`),{package:e.name,method:"pip",duration:r,success:!0,priority:e.priority}}try{await this.pyodide.loadPackage([e.name]);const r=Date.now()-t;return console.log(`✅ ${e.name} loaded from Pyodide CDN (${r}ms)`),{package:e.name,method:"pyodide",duration:r,success:!0,priority:e.priority}}catch(r){console.log(`📦 ${e.name} not available on CDN, trying pip...`),await this.installViaPipWithOptimizations(e.name);const n=Date.now()-t;return console.log(`✅ ${e.name} installed via pip fallback (${n}ms)`),{package:e.name,method:"pip-fallback",duration:n,success:!0,priority:e.priority}}}catch(r){const n=Date.now()-t;return console.warn(`❌ Failed to install ${e.name} after ${n}ms:`,r),{package:e.name,method:"failed",duration:n,success:!1,priority:e.priority,error:r}}}),r=await Promise.all(t);this.analyzeInstallationResults(r)}async installViaPipWithOptimizations(e){await this.pyodide.runPythonAsync(`\ntry:\n # Import piplite first\n import piplite\n # Use optimized pip installation with caching\n await piplite.install('${e}', keep_going=True, deps=True)\n print("✅ Successfully installed ${e} via optimized pip")\nexcept Exception as e:\n print("⚠️ Warning: Failed to install ${e}:", str(e))\n # Try alternative installation method\n try:\n import micropip\n await micropip.install('${e}', keep_going=True)\n print("✅ Successfully installed ${e} via micropip fallback")\n except Exception as e2:\n print("❌ Both pip methods failed for ${e}:", str(e2))\n raise e2\n`)}analyzeInstallationResults(e){const t=e.filter(e=>e.success),r=e.filter(e=>!e.success),n=t.filter(e=>"pyodide"===e.method),o=t.filter(e=>"pip"===e.method),i=t.filter(e=>"pip-fallback"===e.method),s=Math.max(...e.map(e=>e.duration)),a=e.reduce((e,t)=>e+t.duration,0)/e.length,l=e.reduce((e,t)=>e+t.duration,0);console.log("🎯 INTELLIGENT INSTALLATION COMPLETE!"),console.log(`📊 Results: ${t.length}/${e.length} successful`),console.log(`⚡ Pyodide CDN: ${n.length} packages`),console.log(`📦 Direct pip: ${o.length} packages`),console.log(`🔄 Pip fallback: ${i.length} packages`),console.log(`❌ Failed: ${r.length} packages`),console.log(`⏱️ Total time: ${s}ms (vs ~${l}ms sequential)`),console.log(`🚀 Speed improvement: ~${Math.round(l/s)}x faster`),console.log(`📈 Average per package: ${Math.round(a)}ms`),r.length>0&&(console.warn(`⚠️ Failed packages: ${r.map(e=>e.package).join(", ")}`),r.forEach(e=>{console.warn(` - ${e.package}: ${e.error?.message||"Unknown error"}`)}));const c=Math.min(...t.map(e=>e.duration)),u=Math.max(...t.map(e=>e.duration));console.log(`📊 Performance range: ${c}ms (fastest) to ${u}ms (slowest)`)}async initGlobals(){console.log("Initializing globals...");const{globals:e}=this.pyodide;this._kernel=e.get("pyodide_kernel").kernel_instance.copy(),this._stdout_stream=e.get("pyodide_kernel").stdout_stream.copy(),this._stderr_stream=e.get("pyodide_kernel").stderr_stream.copy(),this._interpreter=this._kernel.interpreter.copy(),this._interpreter.send_comm=this.sendComm.bind(this),this.setupCallbacks()}setupCallbacks(){const e=(e,t)=>{const r={name:this.formatResult(e),text:this.formatResult(t)};this._sendMessage({parentHeader:this.formatResult(this._parent_header).header,bundle:r,type:"stream"})};this._stdout_stream.publish_stream_callback=e,this._stderr_stream.publish_stream_callback=e,this._interpreter.display_pub.clear_output_callback=e=>{const t={wait:this.formatResult(e)};this._sendMessage({parentHeader:this.formatResult(this._parent_header).header,bundle:t,type:"clear_output"})},this._interpreter.display_pub.display_data_callback=(e,t,r)=>{const n={data:this.formatResult(e),metadata:this.formatResult(t),transient:this.formatResult(r)};this._sendMessage({parentHeader:this.formatResult(this._parent_header).header,bundle:n,type:"display_data"})},this._interpreter.display_pub.update_display_data_callback=(e,t,r)=>{const n={data:this.formatResult(e),metadata:this.formatResult(t),transient:this.formatResult(r)};this._sendMessage({parentHeader:this.formatResult(this._parent_header).header,bundle:n,type:"update_display_data"})},this._interpreter.displayhook.publish_execution_result=(e,t,r)=>{const n={execution_count:e,data:this.formatResult(t),metadata:this.formatResult(r)};this._sendMessage({parentHeader:this.formatResult(this._parent_header).header,bundle:n,type:"execute_result"})},this._interpreter.input=this.input.bind(this),this._interpreter.getpass=this.getpass.bind(this)}_sendMessage(e){this._processMessage(e)}_processMessage(e){if(!e.type)return;let t;switch(e.type){case"stream":{const r=e.bundle??{name:"stdout",text:""};super.emit(c.z.STREAM,r),t=r;break}case"input_request":{const r=e.content??{prompt:"",password:!1};super.emit(c.z.INPUT_REQUEST,r),t=r;break}case"display_data":{const r=e.bundle??{data:{},metadata:{},transient:{}};super.emit(c.z.DISPLAY_DATA,r),t=r;break}case"update_display_data":{const r=e.bundle??{data:{},metadata:{},transient:{}};super.emit(c.z.UPDATE_DISPLAY_DATA,r),t=r;break}case"clear_output":{const r=e.bundle??{wait:!1};super.emit(c.z.CLEAR_OUTPUT,r),t=r;break}case"execute_result":{const r=e.bundle??{execution_count:this.executionCount,data:{},metadata:{}};super.emit(c.z.EXECUTE_RESULT,r),t=r;break}case"execute_error":{const r=e.bundle??{ename:"",evalue:"",traceback:[]};super.emit(c.z.EXECUTE_ERROR,r),t=r;break}case"comm_open":case"comm_msg":case"comm_close":{const r=e.content??{};super.emit(e.type,r,e.metadata,e.buffers),t={content:r,metadata:e.metadata,buffers:e.buffers};break}}t&&super.emit(c.z.ALL,{type:e.type,data:t})}isInitialized(){return this.initialized}async setup(e){await this.initialize(),this._parent_header=this.pyodide.toPy(e||{})}async execute(e,t={}){this.initialized||await this.initialize();try{this._status="busy",super.emit(c.z.KERNEL_BUSY,{}),await this.setup(t);const r="\n# Kernel isolation - reset commonly conflicting variables to prevent cross-kernel state sharing\nfor _var in ['x', 'value', 'result', 'a', 'b', 'c', 'data', 'temp']:\n if _var in globals():\n del globals()[_var]\ndel _var\n";return this.pyodide.runPython(r),new Promise((t,r)=>{const n={allMessages:[],executionComplete:!1,executionResult:null,executionError:null,timeout:null},o=e=>{n.allMessages.push(e)},i=async e=>{if(n.executionComplete)return;console.log(`[KERNEL] Execution completed, processing ${n.allMessages.length} messages`),n.executionComplete=!0,super.off(c.z.ALL,o);let r,i=!1,s=null;const a=n.executionResult;a&&"error"===a.status&&(i=!0,s={ename:a.ename,evalue:a.evalue,traceback:a.traceback});for(const e of n.allMessages){if("execute_error"===e.type){i=!0,s=e.data;break}"execute_result"===e.type&&(r=e.data)}if(this._status="active",super.emit(c.z.KERNEL_IDLE,{}),i){console.log("[KERNEL] Execution failed with error:",s);const e=s.ename?s.ename.replace(/^<class '(.+)'>$/,"$1"):s.ename;super.emit(c.z.EXECUTE_ERROR,{ename:e,evalue:s.evalue,traceback:s.traceback});const r=`${s.ename||"Error"}: ${s.evalue||"Unknown error"}`;t({success:!1,error:new Error(r),result:n.executionResult})}else{console.log(`[KERNEL] Execution successful, captured ${n.allMessages.length} output messages`);let e=void 0!==r?r:n.executionResult;t({success:!0,result:e})}};super.on(c.z.ALL,o),this._kernel.run(e).then(e=>{console.log("[KERNEL] Python execution finished, waiting for messages to settle"),n.executionResult=this.formatResult(e),setTimeout(()=>{i()},100)}).catch(e=>{console.error("[KERNEL] Python execution error:",e),n.executionError=e instanceof Error?e:new Error(String(e)),setTimeout(()=>{i()},100)})})}catch(e){return console.error("[KERNEL] Execute setup error:",e),this._status="active",super.emit(c.z.KERNEL_IDLE,{}),{success:!1,error:e instanceof Error?e:new Error(String(e))}}}formatResult(e){if(!(e instanceof this.pyodide.ffi.PyProxy))return e;try{const t=e.toJs();return this.mapToObject(t)}catch(e){return console.error("Error formatting result:",e),{status:"error",error:String(e)}}}mapToObject(e){const t=e instanceof Array?[]:{};return e.forEach((e,r)=>{t[r]=e instanceof Map||e instanceof Array?this.mapToObject(e):e}),t}async inputReply(e){this._resolveInputReply&&(this._resolveInputReply(e),this._resolveInputReply=null)}async sendInputRequest(e,t){const r={prompt:e,password:t};this._sendMessage({type:"input_request",content:r,parentHeader:this.formatResult(this._parent_header).header})}async getpass(e){e=void 0===e?"":e,await this.sendInputRequest(e,!0);const t=new Promise(e=>{this._resolveInputReply=e});return(await t).value}async input(e){e=void 0===e?"":e,await this.sendInputRequest(e,!1);const t=new Promise(e=>{this._resolveInputReply=e});return(await t).value}async sendComm(e,t,r,n,o){this._sendMessage({type:e,content:this.formatResult(t),metadata:this.formatResult(r),ident:this.formatResult(n),buffers:this.formatResult(o),parentHeader:this.formatResult(this._parent_header).header})}async complete(e,t,r={}){await this.setup(r);const n=this._kernel.complete(e,t);return this.formatResult(n)}async inspect(e,t,r,n={}){await this.setup(n);const o=this._kernel.inspect(e,t,r);return this.formatResult(o)}async isComplete(e,t={}){await this.setup(t);const r=this._kernel.is_complete(e);return this.formatResult(r)}async commInfo(e,t={}){await this.setup(t);const r=this._kernel.comm_info(e);return{comms:this.formatResult(r),status:"ok"}}async commOpen(e,t={}){await this.setup(t);const r=this._kernel.comm_manager.comm_open(this.pyodide.toPy(null),this.pyodide.toPy(null),this.pyodide.toPy(e));return this.formatResult(r)}async commMsg(e,t={}){await this.setup(t);const r=this._kernel.comm_manager.comm_msg(this.pyodide.toPy(null),this.pyodide.toPy(null),this.pyodide.toPy(e));return this.formatResult(r)}async commClose(e,t={}){await this.setup(t);const r=this._kernel.comm_manager.comm_close(this.pyodide.toPy(null),this.pyodide.toPy(null),this.pyodide.toPy(e));return this.formatResult(r)}async*executeStream(e,t={}){try{await this.initialize();const r=[],n=e=>{r.push(e)};super.on(c.z.ALL,n);try{const n=this.execute(e,t);for(;;)if(r.length>0&&(yield r.shift()),await Promise.race([n.then(()=>!0),new Promise(e=>setTimeout(()=>e(!1),10))])){for(;r.length>0;)yield r.shift();return await n}}catch(e){throw console.error("Error in executeStream:",e),e}finally{super.off(c.z.ALL,n)}}catch(e){return console.error("Error in executeStream setup:",e),{success:!1,error:e instanceof Error?e:new Error(String(e))}}}async interrupt(){if(!this.initialized||!this.pyodide)return console.warn("[KERNEL] Cannot interrupt: kernel not initialized"),!1;console.log("[KERNEL] Attempting to interrupt execution...");try{if(this._interruptBuffer&&this._interruptSupported&&(console.log("[KERNEL] Using interrupt buffer method"),this._interruptBuffer[0]=2,await new Promise(e=>setTimeout(e,100)),0===this._interruptBuffer[0]))return console.log("[KERNEL] Interrupt processed successfully via buffer"),!0;try{return console.log("[KERNEL] Attempting Python-level interrupt"),await this.pyodide.runPythonAsync("\nimport sys\nimport _thread\n# Try to interrupt the main thread\n_thread.interrupt_main()\n"),console.log("[KERNEL] Python interrupt signal sent"),!0}catch(e){console.log("[KERNEL] Python interrupt attempt failed:",e)}return this._interpreter&&"function"==typeof this._interpreter.interrupt?(console.log("[KERNEL] Using interpreter interrupt method"),this._interpreter.interrupt(),!0):(console.log("[KERNEL] Sending interrupt messages for UI feedback"),this._sendMessage({type:"stream",bundle:{name:"stderr",text:"KeyboardInterrupt: Execution interrupted by user\n"}}),this._sendMessage({type:"execute_error",bundle:{ename:"KeyboardInterrupt",evalue:"Execution interrupted by user",traceback:["KeyboardInterrupt: Execution interrupted by user"]}}),!1)}catch(e){return console.error("[KERNEL] Error during interrupt:",e),!1}}setInterruptBuffer(e){this._interruptBuffer=e;try{this.pyodide&&"function"==typeof this.pyodide.setInterruptBuffer?(this.pyodide.setInterruptBuffer(e),this._interruptSupported=!0):(console.warn("[KERNEL] pyodide.setInterruptBuffer not available, interrupt support limited"),this._interruptSupported=!1)}catch(e){console.error("[KERNEL] Error setting interrupt buffer:",e),this._interruptSupported=!1}}async setEnvironmentVariables(){if(0===Object.keys(this.environmentVariables).length)return;const e=Date.now();console.log(`🌍 Setting ${Object.keys(this.environmentVariables).length} environment variables...`);try{for(const[e,t]of Object.entries(this.environmentVariables)){let r;r=null==t?"":String(t),await this.pyodide.runPythonAsync(`\nimport os\nos.environ[${JSON.stringify(e)}] = ${JSON.stringify(r)}\n`)}const t=Date.now()-e;console.log(`⚡ Environment variables set in ${t}ms`)}catch(e){throw console.error("❌ Failed to set environment variables:",e),e}}}return n})());
//# sourceMappingURL=web-python-kernel.min.js.map
/*! For license information please see web-python-kernel.min.mjs.LICENSE.txt */
var e={590:(e,t,r)=>{r.d(t,{LV:()=>d,p:()=>u});const n=Symbol("Comlink.proxy"),o=Symbol("Comlink.endpoint"),s=Symbol("Comlink.releaseProxy"),i=Symbol("Comlink.finalizer"),a=Symbol("Comlink.thrown"),l=e=>"object"==typeof e&&null!==e||"function"==typeof e,c=new Map([["proxy",{canHandle:e=>l(e)&&e[n],serialize(e){const{port1:t,port2:r}=new MessageChannel;return u(e,t),[r,[r]]},deserialize:e=>(e.start(),d(e))}],["throw",{canHandle:e=>l(e)&&a in e,serialize({value:e}){let t;return t=e instanceof Error?{isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:{isError:!1,value:e},[t,[]]},deserialize(e){if(e.isError)throw Object.assign(new Error(e.value.message),e.value);throw e.value}}]]);function u(e,t=globalThis,r=["*"]){t.addEventListener("message",function o(s){if(!s||!s.data)return;if(!function(e,t){for(const r of e){if(t===r||"*"===r)return!0;if(r instanceof RegExp&&r.test(t))return!0}return!1}(r,s.origin))return void console.warn(`Invalid origin '${s.origin}' for comlink proxy`);const{id:l,type:c,path:d}=Object.assign({path:[]},s.data),m=(s.data.argumentList||[]).map(R);let h;try{const t=d.slice(0,-1).reduce((e,t)=>e[t],e),r=d.reduce((e,t)=>e[t],e);switch(c){case"GET":h=r;break;case"SET":t[d.slice(-1)[0]]=R(s.data.value),h=!0;break;case"APPLY":h=r.apply(t,m);break;case"CONSTRUCT":h=function(e){return Object.assign(e,{[n]:!0})}(new r(...m));break;case"ENDPOINT":{const{port1:t,port2:r}=new MessageChannel;u(e,r),h=function(e,t){return w.set(e,t),e}(t,[t])}break;case"RELEASE":h=void 0;break;default:return}}catch(e){h={value:e,[a]:0}}Promise.resolve(h).catch(e=>({value:e,[a]:0})).then(r=>{const[n,s]=k(r);t.postMessage(Object.assign(Object.assign({},n),{id:l}),s),"RELEASE"===c&&(t.removeEventListener("message",o),p(t),i in e&&"function"==typeof e[i]&&e[i]())}).catch(e=>{const[r,n]=k({value:new TypeError("Unserializable return value"),[a]:0});t.postMessage(Object.assign(Object.assign({},r),{id:l}),n)})}),t.start&&t.start()}function p(e){(function(e){return"MessagePort"===e.constructor.name})(e)&&e.close()}function d(e,t){const r=new Map;return e.addEventListener("message",function(e){const{data:t}=e;if(!t||!t.id)return;const n=r.get(t.id);if(n)try{n(t)}finally{r.delete(t.id)}}),g(e,r,[],t)}function m(e){if(e)throw new Error("Proxy has been released and is not useable")}function h(e){return x(e,new Map,{type:"RELEASE"}).then(()=>{p(e)})}const f=new WeakMap,y="FinalizationRegistry"in globalThis&&new FinalizationRegistry(e=>{const t=(f.get(e)||0)-1;f.set(e,t),0===t&&h(e)});function g(e,t,r=[],n=function(){}){let i=!1;const a=new Proxy(n,{get(n,o){if(m(i),o===s)return()=>{!function(e){y&&y.unregister(e)}(a),h(e),t.clear(),i=!0};if("then"===o){if(0===r.length)return{then:()=>a};const n=x(e,t,{type:"GET",path:r.map(e=>e.toString())}).then(R);return n.then.bind(n)}return g(e,t,[...r,o])},set(n,o,s){m(i);const[a,l]=k(s);return x(e,t,{type:"SET",path:[...r,o].map(e=>e.toString()),value:a},l).then(R)},apply(n,s,a){m(i);const l=r[r.length-1];if(l===o)return x(e,t,{type:"ENDPOINT"}).then(R);if("bind"===l)return g(e,t,r.slice(0,-1));const[c,u]=E(a);return x(e,t,{type:"APPLY",path:r.map(e=>e.toString()),argumentList:c},u).then(R)},construct(n,o){m(i);const[s,a]=E(o);return x(e,t,{type:"CONSTRUCT",path:r.map(e=>e.toString()),argumentList:s},a).then(R)}});return function(e,t){const r=(f.get(t)||0)+1;f.set(t,r),y&&y.register(e,t,e)}(a,e),a}function E(e){const t=e.map(k);return[t.map(e=>e[0]),(r=t.map(e=>e[1]),Array.prototype.concat.apply([],r))];var r}const w=new WeakMap;function k(e){for(const[t,r]of c)if(r.canHandle(e)){const[n,o]=r.serialize(e);return[{type:"HANDLER",name:t,value:n},o]}return[{type:"RAW",value:e},w.get(e)||[]]}function R(e){switch(e.type){case"HANDLER":return c.get(e.name).deserialize(e.value);case"RAW":return e.value}}function x(e,t,r,n){return new Promise(o=>{const s=new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-");t.set(s,o),e.start&&e.start(),e.postMessage(Object.assign({id:s},r),n)})}},637:(e,t,r)=>{r.d(t,{MB:()=>m,zZ:()=>l.z,y9:()=>a,dR:()=>p,J9:()=>i});const n="https://cdn.jsdelivr.net/pyodide/v0.28.0/full/pyodide.js";let o=!1,s=null;var i,a,l=r(696),c=r(590);class u{constructor(){this.events={}}on(e,t){this.events[e]||(this.events[e]=[]),this.events[e].push(t)}off(e,t){if(!this.events[e])return;const r=this.events[e].indexOf(t);r>-1&&this.events[e].splice(r,1)}removeListener(e,t){this.off(e,t)}emit(e,...t){this.events[e]&&this.events[e].forEach(e=>e(...t))}setMaxListeners(e){}}!function(e){e.MAIN_THREAD="main_thread",e.WORKER="worker"}(i||(i={})),function(e){e.PYTHON="python"}(a||(a={}));class p extends u{isKeyboardInterrupt(e){return e&&"object"==typeof e&&("type"in e&&"KeyboardInterrupt"===e.type||"message"in e&&"string"==typeof e.message&&e.message.includes("KeyboardInterrupt"))}createKeyboardInterruptResult(){return{success:!1,error:new Error("KeyboardInterrupt: Execution interrupted by user"),result:{status:"error",ename:"KeyboardInterrupt",evalue:"Execution interrupted by user",traceback:["KeyboardInterrupt: Execution interrupted by user"]}}}storeAbortController(e,t,r){this.abortControllers.has(e)||this.abortControllers.set(e,new Map),this.abortControllers.get(e).set(t,r)}removeAbortController(e,t){const r=this.abortControllers.get(e);if(!r)return;const n=r.get(t);return n&&(r.delete(t),0===r.size&&this.abortControllers.delete(e)),n}abortAllKernelOperations(e){const t=this.abortControllers.get(e);if(t){for(const[r,n]of t)try{n.abort(),console.log(`🚫 Aborted execution ${r} for kernel ${e}`)}catch(e){console.warn(`⚠️ Error aborting execution ${r}:`,e)}this.abortControllers.delete(e)}}constructor(e={}){super(),this.kernels=new Map,this.listenerWrappers=new Map,this.lastActivityTime=new Map,this.inactivityTimers=new Map,this.ongoingExecutions=new Map,this.executionTimeouts=new Map,this.executionStartTimes=new Map,this.executionMetadata=new Map,this.abortControllers=new Map,this.pool=new Map,this.isPreloading=!1,this.prefillingInProgress=new Map,this.interruptBuffers=new Map,super.setMaxListeners(100),this.allowedKernelTypes=e.allowedKernelTypes||[{mode:i.WORKER,language:a.PYTHON}];const t=this.allowedKernelTypes.filter(e=>e.language===a.PYTHON);this.poolConfig={enabled:!1,poolSize:2,autoRefill:!0,preloadConfigs:t,...e.pool},this.poolConfig.preloadConfigs&&(this.poolConfig.preloadConfigs=this.poolConfig.preloadConfigs.filter(e=>{const t=this.isKernelTypeAllowed(e.mode,e.language);return t||console.warn(`Pool preload config ${e.mode}-${e.language} is not in allowedKernelTypes, skipping`),t})),this.poolConfig.enabled&&this.preloadPool().catch(e=>{console.error("Error preloading kernel pool:",e)})}getPoolKey(e,t){return`${e}-${t}`}getFromPool(e,t){if(!this.poolConfig.enabled)return null;const r=this.getPoolKey(e,t),n=this.pool.get(r);if(!n||0===n.length)return null;const o=n.shift();return this.poolConfig.autoRefill&&setTimeout(()=>{this.refillPoolSingle(e,t).catch(e=>{console.error(`Error refilling single kernel for ${r}:`,e)})},0),o}addToPool(e,t,r){if(!this.poolConfig.enabled)return;const n=this.getPoolKey(e,t);this.pool.has(n)||this.pool.set(n,[]);const o=this.pool.get(n);o.length<this.poolConfig.poolSize?(o.push(r),r.catch(e=>{console.error(`Pool kernel promise rejected for ${n}:`,e);const t=o.indexOf(r);-1!==t&&o.splice(t,1)})):r.then(e=>{e.destroy().catch(e=>{console.error("Error destroying excess pool kernel:",e)})}).catch(e=>{console.error("Excess pool kernel promise rejected:",e)})}async refillPoolSingle(e,t){if(!this.poolConfig.enabled)return;const r=this.getPoolKey(e,t);if((this.pool.get(r)||[]).length<this.poolConfig.poolSize){const r=this.createPoolKernelPromise(e,t);this.addToPool(e,t,r)}}async refillPool(e,t){if(!this.poolConfig.enabled)return;const r=this.getPoolKey(e,t);if(!this.prefillingInProgress.get(r)){this.prefillingInProgress.set(r,!0);try{const n=this.pool.get(r)||[],o=this.poolConfig.poolSize-n.length;if(o<=0)return;const s=Array.from({length:o},()=>this.createPoolKernelPromise(e,t));for(const r of s)this.addToPool(e,t,r)}catch(e){console.error(`Error refilling pool for ${r}:`,e)}finally{this.prefillingInProgress.set(r,!1)}}}createPoolKernelPromise(e,t){return new Promise(async(r,n)=>{try{const n=await this.createPoolKernel(e,t);n.isFromPool=!0,r(n)}catch(r){console.error(`Error creating pool kernel for ${e}-${t}:`,r),n(r)}})}async createPoolKernel(e,t){const r=`pool-${crypto.randomUUID()}`,n={mode:e,lang:t};let o;try{if(e===i.MAIN_THREAD){const s={id:r,options:n,mode:e,language:t};this.kernels.set(r,s);try{o=await this.createMainThreadKernel(r)}finally{this.kernels.delete(r)}}else{const s={id:r,options:n,mode:e,language:t};this.kernels.set(r,s);try{o=await this.createWorkerKernel(r)}finally{this.kernels.delete(r)}}}catch(e){throw this.kernels.delete(r),e}return o}async preloadPool(){if(this.poolConfig.enabled&&!this.isPreloading){this.isPreloading=!0;try{for(const e of this.poolConfig.preloadConfigs)try{await this.refillPool(e.mode,e.language)}catch(t){console.error(`Error preloading ${e.mode}-${e.language}:`,t)}}catch(e){console.error("Error during kernel pool preloading:",e)}finally{this.isPreloading=!1}}}canUsePool(e){return!!this.poolConfig.enabled&&!e.filesystem&&!e.deno?.permissions&&void 0===e.inactivityTimeout&&void 0===e.maxExecutionTime}reassignPoolKernel(e,t,r){const n={id:t,kernel:e.kernel,mode:e.mode,language:e.language,worker:e.worker,created:new Date,options:{...e.options,...r},isFromPool:!0,destroy:e.destroy};if("function"!=typeof n.destroy)throw console.error("Failed to preserve destroy function during pool kernel reassignment"),console.error("poolKernel.destroy type:",typeof e.destroy),console.error("updatedInstance.destroy type:",typeof n.destroy),new Error("Failed to preserve destroy function during pool kernel reassignment");return n}getPoolStats(){const e={};for(const[t,r]of this.pool.entries())e[t]={available:r.length,total:this.poolConfig.poolSize};return e}getPoolConfig(){return{enabled:this.poolConfig.enabled,poolSize:this.poolConfig.poolSize,autoRefill:this.poolConfig.autoRefill,preloadConfigs:[...this.poolConfig.preloadConfigs],isPreloading:this.isPreloading}}async createKernel(e={}){if(e.id&&e.id.includes(":"))throw new Error("Kernel ID cannot contain colons");const t=e.id||crypto.randomUUID(),r=e.mode||i.WORKER,n=e.lang||a.PYTHON;if(!this.isKernelTypeAllowed(r,n))throw new Error(`Kernel type ${r}-${n} is not allowed. Allowed types: ${this.allowedKernelTypes.map(e=>`${e.mode}-${e.language}`).join(", ")}`);const o=e.namespace?`${e.namespace}:${t}`:t;if(this.kernels.has(o))throw new Error(`Kernel with ID ${o} already exists`);if(this.canUsePool(e)){const t=this.getPoolKey(r,n);if(this.poolConfig.preloadConfigs.some(e=>e.mode===r&&e.language===n)){let s=this.getFromPool(r,n);if(s)return await this.setupPoolKernelFromPromise(s,o,e);try{const s=this.createPoolKernelPromise(r,n);return this.poolConfig.autoRefill&&setTimeout(()=>{this.refillPool(r,n).catch(e=>{console.error(`Error refilling exhausted pool for ${t}:`,e)})},0),await this.setupPoolKernelFromPromise(s,o,e)}catch(e){console.error(`Failed to create kernel promise for exhausted pool: ${e}`)}}else{const t=this.getFromPool(r,n);if(t)return await this.setupPoolKernelFromPromise(t,o,e)}}return this.createOnDemandKernel(o,r,n,e)}async setupPoolKernelFromPromise(e,t,r){try{const n=await e,o=this.reassignPoolKernel(n,t,r);if(o.mode===i.WORKER&&o.worker){const e=o.worker,{port1:r,port2:n}=new MessageChannel;e.postMessage({type:"SET_EVENT_PORT",port:n},[n]);const s=e=>{e.data&&e.data.type&&super.emit(e.data.type,{kernelId:t,data:e.data.data})};r.addEventListener("message",s),r.start();const i=o.destroy;o.destroy=async()=>(r.removeEventListener("message",s),r.close(),i())}return this.kernels.set(t,o),this.setupEventForwarding(o),this.updateKernelActivity(t),r.inactivityTimeout&&r.inactivityTimeout>0&&this.setupInactivityTimeout(t,r.inactivityTimeout),r.maxExecutionTime&&r.maxExecutionTime>0&&this.setupStalledExecutionHandler(t),t}catch(e){throw console.error(`Error setting up pool kernel ${t}:`,e),super.emit(l.z.EXECUTE_ERROR,{kernelId:t,data:{ename:"KernelSetupError",evalue:`Failed to setup kernel: ${e instanceof Error?e.message:String(e)}`,traceback:[e instanceof Error?e.stack||e.message:String(e)]}}),e}}setupPoolKernel(e,t,r){const n=this.reassignPoolKernel(e,t,r);if(n.mode===i.WORKER&&n.worker){const e=n.worker,{port1:r,port2:o}=new MessageChannel;e.postMessage({type:"SET_EVENT_PORT",port:o},[o]);const s=e=>{e.data&&e.data.type&&super.emit(e.data.type,{kernelId:t,data:e.data.data})};r.addEventListener("message",s),r.start();const i=n.destroy;n.destroy=async()=>(r.removeEventListener("message",s),r.close(),i())}return this.kernels.set(t,n),this.setupEventForwarding(n),this.updateKernelActivity(t),r.inactivityTimeout&&r.inactivityTimeout>0&&this.setupInactivityTimeout(t,r.inactivityTimeout),r.maxExecutionTime&&r.maxExecutionTime>0&&this.setupStalledExecutionHandler(t),t}async createOnDemandKernel(e,t,r,n){const o={id:e,options:{...n,lang:r},mode:t,language:r};let s;return this.kernels.set(e,o),s=t===i.MAIN_THREAD?await this.createMainThreadKernel(e):await this.createWorkerKernel(e),this.kernels.set(e,s),this.setupEventForwarding(s),this.updateKernelActivity(e),n.inactivityTimeout&&n.inactivityTimeout>0&&this.setupInactivityTimeout(e,n.inactivityTimeout),n.maxExecutionTime&&n.maxExecutionTime>0&&this.setupStalledExecutionHandler(e),e}async createMainThreadKernel(e){const t=this.kernels.get(e)?.options||{},r=t.lang||a.PYTHON,n=new m,o={id:e,kernel:n,mode:i.MAIN_THREAD,language:r,created:new Date,options:t,destroy:async()=>Promise.resolve()},s={};return t.filesystem&&(s.filesystem=t.filesystem),t.env&&(s.env=t.env),t.lockFileURL&&(s.lockFileURL=t.lockFileURL),await n.initialize(s),o}async createWorkerKernel(e){const t=this.kernels.get(e)?.options||{},n=t.lang||a.PYTHON;t.deno?.permissions&&t.deno.permissions;const o=r(757),s=o.default?new o.default:new o,{port1:l,port2:u}=new MessageChannel,p=new Promise((e,t)=>{const r=n=>{"KERNEL_INITIALIZED"===n.data?.type&&(n.data.data.success?(l.removeEventListener("message",r),e()):(l.removeEventListener("message",r),t(new Error("Kernel initialization failed"))))};l.addEventListener("message",r)});s.postMessage({type:"SET_EVENT_PORT",port:u},[u]);const d=c.LV(s),m=t=>{t.data&&t.data.type&&super.emit(t.data.type,{kernelId:e,data:t.data.data})};return l.addEventListener("message",m),l.start(),s.postMessage({type:"INITIALIZE_KERNEL",options:{filesystem:t.filesystem,env:t.env,lockFileURL:t.lockFileURL,lang:n}}),await p,await this.setupWorkerInterruptBuffer(e,s),{id:e,kernel:{initialize:async e=>d.initialize(e),execute:async(e,t)=>await d.execute(e,t),isInitialized:()=>d.isInitialized(),inputReply:async e=>d.inputReply(e),getStatus:async()=>{try{return"function"==typeof d.getStatus?await d.getStatus():"unknown"}catch(e){return"unknown"}},complete:async(e,t,r)=>{try{return"function"==typeof d.complete?await d.complete(e,t,r):{status:"error",error:"Completion not supported"}}catch(e){return{status:"error",error:String(e)}}},inspect:async(e,t,r,n)=>{try{return"function"==typeof d.inspect?await d.inspect(e,t,r,n):{status:"error",error:"Inspection not supported"}}catch(e){return{status:"error",error:String(e)}}},isComplete:async(e,t)=>{try{return"function"==typeof d.isComplete?await d.isComplete(e,t):{status:"unknown"}}catch(e){return{status:"error",error:String(e)}}},interrupt:async()=>{try{return"function"==typeof d.interrupt&&await d.interrupt()}catch(e){return!1}},setInterruptBuffer:e=>{try{"function"==typeof d.setInterruptBuffer&&d.setInterruptBuffer(e)}catch(e){console.warn("Failed to set interrupt buffer:",e)}},commInfo:async(e,t)=>{try{return"function"==typeof d.commInfo?await d.commInfo(e,t):{comms:{},status:"ok"}}catch(e){return{comms:{},status:"error",error:String(e)}}},commOpen:async(e,t)=>{try{if("function"==typeof d.commOpen)return await d.commOpen(e,t)}catch(e){console.warn("Failed to open comm:",e)}},commMsg:async(e,t)=>{try{if("function"==typeof d.commMsg)return await d.commMsg(e,t)}catch(e){console.warn("Failed to send comm message:",e)}},commClose:async(e,t)=>{try{if("function"==typeof d.commClose)return await d.commClose(e,t)}catch(e){console.warn("Failed to close comm:",e)}}},mode:i.WORKER,language:n,worker:s,created:new Date,options:t,destroy:async()=>(l.removeEventListener("message",m),l.close(),s.terminate(),Promise.resolve())}}setupEventForwarding(e){e.mode===i.MAIN_THREAD&&Object.values(l.z).forEach(t=>{e.kernel.on(t,r=>{super.emit(t,{kernelId:e.id,data:r})})})}getKernel(e){return this.kernels.get(e)}getKernelIds(){return Array.from(this.kernels.keys())}async listKernels(e){const t=Array.from(this.kernels.entries()).filter(([t])=>!t.startsWith("pool-")&&(!e||t.startsWith(`${e}:`)));return await Promise.all(t.map(async([e,t])=>{const r=e.match(/^([^:]+):/),n=r?r[1]:void 0;let o="unknown";try{t&&t.kernel&&"function"==typeof t.kernel.getStatus&&(o=await t.kernel.getStatus())}catch(t){console.warn(`Error getting status for kernel ${e}:`,t),o="unknown"}return{id:e,mode:t.mode,language:t.language,status:o,created:t.created||new Date,namespace:n,deno:t.options?.deno}}))}async destroyKernel(e){const t=this.kernels.get(e);if(t){if("function"!=typeof t.destroy)throw new Error(`Kernel ${e} is missing destroy function (type: ${typeof t.destroy})`);if(this.abortAllKernelOperations(e),this.clearInactivityTimeout(e),this.executionTimeouts.has(e)){const t=this.executionTimeouts.get(e);for(const e of t.values())clearTimeout(e);this.executionTimeouts.delete(e)}this.executionStartTimes.has(e)&&this.executionStartTimes.delete(e),this.executionMetadata.has(e)&&this.executionMetadata.delete(e),this.interruptBuffers.has(e)&&this.interruptBuffers.delete(e),this.ongoingExecutions.delete(e),this.lastActivityTime.delete(e),this.removeAllKernelListeners(e),await t.destroy(),this.kernels.delete(e)}}async destroyAll(e){const t=Array.from(this.kernels.keys()).filter(t=>!e||t.startsWith(`${e}:`)).map(async e=>{const t=this.kernels.get(e);return t&&"function"==typeof t.destroy?this.destroyKernel(e):(console.warn(`Skipping incomplete kernel instance ${e} during destroyAll`),void this.kernels.delete(e))});await Promise.all(t),e||await this.destroyPool()}async destroyPool(){const e=[];for(const[t,r]of this.pool.entries())for(const t of r){const r=t.then(e=>e.destroy()).catch(e=>{console.error("Error destroying pool kernel from promise:",e)});e.push(r)}await Promise.all(e),this.pool.clear(),this.prefillingInProgress.clear()}onKernelEvent(e,t,r){if(!this.kernels.has(e))throw new Error(`Kernel with ID ${e} not found`);const n={original:r,wrapped:t=>{t.kernelId===e&&r(t.data)}};this.storeListener(e,t,r,n),super.on(t,n.wrapped)}offKernelEvent(e,t,r){const n=this.getListener(e,t,r);n&&(super.removeListener(t,n.wrapped),this.removeStoredListener(e,t,r))}storeListener(e,t,r,n){this.listenerWrappers.has(e)||this.listenerWrappers.set(e,new Map);const o=this.listenerWrappers.get(e);o.has(t)||o.set(t,new Map),o.get(t).set(r,n)}getListener(e,t,r){const n=this.listenerWrappers.get(e);if(!n)return;const o=n.get(t);return o?o.get(r):void 0}removeStoredListener(e,t,r){const n=this.listenerWrappers.get(e);if(!n)return;const o=n.get(t);o&&(o.delete(r),0===o.size&&n.delete(t),0===n.size&&this.listenerWrappers.delete(e))}removeAllKernelListeners(e){const t=this.listenerWrappers.get(e);if(t){for(const[e,r]of t.entries())for(const t of r.values())super.removeListener(e,t.wrapped);this.listenerWrappers.delete(e)}}getListeners(e,t){const r=this.listenerWrappers.get(e);if(!r)return[];const n=r.get(t);return n?Array.from(n.keys()):[]}async*executeStream(e,t,r={}){const n=this.getKernel(e);if(!n)throw new Error(`Kernel with ID ${e} not found`);this.updateKernelActivity(e);const o=this.trackExecution(e,t),s=new AbortController;this.storeAbortController(e,o,s);try{if(n.mode===i.MAIN_THREAD){const s=n.kernel;if("function"==typeof s.executeStream)try{return yield*s.executeStream(t,r),this.updateKernelActivity(e),this.completeExecution(e,o),{success:!0}}catch(t){return console.error("Error in main thread executeStream:",t),this.updateKernelActivity(e),this.completeExecution(e,o),{success:!1,error:t instanceof Error?t:new Error(String(t))}}}try{const i=[];let a=!1,c={success:!0};const u=new Map,p=()=>{for(const[e,t]of u.entries())super.off(e,t);u.clear()},d=t=>{const r=r=>{r.kernelId!==e||a||(i.push({type:t,data:r.data,executionId:o}),this.updateKernelActivity(e))};return u.set(t,r),r},m=d("stream"),h=d("display_data"),f=d("update_display_data"),y=d("execute_result"),g=d("execute_error");super.on(l.z.STREAM,m),super.on(l.z.DISPLAY_DATA,h),super.on(l.z.UPDATE_DISPLAY_DATA,f),super.on(l.z.EXECUTE_RESULT,y),super.on(l.z.EXECUTE_ERROR,g);const E=new Promise((p,d)=>{const m=t=>{t.kernelId!==e||a||(a=!0,c={success:!1,error:new Error(`${t.data.ename}: ${t.data.evalue}`),result:t.data},this.updateKernelActivity(e),p(c))};if(u.set("execute_error_completion",m),super.on(l.z.EXECUTE_ERROR,m),s.signal.aborted)return a=!0,void p({success:!1,error:new Error("Execution was aborted")});s.signal.addEventListener("abort",()=>{a||(console.log(`🚫 Execution ${o} aborted`),a=!0,p({success:!1,error:new Error("Execution was aborted")}))});try{n.kernel.execute(t,r).then(t=>{if(!a){if(t.success&&t.result&&"error"===t.result.status){const e={status:t.result.status,ename:t.result.ename,evalue:t.result.evalue,traceback:t.result.traceback};i.push({type:"error",data:e,executionId:o}),c={success:!1,error:new Error(`${t.result.ename}: ${t.result.evalue}`),result:t.result}}else c=t;a=!0,this.updateKernelActivity(e),p(c)}}).catch(t=>{if(!a){let r;console.error(`Error in execute for kernel ${e}:`,t),this.isKeyboardInterrupt(t)?(console.log(`KeyboardInterrupt caught in executeStream for kernel ${e}`),r=this.createKeyboardInterruptResult(),i.push({type:"error",data:r.result,executionId:o})):r={success:!1,error:t instanceof Error?t:new Error(String(t))},a=!0,c=r,this.updateKernelActivity(e),p(r)}})}catch(t){if(!a){console.error(`Error calling execute for kernel ${e}:`,t);const r={success:!1,error:t instanceof Error?t:new Error(String(t))};a=!0,c=r,this.updateKernelActivity(e),p(r)}}});try{for(;(!a||i.length>0)&&!s.signal.aborted;){if(i.length>0){const e=i.shift();yield e;continue}if(!a)try{await new Promise((e,t)=>{const r=setTimeout(e,10);s.signal.addEventListener("abort",()=>{clearTimeout(r),t(new Error("Aborted"))})})}catch(e){if(s.signal.aborted)break}}if(s.signal.aborted&&!a)throw new Error("Execution was aborted during stream monitoring");return await E}finally{p(),this.removeAbortController(e,o),this.completeExecution(e,o)}}catch(t){return this.completeExecution(e,o),console.error("Unexpected error in executeStream:",t),{success:!1,error:t instanceof Error?t:new Error(String(t))}}}catch(t){return this.completeExecution(e,o),console.error("Unexpected error in executeStream:",t),{success:!1,error:t instanceof Error?t:new Error(String(t))}}}trackExecution(e,t){const r=`exec-${crypto.randomUUID()}`,n=Date.now(),o=this.kernels.get(e);if(o&&o.mode===i.WORKER&&this.interruptBuffers.has(e)&&(this.interruptBuffers.get(e)[0]=0),this.ongoingExecutions.has(e)||this.ongoingExecutions.set(e,new Set),this.ongoingExecutions.get(e).add(r),this.executionStartTimes.has(e)||this.executionStartTimes.set(e,new Map),this.executionStartTimes.get(e).set(r,n),this.executionMetadata.has(e)||this.executionMetadata.set(e,new Map),this.updateKernelActivity(e),o&&o.options.maxExecutionTime&&o.options.maxExecutionTime>0){this.executionTimeouts.has(e)||this.executionTimeouts.set(e,new Map);const s=setTimeout(()=>{console.warn(`Execution ${r} on kernel ${e} has been running for ${o.options.maxExecutionTime}ms and may be stuck/dead.`);const s=this.executionMetadata.get(e)?.get(r),i=Date.now()-(s?.startTime||n);super.emit("execution_stalled",{kernelId:e,executionId:r,maxExecutionTime:o.options.maxExecutionTime,actualRuntime:i,code:s?.code||t,startTime:s?.startTime||n}),this.handleStuckExecution(e,r,i,s?.code||t)},o.options.maxExecutionTime);this.executionTimeouts.get(e).set(r,s),this.executionMetadata.get(e).set(r,{startTime:n,code:t,timeoutId:s})}else this.executionMetadata.get(e).set(r,{startTime:n,code:t});return r}completeExecution(e,t){if(this.executionTimeouts.has(e)){const r=this.executionTimeouts.get(e);r.has(t)&&(clearTimeout(r.get(t)),r.delete(t)),0===r.size&&this.executionTimeouts.delete(e)}if(this.executionStartTimes.has(e)){const r=this.executionStartTimes.get(e);r.delete(t),0===r.size&&this.executionStartTimes.delete(e)}if(this.executionMetadata.has(e)){const r=this.executionMetadata.get(e);r.delete(t),0===r.size&&this.executionMetadata.delete(e)}if(this.ongoingExecutions.has(e)){const r=this.ongoingExecutions.get(e);r.delete(t),0===r.size&&(this.ongoingExecutions.delete(e),this.updateKernelActivity(e))}}hasOngoingExecutions(e){return this.ongoingExecutions.has(e)&&this.ongoingExecutions.get(e).size>0}getOngoingExecutionCount(e){return this.ongoingExecutions.has(e)?this.ongoingExecutions.get(e).size:0}setupInactivityTimeout(e,t){if(t<=0)return;this.clearInactivityTimeout(e);const r=this.lastActivityTime.get(e)||Date.now(),n=Date.now()-r,o=Math.max(0,t-n);if(0===o)return this.hasOngoingExecutions(e)?void this.setupInactivityTimeout(e,t):void this.destroyKernel(e).catch(t=>{console.error(`Error destroying inactive kernel ${e}:`,t)});const s=setTimeout(()=>{this.hasOngoingExecutions(e)?this.setupInactivityTimeout(e,t):this.destroyKernel(e).catch(t=>{console.error(`Error destroying inactive kernel ${e}:`,t)})},o);this.inactivityTimers.set(e,s)}clearInactivityTimeout(e){if(this.inactivityTimers.has(e)){const t=this.inactivityTimers.get(e);clearTimeout(t),this.inactivityTimers.delete(e)}}updateKernelActivity(e){this.lastActivityTime.set(e,Date.now());const t=this.kernels.get(e);if(!t)return;const r=t.options.inactivityTimeout;r&&r>0&&this.setupInactivityTimeout(e,r)}getLastActivityTime(e){return this.lastActivityTime.get(e)}getInactivityTimeout(e){const t=this.kernels.get(e);if(t)return t.options.inactivityTimeout}setInactivityTimeout(e,t){const r=this.kernels.get(e);return!!r&&(r.options.inactivityTimeout=t,this.clearInactivityTimeout(e),t>0&&this.setupInactivityTimeout(e,t),!0)}getTimeUntilShutdown(e){const t=this.kernels.get(e);if(!t)return;const r=t.options.inactivityTimeout;if(!r||r<=0)return;const n=this.lastActivityTime.get(e);if(!n)return;const o=r-(Date.now()-n);return Math.max(0,o)}getInactivityTimers(){const e={};return this.inactivityTimers.forEach((t,r)=>{e[r]=t}),e}setupStalledExecutionHandler(e){super.on(l.z.EXECUTION_STALLED,t=>{t.kernelId===e&&(console.warn(`Handling stalled execution ${t.executionId} on kernel ${e} (running longer than ${t.maxExecutionTime}ms)`),this.kernels.get(e)&&super.emit(l.z.EXECUTE_ERROR,{kernelId:e,data:{ename:"ExecutionStalledError",evalue:`Execution stalled or potentially deadlocked (running > ${t.maxExecutionTime}ms)`,traceback:["Execution may be stuck in an infinite loop or deadlocked."]}}))})}async forceTerminateKernel(e,t="Force terminated due to stalled execution"){if(!this.kernels.get(e))return!1;try{return console.warn(`Force terminating kernel ${e}: ${t}`),super.emit(l.z.EXECUTE_ERROR,{kernelId:e,data:{ename:"KernelForcedTermination",evalue:t,traceback:["Kernel was forcefully terminated by the system."]}}),await this.destroyKernel(e),!0}catch(t){return console.error(`Error during forced termination of kernel ${e}:`,t),!1}}getExecutionInfo(e){const t=this.kernels.get(e);if(!t)return{count:0,isStuck:!1,executionIds:[],executions:[]};if(!t.options)return{count:0,isStuck:!1,executionIds:[],executions:[]};const r=this.ongoingExecutions.get(e)?Array.from(this.ongoingExecutions.get(e)):[],n=r.length,o=Date.now(),s=t.options.maxExecutionTime,i=[];let a,l=!1;const c=this.executionStartTimes.get(e),u=this.executionMetadata.get(e);for(const t of r){const r=c?.get(t),n=u?.get(t);if(void 0!==r){const e=o-r,c=void 0!==s&&e>s;i.push({id:t,startTime:r,runtime:e,code:n?.code,isStuck:c}),(void 0===a||e>a)&&(a=e),c&&(l=!0)}else console.warn(`No start time found for execution ${t} on kernel ${e}`),i.push({id:t,startTime:0,runtime:0,code:n?.code,isStuck:!1})}return i.sort((e,t)=>e.startTime-t.startTime),{count:n,isStuck:l,executionIds:r,longestRunningTime:a,executions:i}}async execute(e,t,r={}){const n=this.getKernel(e);if(!n)throw new Error(`Kernel with ID ${e} not found`);this.updateKernelActivity(e);const o=this.trackExecution(e,t);try{const s=await n.kernel.execute(t,r);return this.updateKernelActivity(e),this.completeExecution(e,o),s}catch(t){return this.updateKernelActivity(e),this.completeExecution(e,o),{success:!1,error:t instanceof Error?t:new Error(String(t))}}}isKernelTypeAllowed(e,t){return this.allowedKernelTypes.some(r=>r.mode===e&&r.language===t)}getAllowedKernelTypes(){return[...this.allowedKernelTypes]}pingKernel(e){return!!this.kernels.get(e)&&(this.updateKernelActivity(e),!0)}async restartKernel(e){const t=this.kernels.get(e);if(!t)return console.warn(`Cannot restart kernel ${e}: kernel not found`),!1;try{const r={mode:t.mode,language:t.language,options:{...t.options}};let n,o;if(e.includes(":")){const t=e.split(":");n=t[0],o=t[1]}else o=e;await this.destroyKernel(e);const s={id:o,mode:r.mode,lang:r.language,namespace:n,deno:r.options.deno,filesystem:r.options.filesystem,inactivityTimeout:r.options.inactivityTimeout,maxExecutionTime:r.options.maxExecutionTime},i=await this.createKernel(s);return i===e||(console.error(`Kernel restart failed: expected ID ${e}, got ${i}`),!1)}catch(t){return console.error(`Error restarting kernel ${e}:`,t),!1}}async interruptKernel(e){const t=this.kernels.get(e);if(!t)return console.warn(`Cannot interrupt kernel ${e}: kernel not found`),!1;try{return t.mode===i.WORKER&&t.worker?await this.interruptWorkerKernel(e,t):await this.interruptMainThreadKernel(e,t)}catch(t){return console.error(`Error interrupting kernel ${e}:`,t instanceof Error?t.message:String(t)),!1}}async interruptMainThreadKernel(e,t){throw new Error(`Main thread kernel ${e} does not support reliable interruption. Use worker kernels for interruptible execution.`)}async interruptWorkerKernel(e,t){try{const r=t.worker;if(!r)return console.error(`Worker not found for kernel ${e}`),!1;let n=this.interruptBuffers.get(e);if(!n)try{const t=new SharedArrayBuffer(1);n=new Uint8Array(t),n[0]=0,this.interruptBuffers.set(e,n),r.postMessage({type:"SET_INTERRUPT_BUFFER",buffer:n}),await new Promise((e,t)=>{const n=setTimeout(()=>{t(new Error("Timeout waiting for interrupt buffer setup"))},2e3),o=t=>{"INTERRUPT_BUFFER_SET"===t.data?.type&&(r.removeEventListener("message",o),clearTimeout(n),e())};r.addEventListener("message",o)}),console.log(`Interrupt buffer set up for kernel ${e}`)}catch(t){return console.warn(`Failed to create SharedArrayBuffer for kernel ${e}, falling back to message-based interrupt:`,t),await this.interruptWorkerKernelFallback(e,r)}console.log(`Setting interrupt signal for kernel ${e}...`),n[0]=2;let o=0;const s=50;for(;o<s&&0!==n[0];)await new Promise(e=>setTimeout(e,100)),o++;return 0===n[0]?(console.log(`Interrupt processed successfully for kernel ${e} after ${100*o}ms`),!0):(console.warn(`Interrupt signal not processed for kernel ${e} after ${100*s}ms`),!0)}catch(t){return console.error(`Error interrupting worker kernel ${e}:`,t),!1}}async interruptWorkerKernelFallback(e,t){return new Promise(r=>{const n=e=>{if("INTERRUPT_TRIGGERED"===e.data?.type){t.removeEventListener("message",n);const o=e.data.data?.success||!1;r(o)}};t.addEventListener("message",n),t.postMessage({type:"INTERRUPT_KERNEL"}),setTimeout(()=>{t.removeEventListener("message",n),console.warn(`Timeout waiting for interrupt response from kernel ${e}`),r(!1)},5e3)})}async handleStuckExecution(e,t,r,n){const o=this.kernels.get(e);if(o){if(console.warn(`Handling stuck execution ${t} on kernel ${e} (runtime: ${r}ms)`),await this.interruptKernel(e))return console.log(`Successfully interrupted kernel ${e}`),void super.emit(l.z.EXECUTE_ERROR,{kernelId:e,data:{ename:"ExecutionInterrupted",evalue:`Execution automatically interrupted after ${r}ms (exceeded maxExecutionTime)`,traceback:["Execution was automatically interrupted due to timeout.",`Runtime: ${r}ms`,`Max allowed: ${o.options.maxExecutionTime}ms`,n?`Code: ${n.substring(0,200)}${n.length>200?"...":""}`:"Code: <unknown>"]}});if(console.warn(`Interrupt failed for kernel ${e}, attempting restart...`),await this.restartKernel(e))return console.log(`Successfully restarted kernel ${e}`),void super.emit(l.z.EXECUTE_ERROR,{kernelId:e,data:{ename:"KernelRestarted",evalue:`Kernel automatically restarted due to stuck execution (runtime: ${r}ms)`,traceback:["Kernel was automatically restarted due to stuck execution.",`Runtime: ${r}ms`,`Max allowed: ${o.options.maxExecutionTime}ms`,"Interrupt attempt failed, kernel was restarted instead.",n?`Code: ${n.substring(0,200)}${n.length>200?"...":""}`:"Code: <unknown>"]}});console.error(`Restart failed for kernel ${e}, force terminating...`),await this.forceTerminateKernel(e,`Stuck execution could not be interrupted or restarted (runtime: ${r}ms)`)?console.log(`Successfully terminated kernel ${e}`):(console.error(`Failed to terminate kernel ${e} - manual intervention may be required`),super.emit("kernel_unrecoverable",{kernelId:e,executionId:t,actualRuntime:r,code:n,message:"Kernel is stuck and could not be recovered through interrupt, restart, or termination"}))}}getStuckExecutions(){const e=[],t=Date.now();for(const[r,n]of this.kernels.entries()){if(r.startsWith("pool-"))continue;if(!n.options?.maxExecutionTime||n.options.maxExecutionTime<=0)continue;const o=n.options.maxExecutionTime,s=this.executionStartTimes.get(r),i=this.executionMetadata.get(r),a=this.ongoingExecutions.get(r);if(a&&0!==a.size)for(const l of a){const a=s?.get(l);if(void 0===a)continue;const c=t-a;if(c>o){const t=i?.get(l);e.push({kernelId:r,executionId:l,startTime:a,runtime:c,maxAllowed:o,code:t?.code,kernelMode:n.mode,kernelLanguage:n.language})}}}return e.sort((e,t)=>t.runtime-e.runtime),e}async handleAllStuckExecutions(){const e=this.getStuckExecutions(),t=[];console.log(`Found ${e.length} stuck executions to handle`);const r=new Map;for(const t of e)r.has(t.kernelId)||r.set(t.kernelId,[]),r.get(t.kernelId).push(t);for(const[e,n]of r)try{const r=n[0];console.log(`Handling stuck kernel ${e} with ${n.length} stuck executions (primary: ${r.runtime}ms)`),await this.handleStuckExecution(e,r.executionId,r.runtime,r.code);for(const e of n)t.push({kernelId:e.kernelId,executionId:e.executionId,action:"interrupted",success:!0})}catch(r){console.error(`Error handling stuck executions for kernel ${e}:`,r);for(const e of n)t.push({kernelId:e.kernelId,executionId:e.executionId,action:"failed",success:!1,error:r instanceof Error?r.message:String(r)})}return t}async setupWorkerInterruptBuffer(e,t){try{const r=new SharedArrayBuffer(1),n=new Uint8Array(r);n[0]=0,this.interruptBuffers.set(e,n),t.postMessage({type:"SET_INTERRUPT_BUFFER",buffer:n}),await new Promise((e,r)=>{const n=setTimeout(()=>{r(new Error("Timeout waiting for interrupt buffer setup"))},5e3),o=r=>{"INTERRUPT_BUFFER_SET"===r.data?.type&&(t.removeEventListener("message",o),clearTimeout(n),e())};t.addEventListener("message",o)})}catch(t){console.warn(`Failed to set up interrupt buffer for kernel ${e}:`,t)}}}class d{constructor(){this.events={}}on(e,t){this.events[e]||(this.events[e]=[]),this.events[e].push(t)}off(e,t){if(!this.events[e])return;const r=this.events[e].indexOf(t);r>-1&&this.events[e].splice(r,1)}emit(e,...t){this.events[e]&&this.events[e].forEach(e=>e(...t))}setMaxListeners(e){}}class m extends d{constructor(){super(),this.initialized=!1,this.initPromise=null,this.filesystemOptions={enabled:!1,root:".",mountPoint:"/home/pyodide"},this._resolveInputReply=null,this._parent_header={},this.executionCount=0,this._status="unknown",this._interruptBuffer=null,this._interruptSupported=!1,this.environmentVariables={},super.setMaxListeners(20),this.kernelId=`kernel_${Math.random().toString(36).substring(2)}_${Date.now()}`}async getStatus(){return this._status}async initialize(e){if(!this.initialized)return this.initPromise||(e?.filesystem&&(this.filesystemOptions={...this.filesystemOptions,...e.filesystem}),e?.env&&(this.environmentVariables={...e.env}),e?.lockFileURL&&(this.lockFileURL=e.lockFileURL),this.initPromise=this._initializeInternal()),this.initPromise}async _initializeInternal(){const e=Date.now();console.log("🚀 Starting optimized kernel initialization...");try{const t=Date.now(),r={};this.lockFileURL&&(r.lockFileURL=this.lockFileURL,console.log(`🔒 Using lockFileURL: ${this.lockFileURL}`)),this.pyodide=await async function(e={}){return s||(s=(async()=>{try{"undefined"!=typeof importScripts?await new Promise((e,t)=>{try{if("undefined"==typeof importScripts)return void t(new Error("importScripts is not available - not in a worker context"));if(void 0!==globalThis.loadPyodide)return void e();importScripts(n),e()}catch(e){t(new Error(`Failed to import Pyodide in worker: ${e}`))}}):await new Promise((e,t)=>{if(void 0!==globalThis.loadPyodide)return void e();const r=document.createElement("script");r.src=n,r.onload=()=>e(),r.onerror=()=>t(new Error(`Failed to load Pyodide from ${n}`)),document.head.appendChild(r)});const t=globalThis.loadPyodide;if(!t)throw new Error("loadPyodide function not found after script load");const r={indexURL:"https://cdn.jsdelivr.net/pyodide/v0.28.0/full/",...e},s=await t(r);return o=!0,console.log("✅ Pyodide loaded successfully from CDN"),s}catch(e){throw s=null,e}})(),s)}(r);const i=Date.now()-t;if(console.log(`✅ Pyodide loaded in ${i}ms`),this.lockFileURL){console.log("🚀 Using lock file - skipping package installation");const[,]=await Promise.all([this.filesystemOptions.enabled?this.mountFilesystem():Promise.resolve(),this.setEnvironmentVariables()]);await this.initGlobals()}else{const[,,]=await Promise.all([this.filesystemOptions.enabled?this.mountFilesystem():Promise.resolve(),this.initPackageManager(),this.setEnvironmentVariables()]);await this.initKernel(),await this.initGlobals()}const a=Date.now()-e;console.log(`🎯 KERNEL INITIALIZATION COMPLETE in ${a}ms`),console.log(`⚡ Performance: Pyodide(${i}ms) + Setup(${a-i}ms)`),this.initialized=!0,this._status="active",console.log("🟢 Kernel is now ACTIVE and ready for execution!")}catch(e){throw console.error("❌ Kernel initialization failed:",e),this._status="unknown",e}}async mountFilesystem(){try{console.log(`Mounting filesystem from ${this.filesystemOptions.root} to ${this.filesystemOptions.mountPoint}`),await this.pyodide.FS.mount(this.pyodide.FS.filesystems.NODEFS,{root:this.filesystemOptions.root||"."},this.filesystemOptions.mountPoint||"/home/pyodide"),console.log("Filesystem mounted successfully");try{const e=this.pyodide.FS.readdir(this.filesystemOptions.mountPoint||"/home/pyodide");console.log(`Files in ${this.filesystemOptions.mountPoint} directory: ${e.join(", ")}`)}catch(e){console.error(`Error listing mounted directory: ${e}`)}}catch(e){throw console.error("Error mounting filesystem:",e),e}}async initPackageManager(){const e=Date.now();console.log("⚡ Initializing optimized package manager...");try{let t;console.log("📦 Loading micropip, packaging..."),await this.pyodide.loadPackage(["micropip","packaging"]),console.log("✅ Loaded micropip, packaging"),t="undefined"!=typeof window&&window.location?new URL(".",window.location.href).href:"undefined"!=typeof self&&self.location?new URL(".",self.location.href).href:"/";const r=new URL("pypi/all.json",t).href,n=[new URL("pypi/piplite-0.6.0a5-py3-none-any.whl",t).href,new URL("pypi/pyodide_kernel-0.6.0a5-py3-none-any.whl",t).href,new URL("pypi/ipykernel-6.9.2-py3-none-any.whl",t).href,new URL("pypi/widgetsnbextension-3.6.999-py3-none-any.whl",t).href,new URL("pypi/widgetsnbextension-4.0.999-py3-none-any.whl",t).href];console.log(`🚀 Installing ${n.length} wheel packages in parallel...`);const o=n.map(async(e,t)=>{const r=Date.now();try{await this.pyodide.runPythonAsync(`\nimport micropip\nawait micropip.install('${e}', keep_going=True)\nprint(f"✅ Wheel ${t+1}/${n.length} installed")\n`);const o=Date.now()-r;return console.log(`⚡ Wheel ${t+1} installed in ${o}ms`),{index:t,success:!0,time:o}}catch(e){const n=Date.now()-r;return console.warn(`⚠️ Wheel ${t+1} failed after ${n}ms:`,e),{index:t,success:!1,time:n,error:e}}}),s=await Promise.all(o),i=s.filter(e=>e.success),a=s.filter(e=>!e.success);console.log(`📊 Wheels: ${i.length}/${n.length} successful`),a.length>0&&console.warn(`⚠️ Failed wheels: ${a.map(e=>e.index+1).join(", ")}`);try{await this.pyodide.runPythonAsync(`\ntry:\n import piplite.piplite\n import json\n\n # Load package index for faster lookups\n try:\n piplite.piplite.PIPLITE_URL = "${r}"\n # Pre-load package index for faster installation\n print("📋 Package index configured")\n except Exception as e:\n print(f"⚠️ Package index setup warning: {e}")\n\n # Configure piplite for optimal performance\n piplite.piplite.REPODATA_INFO = {}\n print("⚡ Piplite optimized for performance")\nexcept ImportError:\n print("⚠️ Piplite not available, continuing without it")\nexcept Exception as e:\n print(f"⚠️ Piplite setup failed: {e}")\n`)}catch(e){console.warn("⚠️ Piplite configuration failed, continuing without it:",e)}const l=Date.now()-e;console.log(`🎯 Package manager initialized in ${l}ms`)}catch(e){throw console.error("❌ Package manager initialization failed:",e),e}}async initKernel(){const e=Date.now();console.log("🚀 Initializing kernel packages with maximum optimization...");const t=[{name:"pure-eval",priority:1,source:"pyodide"},{name:"stack-data",priority:1,source:"pyodide"},{name:"pygments",priority:1,source:"pyodide"},{name:"ssl",priority:1,source:"pyodide"},{name:"sqlite3",priority:1,source:"pyodide"},{name:"prompt_toolkit",priority:1,source:"pyodide"},{name:"jedi",priority:1,source:"pyodide"},{name:"ipython",priority:1,source:"pyodide"},{name:"comm",priority:2,source:"pip"},{name:"hypha-rpc",priority:2,source:"pip"},{name:"nbformat",priority:2,source:"pip"},{name:"ipykernel",priority:3,source:"pip"},{name:"pyodide_kernel",priority:3,source:"pip"}];try{console.log(`📦 Installing ${t.length} packages with intelligent optimization...`),await this.installPackagesWithIntelligentOptimization(t),console.log("📥 Importing pyodide_kernel...");const r=Date.now();await this.pyodide.runPythonAsync("import pyodide_kernel");const n=Date.now()-r;console.log(`✅ pyodide_kernel imported in ${n}ms`);const o=Date.now()-e;console.log(`🎯 Kernel packages initialized in ${o}ms`)}catch(e){throw console.error("❌ Kernel package initialization failed:",e),e}}async installPackagesWithIntelligentOptimization(e){console.log(`⚡ Starting intelligent parallel installation of ${e.length} packages...`);const t=e.map(async e=>{const t=Date.now();try{if(console.log(`🔄 Installing ${e.name} (priority: ${e.priority}, preferred: ${e.source})...`),"pyodide"!==e.source){await this.installViaPipWithOptimizations(e.name);const r=Date.now()-t;return console.log(`✅ ${e.name} installed via pip (${r}ms)`),{package:e.name,method:"pip",duration:r,success:!0,priority:e.priority}}try{await this.pyodide.loadPackage([e.name]);const r=Date.now()-t;return console.log(`✅ ${e.name} loaded from Pyodide CDN (${r}ms)`),{package:e.name,method:"pyodide",duration:r,success:!0,priority:e.priority}}catch(r){console.log(`📦 ${e.name} not available on CDN, trying pip...`),await this.installViaPipWithOptimizations(e.name);const n=Date.now()-t;return console.log(`✅ ${e.name} installed via pip fallback (${n}ms)`),{package:e.name,method:"pip-fallback",duration:n,success:!0,priority:e.priority}}}catch(r){const n=Date.now()-t;return console.warn(`❌ Failed to install ${e.name} after ${n}ms:`,r),{package:e.name,method:"failed",duration:n,success:!1,priority:e.priority,error:r}}}),r=await Promise.all(t);this.analyzeInstallationResults(r)}async installViaPipWithOptimizations(e){await this.pyodide.runPythonAsync(`\ntry:\n # Use optimized pip installation with caching\n await piplite.install('${e}', keep_going=True, deps=True)\n print("✅ Successfully installed ${e} via optimized pip")\nexcept Exception as e:\n print("⚠️ Warning: Failed to install ${e}:", str(e))\n # Try alternative installation method\n try:\n import micropip\n await micropip.install('${e}', keep_going=True)\n print("✅ Successfully installed ${e} via micropip fallback")\n except Exception as e2:\n print("❌ Both pip methods failed for ${e}:", str(e2))\n raise e2\n`)}analyzeInstallationResults(e){const t=e.filter(e=>e.success),r=e.filter(e=>!e.success),n=t.filter(e=>"pyodide"===e.method),o=t.filter(e=>"pip"===e.method),s=t.filter(e=>"pip-fallback"===e.method),i=Math.max(...e.map(e=>e.duration)),a=e.reduce((e,t)=>e+t.duration,0)/e.length,l=e.reduce((e,t)=>e+t.duration,0);console.log("🎯 INTELLIGENT INSTALLATION COMPLETE!"),console.log(`📊 Results: ${t.length}/${e.length} successful`),console.log(`⚡ Pyodide CDN: ${n.length} packages`),console.log(`📦 Direct pip: ${o.length} packages`),console.log(`🔄 Pip fallback: ${s.length} packages`),console.log(`❌ Failed: ${r.length} packages`),console.log(`⏱️ Total time: ${i}ms (vs ~${l}ms sequential)`),console.log(`🚀 Speed improvement: ~${Math.round(l/i)}x faster`),console.log(`📈 Average per package: ${Math.round(a)}ms`),r.length>0&&(console.warn(`⚠️ Failed packages: ${r.map(e=>e.package).join(", ")}`),r.forEach(e=>{console.warn(` - ${e.package}: ${e.error?.message||"Unknown error"}`)}));const c=Math.min(...t.map(e=>e.duration)),u=Math.max(...t.map(e=>e.duration));console.log(`📊 Performance range: ${c}ms (fastest) to ${u}ms (slowest)`)}async initGlobals(){console.log("Initializing globals...");const{globals:e}=this.pyodide;this._kernel=e.get("pyodide_kernel").kernel_instance.copy(),this._stdout_stream=e.get("pyodide_kernel").stdout_stream.copy(),this._stderr_stream=e.get("pyodide_kernel").stderr_stream.copy(),this._interpreter=this._kernel.interpreter.copy(),this._interpreter.send_comm=this.sendComm.bind(this),this.setupCallbacks()}setupCallbacks(){const e=(e,t)=>{const r={name:this.formatResult(e),text:this.formatResult(t)};this._sendMessage({parentHeader:this.formatResult(this._parent_header).header,bundle:r,type:"stream"})};this._stdout_stream.publish_stream_callback=e,this._stderr_stream.publish_stream_callback=e,this._interpreter.display_pub.clear_output_callback=e=>{const t={wait:this.formatResult(e)};this._sendMessage({parentHeader:this.formatResult(this._parent_header).header,bundle:t,type:"clear_output"})},this._interpreter.display_pub.display_data_callback=(e,t,r)=>{const n={data:this.formatResult(e),metadata:this.formatResult(t),transient:this.formatResult(r)};this._sendMessage({parentHeader:this.formatResult(this._parent_header).header,bundle:n,type:"display_data"})},this._interpreter.display_pub.update_display_data_callback=(e,t,r)=>{const n={data:this.formatResult(e),metadata:this.formatResult(t),transient:this.formatResult(r)};this._sendMessage({parentHeader:this.formatResult(this._parent_header).header,bundle:n,type:"update_display_data"})},this._interpreter.displayhook.publish_execution_result=(e,t,r)=>{const n={execution_count:e,data:this.formatResult(t),metadata:this.formatResult(r)};this._sendMessage({parentHeader:this.formatResult(this._parent_header).header,bundle:n,type:"execute_result"})},this._interpreter.input=this.input.bind(this),this._interpreter.getpass=this.getpass.bind(this)}_sendMessage(e){this._processMessage(e)}_processMessage(e){if(!e.type)return;let t;switch(e.type){case"stream":{const r=e.bundle??{name:"stdout",text:""};super.emit(l.z.STREAM,r),t=r;break}case"input_request":{const r=e.content??{prompt:"",password:!1};super.emit(l.z.INPUT_REQUEST,r),t=r;break}case"display_data":{const r=e.bundle??{data:{},metadata:{},transient:{}};super.emit(l.z.DISPLAY_DATA,r),t=r;break}case"update_display_data":{const r=e.bundle??{data:{},metadata:{},transient:{}};super.emit(l.z.UPDATE_DISPLAY_DATA,r),t=r;break}case"clear_output":{const r=e.bundle??{wait:!1};super.emit(l.z.CLEAR_OUTPUT,r),t=r;break}case"execute_result":{const r=e.bundle??{execution_count:this.executionCount,data:{},metadata:{}};super.emit(l.z.EXECUTE_RESULT,r),t=r;break}case"execute_error":{const r=e.bundle??{ename:"",evalue:"",traceback:[]};super.emit(l.z.EXECUTE_ERROR,r),t=r;break}case"comm_open":case"comm_msg":case"comm_close":{const r=e.content??{};super.emit(e.type,r,e.metadata,e.buffers),t={content:r,metadata:e.metadata,buffers:e.buffers};break}}t&&super.emit(l.z.ALL,{type:e.type,data:t})}isInitialized(){return this.initialized}async setup(e){await this.initialize(),this._parent_header=this.pyodide.toPy(e||{})}async execute(e,t={}){this.initialized||await this.initialize();try{this._status="busy",super.emit(l.z.KERNEL_BUSY,{}),await this.setup(t);const r="\n# Kernel isolation - reset commonly conflicting variables to prevent cross-kernel state sharing\nfor _var in ['x', 'value', 'result', 'a', 'b', 'c', 'data', 'temp']:\n if _var in globals():\n del globals()[_var]\ndel _var\n";return this.pyodide.runPython(r),new Promise((t,r)=>{const n={allMessages:[],executionComplete:!1,executionResult:null,executionError:null,timeout:null},o=e=>{n.allMessages.push(e)},s=async e=>{if(n.executionComplete)return;console.log(`[KERNEL] Execution completed, processing ${n.allMessages.length} messages`),n.executionComplete=!0,super.off(l.z.ALL,o);let r,s=!1,i=null;const a=n.executionResult;a&&"error"===a.status&&(s=!0,i={ename:a.ename,evalue:a.evalue,traceback:a.traceback});for(const e of n.allMessages){if("execute_error"===e.type){s=!0,i=e.data;break}"execute_result"===e.type&&(r=e.data)}if(this._status="active",super.emit(l.z.KERNEL_IDLE,{}),s){console.log("[KERNEL] Execution failed with error:",i);const e=i.ename?i.ename.replace(/^<class '(.+)'>$/,"$1"):i.ename;super.emit(l.z.EXECUTE_ERROR,{ename:e,evalue:i.evalue,traceback:i.traceback});const r=`${i.ename||"Error"}: ${i.evalue||"Unknown error"}`;t({success:!1,error:new Error(r),result:n.executionResult})}else{console.log(`[KERNEL] Execution successful, captured ${n.allMessages.length} output messages`);let e=void 0!==r?r:n.executionResult;t({success:!0,result:e})}};super.on(l.z.ALL,o),this._kernel.run(e).then(e=>{console.log("[KERNEL] Python execution finished, waiting for messages to settle"),n.executionResult=this.formatResult(e),setTimeout(()=>{s()},100)}).catch(e=>{console.error("[KERNEL] Python execution error:",e),n.executionError=e instanceof Error?e:new Error(String(e)),setTimeout(()=>{s()},100)})})}catch(e){return console.error("[KERNEL] Execute setup error:",e),this._status="active",super.emit(l.z.KERNEL_IDLE,{}),{success:!1,error:e instanceof Error?e:new Error(String(e))}}}formatResult(e){if(!(e instanceof this.pyodide.ffi.PyProxy))return e;try{const t=e.toJs();return this.mapToObject(t)}catch(e){return console.error("Error formatting result:",e),{status:"error",error:String(e)}}}mapToObject(e){const t=e instanceof Array?[]:{};return e.forEach((e,r)=>{t[r]=e instanceof Map||e instanceof Array?this.mapToObject(e):e}),t}async inputReply(e){this._resolveInputReply&&(this._resolveInputReply(e),this._resolveInputReply=null)}async sendInputRequest(e,t){const r={prompt:e,password:t};this._sendMessage({type:"input_request",content:r,parentHeader:this.formatResult(this._parent_header).header})}async getpass(e){e=void 0===e?"":e,await this.sendInputRequest(e,!0);const t=new Promise(e=>{this._resolveInputReply=e});return(await t).value}async input(e){e=void 0===e?"":e,await this.sendInputRequest(e,!1);const t=new Promise(e=>{this._resolveInputReply=e});return(await t).value}async sendComm(e,t,r,n,o){this._sendMessage({type:e,content:this.formatResult(t),metadata:this.formatResult(r),ident:this.formatResult(n),buffers:this.formatResult(o),parentHeader:this.formatResult(this._parent_header).header})}async complete(e,t,r={}){await this.setup(r);const n=this._kernel.complete(e,t);return this.formatResult(n)}async inspect(e,t,r,n={}){await this.setup(n);const o=this._kernel.inspect(e,t,r);return this.formatResult(o)}async isComplete(e,t={}){await this.setup(t);const r=this._kernel.is_complete(e);return this.formatResult(r)}async commInfo(e,t={}){await this.setup(t);const r=this._kernel.comm_info(e);return{comms:this.formatResult(r),status:"ok"}}async commOpen(e,t={}){await this.setup(t);const r=this._kernel.comm_manager.comm_open(this.pyodide.toPy(null),this.pyodide.toPy(null),this.pyodide.toPy(e));return this.formatResult(r)}async commMsg(e,t={}){await this.setup(t);const r=this._kernel.comm_manager.comm_msg(this.pyodide.toPy(null),this.pyodide.toPy(null),this.pyodide.toPy(e));return this.formatResult(r)}async commClose(e,t={}){await this.setup(t);const r=this._kernel.comm_manager.comm_close(this.pyodide.toPy(null),this.pyodide.toPy(null),this.pyodide.toPy(e));return this.formatResult(r)}async*executeStream(e,t={}){try{await this.initialize();const r=[],n=e=>{r.push(e)};super.on(l.z.ALL,n);try{const n=this.execute(e,t);for(;;)if(r.length>0&&(yield r.shift()),await Promise.race([n.then(()=>!0),new Promise(e=>setTimeout(()=>e(!1),10))])){for(;r.length>0;)yield r.shift();return await n}}catch(e){throw console.error("Error in executeStream:",e),e}finally{super.off(l.z.ALL,n)}}catch(e){return console.error("Error in executeStream setup:",e),{success:!1,error:e instanceof Error?e:new Error(String(e))}}}async interrupt(){if(!this.initialized||!this.pyodide)return console.warn("[KERNEL] Cannot interrupt: kernel not initialized"),!1;console.warn("[KERNEL] Main thread kernels have limited interrupt support");try{return this._interruptBuffer&&this._interruptSupported?(this._interruptBuffer[0]=2,await new Promise(e=>setTimeout(e,100)),0===this._interruptBuffer[0]):this._interpreter&&"function"==typeof this._interpreter.interrupt?(this._interpreter.interrupt(),!0):(this._sendMessage({type:"stream",bundle:{name:"stderr",text:"KeyboardInterrupt: Execution interrupted by user\n"}}),this._sendMessage({type:"execute_error",bundle:{ename:"KeyboardInterrupt",evalue:"Execution interrupted by user",traceback:["KeyboardInterrupt: Execution interrupted by user"]}}),!0)}catch(e){return console.error("[KERNEL] Error during interrupt:",e),!1}}setInterruptBuffer(e){this._interruptBuffer=e;try{this.pyodide&&"function"==typeof this.pyodide.setInterruptBuffer?(this.pyodide.setInterruptBuffer(e),this._interruptSupported=!0):(console.warn("[KERNEL] pyodide.setInterruptBuffer not available, interrupt support limited"),this._interruptSupported=!1)}catch(e){console.error("[KERNEL] Error setting interrupt buffer:",e),this._interruptSupported=!1}}async setEnvironmentVariables(){if(0===Object.keys(this.environmentVariables).length)return;const e=Date.now();console.log(`🌍 Setting ${Object.keys(this.environmentVariables).length} environment variables...`);try{for(const[e,t]of Object.entries(this.environmentVariables)){let r;r=null==t?"":String(t),await this.pyodide.runPythonAsync(`\nimport os\nos.environ[${JSON.stringify(e)}] = ${JSON.stringify(r)}\n`)}const t=Date.now()-e;console.log(`⚡ Environment variables set in ${t}ms`)}catch(e){throw console.error("❌ Failed to set environment variables:",e),e}}}},696:(e,t,r)=>{var n;r.d(t,{z:()=>n}),function(e){e.STREAM="stream",e.DISPLAY_DATA="display_data",e.UPDATE_DISPLAY_DATA="update_display_data",e.EXECUTE_RESULT="execute_result",e.EXECUTE_ERROR="execute_error",e.EXECUTE_REQUEST="execute_request",e.INPUT_REQUEST="input_request",e.CLEAR_OUTPUT="clear_output",e.COMM_OPEN="comm_open",e.COMM_MSG="comm_msg",e.COMM_CLOSE="comm_close",e.KERNEL_READY="kernel_ready",e.KERNEL_BUSY="kernel_busy",e.KERNEL_IDLE="kernel_idle",e.ALL="*",e.EXECUTION_STALLED="execution_stalled",e.KERNEL_UNRECOVERABLE="kernel_unrecoverable",e.EXECUTION_INTERRUPTED="execution_interrupted",e.KERNEL_RESTARTED="kernel_restarted",e.KERNEL_TERMINATED="kernel_terminated"}(n||(n={}))},757:(e,t,r)=>{r.r(t);var n=r(590),o=r(696);const s=new(r(637).MB);let i=null,a={},l=new Map,c=null;function u(e){return e&&"object"==typeof e&&("KeyboardInterrupt"===e.type||e.message&&e.message.includes("KeyboardInterrupt"))}function p(){i?Object.values(o.z).forEach(e=>{const t=t=>{i&&i.postMessage({type:e,data:t})};l.set(e,t),s.on(e,t)}):console.error("[WORKER] Cannot set up event forwarding: no event port available")}self.addEventListener("error",e=>{console.error("[WORKER] Global error caught:",e.error),e.preventDefault()}),self.addEventListener("unhandledrejection",e=>{u(e.reason)?(console.log("[WORKER] KeyboardInterrupt caught in unhandled rejection handler - this is expected during interrupts"),i&&i.postMessage({type:o.z.EXECUTE_ERROR,data:{ename:"KeyboardInterrupt",evalue:"Execution interrupted by user",traceback:["KeyboardInterrupt: Execution interrupted by user"]}})):console.error("[WORKER] Unhandled promise rejection:",e.reason),e.preventDefault()}),self.addEventListener("message",e=>{if("SET_EVENT_PORT"===e.data?.type&&e.data?.port)!function(){if(l.size>0){for(const[e,t]of l.entries())s.off(e,t);l.clear()}i&&(i.close(),i=null)}(),i=e.data.port,s.isInitialized()&&p();else if("INITIALIZE_KERNEL"===e.data?.type)a=e.data.options||{},async function(e){try{await s.initialize(e),c&&"function"==typeof s.setInterruptBuffer&&s.setInterruptBuffer(c),p(),i&&i.postMessage({type:"KERNEL_INITIALIZED",data:{success:!0}})}catch(e){throw console.error("Kernel initialization failed:",e),e}}(a).catch(e=>{console.error("[WORKER] Error initializing kernel in worker:",e),i&&i.postMessage({type:o.z.EXECUTE_ERROR,data:{ename:"WorkerInitError",evalue:`Failed to initialize kernel: ${e.message}`,traceback:[e.stack||""]}})});else if("SET_INTERRUPT_BUFFER"===e.data?.type){c=e.data.buffer,s.isInitialized()&&c&&"function"==typeof s.setInterruptBuffer?(s.setInterruptBuffer(c),console.log("[WORKER] Interrupt buffer set in pyodide kernel")):c&&console.log("[WORKER] Interrupt buffer stored, will be set when kernel initializes");const t={type:"INTERRUPT_BUFFER_SET",data:{success:!0}};i&&i.postMessage(t),self.postMessage(t)}else if("INTERRUPT_KERNEL"===e.data?.type)if(c){c[0]=2;const e={type:"INTERRUPT_TRIGGERED",data:{success:!0,method:"buffer"}};i&&i.postMessage(e),self.postMessage(e)}else if(console.log("[WORKER] No interrupt buffer available, trying kernel.interrupt()"),"function"==typeof s.interrupt)s.interrupt().then(e=>{const t={type:"INTERRUPT_TRIGGERED",data:{success:e,method:"kernel"}};i&&i.postMessage(t),self.postMessage(t)}).catch(e=>{console.error("[WORKER] Error during kernel interrupt:",e);const t={type:"INTERRUPT_TRIGGERED",data:{success:!1,error:e.message,method:"kernel"}};i&&i.postMessage(t),self.postMessage(t)});else{console.warn("[WORKER] No interrupt method available");const e={type:"INTERRUPT_TRIGGERED",data:{success:!1,error:"No interrupt method available",method:"none"}};i&&i.postMessage(e),self.postMessage(e)}}),self.addEventListener("beforeunload",async()=>{try{i&&i.postMessage({type:"WORKER_TERMINATING",data:{message:"Worker is shutting down"}})}catch(e){console.error("Error during worker cleanup:",e)}});const d={initialize:async e=>{try{return void await s.initialize(e)}catch(e){throw console.error("[WORKER] Initialize error:",e),e}},execute:async(e,t)=>{try{return await s.execute(e,t)}catch(e){return console.error("[WORKER] Execute error:",e),u(e)?(console.log("[WORKER] KeyboardInterrupt caught in execute method"),{success:!1,error:new Error("KeyboardInterrupt: Execution interrupted by user"),result:{payload:[],status:"error",ename:"KeyboardInterrupt",evalue:"Execution interrupted by user",traceback:["KeyboardInterrupt: Execution interrupted by user"]}}):{success:!1,error:e instanceof Error?e:new Error(String(e)),result:{payload:[],status:"error",ename:e instanceof Error?e.constructor.name:"Error",evalue:e instanceof Error?e.message:String(e),traceback:e instanceof Error&&e.stack?e.stack.split("\n"):[String(e)]}}}},isInitialized:()=>{try{return s.isInitialized()}catch(e){return console.error("[WORKER] IsInitialized error:",e),!1}},inputReply:async e=>{try{await s.inputReply(e)}catch(e){throw console.error("[WORKER] InputReply error:",e),e}},getStatus:async()=>{try{return await s.getStatus()}catch(e){return console.error("[WORKER] getStatus error:",e),"unknown"}},interrupt:async()=>{try{return"function"==typeof s.interrupt?await s.interrupt():(console.warn("[WORKER] Kernel does not support interrupt method"),!1)}catch(e){return console.error("[WORKER] Interrupt error:",e),!1}},setInterruptBuffer:e=>{try{return"function"==typeof s.setInterruptBuffer?(s.setInterruptBuffer(e),!0):(console.warn("[WORKER] Kernel does not support setInterruptBuffer method"),!1)}catch(e){return console.error("[WORKER] setInterruptBuffer error:",e),!1}},complete:async(e,t,r)=>{try{return"function"==typeof s.complete?await s.complete(e,t,r):(console.warn("[WORKER] Kernel does not support complete method"),{status:"error",error:"Completion not supported"})}catch(e){return console.error("[WORKER] Complete error:",e),{status:"error",error:String(e)}}},inspect:async(e,t,r,n)=>{try{return"function"==typeof s.inspect?await s.inspect(e,t,r,n):(console.warn("[WORKER] Kernel does not support inspect method"),{status:"error",error:"Inspection not supported"})}catch(e){return console.error("[WORKER] Inspect error:",e),{status:"error",error:String(e)}}},isComplete:async(e,t)=>{try{return"function"==typeof s.isComplete?await s.isComplete(e,t):(console.warn("[WORKER] Kernel does not support isComplete method"),{status:"unknown"})}catch(e){return console.error("[WORKER] IsComplete error:",e),{status:"error",error:String(e)}}},commInfo:async(e,t)=>{try{return"function"==typeof s.commInfo?await s.commInfo(e,t):(console.warn("[WORKER] Kernel does not support commInfo method"),{comms:{},status:"ok"})}catch(e){return console.error("[WORKER] CommInfo error:",e),{comms:{},status:"error",error:String(e)}}},commOpen:async(e,t)=>{try{return"function"==typeof s.commOpen?await s.commOpen(e,t):void console.warn("[WORKER] Kernel does not support commOpen method")}catch(e){return void console.error("[WORKER] CommOpen error:",e)}},commMsg:async(e,t)=>{try{return"function"==typeof s.commMsg?await s.commMsg(e,t):void console.warn("[WORKER] Kernel does not support commMsg method")}catch(e){return void console.error("[WORKER] CommMsg error:",e)}},commClose:async(e,t)=>{try{return"function"==typeof s.commClose?await s.commClose(e,t):void console.warn("[WORKER] Kernel does not support commClose method")}catch(e){return void console.error("[WORKER] CommClose error:",e)}}};try{n.p(d)}catch(e){console.error("Error exposing proxy:",e)}}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var s=t[n]={exports:{}};return e[n](s,s.exports,r),s.exports}r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n=r(637);const o=n.MB,s=n.zZ,i=n.y9,a=n.dR,l=n.J9;export{o as Kernel,s as KernelEvents,i as KernelLanguage,a as KernelManager,l as KernelMode};
var e={590:(e,t,r)=>{r.d(t,{LV:()=>d});const n=Symbol("Comlink.proxy"),o=Symbol("Comlink.endpoint"),i=Symbol("Comlink.releaseProxy"),s=Symbol("Comlink.finalizer"),a=Symbol("Comlink.thrown"),l=e=>"object"==typeof e&&null!==e||"function"==typeof e,c=new Map([["proxy",{canHandle:e=>l(e)&&e[n],serialize(e){const{port1:t,port2:r}=new MessageChannel;return u(e,t),[r,[r]]},deserialize:e=>(e.start(),d(e))}],["throw",{canHandle:e=>l(e)&&a in e,serialize({value:e}){let t;return t=e instanceof Error?{isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:{isError:!1,value:e},[t,[]]},deserialize(e){if(e.isError)throw Object.assign(new Error(e.value.message),e.value);throw e.value}}]]);function u(e,t=globalThis,r=["*"]){t.addEventListener("message",function o(i){if(!i||!i.data)return;if(!function(e,t){for(const r of e){if(t===r||"*"===r)return!0;if(r instanceof RegExp&&r.test(t))return!0}return!1}(r,i.origin))return void console.warn(`Invalid origin '${i.origin}' for comlink proxy`);const{id:l,type:c,path:d}=Object.assign({path:[]},i.data),h=(i.data.argumentList||[]).map(x);let m;try{const t=d.slice(0,-1).reduce((e,t)=>e[t],e),r=d.reduce((e,t)=>e[t],e);switch(c){case"GET":m=r;break;case"SET":t[d.slice(-1)[0]]=x(i.data.value),m=!0;break;case"APPLY":m=r.apply(t,h);break;case"CONSTRUCT":m=function(e){return Object.assign(e,{[n]:!0})}(new r(...h));break;case"ENDPOINT":{const{port1:t,port2:r}=new MessageChannel;u(e,r),m=function(e,t){return w.set(e,t),e}(t,[t])}break;case"RELEASE":m=void 0;break;default:return}}catch(e){m={value:e,[a]:0}}Promise.resolve(m).catch(e=>({value:e,[a]:0})).then(r=>{const[n,i]=k(r);t.postMessage(Object.assign(Object.assign({},n),{id:l}),i),"RELEASE"===c&&(t.removeEventListener("message",o),p(t),s in e&&"function"==typeof e[s]&&e[s]())}).catch(e=>{const[r,n]=k({value:new TypeError("Unserializable return value"),[a]:0});t.postMessage(Object.assign(Object.assign({},r),{id:l}),n)})}),t.start&&t.start()}function p(e){(function(e){return"MessagePort"===e.constructor.name})(e)&&e.close()}function d(e,t){const r=new Map;return e.addEventListener("message",function(e){const{data:t}=e;if(!t||!t.id)return;const n=r.get(t.id);if(n)try{n(t)}finally{r.delete(t.id)}}),y(e,r,[],t)}function h(e){if(e)throw new Error("Proxy has been released and is not useable")}function m(e){return v(e,new Map,{type:"RELEASE"}).then(()=>{p(e)})}const g=new WeakMap,f="FinalizationRegistry"in globalThis&&new FinalizationRegistry(e=>{const t=(g.get(e)||0)-1;g.set(e,t),0===t&&m(e)});function y(e,t,r=[],n=function(){}){let s=!1;const a=new Proxy(n,{get(n,o){if(h(s),o===i)return()=>{!function(e){f&&f.unregister(e)}(a),m(e),t.clear(),s=!0};if("then"===o){if(0===r.length)return{then:()=>a};const n=v(e,t,{type:"GET",path:r.map(e=>e.toString())}).then(x);return n.then.bind(n)}return y(e,t,[...r,o])},set(n,o,i){h(s);const[a,l]=k(i);return v(e,t,{type:"SET",path:[...r,o].map(e=>e.toString()),value:a},l).then(x)},apply(n,i,a){h(s);const l=r[r.length-1];if(l===o)return v(e,t,{type:"ENDPOINT"}).then(x);if("bind"===l)return y(e,t,r.slice(0,-1));const[c,u]=E(a);return v(e,t,{type:"APPLY",path:r.map(e=>e.toString()),argumentList:c},u).then(x)},construct(n,o){h(s);const[i,a]=E(o);return v(e,t,{type:"CONSTRUCT",path:r.map(e=>e.toString()),argumentList:i},a).then(x)}});return function(e,t){const r=(g.get(t)||0)+1;g.set(t,r),f&&f.register(e,t,e)}(a,e),a}function E(e){const t=e.map(k);return[t.map(e=>e[0]),(r=t.map(e=>e[1]),Array.prototype.concat.apply([],r))];var r}const w=new WeakMap;function k(e){for(const[t,r]of c)if(r.canHandle(e)){const[n,o]=r.serialize(e);return[{type:"HANDLER",name:t,value:n},o]}return[{type:"RAW",value:e},w.get(e)||[]]}function x(e){switch(e.type){case"HANDLER":return c.get(e.name).deserialize(e.value);case"RAW":return e.value}}function v(e,t,r,n){return new Promise(o=>{const i=new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-");t.set(i,o),e.start&&e.start(),e.postMessage(Object.assign({id:i},r),n)})}},696:(e,t,r)=>{var n;r.d(t,{z:()=>n}),function(e){e.STREAM="stream",e.DISPLAY_DATA="display_data",e.UPDATE_DISPLAY_DATA="update_display_data",e.EXECUTE_RESULT="execute_result",e.EXECUTE_ERROR="execute_error",e.EXECUTE_REQUEST="execute_request",e.INPUT_REQUEST="input_request",e.CLEAR_OUTPUT="clear_output",e.COMM_OPEN="comm_open",e.COMM_MSG="comm_msg",e.COMM_CLOSE="comm_close",e.KERNEL_READY="kernel_ready",e.KERNEL_BUSY="kernel_busy",e.KERNEL_IDLE="kernel_idle",e.ALL="*",e.EXECUTION_STALLED="execution_stalled",e.KERNEL_UNRECOVERABLE="kernel_unrecoverable",e.EXECUTION_INTERRUPTED="execution_interrupted",e.KERNEL_RESTARTED="kernel_restarted",e.KERNEL_TERMINATED="kernel_terminated"}(n||(n={}))}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var i=t[n]={exports:{}};return e[n](i,i.exports,r),i.exports}r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var n={};r.d(n,{MB:()=>m,zZ:()=>c.z,y9:()=>l,dR:()=>d,J9:()=>a});const o="https://cdn.jsdelivr.net/pyodide/v0.28.0/full/pyodide.js";let i=!1,s=null;var a,l,c=r(696),u=r(590);class p{constructor(){this.events={}}on(e,t){this.events[e]||(this.events[e]=[]),this.events[e].push(t)}off(e,t){if(!this.events[e])return;const r=this.events[e].indexOf(t);r>-1&&this.events[e].splice(r,1)}removeListener(e,t){this.off(e,t)}emit(e,...t){this.events[e]&&this.events[e].forEach(e=>e(...t))}setMaxListeners(e){}}!function(e){e.MAIN_THREAD="main_thread",e.WORKER="worker"}(a||(a={})),function(e){e.PYTHON="python"}(l||(l={}));class d extends p{isKeyboardInterrupt(e){return e&&"object"==typeof e&&("type"in e&&"KeyboardInterrupt"===e.type||"message"in e&&"string"==typeof e.message&&e.message.includes("KeyboardInterrupt"))}createKeyboardInterruptResult(){return{success:!1,error:new Error("KeyboardInterrupt: Execution interrupted by user"),result:{status:"error",ename:"KeyboardInterrupt",evalue:"Execution interrupted by user",traceback:["KeyboardInterrupt: Execution interrupted by user"]}}}storeAbortController(e,t,r){this.abortControllers.has(e)||this.abortControllers.set(e,new Map),this.abortControllers.get(e).set(t,r)}removeAbortController(e,t){const r=this.abortControllers.get(e);if(!r)return;const n=r.get(t);return n&&(r.delete(t),0===r.size&&this.abortControllers.delete(e)),n}abortAllKernelOperations(e){const t=this.abortControllers.get(e);if(t){for(const[r,n]of t)try{n.abort(),console.log(`🚫 Aborted execution ${r} for kernel ${e}`)}catch(e){console.warn(`⚠️ Error aborting execution ${r}:`,e)}this.abortControllers.delete(e)}}constructor(e={}){super(),this.kernels=new Map,this.listenerWrappers=new Map,this.lastActivityTime=new Map,this.inactivityTimers=new Map,this.ongoingExecutions=new Map,this.executionTimeouts=new Map,this.executionStartTimes=new Map,this.executionMetadata=new Map,this.abortControllers=new Map,this.pool=new Map,this.isPreloading=!1,this.prefillingInProgress=new Map,this.interruptBuffers=new Map,super.setMaxListeners(100),this.interruptionMode=e.interruptionMode||"auto",this.allowedKernelTypes=e.allowedKernelTypes||[{mode:a.WORKER,language:l.PYTHON}];const t=this.allowedKernelTypes.filter(e=>e.language===l.PYTHON);this.poolConfig={enabled:!1,poolSize:2,autoRefill:!0,preloadConfigs:t,...e.pool},this.poolConfig.preloadConfigs&&(this.poolConfig.preloadConfigs=this.poolConfig.preloadConfigs.filter(e=>{const t=this.isKernelTypeAllowed(e.mode,e.language);return t||console.warn(`Pool preload config ${e.mode}-${e.language} is not in allowedKernelTypes, skipping`),t})),this.poolConfig.enabled&&this.preloadPool().catch(e=>{console.error("Error preloading kernel pool:",e)})}getPoolKey(e,t){return`${e}-${t}`}getFromPool(e,t){if(!this.poolConfig.enabled)return null;const r=this.getPoolKey(e,t),n=this.pool.get(r);if(!n||0===n.length)return null;const o=n.shift();return this.poolConfig.autoRefill&&setTimeout(()=>{this.refillPoolSingle(e,t).catch(e=>{console.error(`Error refilling single kernel for ${r}:`,e)})},0),o}addToPool(e,t,r){if(!this.poolConfig.enabled)return;const n=this.getPoolKey(e,t);this.pool.has(n)||this.pool.set(n,[]);const o=this.pool.get(n);o.length<this.poolConfig.poolSize?(o.push(r),r.catch(e=>{console.error(`Pool kernel promise rejected for ${n}:`,e);const t=o.indexOf(r);-1!==t&&o.splice(t,1)})):r.then(e=>{e.destroy().catch(e=>{console.error("Error destroying excess pool kernel:",e)})}).catch(e=>{console.error("Excess pool kernel promise rejected:",e)})}async refillPoolSingle(e,t){if(!this.poolConfig.enabled)return;const r=this.getPoolKey(e,t);if((this.pool.get(r)||[]).length<this.poolConfig.poolSize){const r=this.createPoolKernelPromise(e,t);this.addToPool(e,t,r)}}async refillPool(e,t){if(!this.poolConfig.enabled)return;const r=this.getPoolKey(e,t);if(!this.prefillingInProgress.get(r)){this.prefillingInProgress.set(r,!0);try{const n=this.pool.get(r)||[],o=this.poolConfig.poolSize-n.length;if(o<=0)return;const i=Array.from({length:o},()=>this.createPoolKernelPromise(e,t));for(const r of i)this.addToPool(e,t,r)}catch(e){console.error(`Error refilling pool for ${r}:`,e)}finally{this.prefillingInProgress.set(r,!1)}}}createPoolKernelPromise(e,t){return new Promise(async(r,n)=>{try{const n=await this.createPoolKernel(e,t);n.isFromPool=!0,r(n)}catch(r){console.error(`Error creating pool kernel for ${e}-${t}:`,r),n(r)}})}async createPoolKernel(e,t){const r=`pool-${crypto.randomUUID()}`,n={mode:e,lang:t};let o;try{if(e===a.MAIN_THREAD){const i={id:r,options:n,mode:e,language:t};this.kernels.set(r,i);try{o=await this.createMainThreadKernel(r)}finally{this.kernels.delete(r)}}else{const i={id:r,options:n,mode:e,language:t};this.kernels.set(r,i);try{o=await this.createWorkerKernel(r)}finally{this.kernels.delete(r)}}}catch(e){throw this.kernels.delete(r),e}return o}async preloadPool(){if(this.poolConfig.enabled&&!this.isPreloading){this.isPreloading=!0;try{for(const e of this.poolConfig.preloadConfigs)try{await this.refillPool(e.mode,e.language)}catch(t){console.error(`Error preloading ${e.mode}-${e.language}:`,t)}}catch(e){console.error("Error during kernel pool preloading:",e)}finally{this.isPreloading=!1}}}canUsePool(e){return!!this.poolConfig.enabled&&!e.filesystem&&!e.deno?.permissions&&void 0===e.inactivityTimeout&&void 0===e.maxExecutionTime}reassignPoolKernel(e,t,r){const n={id:t,kernel:e.kernel,mode:e.mode,language:e.language,worker:e.worker,created:new Date,options:{...e.options,...r},isFromPool:!0,destroy:e.destroy};if("function"!=typeof n.destroy)throw console.error("Failed to preserve destroy function during pool kernel reassignment"),console.error("poolKernel.destroy type:",typeof e.destroy),console.error("updatedInstance.destroy type:",typeof n.destroy),new Error("Failed to preserve destroy function during pool kernel reassignment");return n}getPoolStats(){const e={};for(const[t,r]of this.pool.entries())e[t]={available:r.length,total:this.poolConfig.poolSize};return e}getPoolConfig(){return{enabled:this.poolConfig.enabled,poolSize:this.poolConfig.poolSize,autoRefill:this.poolConfig.autoRefill,preloadConfigs:[...this.poolConfig.preloadConfigs],isPreloading:this.isPreloading}}async createKernel(e={}){if(e.id&&e.id.includes(":"))throw new Error("Kernel ID cannot contain colons");const t=e.id||crypto.randomUUID(),r=e.mode||a.WORKER,n=e.lang||l.PYTHON;if(!this.isKernelTypeAllowed(r,n))throw new Error(`Kernel type ${r}-${n} is not allowed. Allowed types: ${this.allowedKernelTypes.map(e=>`${e.mode}-${e.language}`).join(", ")}`);const o=e.namespace?`${e.namespace}:${t}`:t;if(this.kernels.has(o))throw new Error(`Kernel with ID ${o} already exists`);if(this.canUsePool(e)){const t=this.getPoolKey(r,n);if(this.poolConfig.preloadConfigs.some(e=>e.mode===r&&e.language===n)){let i=this.getFromPool(r,n);if(i)return await this.setupPoolKernelFromPromise(i,o,e);try{const i=this.createPoolKernelPromise(r,n);return this.poolConfig.autoRefill&&setTimeout(()=>{this.refillPool(r,n).catch(e=>{console.error(`Error refilling exhausted pool for ${t}:`,e)})},0),await this.setupPoolKernelFromPromise(i,o,e)}catch(e){console.error(`Failed to create kernel promise for exhausted pool: ${e}`)}}else{const t=this.getFromPool(r,n);if(t)return await this.setupPoolKernelFromPromise(t,o,e)}}return this.createOnDemandKernel(o,r,n,e)}async setupPoolKernelFromPromise(e,t,r){try{const n=await e,o=this.reassignPoolKernel(n,t,r);if(o.mode===a.WORKER&&o.worker){const e=o.worker,{port1:r,port2:n}=new MessageChannel;e.postMessage({type:"SET_EVENT_PORT",port:n},[n]);const i=e=>{e.data&&e.data.type&&super.emit(e.data.type,{kernelId:t,data:e.data.data})};r.addEventListener("message",i),r.start();const s=o.destroy;o.destroy=async()=>(r.removeEventListener("message",i),r.close(),s())}return this.kernels.set(t,o),this.setupEventForwarding(o),this.updateKernelActivity(t),r.inactivityTimeout&&r.inactivityTimeout>0&&this.setupInactivityTimeout(t,r.inactivityTimeout),r.maxExecutionTime&&r.maxExecutionTime>0&&this.setupStalledExecutionHandler(t),t}catch(e){throw console.error(`Error setting up pool kernel ${t}:`,e),super.emit(c.z.EXECUTE_ERROR,{kernelId:t,data:{ename:"KernelSetupError",evalue:`Failed to setup kernel: ${e instanceof Error?e.message:String(e)}`,traceback:[e instanceof Error?e.stack||e.message:String(e)]}}),e}}setupPoolKernel(e,t,r){const n=this.reassignPoolKernel(e,t,r);if(n.mode===a.WORKER&&n.worker){const e=n.worker,{port1:r,port2:o}=new MessageChannel;e.postMessage({type:"SET_EVENT_PORT",port:o},[o]);const i=e=>{e.data&&e.data.type&&super.emit(e.data.type,{kernelId:t,data:e.data.data})};r.addEventListener("message",i),r.start();const s=n.destroy;n.destroy=async()=>(r.removeEventListener("message",i),r.close(),s())}return this.kernels.set(t,n),this.setupEventForwarding(n),this.updateKernelActivity(t),r.inactivityTimeout&&r.inactivityTimeout>0&&this.setupInactivityTimeout(t,r.inactivityTimeout),r.maxExecutionTime&&r.maxExecutionTime>0&&this.setupStalledExecutionHandler(t),t}async createOnDemandKernel(e,t,r,n){const o={id:e,options:{...n,lang:r},mode:t,language:r};let i;return this.kernels.set(e,o),i=t===a.MAIN_THREAD?await this.createMainThreadKernel(e):await this.createWorkerKernel(e),this.kernels.set(e,i),this.setupEventForwarding(i),this.updateKernelActivity(e),n.inactivityTimeout&&n.inactivityTimeout>0&&this.setupInactivityTimeout(e,n.inactivityTimeout),n.maxExecutionTime&&n.maxExecutionTime>0&&this.setupStalledExecutionHandler(e),e}async createMainThreadKernel(e){const t=this.kernels.get(e)?.options||{},r=t.lang||l.PYTHON,n=new m,o={id:e,kernel:n,mode:a.MAIN_THREAD,language:r,created:new Date,options:t,destroy:async()=>Promise.resolve()},i={};return t.filesystem&&(i.filesystem=t.filesystem),t.env&&(i.env=t.env),t.lockFileURL&&(i.lockFileURL=t.lockFileURL),await n.initialize(i),o}async createWorkerKernel(e){const t=this.kernels.get(e)?.options||{},r=t.lang||l.PYTHON;t.deno?.permissions&&t.deno.permissions;const n=new Worker("./dist/kernel.worker.js",{type:"classic"}),{port1:o,port2:i}=new MessageChannel,s=new Promise((e,t)=>{const r=n=>{"KERNEL_INITIALIZED"===n.data?.type&&(n.data.data.success?(o.removeEventListener("message",r),e()):(o.removeEventListener("message",r),t(new Error("Kernel initialization failed"))))};o.addEventListener("message",r)});n.postMessage({type:"SET_EVENT_PORT",port:i},[i]);const c=u.LV(n),p=t=>{t.data&&t.data.type&&super.emit(t.data.type,{kernelId:e,data:t.data.data})};return o.addEventListener("message",p),o.start(),n.postMessage({type:"INITIALIZE_KERNEL",options:{filesystem:t.filesystem,env:t.env,lockFileURL:t.lockFileURL,lang:r}}),await s,await this.setupWorkerInterruptBuffer(e,n),{id:e,kernel:{initialize:async e=>c.initialize(e),execute:async(e,t)=>await c.execute(e,t),isInitialized:()=>c.isInitialized(),inputReply:async e=>c.inputReply(e),getStatus:async()=>{try{return"function"==typeof c.getStatus?await c.getStatus():"unknown"}catch(e){return"unknown"}},complete:async(e,t,r)=>{try{return"function"==typeof c.complete?await c.complete(e,t,r):{status:"error",error:"Completion not supported"}}catch(e){return{status:"error",error:String(e)}}},inspect:async(e,t,r,n)=>{try{return"function"==typeof c.inspect?await c.inspect(e,t,r,n):{status:"error",error:"Inspection not supported"}}catch(e){return{status:"error",error:String(e)}}},isComplete:async(e,t)=>{try{return"function"==typeof c.isComplete?await c.isComplete(e,t):{status:"unknown"}}catch(e){return{status:"error",error:String(e)}}},interrupt:async()=>{try{return"function"==typeof c.interrupt&&await c.interrupt()}catch(e){return!1}},setInterruptBuffer:e=>{try{"function"==typeof c.setInterruptBuffer&&c.setInterruptBuffer(e)}catch(e){console.warn("Failed to set interrupt buffer:",e)}},commInfo:async(e,t)=>{try{return"function"==typeof c.commInfo?await c.commInfo(e,t):{comms:{},status:"ok"}}catch(e){return{comms:{},status:"error",error:String(e)}}},commOpen:async(e,t)=>{try{if("function"==typeof c.commOpen)return await c.commOpen(e,t)}catch(e){console.warn("Failed to open comm:",e)}},commMsg:async(e,t)=>{try{if("function"==typeof c.commMsg)return await c.commMsg(e,t)}catch(e){console.warn("Failed to send comm message:",e)}},commClose:async(e,t)=>{try{if("function"==typeof c.commClose)return await c.commClose(e,t)}catch(e){console.warn("Failed to close comm:",e)}}},mode:a.WORKER,language:r,worker:n,created:new Date,options:t,destroy:async()=>(o.removeEventListener("message",p),o.close(),n.terminate(),Promise.resolve())}}setupEventForwarding(e){e.mode===a.MAIN_THREAD&&Object.values(c.z).forEach(t=>{e.kernel.on(t,r=>{super.emit(t,{kernelId:e.id,data:r})})})}getKernel(e){return this.kernels.get(e)}getKernelIds(){return Array.from(this.kernels.keys())}async listKernels(e){const t=Array.from(this.kernels.entries()).filter(([t])=>!t.startsWith("pool-")&&(!e||t.startsWith(`${e}:`)));return await Promise.all(t.map(async([e,t])=>{const r=e.match(/^([^:]+):/),n=r?r[1]:void 0;let o="unknown";try{t&&t.kernel&&"function"==typeof t.kernel.getStatus&&(o=await t.kernel.getStatus())}catch(t){console.warn(`Error getting status for kernel ${e}:`,t),o="unknown"}return{id:e,mode:t.mode,language:t.language,status:o,created:t.created||new Date,namespace:n,deno:t.options?.deno}}))}async destroyKernel(e){const t=this.kernels.get(e);if(t){if("function"!=typeof t.destroy)throw new Error(`Kernel ${e} is missing destroy function (type: ${typeof t.destroy})`);if(this.abortAllKernelOperations(e),this.clearInactivityTimeout(e),this.executionTimeouts.has(e)){const t=this.executionTimeouts.get(e);for(const e of t.values())clearTimeout(e);this.executionTimeouts.delete(e)}this.executionStartTimes.has(e)&&this.executionStartTimes.delete(e),this.executionMetadata.has(e)&&this.executionMetadata.delete(e),this.interruptBuffers.has(e)&&this.interruptBuffers.delete(e),this.ongoingExecutions.delete(e),this.lastActivityTime.delete(e),this.removeAllKernelListeners(e),await t.destroy(),this.kernels.delete(e)}}async destroyAll(e){const t=Array.from(this.kernels.keys()).filter(t=>!e||t.startsWith(`${e}:`)).map(async e=>{const t=this.kernels.get(e);return t&&"function"==typeof t.destroy?this.destroyKernel(e):(console.warn(`Skipping incomplete kernel instance ${e} during destroyAll`),void this.kernels.delete(e))});await Promise.all(t),e||await this.destroyPool()}async destroyPool(){const e=[];for(const[t,r]of this.pool.entries())for(const t of r){const r=t.then(e=>e.destroy()).catch(e=>{console.error("Error destroying pool kernel from promise:",e)});e.push(r)}await Promise.all(e),this.pool.clear(),this.prefillingInProgress.clear()}onKernelEvent(e,t,r){if(!this.kernels.has(e))throw new Error(`Kernel with ID ${e} not found`);const n={original:r,wrapped:t=>{t.kernelId===e&&r(t.data)}};this.storeListener(e,t,r,n),super.on(t,n.wrapped)}offKernelEvent(e,t,r){const n=this.getListener(e,t,r);n&&(super.removeListener(t,n.wrapped),this.removeStoredListener(e,t,r))}storeListener(e,t,r,n){this.listenerWrappers.has(e)||this.listenerWrappers.set(e,new Map);const o=this.listenerWrappers.get(e);o.has(t)||o.set(t,new Map),o.get(t).set(r,n)}getListener(e,t,r){const n=this.listenerWrappers.get(e);if(!n)return;const o=n.get(t);return o?o.get(r):void 0}removeStoredListener(e,t,r){const n=this.listenerWrappers.get(e);if(!n)return;const o=n.get(t);o&&(o.delete(r),0===o.size&&n.delete(t),0===n.size&&this.listenerWrappers.delete(e))}removeAllKernelListeners(e){const t=this.listenerWrappers.get(e);if(t){for(const[e,r]of t.entries())for(const t of r.values())super.removeListener(e,t.wrapped);this.listenerWrappers.delete(e)}}getListeners(e,t){const r=this.listenerWrappers.get(e);if(!r)return[];const n=r.get(t);return n?Array.from(n.keys()):[]}async*executeStream(e,t,r={}){const n=this.getKernel(e);if(!n)throw new Error(`Kernel with ID ${e} not found`);this.updateKernelActivity(e);const o=this.trackExecution(e,t),i=new AbortController;this.storeAbortController(e,o,i);try{if(n.mode===a.MAIN_THREAD){const i=n.kernel;if("function"==typeof i.executeStream)try{return yield*i.executeStream(t,r),this.updateKernelActivity(e),this.completeExecution(e,o),{success:!0}}catch(t){return console.error("Error in main thread executeStream:",t),this.updateKernelActivity(e),this.completeExecution(e,o),{success:!1,error:t instanceof Error?t:new Error(String(t))}}}try{const s=[];let a=!1,l={success:!0};const u=new Map,p=()=>{for(const[e,t]of u.entries())super.off(e,t);u.clear()},d=t=>{const r=r=>{r.kernelId!==e||a||(s.push({type:t,data:r.data,executionId:o}),this.updateKernelActivity(e))};return u.set(t,r),r},h=d("stream"),m=d("display_data"),g=d("update_display_data"),f=d("execute_result"),y=d("execute_error");super.on(c.z.STREAM,h),super.on(c.z.DISPLAY_DATA,m),super.on(c.z.UPDATE_DISPLAY_DATA,g),super.on(c.z.EXECUTE_RESULT,f),super.on(c.z.EXECUTE_ERROR,y);const E=new Promise((p,d)=>{const h=t=>{t.kernelId!==e||a||(a=!0,l={success:!1,error:new Error(`${t.data.ename}: ${t.data.evalue}`),result:t.data},this.updateKernelActivity(e),p(l))};if(u.set("execute_error_completion",h),super.on(c.z.EXECUTE_ERROR,h),i.signal.aborted)return a=!0,void p({success:!1,error:new Error("Execution was aborted")});i.signal.addEventListener("abort",()=>{a||(console.log(`🚫 Execution ${o} aborted`),a=!0,p({success:!1,error:new Error("Execution was aborted")}))});try{n.kernel.execute(t,r).then(t=>{if(!a){if(t.success&&t.result&&"error"===t.result.status){const e={status:t.result.status,ename:t.result.ename,evalue:t.result.evalue,traceback:t.result.traceback};s.push({type:"error",data:e,executionId:o}),l={success:!1,error:new Error(`${t.result.ename}: ${t.result.evalue}`),result:t.result}}else l=t;a=!0,this.updateKernelActivity(e),p(l)}}).catch(t=>{if(!a){let r;console.error(`Error in execute for kernel ${e}:`,t),this.isKeyboardInterrupt(t)?(console.log(`KeyboardInterrupt caught in executeStream for kernel ${e}`),r=this.createKeyboardInterruptResult(),s.push({type:"error",data:r.result,executionId:o})):r={success:!1,error:t instanceof Error?t:new Error(String(t))},a=!0,l=r,this.updateKernelActivity(e),p(r)}})}catch(t){if(!a){console.error(`Error calling execute for kernel ${e}:`,t);const r={success:!1,error:t instanceof Error?t:new Error(String(t))};a=!0,l=r,this.updateKernelActivity(e),p(r)}}});try{for(;(!a||s.length>0)&&!i.signal.aborted;){if(s.length>0){const e=s.shift();yield e;continue}if(!a)try{await new Promise((e,t)=>{const r=setTimeout(e,10);i.signal.addEventListener("abort",()=>{clearTimeout(r),t(new Error("Aborted"))})})}catch(e){if(i.signal.aborted)break}}if(i.signal.aborted&&!a)throw new Error("Execution was aborted during stream monitoring");return await E}finally{p(),this.removeAbortController(e,o),this.completeExecution(e,o)}}catch(t){return this.completeExecution(e,o),console.error("Unexpected error in executeStream:",t),{success:!1,error:t instanceof Error?t:new Error(String(t))}}}catch(t){return this.completeExecution(e,o),console.error("Unexpected error in executeStream:",t),{success:!1,error:t instanceof Error?t:new Error(String(t))}}}trackExecution(e,t){const r=`exec-${crypto.randomUUID()}`,n=Date.now(),o=this.kernels.get(e);if(o&&o.mode===a.WORKER&&this.interruptBuffers.has(e)&&(this.interruptBuffers.get(e)[0]=0),this.ongoingExecutions.has(e)||this.ongoingExecutions.set(e,new Set),this.ongoingExecutions.get(e).add(r),this.executionStartTimes.has(e)||this.executionStartTimes.set(e,new Map),this.executionStartTimes.get(e).set(r,n),this.executionMetadata.has(e)||this.executionMetadata.set(e,new Map),this.updateKernelActivity(e),o&&o.options.maxExecutionTime&&o.options.maxExecutionTime>0){this.executionTimeouts.has(e)||this.executionTimeouts.set(e,new Map);const i=setTimeout(()=>{console.warn(`Execution ${r} on kernel ${e} has been running for ${o.options.maxExecutionTime}ms and may be stuck/dead.`);const i=this.executionMetadata.get(e)?.get(r),s=Date.now()-(i?.startTime||n);super.emit("execution_stalled",{kernelId:e,executionId:r,maxExecutionTime:o.options.maxExecutionTime,actualRuntime:s,code:i?.code||t,startTime:i?.startTime||n}),this.handleStuckExecution(e,r,s,i?.code||t)},o.options.maxExecutionTime);this.executionTimeouts.get(e).set(r,i),this.executionMetadata.get(e).set(r,{startTime:n,code:t,timeoutId:i})}else this.executionMetadata.get(e).set(r,{startTime:n,code:t});return r}completeExecution(e,t){if(this.executionTimeouts.has(e)){const r=this.executionTimeouts.get(e);r.has(t)&&(clearTimeout(r.get(t)),r.delete(t)),0===r.size&&this.executionTimeouts.delete(e)}if(this.executionStartTimes.has(e)){const r=this.executionStartTimes.get(e);r.delete(t),0===r.size&&this.executionStartTimes.delete(e)}if(this.executionMetadata.has(e)){const r=this.executionMetadata.get(e);r.delete(t),0===r.size&&this.executionMetadata.delete(e)}if(this.ongoingExecutions.has(e)){const r=this.ongoingExecutions.get(e);r.delete(t),0===r.size&&(this.ongoingExecutions.delete(e),this.updateKernelActivity(e))}}hasOngoingExecutions(e){return this.ongoingExecutions.has(e)&&this.ongoingExecutions.get(e).size>0}getOngoingExecutionCount(e){return this.ongoingExecutions.has(e)?this.ongoingExecutions.get(e).size:0}setupInactivityTimeout(e,t){if(t<=0)return;this.clearInactivityTimeout(e);const r=this.lastActivityTime.get(e)||Date.now(),n=Date.now()-r,o=Math.max(0,t-n);if(0===o)return this.hasOngoingExecutions(e)?void this.setupInactivityTimeout(e,t):void this.destroyKernel(e).catch(t=>{console.error(`Error destroying inactive kernel ${e}:`,t)});const i=setTimeout(()=>{this.hasOngoingExecutions(e)?this.setupInactivityTimeout(e,t):this.destroyKernel(e).catch(t=>{console.error(`Error destroying inactive kernel ${e}:`,t)})},o);this.inactivityTimers.set(e,i)}clearInactivityTimeout(e){if(this.inactivityTimers.has(e)){const t=this.inactivityTimers.get(e);clearTimeout(t),this.inactivityTimers.delete(e)}}updateKernelActivity(e){this.lastActivityTime.set(e,Date.now());const t=this.kernels.get(e);if(!t)return;const r=t.options.inactivityTimeout;r&&r>0&&this.setupInactivityTimeout(e,r)}getLastActivityTime(e){return this.lastActivityTime.get(e)}getInactivityTimeout(e){const t=this.kernels.get(e);if(t)return t.options.inactivityTimeout}setInactivityTimeout(e,t){const r=this.kernels.get(e);return!!r&&(r.options.inactivityTimeout=t,this.clearInactivityTimeout(e),t>0&&this.setupInactivityTimeout(e,t),!0)}getTimeUntilShutdown(e){const t=this.kernels.get(e);if(!t)return;const r=t.options.inactivityTimeout;if(!r||r<=0)return;const n=this.lastActivityTime.get(e);if(!n)return;const o=r-(Date.now()-n);return Math.max(0,o)}getInactivityTimers(){const e={};return this.inactivityTimers.forEach((t,r)=>{e[r]=t}),e}setupStalledExecutionHandler(e){super.on(c.z.EXECUTION_STALLED,t=>{t.kernelId===e&&(console.warn(`Handling stalled execution ${t.executionId} on kernel ${e} (running longer than ${t.maxExecutionTime}ms)`),this.kernels.get(e)&&super.emit(c.z.EXECUTE_ERROR,{kernelId:e,data:{ename:"ExecutionStalledError",evalue:`Execution stalled or potentially deadlocked (running > ${t.maxExecutionTime}ms)`,traceback:["Execution may be stuck in an infinite loop or deadlocked."]}}))})}async forceTerminateKernel(e,t="Force terminated due to stalled execution"){if(!this.kernels.get(e))return!1;try{return console.warn(`Force terminating kernel ${e}: ${t}`),super.emit(c.z.EXECUTE_ERROR,{kernelId:e,data:{ename:"KernelForcedTermination",evalue:t,traceback:["Kernel was forcefully terminated by the system."]}}),await this.destroyKernel(e),!0}catch(t){return console.error(`Error during forced termination of kernel ${e}:`,t),!1}}getExecutionInfo(e){const t=this.kernels.get(e);if(!t)return{count:0,isStuck:!1,executionIds:[],executions:[]};if(!t.options)return{count:0,isStuck:!1,executionIds:[],executions:[]};const r=this.ongoingExecutions.get(e)?Array.from(this.ongoingExecutions.get(e)):[],n=r.length,o=Date.now(),i=t.options.maxExecutionTime,s=[];let a,l=!1;const c=this.executionStartTimes.get(e),u=this.executionMetadata.get(e);for(const t of r){const r=c?.get(t),n=u?.get(t);if(void 0!==r){const e=o-r,c=void 0!==i&&e>i;s.push({id:t,startTime:r,runtime:e,code:n?.code,isStuck:c}),(void 0===a||e>a)&&(a=e),c&&(l=!0)}else console.warn(`No start time found for execution ${t} on kernel ${e}`),s.push({id:t,startTime:0,runtime:0,code:n?.code,isStuck:!1})}return s.sort((e,t)=>e.startTime-t.startTime),{count:n,isStuck:l,executionIds:r,longestRunningTime:a,executions:s}}async execute(e,t,r={}){const n=this.getKernel(e);if(!n)throw new Error(`Kernel with ID ${e} not found`);this.updateKernelActivity(e);const o=this.trackExecution(e,t);try{const i=await n.kernel.execute(t,r);return this.updateKernelActivity(e),this.completeExecution(e,o),i}catch(t){return this.updateKernelActivity(e),this.completeExecution(e,o),{success:!1,error:t instanceof Error?t:new Error(String(t))}}}isKernelTypeAllowed(e,t){return this.allowedKernelTypes.some(r=>r.mode===e&&r.language===t)}getAllowedKernelTypes(){return[...this.allowedKernelTypes]}pingKernel(e){return!!this.kernels.get(e)&&(this.updateKernelActivity(e),!0)}async restartKernel(e){const t=this.kernels.get(e);if(!t)return console.warn(`Cannot restart kernel ${e}: kernel not found`),!1;try{const r={mode:t.mode,language:t.language,options:{...t.options}};let n,o;if(e.includes(":")){const t=e.split(":");n=t[0],o=t[1]}else o=e;await this.destroyKernel(e);const i={id:o,mode:r.mode,lang:r.language,namespace:n,deno:r.options.deno,filesystem:r.options.filesystem,inactivityTimeout:r.options.inactivityTimeout,maxExecutionTime:r.options.maxExecutionTime},s=await this.createKernel(i);return s===e||(console.error(`Kernel restart failed: expected ID ${e}, got ${s}`),!1)}catch(t){return console.error(`Error restarting kernel ${e}:`,t),!1}}async interruptKernel(e){const t=this.kernels.get(e);if(!t)return console.warn(`Cannot interrupt kernel ${e}: kernel not found`),!1;try{return t.mode===a.WORKER&&t.worker?await this.interruptWorkerKernel(e,t):await this.interruptMainThreadKernel(e,t)}catch(t){return console.error(`Error interrupting kernel ${e}:`,t instanceof Error?t.message:String(t)),!1}}async interruptMainThreadKernel(e,t){throw new Error(`Main thread kernel ${e} does not support reliable interruption. Use worker kernels for interruptible execution.`)}async interruptWorkerKernel(e,t){try{const r=t.worker;if(!r)return console.error(`Worker not found for kernel ${e}`),!1;if("kernel-interrupt"===this.interruptionMode)return await this.interruptWorkerKernelFallback(e,r);let n=this.interruptBuffers.get(e);if(!n)try{const t=new SharedArrayBuffer(1);n=new Uint8Array(t),n[0]=0,this.interruptBuffers.set(e,n),r.postMessage({type:"SET_INTERRUPT_BUFFER",buffer:n}),await new Promise((e,t)=>{const n=setTimeout(()=>{t(new Error("Timeout waiting for interrupt buffer setup"))},2e3),o=t=>{"INTERRUPT_BUFFER_SET"===t.data?.type&&(r.removeEventListener("message",o),clearTimeout(n),e())};r.addEventListener("message",o)}),console.log(`Interrupt buffer set up for kernel ${e}`)}catch(t){if("shared-array-buffer"===this.interruptionMode)throw console.error(`❌ Cannot create SharedArrayBuffer for interrupt handling in kernel ${e}`),new Error("SharedArrayBuffer is required for interruption mode 'shared-array-buffer' but is not available.\n\nTo fix this issue, either:\n1. Configure your web server with these headers:\n - Cross-Origin-Opener-Policy: same-origin\n - Cross-Origin-Embedder-Policy: require-corp\n\n2. Or change the interruption mode when creating KernelManager:\n new KernelManager({ interruptionMode: 'auto' })");return console.info(`ℹ️ Using message-based interrupt for kernel ${e} (SharedArrayBuffer not available)`),await this.interruptWorkerKernelFallback(e,r)}console.log(`Setting interrupt signal for kernel ${e}...`),n[0]=2;let o=0;const i=50;for(;o<i&&0!==n[0];)await new Promise(e=>setTimeout(e,100)),o++;return 0===n[0]?(console.log(`Interrupt processed successfully for kernel ${e} after ${100*o}ms`),!0):(console.warn(`Interrupt signal not processed for kernel ${e} after ${100*i}ms`),!0)}catch(t){return console.error(`Error interrupting worker kernel ${e}:`,t),!1}}async interruptWorkerKernelFallback(e,t){return new Promise(r=>{const n=e=>{if("INTERRUPT_TRIGGERED"===e.data?.type){t.removeEventListener("message",n);const o=e.data.data?.success||!1;r(o)}};t.addEventListener("message",n),t.postMessage({type:"INTERRUPT_KERNEL"}),setTimeout(()=>{t.removeEventListener("message",n),console.warn(`⏱️ Interrupt request timed out for kernel ${e} after 5 seconds.\nThis may happen if:\n- The kernel is running code that cannot be interrupted\n- The kernel is in an unresponsive state\nYou may need to restart the kernel if it remains unresponsive.`),r(!1)},5e3)})}async handleStuckExecution(e,t,r,n){const o=this.kernels.get(e);if(o){if(console.warn(`Handling stuck execution ${t} on kernel ${e} (runtime: ${r}ms)`),await this.interruptKernel(e))return console.log(`Successfully interrupted kernel ${e}`),void super.emit(c.z.EXECUTE_ERROR,{kernelId:e,data:{ename:"ExecutionInterrupted",evalue:`Execution automatically interrupted after ${r}ms (exceeded maxExecutionTime)`,traceback:["Execution was automatically interrupted due to timeout.",`Runtime: ${r}ms`,`Max allowed: ${o.options.maxExecutionTime}ms`,n?`Code: ${n.substring(0,200)}${n.length>200?"...":""}`:"Code: <unknown>"]}});if(console.warn(`Interrupt failed for kernel ${e}, attempting restart...`),await this.restartKernel(e))return console.log(`Successfully restarted kernel ${e}`),void super.emit(c.z.EXECUTE_ERROR,{kernelId:e,data:{ename:"KernelRestarted",evalue:`Kernel automatically restarted due to stuck execution (runtime: ${r}ms)`,traceback:["Kernel was automatically restarted due to stuck execution.",`Runtime: ${r}ms`,`Max allowed: ${o.options.maxExecutionTime}ms`,"Interrupt attempt failed, kernel was restarted instead.",n?`Code: ${n.substring(0,200)}${n.length>200?"...":""}`:"Code: <unknown>"]}});console.error(`Restart failed for kernel ${e}, force terminating...`),await this.forceTerminateKernel(e,`Stuck execution could not be interrupted or restarted (runtime: ${r}ms)`)?console.log(`Successfully terminated kernel ${e}`):(console.error(`Failed to terminate kernel ${e} - manual intervention may be required`),super.emit("kernel_unrecoverable",{kernelId:e,executionId:t,actualRuntime:r,code:n,message:"Kernel is stuck and could not be recovered through interrupt, restart, or termination"}))}}getStuckExecutions(){const e=[],t=Date.now();for(const[r,n]of this.kernels.entries()){if(r.startsWith("pool-"))continue;if(!n.options?.maxExecutionTime||n.options.maxExecutionTime<=0)continue;const o=n.options.maxExecutionTime,i=this.executionStartTimes.get(r),s=this.executionMetadata.get(r),a=this.ongoingExecutions.get(r);if(a&&0!==a.size)for(const l of a){const a=i?.get(l);if(void 0===a)continue;const c=t-a;if(c>o){const t=s?.get(l);e.push({kernelId:r,executionId:l,startTime:a,runtime:c,maxAllowed:o,code:t?.code,kernelMode:n.mode,kernelLanguage:n.language})}}}return e.sort((e,t)=>t.runtime-e.runtime),e}async handleAllStuckExecutions(){const e=this.getStuckExecutions(),t=[];console.log(`Found ${e.length} stuck executions to handle`);const r=new Map;for(const t of e)r.has(t.kernelId)||r.set(t.kernelId,[]),r.get(t.kernelId).push(t);for(const[e,n]of r)try{const r=n[0];console.log(`Handling stuck kernel ${e} with ${n.length} stuck executions (primary: ${r.runtime}ms)`),await this.handleStuckExecution(e,r.executionId,r.runtime,r.code);for(const e of n)t.push({kernelId:e.kernelId,executionId:e.executionId,action:"interrupted",success:!0})}catch(r){console.error(`Error handling stuck executions for kernel ${e}:`,r);for(const e of n)t.push({kernelId:e.kernelId,executionId:e.executionId,action:"failed",success:!1,error:r instanceof Error?r.message:String(r)})}return t}async setupWorkerInterruptBuffer(e,t){if("kernel-interrupt"!==this.interruptionMode)try{const r=new SharedArrayBuffer(1),n=new Uint8Array(r);n[0]=0,this.interruptBuffers.set(e,n),t.postMessage({type:"SET_INTERRUPT_BUFFER",buffer:n}),await new Promise((e,r)=>{const n=setTimeout(()=>{r(new Error("Timeout waiting for interrupt buffer setup"))},5e3),o=r=>{"INTERRUPT_BUFFER_SET"===r.data?.type&&(t.removeEventListener("message",o),clearTimeout(n),e())};t.addEventListener("message",o)})}catch(t){if("shared-array-buffer"===this.interruptionMode)throw console.error(`❌ SharedArrayBuffer required but not available for kernel ${e}`),new Error("SharedArrayBuffer is required but not available. To enable SharedArrayBuffer, your server must set these headers:\n- Cross-Origin-Opener-Policy: same-origin\n- Cross-Origin-Embedder-Policy: require-corp\n\nAlternatively, use interruptionMode: 'kernel-interrupt' or 'auto' in KernelManager options.");console.info(`ℹ️ SharedArrayBuffer not available for kernel ${e}. Using alternative interrupt method.\n\nTo enable faster interrupts, configure your server with these headers:\n- Cross-Origin-Opener-Policy: same-origin\n- Cross-Origin-Embedder-Policy: require-corp\n\nNote: Some development servers (e.g., Vite, webpack-dev-server) can be configured to add these headers.\nThe alternative interrupt method will still work but may be less responsive for long-running code.`)}else console.log(`Skipping SharedArrayBuffer setup for kernel ${e} - using kernel.interrupt() mode`)}}class h{constructor(){this.events={}}on(e,t){this.events[e]||(this.events[e]=[]),this.events[e].push(t)}off(e,t){if(!this.events[e])return;const r=this.events[e].indexOf(t);r>-1&&this.events[e].splice(r,1)}emit(e,...t){this.events[e]&&this.events[e].forEach(e=>e(...t))}setMaxListeners(e){}}class m extends h{constructor(){super(),this.initialized=!1,this.initPromise=null,this.filesystemOptions={enabled:!1,root:".",mountPoint:"/home/pyodide"},this._resolveInputReply=null,this._parent_header={},this.executionCount=0,this._status="unknown",this._interruptBuffer=null,this._interruptSupported=!1,this.environmentVariables={},super.setMaxListeners(20),this.kernelId=`kernel_${Math.random().toString(36).substring(2)}_${Date.now()}`}async getStatus(){return this._status}async initialize(e){if(!this.initialized)return this.initPromise||(e?.filesystem&&(this.filesystemOptions={...this.filesystemOptions,...e.filesystem}),e?.env&&(this.environmentVariables={...e.env}),e?.lockFileURL&&(this.lockFileURL=e.lockFileURL),this.initPromise=this._initializeInternal()),this.initPromise}async _initializeInternal(){const e=Date.now();console.log("🚀 Starting optimized kernel initialization...");try{const t=Date.now(),r={};this.lockFileURL&&(r.lockFileURL=this.lockFileURL,console.log(`🔒 Using lockFileURL: ${this.lockFileURL}`)),this.pyodide=await async function(e={}){return s||(s=(async()=>{try{"undefined"!=typeof importScripts?await new Promise((e,t)=>{try{if("undefined"==typeof importScripts)return void t(new Error("importScripts is not available - not in a worker context"));if(void 0!==globalThis.loadPyodide)return void e();importScripts(o),e()}catch(e){t(new Error(`Failed to import Pyodide in worker: ${e}`))}}):await new Promise((e,t)=>{if(void 0!==globalThis.loadPyodide)return void e();const r=document.createElement("script");r.src=o,r.onload=()=>e(),r.onerror=()=>t(new Error(`Failed to load Pyodide from ${o}`)),document.head.appendChild(r)});const t=globalThis.loadPyodide;if(!t)throw new Error("loadPyodide function not found after script load");const r={indexURL:"https://cdn.jsdelivr.net/pyodide/v0.28.0/full/",...e},n=await t(r);return i=!0,console.log("✅ Pyodide loaded successfully from CDN"),n}catch(e){throw s=null,e}})(),s)}(r);const n=Date.now()-t;if(console.log(`✅ Pyodide loaded in ${n}ms`),this.lockFileURL){console.log("🚀 Using lock file - skipping package installation");const[,]=await Promise.all([this.filesystemOptions.enabled?this.mountFilesystem():Promise.resolve(),this.setEnvironmentVariables()]);await this.initGlobals()}else{const[,,]=await Promise.all([this.filesystemOptions.enabled?this.mountFilesystem():Promise.resolve(),this.initPackageManager(),this.setEnvironmentVariables()]);await this.initKernel(),await this.initGlobals()}const a=Date.now()-e;console.log(`🎯 KERNEL INITIALIZATION COMPLETE in ${a}ms`),console.log(`⚡ Performance: Pyodide(${n}ms) + Setup(${a-n}ms)`),this.initialized=!0,this._status="active",console.log("🟢 Kernel is now ACTIVE and ready for execution!")}catch(e){throw console.error("❌ Kernel initialization failed:",e),this._status="unknown",e}}async mountFilesystem(){try{console.log(`Mounting filesystem from ${this.filesystemOptions.root} to ${this.filesystemOptions.mountPoint}`),await this.pyodide.FS.mount(this.pyodide.FS.filesystems.NODEFS,{root:this.filesystemOptions.root||"."},this.filesystemOptions.mountPoint||"/home/pyodide"),console.log("Filesystem mounted successfully");try{const e=this.pyodide.FS.readdir(this.filesystemOptions.mountPoint||"/home/pyodide");console.log(`Files in ${this.filesystemOptions.mountPoint} directory: ${e.join(", ")}`)}catch(e){console.error(`Error listing mounted directory: ${e}`)}}catch(e){throw console.error("Error mounting filesystem:",e),e}}async initPackageManager(){const e=Date.now();console.log("⚡ Initializing optimized package manager...");try{let t;console.log("📦 Loading micropip, packaging..."),await this.pyodide.loadPackage(["micropip","packaging"]),console.log("✅ Loaded micropip, packaging"),t="undefined"!=typeof window&&window.location?new URL(".",window.location.href).href:"undefined"!=typeof self&&self.location?new URL(".",self.location.href).href:"/";const r=new URL("pypi/all.json",t).href,n=[new URL("pypi/piplite-0.6.0a5-py3-none-any.whl",t).href,new URL("pypi/pyodide_kernel-0.6.0a5-py3-none-any.whl",t).href,new URL("pypi/ipykernel-6.9.2-py3-none-any.whl",t).href,new URL("pypi/widgetsnbextension-3.6.999-py3-none-any.whl",t).href,new URL("pypi/widgetsnbextension-4.0.999-py3-none-any.whl",t).href];console.log(`🚀 Installing ${n.length} wheel packages in parallel...`);const o=n.map(async(e,t)=>{const r=Date.now();try{await this.pyodide.runPythonAsync(`\nimport micropip\nawait micropip.install('${e}', keep_going=True)\nprint(f"✅ Wheel ${t+1}/${n.length} installed")\n`);const o=Date.now()-r;return console.log(`⚡ Wheel ${t+1} installed in ${o}ms`),{index:t,success:!0,time:o}}catch(e){const n=Date.now()-r;return console.warn(`⚠️ Wheel ${t+1} failed after ${n}ms:`,e),{index:t,success:!1,time:n,error:e}}}),i=await Promise.all(o),s=i.filter(e=>e.success),a=i.filter(e=>!e.success);console.log(`📊 Wheels: ${s.length}/${n.length} successful`),a.length>0&&console.warn(`⚠️ Failed wheels: ${a.map(e=>e.index+1).join(", ")}`);try{await this.pyodide.runPythonAsync(`\ntry:\n import piplite.piplite\n import json\n\n # Load package index for faster lookups\n try:\n piplite.piplite.PIPLITE_URL = "${r}"\n # Pre-load package index for faster installation\n print("📋 Package index configured")\n except Exception as e:\n print(f"⚠️ Package index setup warning: {e}")\n\n # Configure piplite for optimal performance\n piplite.piplite.REPODATA_INFO = {}\n print("⚡ Piplite optimized for performance")\nexcept ImportError:\n print("⚠️ Piplite not available, continuing without it")\nexcept Exception as e:\n print(f"⚠️ Piplite setup failed: {e}")\n`)}catch(e){console.warn("⚠️ Piplite configuration failed, continuing without it:",e)}const l=Date.now()-e;console.log(`🎯 Package manager initialized in ${l}ms`)}catch(e){throw console.error("❌ Package manager initialization failed:",e),e}}async initKernel(){const e=Date.now();console.log("🚀 Initializing kernel packages with maximum optimization...");const t=[{name:"pure-eval",priority:1,source:"pyodide"},{name:"stack-data",priority:1,source:"pyodide"},{name:"pygments",priority:1,source:"pyodide"},{name:"ssl",priority:1,source:"pyodide"},{name:"sqlite3",priority:1,source:"pyodide"},{name:"prompt_toolkit",priority:1,source:"pyodide"},{name:"jedi",priority:1,source:"pyodide"},{name:"ipython",priority:1,source:"pyodide"},{name:"comm",priority:2,source:"pip"},{name:"hypha-rpc",priority:2,source:"pip"},{name:"nbformat",priority:2,source:"pip"},{name:"ipykernel",priority:3,source:"pip"},{name:"pyodide_kernel",priority:3,source:"pip"}];try{console.log(`📦 Installing ${t.length} packages with intelligent optimization...`),await this.installPackagesWithIntelligentOptimization(t),console.log("📥 Importing pyodide_kernel...");const r=Date.now();await this.pyodide.runPythonAsync("import pyodide_kernel");const n=Date.now()-r;console.log(`✅ pyodide_kernel imported in ${n}ms`);const o=Date.now()-e;console.log(`🎯 Kernel packages initialized in ${o}ms`)}catch(e){throw console.error("❌ Kernel package initialization failed:",e),e}}async installPackagesWithIntelligentOptimization(e){console.log(`⚡ Starting intelligent parallel installation of ${e.length} packages...`);const t=e.map(async e=>{const t=Date.now();try{if(console.log(`🔄 Installing ${e.name} (priority: ${e.priority}, preferred: ${e.source})...`),"pyodide"!==e.source){await this.installViaPipWithOptimizations(e.name);const r=Date.now()-t;return console.log(`✅ ${e.name} installed via pip (${r}ms)`),{package:e.name,method:"pip",duration:r,success:!0,priority:e.priority}}try{await this.pyodide.loadPackage([e.name]);const r=Date.now()-t;return console.log(`✅ ${e.name} loaded from Pyodide CDN (${r}ms)`),{package:e.name,method:"pyodide",duration:r,success:!0,priority:e.priority}}catch(r){console.log(`📦 ${e.name} not available on CDN, trying pip...`),await this.installViaPipWithOptimizations(e.name);const n=Date.now()-t;return console.log(`✅ ${e.name} installed via pip fallback (${n}ms)`),{package:e.name,method:"pip-fallback",duration:n,success:!0,priority:e.priority}}}catch(r){const n=Date.now()-t;return console.warn(`❌ Failed to install ${e.name} after ${n}ms:`,r),{package:e.name,method:"failed",duration:n,success:!1,priority:e.priority,error:r}}}),r=await Promise.all(t);this.analyzeInstallationResults(r)}async installViaPipWithOptimizations(e){await this.pyodide.runPythonAsync(`\ntry:\n # Import piplite first\n import piplite\n # Use optimized pip installation with caching\n await piplite.install('${e}', keep_going=True, deps=True)\n print("✅ Successfully installed ${e} via optimized pip")\nexcept Exception as e:\n print("⚠️ Warning: Failed to install ${e}:", str(e))\n # Try alternative installation method\n try:\n import micropip\n await micropip.install('${e}', keep_going=True)\n print("✅ Successfully installed ${e} via micropip fallback")\n except Exception as e2:\n print("❌ Both pip methods failed for ${e}:", str(e2))\n raise e2\n`)}analyzeInstallationResults(e){const t=e.filter(e=>e.success),r=e.filter(e=>!e.success),n=t.filter(e=>"pyodide"===e.method),o=t.filter(e=>"pip"===e.method),i=t.filter(e=>"pip-fallback"===e.method),s=Math.max(...e.map(e=>e.duration)),a=e.reduce((e,t)=>e+t.duration,0)/e.length,l=e.reduce((e,t)=>e+t.duration,0);console.log("🎯 INTELLIGENT INSTALLATION COMPLETE!"),console.log(`📊 Results: ${t.length}/${e.length} successful`),console.log(`⚡ Pyodide CDN: ${n.length} packages`),console.log(`📦 Direct pip: ${o.length} packages`),console.log(`🔄 Pip fallback: ${i.length} packages`),console.log(`❌ Failed: ${r.length} packages`),console.log(`⏱️ Total time: ${s}ms (vs ~${l}ms sequential)`),console.log(`🚀 Speed improvement: ~${Math.round(l/s)}x faster`),console.log(`📈 Average per package: ${Math.round(a)}ms`),r.length>0&&(console.warn(`⚠️ Failed packages: ${r.map(e=>e.package).join(", ")}`),r.forEach(e=>{console.warn(` - ${e.package}: ${e.error?.message||"Unknown error"}`)}));const c=Math.min(...t.map(e=>e.duration)),u=Math.max(...t.map(e=>e.duration));console.log(`📊 Performance range: ${c}ms (fastest) to ${u}ms (slowest)`)}async initGlobals(){console.log("Initializing globals...");const{globals:e}=this.pyodide;this._kernel=e.get("pyodide_kernel").kernel_instance.copy(),this._stdout_stream=e.get("pyodide_kernel").stdout_stream.copy(),this._stderr_stream=e.get("pyodide_kernel").stderr_stream.copy(),this._interpreter=this._kernel.interpreter.copy(),this._interpreter.send_comm=this.sendComm.bind(this),this.setupCallbacks()}setupCallbacks(){const e=(e,t)=>{const r={name:this.formatResult(e),text:this.formatResult(t)};this._sendMessage({parentHeader:this.formatResult(this._parent_header).header,bundle:r,type:"stream"})};this._stdout_stream.publish_stream_callback=e,this._stderr_stream.publish_stream_callback=e,this._interpreter.display_pub.clear_output_callback=e=>{const t={wait:this.formatResult(e)};this._sendMessage({parentHeader:this.formatResult(this._parent_header).header,bundle:t,type:"clear_output"})},this._interpreter.display_pub.display_data_callback=(e,t,r)=>{const n={data:this.formatResult(e),metadata:this.formatResult(t),transient:this.formatResult(r)};this._sendMessage({parentHeader:this.formatResult(this._parent_header).header,bundle:n,type:"display_data"})},this._interpreter.display_pub.update_display_data_callback=(e,t,r)=>{const n={data:this.formatResult(e),metadata:this.formatResult(t),transient:this.formatResult(r)};this._sendMessage({parentHeader:this.formatResult(this._parent_header).header,bundle:n,type:"update_display_data"})},this._interpreter.displayhook.publish_execution_result=(e,t,r)=>{const n={execution_count:e,data:this.formatResult(t),metadata:this.formatResult(r)};this._sendMessage({parentHeader:this.formatResult(this._parent_header).header,bundle:n,type:"execute_result"})},this._interpreter.input=this.input.bind(this),this._interpreter.getpass=this.getpass.bind(this)}_sendMessage(e){this._processMessage(e)}_processMessage(e){if(!e.type)return;let t;switch(e.type){case"stream":{const r=e.bundle??{name:"stdout",text:""};super.emit(c.z.STREAM,r),t=r;break}case"input_request":{const r=e.content??{prompt:"",password:!1};super.emit(c.z.INPUT_REQUEST,r),t=r;break}case"display_data":{const r=e.bundle??{data:{},metadata:{},transient:{}};super.emit(c.z.DISPLAY_DATA,r),t=r;break}case"update_display_data":{const r=e.bundle??{data:{},metadata:{},transient:{}};super.emit(c.z.UPDATE_DISPLAY_DATA,r),t=r;break}case"clear_output":{const r=e.bundle??{wait:!1};super.emit(c.z.CLEAR_OUTPUT,r),t=r;break}case"execute_result":{const r=e.bundle??{execution_count:this.executionCount,data:{},metadata:{}};super.emit(c.z.EXECUTE_RESULT,r),t=r;break}case"execute_error":{const r=e.bundle??{ename:"",evalue:"",traceback:[]};super.emit(c.z.EXECUTE_ERROR,r),t=r;break}case"comm_open":case"comm_msg":case"comm_close":{const r=e.content??{};super.emit(e.type,r,e.metadata,e.buffers),t={content:r,metadata:e.metadata,buffers:e.buffers};break}}t&&super.emit(c.z.ALL,{type:e.type,data:t})}isInitialized(){return this.initialized}async setup(e){await this.initialize(),this._parent_header=this.pyodide.toPy(e||{})}async execute(e,t={}){this.initialized||await this.initialize();try{this._status="busy",super.emit(c.z.KERNEL_BUSY,{}),await this.setup(t);const r="\n# Kernel isolation - reset commonly conflicting variables to prevent cross-kernel state sharing\nfor _var in ['x', 'value', 'result', 'a', 'b', 'c', 'data', 'temp']:\n if _var in globals():\n del globals()[_var]\ndel _var\n";return this.pyodide.runPython(r),new Promise((t,r)=>{const n={allMessages:[],executionComplete:!1,executionResult:null,executionError:null,timeout:null},o=e=>{n.allMessages.push(e)},i=async e=>{if(n.executionComplete)return;console.log(`[KERNEL] Execution completed, processing ${n.allMessages.length} messages`),n.executionComplete=!0,super.off(c.z.ALL,o);let r,i=!1,s=null;const a=n.executionResult;a&&"error"===a.status&&(i=!0,s={ename:a.ename,evalue:a.evalue,traceback:a.traceback});for(const e of n.allMessages){if("execute_error"===e.type){i=!0,s=e.data;break}"execute_result"===e.type&&(r=e.data)}if(this._status="active",super.emit(c.z.KERNEL_IDLE,{}),i){console.log("[KERNEL] Execution failed with error:",s);const e=s.ename?s.ename.replace(/^<class '(.+)'>$/,"$1"):s.ename;super.emit(c.z.EXECUTE_ERROR,{ename:e,evalue:s.evalue,traceback:s.traceback});const r=`${s.ename||"Error"}: ${s.evalue||"Unknown error"}`;t({success:!1,error:new Error(r),result:n.executionResult})}else{console.log(`[KERNEL] Execution successful, captured ${n.allMessages.length} output messages`);let e=void 0!==r?r:n.executionResult;t({success:!0,result:e})}};super.on(c.z.ALL,o),this._kernel.run(e).then(e=>{console.log("[KERNEL] Python execution finished, waiting for messages to settle"),n.executionResult=this.formatResult(e),setTimeout(()=>{i()},100)}).catch(e=>{console.error("[KERNEL] Python execution error:",e),n.executionError=e instanceof Error?e:new Error(String(e)),setTimeout(()=>{i()},100)})})}catch(e){return console.error("[KERNEL] Execute setup error:",e),this._status="active",super.emit(c.z.KERNEL_IDLE,{}),{success:!1,error:e instanceof Error?e:new Error(String(e))}}}formatResult(e){if(!(e instanceof this.pyodide.ffi.PyProxy))return e;try{const t=e.toJs();return this.mapToObject(t)}catch(e){return console.error("Error formatting result:",e),{status:"error",error:String(e)}}}mapToObject(e){const t=e instanceof Array?[]:{};return e.forEach((e,r)=>{t[r]=e instanceof Map||e instanceof Array?this.mapToObject(e):e}),t}async inputReply(e){this._resolveInputReply&&(this._resolveInputReply(e),this._resolveInputReply=null)}async sendInputRequest(e,t){const r={prompt:e,password:t};this._sendMessage({type:"input_request",content:r,parentHeader:this.formatResult(this._parent_header).header})}async getpass(e){e=void 0===e?"":e,await this.sendInputRequest(e,!0);const t=new Promise(e=>{this._resolveInputReply=e});return(await t).value}async input(e){e=void 0===e?"":e,await this.sendInputRequest(e,!1);const t=new Promise(e=>{this._resolveInputReply=e});return(await t).value}async sendComm(e,t,r,n,o){this._sendMessage({type:e,content:this.formatResult(t),metadata:this.formatResult(r),ident:this.formatResult(n),buffers:this.formatResult(o),parentHeader:this.formatResult(this._parent_header).header})}async complete(e,t,r={}){await this.setup(r);const n=this._kernel.complete(e,t);return this.formatResult(n)}async inspect(e,t,r,n={}){await this.setup(n);const o=this._kernel.inspect(e,t,r);return this.formatResult(o)}async isComplete(e,t={}){await this.setup(t);const r=this._kernel.is_complete(e);return this.formatResult(r)}async commInfo(e,t={}){await this.setup(t);const r=this._kernel.comm_info(e);return{comms:this.formatResult(r),status:"ok"}}async commOpen(e,t={}){await this.setup(t);const r=this._kernel.comm_manager.comm_open(this.pyodide.toPy(null),this.pyodide.toPy(null),this.pyodide.toPy(e));return this.formatResult(r)}async commMsg(e,t={}){await this.setup(t);const r=this._kernel.comm_manager.comm_msg(this.pyodide.toPy(null),this.pyodide.toPy(null),this.pyodide.toPy(e));return this.formatResult(r)}async commClose(e,t={}){await this.setup(t);const r=this._kernel.comm_manager.comm_close(this.pyodide.toPy(null),this.pyodide.toPy(null),this.pyodide.toPy(e));return this.formatResult(r)}async*executeStream(e,t={}){try{await this.initialize();const r=[],n=e=>{r.push(e)};super.on(c.z.ALL,n);try{const n=this.execute(e,t);for(;;)if(r.length>0&&(yield r.shift()),await Promise.race([n.then(()=>!0),new Promise(e=>setTimeout(()=>e(!1),10))])){for(;r.length>0;)yield r.shift();return await n}}catch(e){throw console.error("Error in executeStream:",e),e}finally{super.off(c.z.ALL,n)}}catch(e){return console.error("Error in executeStream setup:",e),{success:!1,error:e instanceof Error?e:new Error(String(e))}}}async interrupt(){if(!this.initialized||!this.pyodide)return console.warn("[KERNEL] Cannot interrupt: kernel not initialized"),!1;console.log("[KERNEL] Attempting to interrupt execution...");try{if(this._interruptBuffer&&this._interruptSupported&&(console.log("[KERNEL] Using interrupt buffer method"),this._interruptBuffer[0]=2,await new Promise(e=>setTimeout(e,100)),0===this._interruptBuffer[0]))return console.log("[KERNEL] Interrupt processed successfully via buffer"),!0;try{return console.log("[KERNEL] Attempting Python-level interrupt"),await this.pyodide.runPythonAsync("\nimport sys\nimport _thread\n# Try to interrupt the main thread\n_thread.interrupt_main()\n"),console.log("[KERNEL] Python interrupt signal sent"),!0}catch(e){console.log("[KERNEL] Python interrupt attempt failed:",e)}return this._interpreter&&"function"==typeof this._interpreter.interrupt?(console.log("[KERNEL] Using interpreter interrupt method"),this._interpreter.interrupt(),!0):(console.log("[KERNEL] Sending interrupt messages for UI feedback"),this._sendMessage({type:"stream",bundle:{name:"stderr",text:"KeyboardInterrupt: Execution interrupted by user\n"}}),this._sendMessage({type:"execute_error",bundle:{ename:"KeyboardInterrupt",evalue:"Execution interrupted by user",traceback:["KeyboardInterrupt: Execution interrupted by user"]}}),!1)}catch(e){return console.error("[KERNEL] Error during interrupt:",e),!1}}setInterruptBuffer(e){this._interruptBuffer=e;try{this.pyodide&&"function"==typeof this.pyodide.setInterruptBuffer?(this.pyodide.setInterruptBuffer(e),this._interruptSupported=!0):(console.warn("[KERNEL] pyodide.setInterruptBuffer not available, interrupt support limited"),this._interruptSupported=!1)}catch(e){console.error("[KERNEL] Error setting interrupt buffer:",e),this._interruptSupported=!1}}async setEnvironmentVariables(){if(0===Object.keys(this.environmentVariables).length)return;const e=Date.now();console.log(`🌍 Setting ${Object.keys(this.environmentVariables).length} environment variables...`);try{for(const[e,t]of Object.entries(this.environmentVariables)){let r;r=null==t?"":String(t),await this.pyodide.runPythonAsync(`\nimport os\nos.environ[${JSON.stringify(e)}] = ${JSON.stringify(r)}\n`)}const t=Date.now()-e;console.log(`⚡ Environment variables set in ${t}ms`)}catch(e){throw console.error("❌ Failed to set environment variables:",e),e}}}const g=n.MB,f=n.zZ,y=n.y9,E=n.dR,w=n.J9;export{g as Kernel,f as KernelEvents,y as KernelLanguage,E as KernelManager,w as KernelMode};
//# sourceMappingURL=web-python-kernel.min.mjs.map
{
"name": "web-python-kernel",
"version": "0.1.0",
"version": "0.1.1",
"description": "A web-based Python kernel for browser environments with TypeScript support",

@@ -5,0 +5,0 @@ "main": "dist/web-python-kernel.js",

export {};
//# sourceMappingURL=worker.worker.d.ts.map
{"version":3,"file":"worker.worker.d.ts","sourceRoot":"","sources":["../../src/worker.worker.ts"],"names":[],"mappings":""}

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display