icoa-cli 2.19.389 → 2.19.390
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.
package/dist/commands/ipynb.js
CHANGED
|
@@ -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 f}from"../lib/ipynb-input.js";import{looksLikeMarkdown as w,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()),j=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 T=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,D=T?T.doc:{cells:[],path:null,dirty:!1};let W=new k({venvPython:N.python,venvRoot:N.root}),V=null,Y=_(D.path);process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await W.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.")),T&&console.log(T.note),O();const B=$(),F=null!==B,J=F?B.listeners("line").slice():[];F&&B.removeAllListeners("line");const z=F?B:a({input:process.stdin,output:process.stdout,terminal:!0}),H=F?z.prompt:null;F&&(z.prompt=r.prototype.prompt);const Q=[];let X=!1,Z=!1;const ee=()=>{const e=V?"icoa ipynb ⚡gpu":"icoa ipynb";z.setPrompt(chalk.bold.cyan(Q.length?`${e} ...> `:`${e}> `)),z.prompt()};let oe=()=>{};const ne=new Promise(e=>{oe=e}),le=async()=>{if(!V)return void console.log(chalk.gray(" not on a GPU kernel."));const e=q();await W.shutdown().catch(()=>{}),e&&await L("release",e),V=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped.")),await(async()=>{W=new k({venvPython:N.python,venvRoot:N.root}),process.stdout.write(chalk.gray(" Starting local kernel…"));try{await W.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"))}})()},te=async e=>{const[n,...r]=e.trim().split(/\s+/),a=(n??"").toLowerCase();"on"===a||"connect"===a?await(async()=>{if(V)return void console.log(chalk.gray(" already on the GPU kernel — ")+chalk.cyan("gpu status")+chalk.gray(" for time left."));const e=q();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)."));Y||(Y=_(D.path)),process.stdout.write(chalk.gray(" Requesting a GPU box…"));let n=await L("lease",e,Y??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 L("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 L("release",e);const s=Y?`${n.dataRoot}/${Y}`: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 L("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 L("release",e)}await W.shutdown().catch(()=>{}),W=g,V=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.")),Y&&console.log(chalk.gray(` Dataset is already on the box (${Y}) — 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 le():"status"===a||""===a?await(async()=>{const e=q();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const o=await L("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(V?" (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(R(),`${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(` (${R()})`))}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>"))},re=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>D.cells.length?(console.log(0===D.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${D.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:D.cells[o-1],idx:o}},ae=(e,o)=>!(!e.result||e.result.ok)&&!(!e.result.outputs.some(e=>"error"===e.kind&&"SyntaxError"===e.ename)||!w(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(").")),0)),se=async e=>{if(X)return void(e.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));const n=e.trim();if(0===Q.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&&(Z=!1),"quit"===t||"exit"===t||"back"===t||"q"===t)return D.dirty&&!Z?(Z=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void ee()):void await(async()=>{if(z.removeAllListeners("line"),console.log(),V){const e=q();e&&await L("release",e),V=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await W.shutdown().catch(()=>{}),F){H&&(z.prompt=H);for(const e of J)z.on("line",e);z.prompt(),oe()}else oe(),z.close()})();if("clear"===t||"cls"===t)return console.clear(),A(),void ee();if("restart"===t)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await W.shutdown().catch(()=>{});try{await W.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 ee();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 ee();if("guide"===t||"/guide"===t)return O(),void ee();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 ee();if("open"===t)return K&&C(K)?console.log(chalk.gray(" reopening ")+chalk.cyan(K)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void ee();if("cells"===t||"ls"===t)return(()=>{if(0===D.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);D.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 ee();if("show"===t)return(e=>{const o=re(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 ──")),M(o.cell.result,j)),console.log()}})(r),void ee();if("edit"===t)return(e=>{const o=re(e);if(!o)return;z.pause();const n=d(o.cell.source,"markdown"===o.cell.kind?".md":".py");if(z.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,D.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 ee();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)"));z.pause();const l=d(n?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",n?".md":".py");z.resume();const t=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");t?(D.cells.push({kind:n?"markdown":"code",source:t,result:null}),D.dirty=!0,console.log(chalk.green(` ✓ added ${n?"markdown ":""}cell ${D.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${D.cells.length}`)+chalk.gray(n?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(r),void ee();if("del"===t||"delete"===t)return(e=>{const o=re(e);o&&(D.cells.splice(o.idx-1,1),D.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${D.cells.length} left.`)))})(r),void ee();if(("md"===t||"py"===t)&&/^\d+$/.test(r))return((e,o)=>{const n=re(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,D.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 ee();if("gpu"===t)return X=!0,await te(r),X=!1,void ee();if("download"===t||"dl"===t)return X=!0,await(async e=>{if(!V)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:`${V.outDir}/${n}`;let r;try{r=await W.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=Y?i(process.cwd(),"icoa-kaggle",Y):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)`)),Y&&"submission.csv"===s(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${Y}`)+chalk.gray(" — then upload on Kaggle yourself."))})(r),X=!1,void ee();if("run"===t)return X=!0,await(async e=>{const o=G(e,D.cells.length);if(o)for(const e of o){const n=D.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 W.execute(n.source)}catch(e){return console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),void I()}if(D.dirty=!0,M(n.result,j),ae(n,e),!n.result.ok){const n=e!==o[o.length-1];return console.log(chalk.yellow(` ✗ cell ${e} raised${n?" — stopping here.":"."}`)+chalk.gray(" Fix it (")+chalk.cyan(`edit ${e}`)+chalk.gray(") and re-run.")),void I()}}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of v(n.source))console.log(e);console.log()}}else console.log(0===D.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),X=!1,void ee();if("save"===t)return(e=>{if(0===D.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()):D.path?D.path.endsWith(".ipynb")?D.path:`${D.path.replace(/\.[^./]+$/,"")}.ipynb`:y(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");try{l(o,S(D.cells)),D.path=o,D.dirty=!1,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${D.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(r),void ee();if(""===n)return void ee()}if(Q.push(e),!f(Q))return void ee();const t=Q.join("\n").replace(/\s+$/,"");if(Q.length=0,""!==t.trim()){X=!0;try{const e=await W.execute(t);D.cells.push({kind:"code",source:t,result:e}),D.dirty=!0,M(e,j);const o=ae(D.cells[D.cells.length-1],D.cells.length);e.ok||o||I()}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),I()}X=!1,ee()}else ee()};z.on("line",e=>{se(e)}),F||z.on("close",async()=>{await W.shutdown().catch(()=>{}),process.exit(0)}),ee(),await ne}(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("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(chalk.bold.yellow(" 🧭 Lost at any point? Type ")+chalk.bold.cyan("guide")+chalk.bold.yellow(" — these instructions reprint right here.")),console.log()}function I(){console.log(chalk.gray(" 🧭 stuck? type ")+chalk.cyan("guide")+chalk.gray(" for the basics · ")+chalk.cyan("help")+chalk.gray(" for every command."))}const j="https://practice.icoa2026.au";function R(){return i(t(),".icoa","gpu-key")}function q(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return n(R(),"utf-8").trim()||null}catch{return null}}async function L(e,o,n){try{const l=await fetch(`${process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):j}/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 T=0,K=null;function M(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&&D(n.data,o)}function D(e,n){if(e["image/png"])try{o(n,{recursive:!0}),T+=1;const t=i(n,`figure-${T}.png`);return l(t,Buffer.from(e["image/png"],"base64")),K=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"]}`))}
|
|
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 S}from"../lib/notebook-doc.js";import{openFile as U}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()),L=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 K=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,W=K?K.doc:{cells:[],path:null,dirty:!1};let V=new k({venvPython:N.python,venvRoot:N.root}),Y=null,z=_(W.path);process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await V.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.")),K&&console.log(K.note),O();const B=$(),F=null!==B,J=F?B.listeners("line").slice():[];F&&B.removeAllListeners("line");const H=F?B:a({input:process.stdin,output:process.stdout,terminal:!0}),Q=F?H.prompt:null;F&&(H.prompt=r.prototype.prompt);const X=[];let Z=!1,ee=!1,oe=!1;const ne=()=>{const e=Y?"icoa ipynb ⚡gpu":"icoa ipynb";H.setPrompt(chalk.bold.cyan(X.length?`${e} ...> `:`${e}> `)),H.prompt()};let le=()=>{};const te=new Promise(e=>{le=e}),re=async()=>{if(!Y)return void console.log(chalk.gray(" not on a GPU kernel."));const e=q();await V.shutdown().catch(()=>{}),e&&await T("release",e),Y=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped.")),await(async()=>{V=new k({venvPython:N.python,venvRoot:N.root}),process.stdout.write(chalk.gray(" Starting local kernel…"));try{await V.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"))}})()},ae=async e=>{const[n,...r]=e.trim().split(/\s+/),a=(n??"").toLowerCase();"on"===a||"connect"===a?await(async()=>{if(Y)return void console.log(chalk.gray(" already on the GPU kernel — ")+chalk.cyan("gpu status")+chalk.gray(" for time left."));const e=q();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)."));z||(z=_(W.path)),process.stdout.write(chalk.gray(" Requesting a GPU box…"));let n=await T("lease",e,z??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 T("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 T("release",e);const s=z?`${n.dataRoot}/${z}`: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 T("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 T("release",e)}await V.shutdown().catch(()=>{}),V=g,Y=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.")),z&&console.log(chalk.gray(` Dataset is already on the box (${z}) — 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 re():"status"===a||""===a?await(async()=>{const e=q();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const o=await T("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(Y?" (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(R(),`${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(` (${R()})`))}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>"))},se=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>W.cells.length?(console.log(0===W.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${W.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:W.cells[o-1],idx:o}},ce=(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(").")),0)),ie=async e=>{if(ee)return void(e.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));let n=e.trim();if(0===X.length&&/^icoa\s+[a-z/]/i.test(n)&&(n=n.replace(/^icoa\s+/i,"")),0===X.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&&(oe=!1),"quit"===t||"exit"===t||"back"===t||"q"===t)return W.dirty&&!oe?(oe=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void ne()):void await(async()=>{if(H.removeAllListeners("line"),console.log(),Y){const e=q();e&&await T("release",e),Y=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await V.shutdown().catch(()=>{}),F){Q&&(H.prompt=Q);for(const e of J)H.on("line",e);H.prompt(),le()}else le(),H.close()})();if("clear"===t||"cls"===t)return console.clear(),A(),void ne();if("restart"===t)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await V.shutdown().catch(()=>{});try{await V.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 ne();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 ne();if("guide"===t||"/guide"===t)return O(),void ne();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 ne();if("open"===t)return M&&U(M)?console.log(chalk.gray(" reopening ")+chalk.cyan(M)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void ne();if("cells"===t||"ls"===t)return(()=>{if(0===W.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);W.cells.forEach((o,n)=>{const l=S(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 ne();if("show"===t)return(e=>{const o=se(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 ──")),D(o.cell.result,L)),console.log()}})(r),void ne();if("edit"===t)return(e=>{const o=se(e);if(!o)return;H.pause();const n=d(o.cell.source,"markdown"===o.cell.kind?".md":".py");if(H.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,W.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 ne();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)"));H.pause();const l=d(n?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",n?".md":".py");H.resume();const t=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");t?(W.cells.push({kind:n?"markdown":"code",source:t,result:null}),W.dirty=!0,console.log(chalk.green(` ✓ added ${n?"markdown ":""}cell ${W.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${W.cells.length}`)+chalk.gray(n?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(r),void ne();if("del"===t||"delete"===t)return(e=>{const o=se(e);o&&(W.cells.splice(o.idx-1,1),W.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${W.cells.length} left.`)))})(r),void ne();if(("md"===t||"py"===t)&&/^\d+$/.test(r))return((e,o)=>{const n=se(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,W.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 ne();if("gpu"===t)return ee=!0,await ae(r),ee=!1,void ne();if("download"===t||"dl"===t)return ee=!0,await(async e=>{if(!Y)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:`${Y.outDir}/${n}`;let r;try{r=await V.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=z?i(process.cwd(),"icoa-kaggle",z):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)`)),z&&"submission.csv"===s(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${z}`)+chalk.gray(" — then upload on Kaggle yourself."))})(r),ee=!1,void ne();if("run"===t)return ee=!0,await(async e=>{const o=G(e,W.cells.length);if(o)for(const e of o){const n=W.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 V.execute(n.source)}catch(e){return console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),void j()}if(W.dirty=!0,D(n.result,L),ce(n,e),!n.result.ok){const n=e!==o[o.length-1];return console.log(chalk.yellow(` ✗ cell ${e} raised${n?" — stopping here.":"."}`)+chalk.gray(" Fix it (")+chalk.cyan(`edit ${e}`)+chalk.gray(") and re-run.")),void j()}}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of v(n.source))console.log(e);console.log()}}else console.log(0===W.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),ee=!1,void ne();if("save"===t)return(e=>{if(0===W.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()):W.path?W.path.endsWith(".ipynb")?W.path:`${W.path.replace(/\.[^./]+$/,"")}.ipynb`:y(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");try{l(o,C(W.cells)),W.path=o,W.dirty=!1,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${W.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(r),void ne();if(""===n)return void ne()}if(X.length>0&&I.has(n.toLowerCase()))return console.log(chalk.gray(" (⏸ you are inside a multi-line block — press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(" to run it; then ")+chalk.cyan(n.toLowerCase().replace(/^\//,""))+chalk.gray(" will work. This line was not added to the block.)")),void ne();if(X.push(e),!w(X))return 1!==X.length||Z||(Z=!0,console.log(chalk.gray(" (multi-line block started — keep typing; an empty line runs it)"))),void ne();const t=X.join("\n").replace(/\s+$/,"");if(X.length=0,""!==t.trim()){ee=!0;try{const e=await V.execute(t);W.cells.push({kind:"code",source:t,result:e}),W.dirty=!0,D(e,L);const o=ce(W.cells[W.cells.length-1],W.cells.length);e.ok||o||j()}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),j()}ee=!1,ne()}else ne()};H.on("line",e=>{ie(e)}),F||H.on("close",async()=>{await V.shutdown().catch(()=>{}),process.exit(0)}),ne(),await te}(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("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(chalk.bold.yellow(" 🧭 Lost at any point? Type ")+chalk.bold.cyan("guide")+chalk.bold.yellow(" — these instructions reprint right here.")),console.log()}const I=new Set(["guide","/guide","help","?","quit","exit","back","menu","cells","run all"]);function j(){console.log(chalk.gray(" 🧭 stuck? type ")+chalk.cyan("guide")+chalk.gray(" for the basics · ")+chalk.cyan("help")+chalk.gray(" for every command."))}const L="https://practice.icoa2026.au";function R(){return i(t(),".icoa","gpu-key")}function q(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return n(R(),"utf-8").trim()||null}catch{return null}}async function T(e,o,n){try{const l=await fetch(`${process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):L}/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 K=0,M=null;function D(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&&W(n.data,o)}function W(e,n){if(e["image/png"])try{o(n,{recursive:!0}),K+=1;const t=i(n,`figure-${K}.png`);return l(t,Buffer.from(e["image/png"],"base64")),M=t,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(t)),void(U(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.
|
|
3
|
+
"version": "2.19.390",
|
|
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": {
|