icoa-cli 2.19.387 → 2.19.388

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{existsSync as e,mkdirSync as o,readFileSync as n,writeFileSync as l}from"node:fs";import{homedir as t}from"node:os";import{Interface as r,createInterface as a}from"node:readline";import{basename as s,isAbsolute as c,join as i,resolve as y}from"node:path";import chalk from"chalk";import{aienvPaths as g}from"../lib/aienv.js";import{editTextInEditor as d}from"../lib/editor-spawn.js";import{buildSshArgs as u,leaseConnectProblems as p,parseLeaseResponse as h,queueLine as m}from"../lib/gpu.js";import{shouldExecuteCell as w}from"../lib/ipynb-input.js";import{looksLikeMarkdown as f,renderMarkdown as v}from"../lib/md-term.js";import{NotebookKernel as k,buildRemoteBridgeCommand as b}from"../lib/kernel.js";import{getMainRl as $}from"../lib/main-rl.js";import{cellPreview as x,parseIpynb as P,parsePercentPy as E,parseRunRange as G,serializeIpynb as C,statusChar as U}from"../lib/notebook-doc.js";import{openFile as N}from"../lib/open-file.js";const S=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");export function registerIpynbCommand(h){h.command("ipynb").argument("[file]","notebook (.ipynb) or script (.py, split on # %%) to open").description("Open an in-terminal Python notebook (AI/ML — needs `aienv setup`)").action(async h=>{await async function(h){const S=g(t()),O=i(t(),".icoa","ipynb-out");if(A(),!e(S.python))return console.log(chalk.yellow(" The AI/ML environment is not set up yet.")),console.log(chalk.gray(" Run ")+chalk.bold.cyan("aienv setup")+chalk.gray(" first (one-time, ~300 MB).")),void console.log();const _=h?function(o){const l=c(o)?o:y(process.cwd(),o);if(!e(l))return{doc:{cells:[],path:l,dirty:!1},note:chalk.gray(" new notebook — will be created on ")+chalk.cyan("save")};try{const e=n(l,"utf8"),o=l.endsWith(".ipynb")?P(e):E(e);return{doc:{cells:o,path:l,dirty:!1},note:chalk.gray(" loaded ")+chalk.cyan(l)+chalk.gray(` — ${o.length} cell${1===o.length?"":"s"}. Type `)+chalk.cyan("cells")+chalk.gray(" to list them.")}}catch(e){return{doc:{cells:[],path:null,dirty:!1},note:chalk.yellow(` could not open ${l}: ${e instanceof Error?e.message:String(e)}`)+chalk.gray(" — starting an empty notebook.")}}}(h):null,K=_?_.doc:{cells:[],path:null,dirty:!1};let D=new k({venvPython:S.python,venvRoot:S.root}),M=null,W=q(K.path);process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await D.start()}catch{return console.log(chalk.red(" failed.")),console.log(chalk.gray(" Check the environment: ")+chalk.cyan("aienv status")),void console.log()}console.log(chalk.green(" ready.")),_&&console.log(_.note),console.log(chalk.gray(" Type Python and press Enter. Blocks (def/for/…) continue until a blank line.")),console.log(chalk.gray(" Cells: ")+chalk.cyan("cells")+chalk.gray(" list · ")+chalk.cyan("edit N")+chalk.gray(" edit in $EDITOR · ")+chalk.cyan("run N")+chalk.gray(" / ")+chalk.cyan("run all")+chalk.gray(" · ")+chalk.cyan("add md")+chalk.gray(" notes · ")+chalk.cyan("save")+chalk.gray(" · ")+chalk.cyan("help")+chalk.gray(" · ")+chalk.cyan("quit")),console.log();const V=$(),B=null!==V,F=B?V.listeners("line").slice():[];B&&V.removeAllListeners("line");const Y=B?V:a({input:process.stdin,output:process.stdout,terminal:!0}),z=B?Y.prompt:null;B&&(Y.prompt=r.prototype.prompt);const J=[];let H=!1,Q=!1;const X=()=>{const e=M?"icoa ipynb ⚡gpu":"icoa ipynb";Y.setPrompt(chalk.bold.cyan(J.length?`${e} ...> `:`${e}> `)),Y.prompt()};let Z=()=>{};const ee=new Promise(e=>{Z=e}),oe=async()=>{if(!M)return void console.log(chalk.gray(" not on a GPU kernel."));const e=R();await D.shutdown().catch(()=>{}),e&&await j("release",e),M=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped.")),await(async()=>{D=new k({venvPython:S.python,venvRoot:S.root}),process.stdout.write(chalk.gray(" Starting local kernel…"));try{await D.start(),console.log(chalk.green(" ready.")+chalk.gray(" (local CPU — variables were reset)"))}catch{console.log(chalk.red(" failed.")+chalk.gray(" Check ")+chalk.cyan("aienv status"))}})()},ne=async e=>{const[n,...r]=e.trim().split(/\s+/),a=(n??"").toLowerCase();"on"===a||"connect"===a?await(async()=>{if(M)return void console.log(chalk.gray(" already on the GPU kernel — ")+chalk.cyan("gpu status")+chalk.gray(" for time left."));const e=R();if(!e)return console.log(chalk.yellow(" No GPU access key found.")),void console.log(chalk.gray(" Save yours once with ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" (issued by your coach/ICOA)."));W||(W=q(K.path)),process.stdout.write(chalk.gray(" Requesting a GPU box…"));let n=await j("lease",e,W??void 0),r=0;for(;"queued"===n.state&&r<24;)0===r&&console.log(),process.stdout.write(`\r ${chalk.yellow(m(n))} `),await new Promise(e=>setTimeout(e,5e3)),n=await j("status",e),r++;if("queued"===n.state)return console.log(),console.log(chalk.yellow(" Still queued — your place is held server-side.")),void console.log(chalk.gray(" Keep working locally; ")+chalk.cyan("gpu on")+chalk.gray(" again in a few minutes."));if("ready"!==n.state)return void console.log(chalk.red(" failed.")+chalk.gray(` ${n.message??"no lease granted"}`));const a=p(n);if("local"!==n.transport||process.env.ICOA_GPU_SERVER||a.push("local transport from a non-dev broker"),a.length>0)return console.log(chalk.red(" rejected: ")+chalk.gray(a.join(", "))),void await j("release",e);const s=W?`${n.dataRoot}/${W}`:n.dataRoot,c=b(n.python,{ICOA_KAGGLE_DATA:s,ICOA_KAGGLE_OUT:n.outDir},n.outDir);let y;if("local"===n.transport)y={command:"/bin/sh",args:["-c",c]};else{const r=i(t(),".icoa","gpu","lease-key");try{o(i(t(),".icoa","gpu"),{recursive:!0}),l(r,n.keyPem,{mode:384})}catch{return console.log(chalk.red(" could not write the ssh key locally.")),void await j("release",e)}y={command:"ssh",args:u(n,r,c)}}const g=new k({spawnSpec:y,readyTimeoutMs:9e4});process.stdout.write(chalk.gray(" connecting…"));try{await g.start()}catch(o){return console.log(chalk.red(" connect failed.")),console.log(chalk.gray(` ${o instanceof Error?o.message:String(o)}`)),void await j("release",e)}await D.shutdown().catch(()=>{}),D=g,M=n;const d=Math.round((n.timeLeftSec??0)/60);console.log(chalk.bold.green(" ⚡ GPU connected.")),console.log(chalk.gray(` Cells now run on the GPU box · ${d}m left on this lease.`)),console.log(chalk.gray(" Variables were reset — ")+chalk.cyan("run all")+chalk.gray(" to retrain there.")),W&&console.log(chalk.gray(` Dataset is already on the box (${W}) — same cells, no edits.`)),console.log(chalk.gray(" When done: ")+chalk.cyan("download")+chalk.gray(" your submission, then ")+chalk.cyan("gpu off")+chalk.gray("."))})():"off"===a||"disconnect"===a?await oe():"status"===a||""===a?await(async()=>{const e=R();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const o=await j("status",e);if("ready"===o.state){const e=Math.round((o.timeLeftSec??0)/60);console.log(chalk.green(` ⚡ GPU lease active · ${e}m left`)+chalk.gray(M?" (this notebook is connected)":" (not connected here — gpu on)"))}else"queued"===o.state?console.log(chalk.yellow(` ${m(o)}`)):"none"===o.state?console.log(chalk.gray(" no GPU lease — ")+chalk.cyan("gpu on")+chalk.gray(" to request one.")):console.log(chalk.yellow(` ${o.message??"GPU broker not reachable"}`))})():"key"===a?(e=>{const n=e.trim();if(n)try{o(i(t(),".icoa"),{recursive:!0}),l(I(),`${n}\n`,{mode:384}),console.log(chalk.green(" ✓ GPU key saved")+chalk.gray(" — ")+chalk.cyan("gpu on")+chalk.gray(" when you need the box."))}catch{console.log(chalk.red(" could not save the key")+chalk.gray(` (${I()})`))}else console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu key <your-key>"))})(r.join(" ")):console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu on")+chalk.yellow(" · ")+chalk.cyan("gpu off")+chalk.yellow(" · ")+chalk.cyan("gpu status")+chalk.yellow(" · ")+chalk.cyan("gpu key <k>"))},le=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>K.cells.length?(console.log(0===K.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${K.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:K.cells[o-1],idx:o}},te=(e,o)=>{e.result&&!e.result.ok&&e.result.outputs.some(e=>"error"===e.kind&&"SyntaxError"===e.ename)&&f(e.source)&&console.log(chalk.gray(" ✎ looks like text/markdown, not Python — ")+chalk.cyan(`md ${o}`)+chalk.gray(" converts this cell to markdown (new note: ")+chalk.cyan("add md")+chalk.gray(")."))},re=async e=>{if(H)return void(e.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));const n=e.trim();if(0===J.length){const e=n.split(/\s+/),t=(e[0]??"").toLowerCase(),r=n.slice(e[0]?.length??0).trim();if("quit"!==t&&"exit"!==t&&"q"!==t&&(Q=!1),"quit"===t||"exit"===t||"back"===t||"q"===t)return K.dirty&&!Q?(Q=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void X()):void await(async()=>{if(Y.removeAllListeners("line"),console.log(),M){const e=R();e&&await j("release",e),M=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await D.shutdown().catch(()=>{}),B){z&&(Y.prompt=z);for(const e of F)Y.on("line",e);Y.prompt(),Z()}else Z(),Y.close()})();if("clear"===t||"cls"===t)return console.clear(),A(),void X();if("restart"===t)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await D.shutdown().catch(()=>{});try{await D.start(),console.log(chalk.green(" fresh kernel ready.")+chalk.gray(" (all variables cleared)"))}catch{console.log(chalk.red(" restart failed.")+chalk.gray(" Leave and re-enter the notebook."))}})(),void X();if("help"===t||"?"===t)return console.log(),console.log(chalk.bold.white(" Notebook commands")),console.log(chalk.cyan(" cells")+chalk.gray(" list cells (○ not run · ✓ ok · ✗ error)")),console.log(chalk.cyan(" show N")+chalk.gray(" print cell N source + outputs")),console.log(chalk.cyan(" edit N")+chalk.gray(" edit cell N in your editor ($EDITOR, default vi)")),console.log(chalk.cyan(" add")+chalk.gray(" write a new Python cell in your editor")),console.log(chalk.cyan(" add md")+chalk.gray(" write a markdown/text cell (notes, headings)")),console.log(chalk.cyan(" md N / py N")+chalk.gray(" convert cell N to markdown / Python")),console.log(chalk.cyan(" del N")+chalk.gray(" delete cell N")),console.log(chalk.cyan(" run N")+chalk.gray(" run cell N — markdown cells render (also: run 2-5, run all)")),console.log(chalk.cyan(" save [file]")+chalk.gray(" save as a real .ipynb")),console.log(chalk.cyan(" restart")+chalk.gray(" restart the kernel (wipes all variables)")),console.log(chalk.cyan(" gpu on/off")+chalk.gray(" run cells on a leased GPU box (dataset pre-mounted)")),console.log(chalk.cyan(" gpu status")+chalk.gray(" lease/queue state · ")+chalk.cyan("gpu key <k>")+chalk.gray(" save your access key")),console.log(chalk.cyan(" download")+chalk.gray(" pull submission.csv from the GPU box to this machine")),console.log(chalk.cyan(" open")+chalk.gray(" reopen the last figure in your image viewer")),console.log(chalk.cyan(" clear")+chalk.gray(" clear the screen · ")+chalk.cyan("quit")+chalk.gray(" leave")),console.log(chalk.gray(" Everything else runs as Python in the persistent kernel (and is appended as a cell).")),console.log(),void X();if("open"===t)return L&&N(L)?console.log(chalk.gray(" reopening ")+chalk.cyan(L)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void X();if("cells"===t||"ls"===t)return(()=>{if(0===K.cells.length)return void console.log(chalk.gray(" no cells yet — type Python, or ")+chalk.cyan("add")+chalk.gray(" to write one in your editor."));console.log();const e=Math.max(20,(process.stdout.columns??80)-12);K.cells.forEach((o,n)=>{const l=U(o),t="✓"===l?chalk.green(l.padEnd(2)):"✗"===l?chalk.red(l.padEnd(2)):"md"===l?chalk.magenta(l.padEnd(2)):chalk.gray(l.padEnd(2));console.log(`${chalk.cyan(String(n+1).padStart(4))} ${t} ${chalk.white(x(o,e))}`)}),console.log(),console.log(chalk.gray(" ")+chalk.cyan("show N")+chalk.gray(" · ")+chalk.cyan("edit N")+chalk.gray(" · ")+chalk.cyan("run N")+chalk.gray(" · ")+chalk.cyan("run all"))})(),void X();if("show"===t)return(e=>{const o=le(e);if(o){if(console.log(),console.log(chalk.gray(` ── cell ${o.idx} ${"markdown"===o.cell.kind?"(markdown) ":""}──`)),"markdown"===o.cell.kind){for(const e of v(o.cell.source))console.log(e);console.log(chalk.gray(" (rendered — ")+chalk.cyan(`edit ${o.idx}`)+chalk.gray(" for the raw source)"))}else for(const e of o.cell.source.split("\n"))console.log(chalk.white(` ${e}`));o.cell.result&&(console.log(chalk.gray(" ── output ──")),T(o.cell.result,O)),console.log()}})(r),void X();if("edit"===t)return(e=>{const o=le(e);if(!o)return;Y.pause();const n=d(o.cell.source,"markdown"===o.cell.kind?".md":".py");if(Y.resume(),null===n)return void console.log(chalk.yellow(" editor cancelled or failed — cell unchanged.")+chalk.gray(" (set $EDITOR to choose your editor)"));const l=n.replace(/\s+$/,"");l!==o.cell.source?(o.cell.source=l,o.cell.result=null,o.cell.rawOutputs=void 0,o.cell.rawExecCount=void 0,K.dirty=!0,console.log(chalk.green(` ✓ cell ${o.idx} updated`)+chalk.gray(" — ")+chalk.cyan(`run ${o.idx}`)+chalk.gray(" to execute."))):console.log(chalk.gray(" no changes."))})(r),void X();if("add"===t)return(e=>{const o=e.trim().toLowerCase(),n="md"===o||"markdown"===o||"text"===o||"txt"===o;if(o&&!n&&"py"!==o&&"code"!==o&&"python"!==o)return void console.log(chalk.yellow(" usage: ")+chalk.cyan("add")+chalk.yellow(" (Python cell) · ")+chalk.cyan("add md")+chalk.yellow(" (markdown/text cell)"));Y.pause();const l=d(n?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",n?".md":".py");Y.resume();const t=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");t?(K.cells.push({kind:n?"markdown":"code",source:t,result:null}),K.dirty=!0,console.log(chalk.green(` ✓ added ${n?"markdown ":""}cell ${K.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${K.cells.length}`)+chalk.gray(n?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(r),void X();if("del"===t||"delete"===t)return(e=>{const o=le(e);o&&(K.cells.splice(o.idx-1,1),K.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${K.cells.length} left.`)))})(r),void X();if(("md"===t||"py"===t)&&/^\d+$/.test(r))return((e,o)=>{const n=le(e);if(!n)return;const l="markdown"===o?"markdown":"Python";n.cell.kind!==o?(n.cell.kind=o,n.cell.result=null,n.cell.rawOutputs=void 0,n.cell.rawExecCount=void 0,K.dirty=!0,console.log(chalk.green(` ✓ cell ${n.idx} → ${l}`)+chalk.gray(" — ")+chalk.cyan(`run ${n.idx}`)+chalk.gray("markdown"===o?" to render it.":" to execute."))):console.log(chalk.gray(` cell ${n.idx} is already ${l}.`))})(r,"md"===t?"markdown":"code"),void X();if("gpu"===t)return H=!0,await ne(r),H=!1,void X();if("download"===t||"dl"===t)return H=!0,await(async e=>{if(!M)return void console.log(chalk.gray(" local kernel — your files are already on this machine (no download needed)."));const n=e.trim()||"submission.csv",t=n.startsWith("/")?n:`${M.outDir}/${n}`;let r;try{r=await D.fetchFile(t)}catch(e){return console.log(chalk.yellow(` could not fetch ${t}: `)+chalk.gray(e instanceof Error?e.message:String(e))),void console.log(chalk.gray(" (run the submission cell first — it writes into the GPU workspace)"))}const a=W?i(process.cwd(),"icoa-kaggle",W):process.cwd(),c=i(a,s(n));try{o(a,{recursive:!0}),l(c,r)}catch{return void console.log(chalk.yellow(" could not write the file here — check directory permissions."))}console.log(chalk.green(" ✓ downloaded ")+chalk.white(c)+chalk.gray(` (${r.length} bytes)`)),W&&"submission.csv"===s(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${W}`)+chalk.gray(" — then upload on Kaggle yourself."))})(r),H=!1,void X();if("run"===t)return H=!0,await(async e=>{const o=G(e,K.cells.length);if(o)for(const e of o){const n=K.cells[e-1];if("markdown"!==n.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(x(n,50))+chalk.gray(" ──"));try{n.result=await D.execute(n.source)}catch(e){return void console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e)))}if(K.dirty=!0,T(n.result,O),te(n,e),!n.result.ok)return void(e!==o[o.length-1]&&console.log(chalk.yellow(` ✗ cell ${e} raised — stopping here.`)+chalk.gray(" Fix it (")+chalk.cyan(`edit ${e}`)+chalk.gray(") and re-run.")))}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of v(n.source))console.log(e);console.log()}}else console.log(0===K.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(" usage: ")+chalk.cyan("run 3")+chalk.yellow(" · ")+chalk.cyan("run 1-5")+chalk.yellow(" · ")+chalk.cyan("run all"))})(r),H=!1,void X();if("save"===t)return(e=>{if(0===K.cells.length)return void console.log(chalk.yellow(" nothing to save — the notebook is empty."));let o;o=e.trim()?c(e.trim())?e.trim():y(process.cwd(),e.trim()):K.path?K.path.endsWith(".ipynb")?K.path:`${K.path.replace(/\.[^./]+$/,"")}.ipynb`:y(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");try{l(o,C(K.cells)),K.path=o,K.dirty=!1,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${K.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(r),void X();if(""===n)return void X()}if(J.push(e),!w(J))return void X();const t=J.join("\n").replace(/\s+$/,"");if(J.length=0,""!==t.trim()){H=!0;try{const e=await D.execute(t);K.cells.push({kind:"code",source:t,result:e}),K.dirty=!0,T(e,O),te(K.cells[K.cells.length-1],K.cells.length)}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e)))}H=!1,X()}else X()};Y.on("line",e=>{re(e)}),B||Y.on("close",async()=>{await D.shutdown().catch(()=>{}),process.exit(0)}),X(),await ee}(h)})}function A(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}const O="https://practice.icoa2026.au";function I(){return i(t(),".icoa","gpu-key")}function R(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return n(I(),"utf-8").trim()||null}catch{return null}}async function j(e,o,n){try{const l=await fetch(`${process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):O}/api/icoa/gpu/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n?{key:o,task:n}:{key:o}),signal:AbortSignal.timeout(2e4)});return h(await l.json())}catch{return{state:"error",message:"GPU broker not reachable"}}}function q(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let _=0,L=null;function T(e,o){for(const n of e.outputs)if("stream"===n.kind){const e=n.text.replace(/\n$/,"");if(0===e.length)continue;console.log("stderr"===n.name?chalk.yellow(e):chalk.white(e))}else if("result"===n.kind)console.log(chalk.cyan(` Out[${e.execCount??"*"}]: `)+chalk.white(n.text));else if("error"===n.kind){console.log(chalk.bold.red(` ${n.ename}: ${n.evalue}`));for(const e of n.traceback)console.log(chalk.gray(` ${e.replace(S,"")}`))}else"display"===n.kind&&K(n.data,o)}function K(e,n){if(e["image/png"])try{o(n,{recursive:!0}),_+=1;const t=i(n,`figure-${_}.png`);return l(t,Buffer.from(e["image/png"],"base64")),L=t,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(t)),void(N(t)?console.log(chalk.gray(" opening in your image viewer… (type ")+chalk.cyan("open")+chalk.gray(" to reopen)")):console.log(chalk.gray(" open it with your file browser (inline images need a graphical viewer).")))}catch{}e["text/plain"]&&console.log(chalk.white(` ${e["text/plain"]}`))}
1
+ import{existsSync as e,mkdirSync as o,readFileSync as n,writeFileSync as l}from"node:fs";import{homedir as t}from"node:os";import{Interface as r,createInterface as a}from"node:readline";import{basename as s,isAbsolute as c,join as i,resolve as y}from"node:path";import chalk from"chalk";import{aienvPaths as g}from"../lib/aienv.js";import{editTextInEditor as d}from"../lib/editor-spawn.js";import{buildSshArgs as u,leaseConnectProblems as p,parseLeaseResponse as h,queueLine as m}from"../lib/gpu.js";import{shouldExecuteCell as w}from"../lib/ipynb-input.js";import{looksLikeMarkdown as f,renderMarkdown as v}from"../lib/md-term.js";import{NotebookKernel as k,buildRemoteBridgeCommand as b}from"../lib/kernel.js";import{getMainRl as $}from"../lib/main-rl.js";import{cellPreview as x,parseIpynb as P,parsePercentPy as E,parseRunRange as G,serializeIpynb as S,statusChar as U}from"../lib/notebook-doc.js";import{openFile as C}from"../lib/open-file.js";const N=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");export function registerIpynbCommand(h){h.command("ipynb").argument("[file]","notebook (.ipynb) or script (.py, split on # %%) to open").description("Open an in-terminal Python notebook (AI/ML — needs `aienv setup`)").action(async h=>{await async function(h){const N=g(t()),I=i(t(),".icoa","ipynb-out");if(A(),!e(N.python))return console.log(chalk.yellow(" The AI/ML environment is not set up yet.")),console.log(chalk.gray(" Run ")+chalk.bold.cyan("aienv setup")+chalk.gray(" first (one-time, ~300 MB).")),void console.log();const L=h?function(o){const l=c(o)?o:y(process.cwd(),o);if(!e(l))return{doc:{cells:[],path:l,dirty:!1},note:chalk.gray(" new notebook — will be created on ")+chalk.cyan("save")};try{const e=n(l,"utf8"),o=l.endsWith(".ipynb")?P(e):E(e);return{doc:{cells:o,path:l,dirty:!1},note:chalk.gray(" loaded ")+chalk.cyan(l)+chalk.gray(` — ${o.length} cell${1===o.length?"":"s"}. Type `)+chalk.cyan("cells")+chalk.gray(" to list them.")}}catch(e){return{doc:{cells:[],path:null,dirty:!1},note:chalk.yellow(` could not open ${l}: ${e instanceof Error?e.message:String(e)}`)+chalk.gray(" — starting an empty notebook.")}}}(h):null,M=L?L.doc:{cells:[],path:null,dirty:!1};let D=new k({venvPython:N.python,venvRoot:N.root}),W=null,V=_(M.path);process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await D.start()}catch{return console.log(chalk.red(" failed.")),console.log(chalk.gray(" Check the environment: ")+chalk.cyan("aienv status")),void console.log()}console.log(chalk.green(" ready.")),L&&console.log(L.note),O();const Y=$(),B=null!==Y,F=B?Y.listeners("line").slice():[];B&&Y.removeAllListeners("line");const J=B?Y:a({input:process.stdin,output:process.stdout,terminal:!0}),z=B?J.prompt:null;B&&(J.prompt=r.prototype.prompt);const H=[];let Q=!1,X=!1;const Z=()=>{const e=W?"icoa ipynb ⚡gpu":"icoa ipynb";J.setPrompt(chalk.bold.cyan(H.length?`${e} ...> `:`${e}> `)),J.prompt()};let ee=()=>{};const oe=new Promise(e=>{ee=e}),ne=async()=>{if(!W)return void console.log(chalk.gray(" not on a GPU kernel."));const e=R();await D.shutdown().catch(()=>{}),e&&await q("release",e),W=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped.")),await(async()=>{D=new k({venvPython:N.python,venvRoot:N.root}),process.stdout.write(chalk.gray(" Starting local kernel…"));try{await D.start(),console.log(chalk.green(" ready.")+chalk.gray(" (local CPU — variables were reset)"))}catch{console.log(chalk.red(" failed.")+chalk.gray(" Check ")+chalk.cyan("aienv status"))}})()},le=async e=>{const[n,...r]=e.trim().split(/\s+/),a=(n??"").toLowerCase();"on"===a||"connect"===a?await(async()=>{if(W)return void console.log(chalk.gray(" already on the GPU kernel — ")+chalk.cyan("gpu status")+chalk.gray(" for time left."));const e=R();if(!e)return console.log(chalk.yellow(" No GPU access key found.")),void console.log(chalk.gray(" Save yours once with ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" (issued by your coach/ICOA)."));V||(V=_(M.path)),process.stdout.write(chalk.gray(" Requesting a GPU box…"));let n=await q("lease",e,V??void 0),r=0;for(;"queued"===n.state&&r<24;)0===r&&console.log(),process.stdout.write(`\r ${chalk.yellow(m(n))} `),await new Promise(e=>setTimeout(e,5e3)),n=await q("status",e),r++;if("queued"===n.state)return console.log(),console.log(chalk.yellow(" Still queued — your place is held server-side.")),void console.log(chalk.gray(" Keep working locally; ")+chalk.cyan("gpu on")+chalk.gray(" again in a few minutes."));if("ready"!==n.state)return void console.log(chalk.red(" failed.")+chalk.gray(` ${n.message??"no lease granted"}`));const a=p(n);if("local"!==n.transport||process.env.ICOA_GPU_SERVER||a.push("local transport from a non-dev broker"),a.length>0)return console.log(chalk.red(" rejected: ")+chalk.gray(a.join(", "))),void await q("release",e);const s=V?`${n.dataRoot}/${V}`:n.dataRoot,c=b(n.python,{ICOA_KAGGLE_DATA:s,ICOA_KAGGLE_OUT:n.outDir},n.outDir);let y;if("local"===n.transport)y={command:"/bin/sh",args:["-c",c]};else{const r=i(t(),".icoa","gpu","lease-key");try{o(i(t(),".icoa","gpu"),{recursive:!0}),l(r,n.keyPem,{mode:384})}catch{return console.log(chalk.red(" could not write the ssh key locally.")),void await q("release",e)}y={command:"ssh",args:u(n,r,c)}}const g=new k({spawnSpec:y,readyTimeoutMs:9e4});process.stdout.write(chalk.gray(" connecting…"));try{await g.start()}catch(o){return console.log(chalk.red(" connect failed.")),console.log(chalk.gray(` ${o instanceof Error?o.message:String(o)}`)),void await q("release",e)}await D.shutdown().catch(()=>{}),D=g,W=n;const d=Math.round((n.timeLeftSec??0)/60);console.log(chalk.bold.green(" ⚡ GPU connected.")),console.log(chalk.gray(` Cells now run on the GPU box · ${d}m left on this lease.`)),console.log(chalk.gray(" Variables were reset — ")+chalk.cyan("run all")+chalk.gray(" to retrain there.")),V&&console.log(chalk.gray(` Dataset is already on the box (${V}) — same cells, no edits.`)),console.log(chalk.gray(" When done: ")+chalk.cyan("download")+chalk.gray(" your submission, then ")+chalk.cyan("gpu off")+chalk.gray("."))})():"off"===a||"disconnect"===a?await ne():"status"===a||""===a?await(async()=>{const e=R();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const o=await q("status",e);if("ready"===o.state){const e=Math.round((o.timeLeftSec??0)/60);console.log(chalk.green(` ⚡ GPU lease active · ${e}m left`)+chalk.gray(W?" (this notebook is connected)":" (not connected here — gpu on)"))}else"queued"===o.state?console.log(chalk.yellow(` ${m(o)}`)):"none"===o.state?console.log(chalk.gray(" no GPU lease — ")+chalk.cyan("gpu on")+chalk.gray(" to request one.")):console.log(chalk.yellow(` ${o.message??"GPU broker not reachable"}`))})():"key"===a?(e=>{const n=e.trim();if(n)try{o(i(t(),".icoa"),{recursive:!0}),l(j(),`${n}\n`,{mode:384}),console.log(chalk.green(" ✓ GPU key saved")+chalk.gray(" — ")+chalk.cyan("gpu on")+chalk.gray(" when you need the box."))}catch{console.log(chalk.red(" could not save the key")+chalk.gray(` (${j()})`))}else console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu key <your-key>"))})(r.join(" ")):console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu on")+chalk.yellow(" · ")+chalk.cyan("gpu off")+chalk.yellow(" · ")+chalk.cyan("gpu status")+chalk.yellow(" · ")+chalk.cyan("gpu key <k>"))},te=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>M.cells.length?(console.log(0===M.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${M.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:M.cells[o-1],idx:o}},re=(e,o)=>{e.result&&!e.result.ok&&e.result.outputs.some(e=>"error"===e.kind&&"SyntaxError"===e.ename)&&f(e.source)&&console.log(chalk.gray(" ✎ looks like text/markdown, not Python — ")+chalk.cyan(`md ${o}`)+chalk.gray(" converts this cell to markdown (new note: ")+chalk.cyan("add md")+chalk.gray(")."))},ae=async e=>{if(Q)return void(e.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));const n=e.trim();if(0===H.length){const e=n.split(/\s+/),t=(e[0]??"").toLowerCase(),r=n.slice(e[0]?.length??0).trim();if("quit"!==t&&"exit"!==t&&"q"!==t&&(X=!1),"quit"===t||"exit"===t||"back"===t||"q"===t)return M.dirty&&!X?(X=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void Z()):void await(async()=>{if(J.removeAllListeners("line"),console.log(),W){const e=R();e&&await q("release",e),W=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await D.shutdown().catch(()=>{}),B){z&&(J.prompt=z);for(const e of F)J.on("line",e);J.prompt(),ee()}else ee(),J.close()})();if("clear"===t||"cls"===t)return console.clear(),A(),void Z();if("restart"===t)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await D.shutdown().catch(()=>{});try{await D.start(),console.log(chalk.green(" fresh kernel ready.")+chalk.gray(" (all variables cleared)"))}catch{console.log(chalk.red(" restart failed.")+chalk.gray(" Leave and re-enter the notebook."))}})(),void Z();if("help"===t||"?"===t)return console.log(),console.log(chalk.bold.white(" Notebook commands")),console.log(chalk.cyan(" cells")+chalk.gray(" list cells (○ not run · ✓ ok · ✗ error)")),console.log(chalk.cyan(" show N")+chalk.gray(" print cell N source + outputs")),console.log(chalk.cyan(" edit N")+chalk.gray(" edit cell N in your editor ($EDITOR, default vi)")),console.log(chalk.cyan(" add")+chalk.gray(" write a new Python cell in your editor")),console.log(chalk.cyan(" add md")+chalk.gray(" write a markdown/text cell (notes, headings)")),console.log(chalk.cyan(" md N / py N")+chalk.gray(" convert cell N to markdown / Python")),console.log(chalk.cyan(" del N")+chalk.gray(" delete cell N")),console.log(chalk.cyan(" run N")+chalk.gray(" run cell N — markdown cells render (also: run 2-5, run all)")),console.log(chalk.cyan(" save [file]")+chalk.gray(" save as a real .ipynb")),console.log(chalk.cyan(" restart")+chalk.gray(" restart the kernel (wipes all variables)")),console.log(chalk.cyan(" gpu on/off")+chalk.gray(" run cells on a leased GPU box (dataset pre-mounted)")),console.log(chalk.cyan(" gpu status")+chalk.gray(" lease/queue state · ")+chalk.cyan("gpu key <k>")+chalk.gray(" save your access key")),console.log(chalk.cyan(" download")+chalk.gray(" pull submission.csv from the GPU box to this machine")),console.log(chalk.cyan(" open")+chalk.gray(" reopen the last figure in your image viewer")),console.log(chalk.cyan(" clear")+chalk.gray(" clear the screen · ")+chalk.cyan("quit")+chalk.gray(" leave")),console.log(chalk.gray(" Everything else runs as Python in the persistent kernel (and is appended as a cell).")),console.log(),void Z();if("guide"===t||"/guide"===t)return O(),void Z();if("python"===t||"python3"===t)return console.log(chalk.gray(" You're already inside the notebook kernel — no need to run python.")),console.log(chalk.gray(" Type ")+chalk.bold.cyan("run all")+chalk.gray(" to run every cell, or ")+chalk.cyan("guide")+chalk.gray(" for the basics.")),void Z();if("open"===t)return T&&C(T)?console.log(chalk.gray(" reopening ")+chalk.cyan(T)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void Z();if("cells"===t||"ls"===t)return(()=>{if(0===M.cells.length)return void console.log(chalk.gray(" no cells yet — type Python, or ")+chalk.cyan("add")+chalk.gray(" to write one in your editor."));console.log();const e=Math.max(20,(process.stdout.columns??80)-12);M.cells.forEach((o,n)=>{const l=U(o),t="✓"===l?chalk.green(l.padEnd(2)):"✗"===l?chalk.red(l.padEnd(2)):"md"===l?chalk.magenta(l.padEnd(2)):chalk.gray(l.padEnd(2));console.log(`${chalk.cyan(String(n+1).padStart(4))} ${t} ${chalk.white(x(o,e))}`)}),console.log(),console.log(chalk.gray(" ")+chalk.cyan("show N")+chalk.gray(" · ")+chalk.cyan("edit N")+chalk.gray(" · ")+chalk.cyan("run N")+chalk.gray(" · ")+chalk.cyan("run all"))})(),void Z();if("show"===t)return(e=>{const o=te(e);if(o){if(console.log(),console.log(chalk.gray(` ── cell ${o.idx} ${"markdown"===o.cell.kind?"(markdown) ":""}──`)),"markdown"===o.cell.kind){for(const e of v(o.cell.source))console.log(e);console.log(chalk.gray(" (rendered — ")+chalk.cyan(`edit ${o.idx}`)+chalk.gray(" for the raw source)"))}else for(const e of o.cell.source.split("\n"))console.log(chalk.white(` ${e}`));o.cell.result&&(console.log(chalk.gray(" ── output ──")),K(o.cell.result,I)),console.log()}})(r),void Z();if("edit"===t)return(e=>{const o=te(e);if(!o)return;J.pause();const n=d(o.cell.source,"markdown"===o.cell.kind?".md":".py");if(J.resume(),null===n)return void console.log(chalk.yellow(" editor cancelled or failed — cell unchanged.")+chalk.gray(" (set $EDITOR to choose your editor)"));const l=n.replace(/\s+$/,"");l!==o.cell.source?(o.cell.source=l,o.cell.result=null,o.cell.rawOutputs=void 0,o.cell.rawExecCount=void 0,M.dirty=!0,console.log(chalk.green(` ✓ cell ${o.idx} updated`)+chalk.gray(" — ")+chalk.cyan(`run ${o.idx}`)+chalk.gray(" to execute."))):console.log(chalk.gray(" no changes."))})(r),void Z();if("add"===t)return(e=>{const o=e.trim().toLowerCase(),n="md"===o||"markdown"===o||"text"===o||"txt"===o;if(o&&!n&&"py"!==o&&"code"!==o&&"python"!==o)return void console.log(chalk.yellow(" usage: ")+chalk.cyan("add")+chalk.yellow(" (Python cell) · ")+chalk.cyan("add md")+chalk.yellow(" (markdown/text cell)"));J.pause();const l=d(n?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",n?".md":".py");J.resume();const t=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");t?(M.cells.push({kind:n?"markdown":"code",source:t,result:null}),M.dirty=!0,console.log(chalk.green(` ✓ added ${n?"markdown ":""}cell ${M.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${M.cells.length}`)+chalk.gray(n?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(r),void Z();if("del"===t||"delete"===t)return(e=>{const o=te(e);o&&(M.cells.splice(o.idx-1,1),M.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${M.cells.length} left.`)))})(r),void Z();if(("md"===t||"py"===t)&&/^\d+$/.test(r))return((e,o)=>{const n=te(e);if(!n)return;const l="markdown"===o?"markdown":"Python";n.cell.kind!==o?(n.cell.kind=o,n.cell.result=null,n.cell.rawOutputs=void 0,n.cell.rawExecCount=void 0,M.dirty=!0,console.log(chalk.green(` ✓ cell ${n.idx} → ${l}`)+chalk.gray(" — ")+chalk.cyan(`run ${n.idx}`)+chalk.gray("markdown"===o?" to render it.":" to execute."))):console.log(chalk.gray(` cell ${n.idx} is already ${l}.`))})(r,"md"===t?"markdown":"code"),void Z();if("gpu"===t)return Q=!0,await le(r),Q=!1,void Z();if("download"===t||"dl"===t)return Q=!0,await(async e=>{if(!W)return void console.log(chalk.gray(" local kernel — your files are already on this machine (no download needed)."));const n=e.trim()||"submission.csv",t=n.startsWith("/")?n:`${W.outDir}/${n}`;let r;try{r=await D.fetchFile(t)}catch(e){return console.log(chalk.yellow(` could not fetch ${t}: `)+chalk.gray(e instanceof Error?e.message:String(e))),void console.log(chalk.gray(" (run the submission cell first — it writes into the GPU workspace)"))}const a=V?i(process.cwd(),"icoa-kaggle",V):process.cwd(),c=i(a,s(n));try{o(a,{recursive:!0}),l(c,r)}catch{return void console.log(chalk.yellow(" could not write the file here — check directory permissions."))}console.log(chalk.green(" ✓ downloaded ")+chalk.white(c)+chalk.gray(` (${r.length} bytes)`)),V&&"submission.csv"===s(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${V}`)+chalk.gray(" — then upload on Kaggle yourself."))})(r),Q=!1,void Z();if("run"===t)return Q=!0,await(async e=>{const o=G(e,M.cells.length);if(o)for(const e of o){const n=M.cells[e-1];if("markdown"!==n.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(x(n,50))+chalk.gray(" ──"));try{n.result=await D.execute(n.source)}catch(e){return void console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e)))}if(M.dirty=!0,K(n.result,I),re(n,e),!n.result.ok)return void(e!==o[o.length-1]&&console.log(chalk.yellow(` ✗ cell ${e} raised — stopping here.`)+chalk.gray(" Fix it (")+chalk.cyan(`edit ${e}`)+chalk.gray(") and re-run.")))}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of v(n.source))console.log(e);console.log()}}else console.log(0===M.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(" usage: ")+chalk.cyan("run 3")+chalk.yellow(" · ")+chalk.cyan("run 1-5")+chalk.yellow(" · ")+chalk.cyan("run all"))})(r),Q=!1,void Z();if("save"===t)return(e=>{if(0===M.cells.length)return void console.log(chalk.yellow(" nothing to save — the notebook is empty."));let o;o=e.trim()?c(e.trim())?e.trim():y(process.cwd(),e.trim()):M.path?M.path.endsWith(".ipynb")?M.path:`${M.path.replace(/\.[^./]+$/,"")}.ipynb`:y(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");try{l(o,S(M.cells)),M.path=o,M.dirty=!1,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${M.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(r),void Z();if(""===n)return void Z()}if(H.push(e),!w(H))return void Z();const t=H.join("\n").replace(/\s+$/,"");if(H.length=0,""!==t.trim()){Q=!0;try{const e=await D.execute(t);M.cells.push({kind:"code",source:t,result:e}),M.dirty=!0,K(e,I),re(M.cells[M.cells.length-1],M.cells.length)}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e)))}Q=!1,Z()}else Z()};J.on("line",e=>{ae(e)}),B||J.on("close",async()=>{await D.shutdown().catch(()=>{}),process.exit(0)}),Z(),await oe}(h)})}function A(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}function O(){console.log(chalk.bold.white(" ▶ Start here: ")+chalk.bold.cyan("run all")+chalk.gray(" — runs every cell (trains the baseline, writes submission.csv).")),console.log(chalk.gray(" You are already inside the notebook — do ")+chalk.bold.red("not")+chalk.gray(" type ")+chalk.cyan("python file.ipynb")+chalk.gray(". Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(chalk.gray(" Then: ")+chalk.cyan("cells")+chalk.gray(" list · ")+chalk.cyan("edit N")+chalk.gray(" edit · ")+chalk.cyan("save")+chalk.gray(" · ")+chalk.cyan("guide")+chalk.gray(" show this again · ")+chalk.cyan("help")+chalk.gray(" full · ")+chalk.cyan("quit")),console.log(chalk.gray(" Or just type Python and press Enter (blocks continue until a blank line).")),console.log()}const I="https://practice.icoa2026.au";function j(){return i(t(),".icoa","gpu-key")}function R(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return n(j(),"utf-8").trim()||null}catch{return null}}async function q(e,o,n){try{const l=await fetch(`${process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):I}/api/icoa/gpu/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n?{key:o,task:n}:{key:o}),signal:AbortSignal.timeout(2e4)});return h(await l.json())}catch{return{state:"error",message:"GPU broker not reachable"}}}function _(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let L=0,T=null;function K(e,o){for(const n of e.outputs)if("stream"===n.kind){const e=n.text.replace(/\n$/,"");if(0===e.length)continue;console.log("stderr"===n.name?chalk.yellow(e):chalk.white(e))}else if("result"===n.kind)console.log(chalk.cyan(` Out[${e.execCount??"*"}]: `)+chalk.white(n.text));else if("error"===n.kind){console.log(chalk.bold.red(` ${n.ename}: ${n.evalue}`));for(const e of n.traceback)console.log(chalk.gray(` ${e.replace(N,"")}`))}else"display"===n.kind&&M(n.data,o)}function M(e,n){if(e["image/png"])try{o(n,{recursive:!0}),L+=1;const t=i(n,`figure-${L}.png`);return l(t,Buffer.from(e["image/png"],"base64")),T=t,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(t)),void(C(t)?console.log(chalk.gray(" opening in your image viewer… (type ")+chalk.cyan("open")+chalk.gray(" to reopen)")):console.log(chalk.gray(" open it with your file browser (inline images need a graphical viewer).")))}catch{}e["text/plain"]&&console.log(chalk.white(` ${e["text/plain"]}`))}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "icoa-cli",
3
- "version": "2.19.387",
3
+ "version": "2.19.388",
4
4
  "description": "ICOA CLI — The world's first CLI-native cyber & AI security olympiad terminal: AI4CTF (Day 1), CTF4AI (Day 2), VLA4CTF (Pioneer Round — embodied AI)",
5
5
  "type": "module",
6
6
  "bin": {