icoa-cli 2.19.397 → 2.19.398

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,dirname as c,isAbsolute as i,join as y,resolve as g}from"node:path";import chalk from"chalk";import{aienvPaths as d}from"../lib/aienv.js";import{editTextInEditor as u}from"../lib/editor-spawn.js";import{buildSshArgs as p,leaseConnectProblems as h,parseLeaseResponse as m,queueLine as w}from"../lib/gpu.js";import{shouldExecuteCell as f}from"../lib/ipynb-input.js";import{looksLikeMarkdown as b,renderMarkdown as k}from"../lib/md-term.js";import{NotebookKernel as v,buildRemoteBridgeCommand as $}from"../lib/kernel.js";import{getMainRl as P}from"../lib/main-rl.js";import{logCommand as x}from"../lib/logger.js";import{startLogSync as E,stopLogSync as G}from"../lib/log-sync.js";import{cellPreview as S,parseIpynb as U,parsePercentPy as N,parseRunRange as q,serializeIpynb as C,statusChar as A}from"../lib/notebook-doc.js";import{openFile as O}from"../lib/open-file.js";const j=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");export function registerIpynbCommand(m){m.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 m=>{await async function(m){const j=d(t()),T=y(t(),".icoa","ipynb-out");if(_(),!e(j.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 J=m?function(o){const l=i(o)?o:g(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")?U(e):N(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.")}}}(m):null,z=J?J.doc:{cells:[],path:null,dirty:!1};let B=new v({venvPython:j.python,venvRoot:j.root}),F=null,H=W(z.path);process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await B.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.")),J&&console.log(J.note),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(" — the full walkthrough + where you are.")),console.log();const Q=P(),X=null!==Q,Z=X?Q.listeners("line").slice():[];X&&Q.removeAllListeners("line");const ee=X?Q:a({input:process.stdin,output:process.stdout,terminal:!0}),oe=X?ee.prompt:null;X&&(ee.prompt=r.prototype.prompt),X||E();const ne=[];let le=!1,te=!1,re=!1;const ae=()=>{const e=F?"icoa ipynb ⚡gpu":"icoa ipynb";ee.setPrompt(chalk.bold.cyan(ne.length?`${e} ...> `:`${e}> `)),ee.prompt()};let se=()=>{};const ce=new Promise(e=>{se=e}),ie=async()=>{if(!F)return void console.log(chalk.gray(" not on a GPU kernel."));const e=D();await B.shutdown().catch(()=>{}),e&&await K("release",e),F=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped.")),await(async()=>{B=new v({venvPython:j.python,venvRoot:j.root}),process.stdout.write(chalk.gray(" Starting local kernel…"));try{await B.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"))}})()},ye=async e=>{const[n,...r]=e.trim().split(/\s+/),a=(n??"").toLowerCase();"on"===a||"connect"===a?await(async()=>{if(F)return void console.log(chalk.gray(" already on the GPU kernel — ")+chalk.cyan("gpu status")+chalk.gray(" for time left."));const e=D();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)."));H||(H=W(z.path)),process.stdout.write(chalk.gray(" Requesting a GPU box…"));let n=await K("lease",e,H??void 0),r=0;for(;"queued"===n.state&&r<24;)0===r&&console.log(),process.stdout.write(`\r ${chalk.yellow(w(n))} `),await new Promise(e=>setTimeout(e,5e3)),n=await K("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=h(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 K("release",e);const s=H?`${n.dataRoot}/${H}`:n.dataRoot,c=$(n.python,{ICOA_KAGGLE_DATA:s,ICOA_KAGGLE_OUT:n.outDir},n.outDir);let i;if("local"===n.transport)i={command:"/bin/sh",args:["-c",c]};else{const r=y(t(),".icoa","gpu","lease-key");try{o(y(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 K("release",e)}i={command:"ssh",args:p(n,r,c)}}const g=new v({spawnSpec:i,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 K("release",e)}await B.shutdown().catch(()=>{}),B=g,F=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.")),H&&console.log(chalk.gray(` Dataset is already on the box (${H}) — 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 ie():"status"===a||""===a?await(async()=>{const e=D();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const o=await K("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(F?" (this notebook is connected)":" (not connected here — gpu on)"))}else"queued"===o.state?console.log(chalk.yellow(` ${w(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"}`))})():"queue"===a||"q"===a?await(async()=>{const e=D();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));let o=null;try{const n=await fetch(`${R()}/api/icoa/gpu/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)}),l=await n.json();o=l.data??l}catch{o=null}if(!o||"object"!=typeof o)return void console.log(chalk.yellow(" GPU queue not reachable right now — try again in a moment."));const n="number"==typeof o.boxes?o.boxes:0,l="number"==typeof o.free?o.free:0,t=Array.isArray(o.running)?o.running:[],r=Array.isArray(o.waiting)?o.waiting:[];console.log(),console.log(chalk.bold.cyan(" GPU queue")+chalk.gray(` · ${n} box${1===n?"":"es"} · ${l} free`)),console.log(chalk.bold.white(" ▶ running now:")),0===t.length&&console.log(chalk.gray(" (idle — gpu on takes a box immediately)"));for(const e of t){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.time_left_sec?e.time_left_sec:0,l=Math.floor(n/60),t=String(n%60).padStart(2,"0"),r=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(" ")+chalk.white(o.padEnd(8))+chalk.gray(` ${l}:${t} left`)+r)}console.log(chalk.bold.white(` ⏳ waiting (${r.length}):`)),0===r.length&&console.log(chalk.gray(" (nobody queued)"));for(const e of r){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.position?e.position:"?",l=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(` #${n} `)+chalk.white(o.padEnd(8))+l)}console.log()})():"key"===a?(e=>{const n=e.trim();if(n)try{o(y(t(),".icoa"),{recursive:!0}),l(M(),`${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(` (${M()})`))}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 queue")+chalk.yellow(" · ")+chalk.cyan("gpu key <k>"))},ge=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>z.cells.length?(console.log(0===z.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${z.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:z.cells[o-1],idx:o}},de=(e,o)=>!(!e.result||e.result.ok)&&!(!e.result.outputs.some(e=>"error"===e.kind&&"SyntaxError"===e.ename)||!b(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)),ue=async t=>{if(t.trim()&&x(`ipynb: ${t.trim()}`),te)return void(t.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));let r=t.trim();if(0===ne.length&&/^icoa\s+[a-z/]/i.test(r)&&(r=r.replace(/^icoa\s+/i,"")),0===ne.length){const t=r.split(/\s+/),a=(t[0]??"").toLowerCase(),d=r.slice(t[0]?.length??0).trim();if("quit"!==a&&"exit"!==a&&"q"!==a&&(re=!1),"quit"===a||"exit"===a||"back"===a||"q"===a)return z.dirty&&!re?(re=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void ae()):void await(async()=>{if(ee.removeAllListeners("line"),X||G(),console.log(),F){const e=D();e&&await K("release",e),F=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await B.shutdown().catch(()=>{}),X){oe&&(ee.prompt=oe);for(const e of Z)ee.on("line",e);ee.prompt(),se()}else se(),ee.close()})();if("clear"===a||"cls"===a)return console.clear(),_(),void ae();if("restart"===a)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await B.shutdown().catch(()=>{});try{await B.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 ae();if("help"===a||"?"===a)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(" your lease/queue · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on the GPU now")),console.log(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 ae();if("guide"===a||"/guide"===a)return(()=>{const o=z.path?c(z.path):process.cwd(),l=W(z.path);let t="",r=!1;try{const e=JSON.parse(n(y(o,"meta.json"),"utf-8"));t=e.judge??"",r=!0===e.needs_gpu}catch{}const a=z.cells.filter(e=>null!==e.result).length,i=e(y(o,"submission.csv"));console.log(),console.log(chalk.bold.white(" ═══ 📖 Notebook guide ═══")),console.log(),console.log(chalk.gray(" Where you are: ")+chalk.white(z.path?s(z.path):"new empty notebook")+chalk.gray(` · ${z.cells.length} cells (${a} run) · submission.csv: `)+(i?chalk.green("written ✓"):chalk.yellow("not yet — run all"))),F?console.log(chalk.gray(" ⚡ GPU: ")+chalk.green("connected")+chalk.gray(" — ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on · ")+chalk.cyan("download <file>")+chalk.gray(" pull results")):r&&console.log(chalk.gray(" ⚡ GPU task, not connected — ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.cyan("gpu on")+chalk.gray(" · ")+chalk.cyan("gpu queue")+chalk.gray(" shows who is on")),console.log(),console.log(chalk.bold.white(" The loop:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan("run all")+chalk.gray(" — trains the baseline, writes submission.csv")),l&&"icoa-holdout"===t?(console.log(chalk.gray(" 2. ")+chalk.cyan("quit")+chalk.gray(", then ")+chalk.cyan(`kaggle submit ${l}`)+chalk.gray(" — scored + ranked on the live board")),console.log(chalk.gray(" 3. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat your score."))):l&&r?(console.log(chalk.gray(" 2. ")+chalk.cyan("download <file>")+chalk.gray(" — pull your results (submission.csv / predictions.zip) off the GPU box")),console.log(chalk.gray(" 3. submit on kaggle.com — the notebook's final cell has the exact steps")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):l?(console.log(chalk.gray(" 2. ")+chalk.cyan("quit")+chalk.gray(", then ")+chalk.cyan(`kaggle check ${l}`)+chalk.gray(" — verifies the file format")),console.log(chalk.gray(" 3. upload submission.csv on kaggle.com — read your public score")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):console.log(chalk.gray(" 2. edit cells (")+chalk.cyan("edit N")+chalk.gray("), re-run, ")+chalk.cyan("save")+chalk.gray(" — this is a free notebook.")),console.log(),console.log(chalk.bold.white(" If it looks stuck:")),console.log(chalk.gray(" · prompt shows ")+chalk.cyan("...>")+chalk.gray(" → you are inside a code block. Press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(".")),console.log(chalk.gray(" · never type ")+chalk.cyan("python file.ipynb")+chalk.gray(" here — you are already inside. Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(),console.log(chalk.bold.white(" 🤝 AI help: ")+chalk.gray("split the screen ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" · right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" then ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" — live Gemma 3")),console.log(chalk.gray(" All commands: ")+chalk.cyan("help")+chalk.gray(" · leave: ")+chalk.cyan("quit")),console.log()})(),void ae();if("python"===a||"python3"===a)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 ae();if("open"===a)return V&&O(V)?console.log(chalk.gray(" reopening ")+chalk.cyan(V)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void ae();if("cells"===a||"ls"===a)return(()=>{if(0===z.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);z.cells.forEach((o,n)=>{const l=A(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(S(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 ae();if("show"===a)return(e=>{const o=ge(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 k(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 ──")),Y(o.cell.result,T)),console.log()}})(d),void ae();if("edit"===a)return(e=>{const o=ge(e);if(!o)return;ee.pause();const n=u(o.cell.source,"markdown"===o.cell.kind?".md":".py");if(ee.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,z.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."))})(d),void ae();if("add"===a)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)"));ee.pause();const l=u(n?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",n?".md":".py");ee.resume();const t=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");t?(z.cells.push({kind:n?"markdown":"code",source:t,result:null}),z.dirty=!0,console.log(chalk.green(` ✓ added ${n?"markdown ":""}cell ${z.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${z.cells.length}`)+chalk.gray(n?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(d),void ae();if("del"===a||"delete"===a)return(e=>{const o=ge(e);o&&(z.cells.splice(o.idx-1,1),z.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${z.cells.length} left.`)))})(d),void ae();if(("md"===a||"py"===a)&&/^\d+$/.test(d))return((e,o)=>{const n=ge(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,z.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}.`))})(d,"md"===a?"markdown":"code"),void ae();if("gpu"===a)return te=!0,await ye(d),te=!1,void ae();if("download"===a||"dl"===a)return te=!0,await(async e=>{if(!F)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:`${F.outDir}/${n}`;let r;try{r=await B.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=H?y(process.cwd(),"icoa-kaggle",H):process.cwd(),c=y(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)`)),H&&"submission.csv"===s(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${H}`)+chalk.gray(" — then upload on Kaggle yourself."))})(d),te=!1,void ae();if("run"===a)return te=!0,await(async e=>{const o=q(e,z.cells.length);if(o)for(const e of o){const n=z.cells[e-1];if("markdown"!==n.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(S(n,50))+chalk.gray(" ──"));try{n.result=await B.execute(n.source)}catch(e){return console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),void L()}if(z.dirty=!0,Y(n.result,T),de(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 L()}}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of k(n.source))console.log(e);console.log()}}else console.log(0===z.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"))})(d),te=!1,void ae();if("save"===a)return(e=>{if(0===z.cells.length)return void console.log(chalk.yellow(" nothing to save — the notebook is empty."));let o;o=e.trim()?i(e.trim())?e.trim():g(process.cwd(),e.trim()):z.path?z.path.endsWith(".ipynb")?z.path:`${z.path.replace(/\.[^./]+$/,"")}.ipynb`:g(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");try{l(o,C(z.cells)),z.path=o,z.dirty=!1,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${z.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(d),void ae();if(""===r)return void ae()}if(ne.length>0&&I.has(r.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(r.toLowerCase().replace(/^\//,""))+chalk.gray(" will work. This line was not added to the block.)")),void ae();if(ne.push(t),!f(ne))return 1!==ne.length||le||(le=!0,console.log(chalk.gray(" (multi-line block started — keep typing; an empty line runs it)"))),void ae();const a=ne.join("\n").replace(/\s+$/,"");if(ne.length=0,""!==a.trim()){te=!0;try{const e=await B.execute(a);z.cells.push({kind:"code",source:a,result:e}),z.dirty=!0,Y(e,T);const o=de(z.cells[z.cells.length-1],z.cells.length);e.ok||o||L()}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),L()}te=!1,ae()}else ae()};ee.on("line",e=>{ue(e)}),X||ee.on("close",async()=>{await B.shutdown().catch(()=>{}),process.exit(0)}),ae(),await ce}(m)})}function _(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}const I=new Set(["guide","/guide","help","?","quit","exit","back","menu","cells","run all"]);function L(){console.log(chalk.gray(" 🧭 stuck? type ")+chalk.cyan("guide")+chalk.gray(" for the basics · ")+chalk.cyan("help")+chalk.gray(" for every command."))}const T="https://practice.icoa2026.au";function R(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):T}function M(){return y(t(),".icoa","gpu-key")}function D(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return n(M(),"utf-8").trim()||null}catch{return null}}async function K(e,o,n){try{const l=await fetch(`${R()}/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 m(await l.json())}catch{return{state:"error",message:"GPU broker not reachable"}}}function W(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let J=0,V=null;function Y(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(j,"")}`))}else"display"===n.kind&&z(n.data,o)}function z(e,n){if(e["image/png"])try{o(n,{recursive:!0}),J+=1;const t=y(n,`figure-${J}.png`);return l(t,Buffer.from(e["image/png"],"base64")),V=t,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(t)),void(O(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,dirname as c,isAbsolute as i,join as y,resolve as g}from"node:path";import chalk from"chalk";import{aienvPaths as d}from"../lib/aienv.js";import{editTextInEditor as u}from"../lib/editor-spawn.js";import{buildSshArgs as p,leaseConnectProblems as h,parseLeaseResponse as m,queueLine as w}from"../lib/gpu.js";import{shouldExecuteCell as f}from"../lib/ipynb-input.js";import{looksLikeMarkdown as b,renderMarkdown as k}from"../lib/md-term.js";import{NotebookKernel as v,buildRemoteBridgeCommand as $}from"../lib/kernel.js";import{getMainRl as x}from"../lib/main-rl.js";import{logCommand as P}from"../lib/logger.js";import{startLogSync as E,stopLogSync as G}from"../lib/log-sync.js";import{cellPreview as S,parseIpynb as N,parsePercentPy as U,parseRunRange as C,serializeIpynb as q,statusChar as A}from"../lib/notebook-doc.js";import{openFile as O}from"../lib/open-file.js";const j=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");export function registerIpynbCommand(m){m.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 m=>{await async function(m){const j=d(t()),T=y(t(),".icoa","ipynb-out");if(_(),!e(j.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 J=m?function(o){const l=i(o)?o:g(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")?N(e):U(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.")}}}(m):null,z=J?J.doc:{cells:[],path:null,dirty:!1};let B=new v({venvPython:j.python,venvRoot:j.root}),F=null,H=W(z.path);process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await B.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.")),J&&console.log(J.note),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(" — the full walkthrough + where you are.")),console.log();const Q=x(),X=null!==Q,Z=X?Q.listeners("line").slice():[];X&&Q.removeAllListeners("line");const ee=X?Q:a({input:process.stdin,output:process.stdout,terminal:!0}),oe=X?ee.prompt:null;X&&(ee.prompt=r.prototype.prompt),X||E();const ne=[];let le=!1,te=!1,re=!1;const ae=()=>{const e=F?"icoa ipynb ⚡gpu":"icoa ipynb";ee.setPrompt(chalk.bold.cyan(ne.length?`${e} ...> `:`${e}> `)),ee.prompt()};let se=()=>{};const ce=new Promise(e=>{se=e}),ie=async()=>{if(!F)return void console.log(chalk.gray(" not on a GPU kernel."));const e=D();await B.shutdown().catch(()=>{}),e&&await K("release",e),F=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped.")),await(async()=>{B=new v({venvPython:j.python,venvRoot:j.root}),process.stdout.write(chalk.gray(" Starting local kernel…"));try{await B.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"))}})()},ye=async e=>{const[n,...r]=e.trim().split(/\s+/),a=(n??"").toLowerCase();"on"===a||"connect"===a?await(async()=>{if(F)return void console.log(chalk.gray(" already on the GPU kernel — ")+chalk.cyan("gpu status")+chalk.gray(" for time left."));const e=D();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)."));H||(H=W(z.path)),process.stdout.write(chalk.gray(" Requesting a GPU box…"));let n=await K("lease",e,H??void 0),r=0;for(;"queued"===n.state&&r<24;)0===r&&console.log(),process.stdout.write(`\r ${chalk.yellow(w(n))} `),await new Promise(e=>setTimeout(e,5e3)),n=await K("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=h(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 K("release",e);const s=H?`${n.dataRoot}/${H}`:n.dataRoot,c=$(n.python,{ICOA_KAGGLE_DATA:s,ICOA_KAGGLE_OUT:n.outDir},n.outDir);let i;if("local"===n.transport)i={command:"/bin/sh",args:["-c",c]};else{const r=y(t(),".icoa","gpu","lease-key");try{o(y(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 K("release",e)}i={command:"ssh",args:p(n,r,c)}}const g=new v({spawnSpec:i,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 K("release",e)}await B.shutdown().catch(()=>{}),B=g,F=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.")),H&&console.log(chalk.gray(` Dataset is already on the box (${H}) — 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 ie():"status"===a||""===a?await(async()=>{const e=D();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const o=await K("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(F?" (this notebook is connected)":" (not connected here — gpu on)"))}else"queued"===o.state?console.log(chalk.yellow(` ${w(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"}`))})():"queue"===a||"q"===a?await(async()=>{const e=D();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));let o=null;try{const n=await fetch(`${R()}/api/icoa/gpu/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)}),l=await n.json();o=l.data??l}catch{o=null}if(!o||"object"!=typeof o)return void console.log(chalk.yellow(" GPU queue not reachable right now — try again in a moment."));const n="number"==typeof o.boxes?o.boxes:0,l="number"==typeof o.free?o.free:0,t=Array.isArray(o.running)?o.running:[],r=Array.isArray(o.waiting)?o.waiting:[];console.log(),console.log(chalk.bold.cyan(" GPU queue")+chalk.gray(` · ${n} box${1===n?"":"es"} · ${l} free`)),console.log(chalk.bold.white(" ▶ running now:")),0===t.length&&console.log(chalk.gray(" (idle — gpu on takes a box immediately)"));for(const e of t){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.time_left_sec?e.time_left_sec:0,l=Math.floor(n/60),t=String(n%60).padStart(2,"0"),r=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(" ")+chalk.white(o.padEnd(8))+chalk.gray(` ${l}:${t} left`)+r)}console.log(chalk.bold.white(` ⏳ waiting (${r.length}):`)),0===r.length&&console.log(chalk.gray(" (nobody queued)"));for(const e of r){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.position?e.position:"?",l=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(` #${n} `)+chalk.white(o.padEnd(8))+l)}console.log()})():"key"===a?(e=>{const n=e.trim();if(n)try{o(y(t(),".icoa"),{recursive:!0}),l(M(),`${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(` (${M()})`))}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 queue")+chalk.yellow(" · ")+chalk.cyan("gpu key <k>"))},ge=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>z.cells.length?(console.log(0===z.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${z.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:z.cells[o-1],idx:o}},de=(e,o)=>!(!e.result||e.result.ok)&&!(!e.result.outputs.some(e=>"error"===e.kind&&"SyntaxError"===e.ename)||!b(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)),ue=async t=>{if(t.trim()&&P(`ipynb: ${t.trim()}`),te)return void(t.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));let r=t.trim();if(0===ne.length&&/^icoa\s+[a-z/]/i.test(r)&&(r=r.replace(/^icoa\s+/i,"")),0===ne.length){const t=r.split(/\s+/),a=(t[0]??"").toLowerCase(),d=r.slice(t[0]?.length??0).trim();if("quit"!==a&&"exit"!==a&&"q"!==a&&(re=!1),"quit"===a||"exit"===a||"back"===a||"q"===a)return z.dirty&&!re?(re=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void ae()):void await(async()=>{if(ee.removeAllListeners("line"),X||G(),console.log(),F){const e=D();e&&await K("release",e),F=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await B.shutdown().catch(()=>{}),X){oe&&(ee.prompt=oe);for(const e of Z)ee.on("line",e);ee.prompt(),se()}else se(),ee.close()})();if("clear"===a||"cls"===a)return console.clear(),_(),void ae();if("restart"===a)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await B.shutdown().catch(()=>{});try{await B.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 ae();if("help"===a||"?"===a)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(" your lease/queue · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on the GPU now")),console.log(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 ae();if("guide"===a||"/guide"===a)return(()=>{const o=z.path?c(z.path):process.cwd(),l=W(z.path);let t="";try{t=JSON.parse(n(y(o,"meta.json"),"utf-8")).judge??""}catch{}const r=z.cells.filter(e=>null!==e.result).length,a=e(y(o,"submission.csv"));console.log(),console.log(chalk.bold.white(" ═══ 📖 Notebook guide ═══")),console.log(),console.log(chalk.gray(" Where you are: ")+chalk.white(z.path?s(z.path):"new empty notebook")+chalk.gray(` · ${z.cells.length} cells (${r} run) · submission.csv: `)+(a?chalk.green("written ✓"):chalk.yellow("not yet — run all"))),console.log(),console.log(chalk.bold.white(" The loop:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan("run all")+chalk.gray(" — trains the baseline, writes submission.csv")),l&&"icoa-holdout"===t?(console.log(chalk.gray(" 2. ")+chalk.cyan("quit")+chalk.gray(", then ")+chalk.cyan(`kaggle submit ${l}`)+chalk.gray(" — scored + ranked on the live board")),console.log(chalk.gray(" 3. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat your score."))):l?(console.log(chalk.gray(" 2. ")+chalk.cyan("quit")+chalk.gray(", then ")+chalk.cyan(`kaggle check ${l}`)+chalk.gray(" — verifies the file format")),console.log(chalk.gray(" 3. upload submission.csv on kaggle.com — read your public score")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):console.log(chalk.gray(" 2. edit cells (")+chalk.cyan("edit N")+chalk.gray("), re-run, ")+chalk.cyan("save")+chalk.gray(" — this is a free notebook.")),console.log(),console.log(chalk.bold.white(" If it looks stuck:")),console.log(chalk.gray(" · prompt shows ")+chalk.cyan("...>")+chalk.gray(" → you are inside a code block. Press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(".")),console.log(chalk.gray(" · never type ")+chalk.cyan("python file.ipynb")+chalk.gray(" here — you are already inside. Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(),console.log(chalk.bold.white(" 🤝 AI help: ")+chalk.gray("split the screen ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" · right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" then ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" — live Gemma 3")),console.log(chalk.gray(" All commands: ")+chalk.cyan("help")+chalk.gray(" · leave: ")+chalk.cyan("quit")),console.log()})(),void ae();if("python"===a||"python3"===a)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 ae();if("open"===a)return V&&O(V)?console.log(chalk.gray(" reopening ")+chalk.cyan(V)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void ae();if("cells"===a||"ls"===a)return(()=>{if(0===z.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);z.cells.forEach((o,n)=>{const l=A(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(S(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 ae();if("show"===a)return(e=>{const o=ge(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 k(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 ──")),Y(o.cell.result,T)),console.log()}})(d),void ae();if("edit"===a)return(e=>{const o=ge(e);if(!o)return;ee.pause();const n=u(o.cell.source,"markdown"===o.cell.kind?".md":".py");if(ee.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,z.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."))})(d),void ae();if("add"===a)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)"));ee.pause();const l=u(n?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",n?".md":".py");ee.resume();const t=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");t?(z.cells.push({kind:n?"markdown":"code",source:t,result:null}),z.dirty=!0,console.log(chalk.green(` ✓ added ${n?"markdown ":""}cell ${z.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${z.cells.length}`)+chalk.gray(n?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(d),void ae();if("del"===a||"delete"===a)return(e=>{const o=ge(e);o&&(z.cells.splice(o.idx-1,1),z.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${z.cells.length} left.`)))})(d),void ae();if(("md"===a||"py"===a)&&/^\d+$/.test(d))return((e,o)=>{const n=ge(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,z.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}.`))})(d,"md"===a?"markdown":"code"),void ae();if("gpu"===a)return te=!0,await ye(d),te=!1,void ae();if("download"===a||"dl"===a)return te=!0,await(async e=>{if(!F)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:`${F.outDir}/${n}`;let r;try{r=await B.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=H?y(process.cwd(),"icoa-kaggle",H):process.cwd(),c=y(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)`)),H&&"submission.csv"===s(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${H}`)+chalk.gray(" — then upload on Kaggle yourself."))})(d),te=!1,void ae();if("run"===a)return te=!0,await(async e=>{const o=C(e,z.cells.length);if(o)for(const e of o){const n=z.cells[e-1];if("markdown"!==n.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(S(n,50))+chalk.gray(" ──"));try{n.result=await B.execute(n.source)}catch(e){return console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),void L()}if(z.dirty=!0,Y(n.result,T),de(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 L()}}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of k(n.source))console.log(e);console.log()}}else console.log(0===z.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"))})(d),te=!1,void ae();if("save"===a)return(e=>{if(0===z.cells.length)return void console.log(chalk.yellow(" nothing to save — the notebook is empty."));let o;o=e.trim()?i(e.trim())?e.trim():g(process.cwd(),e.trim()):z.path?z.path.endsWith(".ipynb")?z.path:`${z.path.replace(/\.[^./]+$/,"")}.ipynb`:g(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");try{l(o,q(z.cells)),z.path=o,z.dirty=!1,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${z.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(d),void ae();if(""===r)return void ae()}if(ne.length>0&&I.has(r.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(r.toLowerCase().replace(/^\//,""))+chalk.gray(" will work. This line was not added to the block.)")),void ae();if(ne.push(t),!f(ne))return 1!==ne.length||le||(le=!0,console.log(chalk.gray(" (multi-line block started — keep typing; an empty line runs it)"))),void ae();const a=ne.join("\n").replace(/\s+$/,"");if(ne.length=0,""!==a.trim()){te=!0;try{const e=await B.execute(a);z.cells.push({kind:"code",source:a,result:e}),z.dirty=!0,Y(e,T);const o=de(z.cells[z.cells.length-1],z.cells.length);e.ok||o||L()}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),L()}te=!1,ae()}else ae()};ee.on("line",e=>{ue(e)}),X||ee.on("close",async()=>{await B.shutdown().catch(()=>{}),process.exit(0)}),ae(),await ce}(m)})}function _(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}const I=new Set(["guide","/guide","help","?","quit","exit","back","menu","cells","run all"]);function L(){console.log(chalk.gray(" 🧭 stuck? type ")+chalk.cyan("guide")+chalk.gray(" for the basics · ")+chalk.cyan("help")+chalk.gray(" for every command."))}const T="https://practice.icoa2026.au";function R(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):T}function M(){return y(t(),".icoa","gpu-key")}function D(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return n(M(),"utf-8").trim()||null}catch{return null}}async function K(e,o,n){try{const l=await fetch(`${R()}/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 m(await l.json())}catch{return{state:"error",message:"GPU broker not reachable"}}}function W(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let J=0,V=null;function Y(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(j,"")}`))}else"display"===n.kind&&z(n.data,o)}function z(e,n){if(e["image/png"])try{o(n,{recursive:!0}),J+=1;const t=y(n,`figure-${J}.png`);return l(t,Buffer.from(e["image/png"],"base64")),V=t,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(t)),void(O(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 +1 @@
1
- import{existsSync as o,mkdirSync as e,readFileSync as n,readdirSync as l,writeFileSync as t}from"node:fs";import{join as s}from"node:path";import chalk from"chalk";import{makeReplAsker as a}from"../lib/repl-asker.js";import{logCommand as i}from"../lib/logger.js";import{openFile as r}from"../lib/open-file.js";import{serializeIpynb as c}from"../lib/notebook-doc.js";import{loadLearnState as g}from"../lib/learn-state.js";import{buildStarterCells as u,dataFileUrls as y,parseKaggleTaskList as d,parseSubmitResponse as h,validateSubmissionText as b}from"../lib/kaggle.js";function m(){return process.env.ICOA_KAGGLE_SERVER?process.env.ICOA_KAGGLE_SERVER.replace(/\/$/,""):"https://practice.icoa2026.au"}async function p(o){try{const e=await fetch(m()+o,{signal:AbortSignal.timeout(3e4)});return await e.json()}catch{return null}}async function f(o){try{const e=await fetch(o,{signal:AbortSignal.timeout(6e4)});return e.ok?await e.text():null}catch{return null}}function w(){console.log(),console.log(chalk.yellow(" The practice server is not reachable right now.")),console.log(chalk.gray(" Check your connection, or try again later.")),console.log()}function k(o){return s(process.cwd(),"icoa-kaggle",o)}function v(o,e){const n=[];let l="";for(const t of o.split(/\s+/))""!==l&&l.length+1+t.length>e?(n.push(l),l=t):l=""===l?t:`${l} ${t}`;return""!==l&&n.push(l),n}function $(o){return"local-eval"===o?.judge?(console.log(chalk.bold.white(" Scoring (inside the notebook):")),void console.log(chalk.gray(" run the final cell — the ")+chalk.white("FINAL")+chalk.gray(" line is your score. Nothing to upload."))):"icoa-holdout"===o?.judge?(console.log(chalk.bold.white(" Submit to ICOA (scored on the server):")),console.log(chalk.gray(" ")+chalk.bold.cyan(`kaggle submit ${o.comp_id}`)),void console.log(chalk.gray(" scores vs the secret test labels → live rank on ")+chalk.cyan("board"))):(console.log(chalk.bold.white(" Submit on Kaggle (manual, your own account):")),void(o?.kaggle_url?(console.log(chalk.gray(" 1. open ")+chalk.cyan(o.kaggle_url)),o?.needs_gpu?console.log(chalk.gray(" 2. submit the file your notebook produced")+chalk.gray(" — its final cell has the exact steps")):console.log(chalk.gray(" 2. Submit Predictions → upload ")+chalk.white("submission.csv")),console.log(chalk.gray(" 3. read your score, improve the MODEL cell, re-run, repeat."))):(console.log(chalk.gray(" (placeholder dataset — no live Kaggle page yet; when the real")),console.log(chalk.gray(" competition dataset lands, its submission link will appear here.)")))))}export async function runKaggle(n){const l=a(),r=async o=>await l.ask(o)??"";try{console.log(),console.log(chalk.bold.cyan(" 📊 KAGGLE PRACTICE")+chalk.gray(" · real ML competitions, a runnable starter notebook")),console.log(chalk.gray(" Small tasks run on your CPU; ")+chalk.magenta("⚡ GPU tasks")+chalk.gray(" run on the ICOA GPU box.")),console.log();const l=await p("/api/icoa/kaggle/tasks");if(!l)return w();const a=d(l);if(0===a.length)return console.log(chalk.yellow(" No practice competitions are live yet — check back soon.")),void console.log();let g=n?a.find(o=>o.comp_id===n):void 0;if(n&&!g&&console.log(chalk.yellow(` No competition called "${n}".`)),!g){console.log(chalk.white(" Live practice competitions:")),a.forEach((o,e)=>{const n=o.needs_gpu?chalk.magenta(" ⚡GPU"):"";console.log(chalk.gray(` ${e+1}. `)+chalk.cyan(o.comp_id)+chalk.gray(` — ${o.title} · ${o.metric}`)+n)});for(let o=0;o<3&&!g;o++){const o=(await r(chalk.cyan(" Pick one (number or id): "))).trim();if(!o)return;const e=Number(o);g=!Number.isNaN(e)&&a[e-1]||a.find(e=>e.comp_id===o.toLowerCase())||void 0,g||console.log(chalk.gray(` Try a number 1-${a.length} or an id like "${a[0].comp_id}".`))}if(!g)return}const h=g.comp_id;if(i(`kaggle: download ${h}`),g.needs_gpu)return void await async function(n,l){const a=k(n);if(console.log(),console.log(chalk.white(` ${l.title}`)+chalk.gray(` · ${l.metric}`)+chalk.bold.magenta(" ⚡ GPU task")),l.description){console.log();for(const o of v(l.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(" Fetching the notebook…")+chalk.gray(" (the dataset stays on the GPU box — no download)"));const i=await p(`/api/icoa/kaggle/${n}/starter`),r=i?.data?.starter??i?.starter;if("string"!=typeof r||0===r.length)return w();const c=s(a,"starter.ipynb");let g=!1;try{e(a,{recursive:!0}),o(c)?g=!0:t(c,r),t(s(a,"meta.json"),`${JSON.stringify(l,null,2)}\n`)}catch{return void console.log(chalk.yellow(" Could not write the notebook here — check directory permissions."))}console.log(chalk.green(" ✓ notebook: ")+chalk.white(c)+chalk.gray(g?" (kept your existing one)":" (the real IOAI task inside)")),console.log(chalk.green(" ✓ dataset: ")+chalk.white("already on the GPU box")+chalk.gray(" — no download needed")),console.log(),console.log(chalk.bold.white(" This is a GPU task — 3 steps:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${c}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.bold.cyan("gpu on")+chalk.gray(" (connects you to the box where the data lives)")),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("run all")+chalk.gray(" → the notebook trains on the GPU.")),console.log(),console.log(chalk.gray(" While you work: ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on, who is waiting")),console.log(),l.kaggle_url&&(console.log(chalk.gray(" Submit on Kaggle: ")+chalk.cyan(l.kaggle_url)),console.log())}(h,g);if(console.log(),console.log(chalk.white(` ${g.title}`)+chalk.gray(` · ${g.metric}`)),g.description){console.log();for(const o of v(g.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(" Downloading data…"));let b=null;const m=y(g);if(m){const[o,e,n]=await Promise.all([f(m.train),f(m.test),f(m.sample_submission)]);o&&e&&n&&(b={train:o,test:e,sample_submission:n})}if(!b){const o=await p(`/api/icoa/kaggle/${h}/data`);b=o?.data??o}if(!b?.train||!b?.test||!b?.sample_submission)return w();const $=k(h),j={...g,...b.meta??{}};try{e($,{recursive:!0}),t(s($,"train.csv"),b.train),t(s($,"test.csv"),b.test),t(s($,"sample_submission.csv"),b.sample_submission),t(s($,"meta.json"),`${JSON.stringify(j,null,2)}\n`)}catch{return void console.log(chalk.yellow(" Could not write the data files here — check directory permissions."))}const S=s($,"starter.ipynb");let x=!1;o(S)?x=!0:t(S,c(u($,j)));const G="number"==typeof j.n_train?`${j.n_train} rows`:"labelled",N="number"==typeof j.n_test?`${j.n_test} rows`:"predict these";console.log(chalk.green(" ✓ train: ")+chalk.white(s($,"train.csv"))+chalk.gray(` (${G})`)),console.log(chalk.green(" ✓ test: ")+chalk.white(s($,"test.csv"))+chalk.gray(` (${N})`)),console.log(chalk.green(" ✓ format: ")+chalk.white(s($,"sample_submission.csv"))),console.log(chalk.green(" ✓ notebook: ")+chalk.white(S)+chalk.gray(x?" (kept your existing one)":" (runnable baseline inside)")),(j.licence||j.attribution)&&console.log(chalk.gray(` licence: ${j.licence??"—"} · ${j.attribution??""}`)),console.log(),_(h,j,S),console.log()}finally{l.close()}}function _(o,e,n){e?.needs_gpu?(console.log(chalk.bold.white(" Your move — 4 steps (⚡ GPU task):")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${n}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.bold.cyan("gpu on")+chalk.gray(" → ")+chalk.bold.cyan("run all")+chalk.gray(" (trains on the GPU box)")),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("download <file>")+chalk.gray(" → pulls your results (submission.csv / predictions.zip) here")),console.log(chalk.gray(" 4. submit on kaggle.com — the notebook's final cell has the exact steps.")),console.log(),console.log(chalk.gray(" While you work: ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on, who is waiting"))):(console.log(chalk.bold.white(" Your move — 3 steps:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${n}`)+chalk.gray(" → run all (baseline trains)")),console.log(chalk.gray(" 2. it writes ")+chalk.white("submission.csv")+chalk.gray(" → verify with ")+chalk.cyan(`kaggle check ${o}`)),"icoa-holdout"===e?.judge?console.log(chalk.gray(" 3. ")+chalk.bold.cyan(`kaggle submit ${o}`)+chalk.gray(" → scored + ranked live.")):console.log(chalk.gray(" 3. upload it on Kaggle yourself — then beat the baseline."))),console.log(),console.log(chalk.bold.white(" 🤝 Want AI help? Set up your cockpit:")),console.log(chalk.gray(" 1. split the screen: ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" (lesson/work left · AI right)")),console.log(chalk.gray(" 2. in the right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" then type ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" → live Gemma 3")),console.log(chalk.gray(" 3. ask it for feature ideas or bug fixes — then ")+chalk.bold.white("VERIFY")+chalk.gray(" with your val score (a tip that lowers it, drop it).")),console.log(),$(e)}export async function runKaggleGuide(e){console.log();const l=j(e,"guide");if(!l)return;const t=k(l);let a=null;try{a=JSON.parse(n(s(t,"meta.json"),"utf-8"))}catch{a=null}i(`kaggle: guide ${l}`);const r=s(t,"starter.ipynb"),c=o(s(t,"submission.csv"));console.log(chalk.bold.white(` ═══ 📖 ${a?.title??l} — walkthrough ═══`)),console.log(),console.log(chalk.gray(" Where you are: data ")+chalk.green("downloaded ✓")+chalk.gray(" · submission.csv: ")+(c?chalk.green("written ✓"):chalk.yellow("not yet — run the notebook"))),console.log(),_(l,a,r),console.log(),console.log(chalk.gray(" Inside the notebook, ")+chalk.cyan("guide")+chalk.gray(" shows the notebook-level guide.")),console.log()}function j(e,n){if(e)return e;const t=s(process.cwd(),"icoa-kaggle"),a=o(t)?l(t,{withFileTypes:!0}).filter(e=>e.isDirectory()&&(o(s(t,e.name,"sample_submission.csv"))||o(s(t,e.name,"meta.json")))).map(o=>o.name):[];if(1===a.length)return a[0];if(0===a.length)return console.log(chalk.yellow(" No downloaded competition found here — run ")+chalk.cyan("kaggle")+chalk.yellow(" first.")),console.log(),null;console.log(chalk.white(" Several competitions downloaded — pick one:"));for(const o of a)console.log(chalk.gray(` kaggle ${n} `)+chalk.cyan(o));return console.log(),null}export async function runKaggleCheck(e){console.log();const l=j(e,"check");if(!l)return;const t=k(l),a=s(t,"submission.csv"),c=s(t,"sample_submission.csv");try{if(JSON.parse(n(s(t,"meta.json"),"utf-8")).needs_gpu&&!o(c))return console.log(chalk.gray(" ⚡ GPU task — results are produced and validated by the notebook itself.")),console.log(chalk.gray(" Pull them with ")+chalk.cyan("download <file>")+chalk.gray(" inside ")+chalk.cyan("icoa ipynb")+chalk.gray(", then submit on kaggle.com (final cell has the steps).")),void console.log()}catch{}if(!o(c))return console.log(chalk.yellow(` No data for "${l}" here — run `)+chalk.cyan(`kaggle ${l}`)+chalk.yellow(" first.")),void console.log();if(!o(a))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(t,"starter.ipynb")}`)),void console.log();const g=b(n(a,"utf-8"),n(c,"utf-8"));i(`kaggle: check ${l} → ${g.ok?"ok":`rejected: ${g.problems[0]??"format"}`}`);let u=null;try{u=JSON.parse(n(s(t,"meta.json"),"utf-8"))}catch{u=null}if(g.ok)console.log(chalk.bold.green(" ✓ submission.csv is Kaggle-ready")+chalk.gray(" (matches sample_submission.csv)")),console.log(chalk.gray(" ")+chalk.white(a)),console.log(),$(u),r(t);else{console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of g.problems)console.log(chalk.yellow(` · ${o}`));console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it."))}console.log()}export async function runKaggleSubmit(e){console.log();const l=j(e,"submit");if(!l)return;const t=k(l),r=s(t,"submission.csv"),c=s(t,"sample_submission.csv");let u=null;try{u=JSON.parse(n(s(t,"meta.json"),"utf-8"))}catch{u=null}if("local-eval"===u?.judge)return console.log(chalk.yellow(" This task is scored inside the notebook — nothing to upload.")),$(u),void console.log();if(!u||!o(c))return console.log(chalk.yellow(` No data for "${l}" here — run `)+chalk.cyan(`kaggle ${l}`)+chalk.yellow(" first.")),void console.log();if("icoa-holdout"!==u.judge)return console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here.")),console.log(),$(u),void console.log();if(!o(r))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(t,"starter.ipynb")}`)),void console.log();const y=n(r,"utf-8"),d=b(y,n(c,"utf-8"));if(!d.ok){i(`kaggle: submit ${l} → local-reject: ${d.problems[0]??"format"}`),console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of d.problems)console.log(chalk.yellow(` · ${o}`));return console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it.")),void console.log()}let p=g()?.token??"";if(!p){const o=a();try{p=(await o.ask(chalk.cyan(" Your learn token: "))??"").trim()}finally{o.close()}if(!p)return console.log(chalk.gray(" A learn token identifies you on the board — ask your coach for one.")),void console.log()}console.log(chalk.gray(" Scoring on the server…"));const f=await async function(o,e){try{const n=await fetch(m()+o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(6e4)});return await n.json()}catch{return null}}(`/api/icoa/kaggle/${l}/submit`,{token:p,submission_csv:y}),w=h(f);if(i(`kaggle: submit ${l} → ${w.ok?`${w.metric}=${w.score}${w.deduped?" (deduped)":""} rank=${w.rank??"-"}`:w.reason??"error"}`),console.log(),w.ok){const o=`${w.metric}: ${Number(w.score).toFixed(4).replace(/\.?0+$/,"")}`;w.deduped?(console.log(chalk.bold.white(` ✓ already scored — ${o}`)),console.log(chalk.gray(" These exact predictions were scored before. Improve the MODEL cell and re-run."))):(console.log(chalk.bold.green(` ✓ scored — ${o}`)),"number"==typeof w.rank&&"number"==typeof w.fieldSize&&console.log(chalk.bold.white(` 🏁 board rank #${w.rank}`)+chalk.gray(` of ${w.fieldSize}`))),w.boardEvent&&console.log(chalk.gray(" standings: ")+chalk.cyan(`board ${w.boardEvent} ${l}`))}else switch(w.reason){case"bad_token":console.log(chalk.bold.red(" ✗ that learn token was not accepted")+chalk.gray(" (invalid or expired)")),console.log(chalk.gray(" Check the token with your coach, then try again."));break;case"format":console.log(chalk.bold.red(" ✗ the server rejected submission.csv:"));for(const o of w.problems??[])console.log(chalk.yellow(` · ${o}`));break;case"event_closed":case"outside_window":console.log(chalk.bold.yellow(" ⏱ the submission window for this competition is closed."));break;case"cap_reached":console.log(chalk.bold.yellow(" ⏱ you have used all your submissions for this competition."));break;case"kaggle_judged":console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here."));break;default:console.log(chalk.yellow(" The scoring server is not reachable right now — try again in a minute."))}console.log()}export function registerKaggleCommand(o){o.command("kaggle").argument("[action]",'competition id, or "check" / "submit"').argument("[comp]",'competition id (with "check" / "submit")').description("Kaggle-style ML practice — dataset + starter notebook, check & submit").action(async(o,e)=>{"check"===o?await runKaggleCheck(e):"submit"===o?await runKaggleSubmit(e):"guide"===o?await runKaggleGuide(e):await runKaggle(o)}),o.command("guide").argument("[comp]","competition id").description("Show the competition walkthrough (3 steps + AI cockpit)").action(async o=>{await runKaggleGuide(o)})}
1
+ import{existsSync as o,mkdirSync as e,readFileSync as n,readdirSync as l,writeFileSync as t}from"node:fs";import{join as s}from"node:path";import chalk from"chalk";import{makeReplAsker as r}from"../lib/repl-asker.js";import{logCommand as i}from"../lib/logger.js";import{openFile as a}from"../lib/open-file.js";import{serializeIpynb as c}from"../lib/notebook-doc.js";import{loadLearnState as g}from"../lib/learn-state.js";import{buildStarterCells as u,dataFileUrls as d,parseKaggleTaskList as y,parseSubmitResponse as m,validateSubmissionText as b}from"../lib/kaggle.js";function h(){return process.env.ICOA_KAGGLE_SERVER?process.env.ICOA_KAGGLE_SERVER.replace(/\/$/,""):"https://practice.icoa2026.au"}async function p(o){try{const e=await fetch(h()+o,{signal:AbortSignal.timeout(3e4)});return await e.json()}catch{return null}}async function f(o){try{const e=await fetch(o,{signal:AbortSignal.timeout(6e4)});return e.ok?await e.text():null}catch{return null}}function k(){console.log(),console.log(chalk.yellow(" The practice server is not reachable right now.")),console.log(chalk.gray(" Check your connection, or try again later.")),console.log()}function w(o){return s(process.cwd(),"icoa-kaggle",o)}function v(o,e){const n=[];let l="";for(const t of o.split(/\s+/))""!==l&&l.length+1+t.length>e?(n.push(l),l=t):l=""===l?t:`${l} ${t}`;return""!==l&&n.push(l),n}function $(o){if("icoa-holdout"===o?.judge)return console.log(chalk.bold.white(" Submit to ICOA (scored on the server):")),console.log(chalk.gray(" ")+chalk.bold.cyan(`kaggle submit ${o.comp_id}`)),void console.log(chalk.gray(" scores vs the secret test labels → live rank on ")+chalk.cyan("board"));console.log(chalk.bold.white(" Submit on Kaggle (manual, your own account):")),o?.kaggle_url?(console.log(chalk.gray(" 1. open ")+chalk.cyan(o.kaggle_url)),console.log(chalk.gray(" 2. Submit Predictions → upload ")+chalk.white("submission.csv")),console.log(chalk.gray(" 3. read your score, improve the MODEL cell, re-run, repeat."))):(console.log(chalk.gray(" (placeholder dataset — no live Kaggle page yet; when the real")),console.log(chalk.gray(" competition dataset lands, its submission link will appear here.)")))}export async function runKaggle(n){const l=r(),a=async o=>await l.ask(o)??"";try{console.log(),console.log(chalk.bold.cyan(" 📊 KAGGLE PRACTICE")+chalk.gray(" · real ML competitions, a runnable starter notebook")),console.log(chalk.gray(" Small tasks run on your CPU; ")+chalk.magenta("⚡ GPU tasks")+chalk.gray(" run on the ICOA GPU box.")),console.log();const l=await p("/api/icoa/kaggle/tasks");if(!l)return k();const r=y(l);if(0===r.length)return console.log(chalk.yellow(" No practice competitions are live yet — check back soon.")),void console.log();let g=n?r.find(o=>o.comp_id===n):void 0;if(n&&!g&&console.log(chalk.yellow(` No competition called "${n}".`)),!g){console.log(chalk.white(" Live practice competitions:")),r.forEach((o,e)=>{const n=o.needs_gpu?chalk.magenta(" ⚡GPU"):"";console.log(chalk.gray(` ${e+1}. `)+chalk.cyan(o.comp_id)+chalk.gray(` — ${o.title} · ${o.metric}`)+n)});for(let o=0;o<3&&!g;o++){const o=(await a(chalk.cyan(" Pick one (number or id): "))).trim();if(!o)return;const e=Number(o);g=!Number.isNaN(e)&&r[e-1]||r.find(e=>e.comp_id===o.toLowerCase())||void 0,g||console.log(chalk.gray(` Try a number 1-${r.length} or an id like "${r[0].comp_id}".`))}if(!g)return}const m=g.comp_id;if(i(`kaggle: download ${m}`),g.needs_gpu)return void await async function(n,l){const r=w(n);if(console.log(),console.log(chalk.white(` ${l.title}`)+chalk.gray(` · ${l.metric}`)+chalk.bold.magenta(" ⚡ GPU task")),l.description){console.log();for(const o of v(l.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(" Fetching the notebook…")+chalk.gray(" (the audio dataset stays on the GPU box — no download)"));const i=await p(`/api/icoa/kaggle/${n}/starter`),a=i?.data?.starter??i?.starter;if("string"!=typeof a||0===a.length)return k();const c=s(r,"starter.ipynb");let g=!1;try{e(r,{recursive:!0}),o(c)?g=!0:t(c,a),t(s(r,"meta.json"),`${JSON.stringify(l,null,2)}\n`)}catch{return void console.log(chalk.yellow(" Could not write the notebook here — check directory permissions."))}console.log(chalk.green(" ✓ notebook: ")+chalk.white(c)+chalk.gray(g?" (kept your existing one)":" (the real IOAI task inside)")),console.log(chalk.green(" ✓ dataset: ")+chalk.white("already on the GPU box")+chalk.gray(" — no download needed")),console.log(),console.log(chalk.bold.white(" This is a GPU task — 3 steps:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${c}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.bold.cyan("gpu on")+chalk.gray(" (connects you to the box where the audio data lives)")),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("run all")+chalk.gray(" → the notebook trains on the GPU.")),console.log(),l.kaggle_url&&(console.log(chalk.gray(" Submit on Kaggle: ")+chalk.cyan(l.kaggle_url)),console.log())}(m,g);if(console.log(),console.log(chalk.white(` ${g.title}`)+chalk.gray(` · ${g.metric}`)),g.description){console.log();for(const o of v(g.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(" Downloading data…"));let b=null;const h=d(g);if(h){const[o,e,n]=await Promise.all([f(h.train),f(h.test),f(h.sample_submission)]);o&&e&&n&&(b={train:o,test:e,sample_submission:n})}if(!b){const o=await p(`/api/icoa/kaggle/${m}/data`);b=o?.data??o}if(!b?.train||!b?.test||!b?.sample_submission)return k();const $=w(m),j={...g,...b.meta??{}};try{e($,{recursive:!0}),t(s($,"train.csv"),b.train),t(s($,"test.csv"),b.test),t(s($,"sample_submission.csv"),b.sample_submission),t(s($,"meta.json"),`${JSON.stringify(j,null,2)}\n`)}catch{return void console.log(chalk.yellow(" Could not write the data files here — check directory permissions."))}const S=s($,"starter.ipynb");let K=!1;o(S)?K=!0:t(S,c(u($,j)));const x="number"==typeof j.n_train?`${j.n_train} rows`:"labelled",G="number"==typeof j.n_test?`${j.n_test} rows`:"predict these";console.log(chalk.green(" ✓ train: ")+chalk.white(s($,"train.csv"))+chalk.gray(` (${x})`)),console.log(chalk.green(" ✓ test: ")+chalk.white(s($,"test.csv"))+chalk.gray(` (${G})`)),console.log(chalk.green(" ✓ format: ")+chalk.white(s($,"sample_submission.csv"))),console.log(chalk.green(" ✓ notebook: ")+chalk.white(S)+chalk.gray(K?" (kept your existing one)":" (runnable baseline inside)")),(j.licence||j.attribution)&&console.log(chalk.gray(` licence: ${j.licence??"—"} · ${j.attribution??""}`)),console.log(),_(m,j,S),console.log()}finally{l.close()}}function _(o,e,n){console.log(chalk.bold.white(" Your move — 3 steps:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${n}`)+chalk.gray(" → run all (baseline trains)")),console.log(chalk.gray(" 2. it writes ")+chalk.white("submission.csv")+chalk.gray(" → verify with ")+chalk.cyan(`kaggle check ${o}`)),"icoa-holdout"===e?.judge?console.log(chalk.gray(" 3. ")+chalk.bold.cyan(`kaggle submit ${o}`)+chalk.gray(" → scored + ranked live.")):console.log(chalk.gray(" 3. upload it on Kaggle yourself — then beat the baseline.")),console.log(),console.log(chalk.bold.white(" 🤝 Want AI help? Set up your cockpit:")),console.log(chalk.gray(" 1. split the screen: ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" (lesson/work left · AI right)")),console.log(chalk.gray(" 2. in the right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" then type ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" → live Gemma 3")),console.log(chalk.gray(" 3. ask it for feature ideas or bug fixes — then ")+chalk.bold.white("VERIFY")+chalk.gray(" with your val score (a tip that lowers it, drop it).")),console.log(),$(e)}export async function runKaggleGuide(e){console.log();const l=j(e,"guide");if(!l)return;const t=w(l);let r=null;try{r=JSON.parse(n(s(t,"meta.json"),"utf-8"))}catch{r=null}i(`kaggle: guide ${l}`);const a=s(t,"starter.ipynb"),c=o(s(t,"submission.csv"));console.log(chalk.bold.white(` ═══ 📖 ${r?.title??l} — walkthrough ═══`)),console.log(),console.log(chalk.gray(" Where you are: data ")+chalk.green("downloaded ✓")+chalk.gray(" · submission.csv: ")+(c?chalk.green("written ✓"):chalk.yellow("not yet — run the notebook"))),console.log(),_(l,r,a),console.log(),console.log(chalk.gray(" Inside the notebook, ")+chalk.cyan("guide")+chalk.gray(" shows the notebook-level guide.")),console.log()}function j(e,n){if(e)return e;const t=s(process.cwd(),"icoa-kaggle"),r=o(t)?l(t,{withFileTypes:!0}).filter(e=>e.isDirectory()&&o(s(t,e.name,"sample_submission.csv"))).map(o=>o.name):[];if(1===r.length)return r[0];if(0===r.length)return console.log(chalk.yellow(" No downloaded competition found here — run ")+chalk.cyan("kaggle")+chalk.yellow(" first.")),console.log(),null;console.log(chalk.white(" Several competitions downloaded — pick one:"));for(const o of r)console.log(chalk.gray(` kaggle ${n} `)+chalk.cyan(o));return console.log(),null}export async function runKaggleCheck(e){console.log();const l=j(e,"check");if(!l)return;const t=w(l),r=s(t,"submission.csv"),c=s(t,"sample_submission.csv");if(!o(c))return console.log(chalk.yellow(` No data for "${l}" here — run `)+chalk.cyan(`kaggle ${l}`)+chalk.yellow(" first.")),void console.log();if(!o(r))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(t,"starter.ipynb")}`)),void console.log();const g=b(n(r,"utf-8"),n(c,"utf-8"));i(`kaggle: check ${l} → ${g.ok?"ok":`rejected: ${g.problems[0]??"format"}`}`);let u=null;try{u=JSON.parse(n(s(t,"meta.json"),"utf-8"))}catch{u=null}if(g.ok)console.log(chalk.bold.green(" ✓ submission.csv is Kaggle-ready")+chalk.gray(" (matches sample_submission.csv)")),console.log(chalk.gray(" ")+chalk.white(r)),console.log(),$(u),a(t);else{console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of g.problems)console.log(chalk.yellow(` · ${o}`));console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it."))}console.log()}export async function runKaggleSubmit(e){console.log();const l=j(e,"submit");if(!l)return;const t=w(l),a=s(t,"submission.csv"),c=s(t,"sample_submission.csv");let u=null;try{u=JSON.parse(n(s(t,"meta.json"),"utf-8"))}catch{u=null}if(!u||!o(c))return console.log(chalk.yellow(` No data for "${l}" here — run `)+chalk.cyan(`kaggle ${l}`)+chalk.yellow(" first.")),void console.log();if("icoa-holdout"!==u.judge)return console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here.")),console.log(),$(u),void console.log();if(!o(a))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(t,"starter.ipynb")}`)),void console.log();const d=n(a,"utf-8"),y=b(d,n(c,"utf-8"));if(!y.ok){i(`kaggle: submit ${l} → local-reject: ${y.problems[0]??"format"}`),console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of y.problems)console.log(chalk.yellow(` · ${o}`));return console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it.")),void console.log()}let p=g()?.token??"";if(!p){const o=r();try{p=(await o.ask(chalk.cyan(" Your learn token: "))??"").trim()}finally{o.close()}if(!p)return console.log(chalk.gray(" A learn token identifies you on the board — ask your coach for one.")),void console.log()}console.log(chalk.gray(" Scoring on the server…"));const f=await async function(o,e){try{const n=await fetch(h()+o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(6e4)});return await n.json()}catch{return null}}(`/api/icoa/kaggle/${l}/submit`,{token:p,submission_csv:d}),k=m(f);if(i(`kaggle: submit ${l} → ${k.ok?`${k.metric}=${k.score}${k.deduped?" (deduped)":""} rank=${k.rank??"-"}`:k.reason??"error"}`),console.log(),k.ok){const o=`${k.metric}: ${Number(k.score).toFixed(4).replace(/\.?0+$/,"")}`;k.deduped?(console.log(chalk.bold.white(` ✓ already scored — ${o}`)),console.log(chalk.gray(" These exact predictions were scored before. Improve the MODEL cell and re-run."))):(console.log(chalk.bold.green(` ✓ scored — ${o}`)),"number"==typeof k.rank&&"number"==typeof k.fieldSize&&console.log(chalk.bold.white(` 🏁 board rank #${k.rank}`)+chalk.gray(` of ${k.fieldSize}`))),k.boardEvent&&console.log(chalk.gray(" standings: ")+chalk.cyan(`board ${k.boardEvent} ${l}`))}else switch(k.reason){case"bad_token":console.log(chalk.bold.red(" ✗ that learn token was not accepted")+chalk.gray(" (invalid or expired)")),console.log(chalk.gray(" Check the token with your coach, then try again."));break;case"format":console.log(chalk.bold.red(" ✗ the server rejected submission.csv:"));for(const o of k.problems??[])console.log(chalk.yellow(` · ${o}`));break;case"event_closed":case"outside_window":console.log(chalk.bold.yellow(" ⏱ the submission window for this competition is closed."));break;case"cap_reached":console.log(chalk.bold.yellow(" ⏱ you have used all your submissions for this competition."));break;case"kaggle_judged":console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here."));break;default:console.log(chalk.yellow(" The scoring server is not reachable right now — try again in a minute."))}console.log()}export function registerKaggleCommand(o){o.command("kaggle").argument("[action]",'competition id, or "check" / "submit"').argument("[comp]",'competition id (with "check" / "submit")').description("Kaggle-style ML practice — dataset + starter notebook, check & submit").action(async(o,e)=>{"check"===o?await runKaggleCheck(e):"submit"===o?await runKaggleSubmit(e):"guide"===o?await runKaggleGuide(e):await runKaggle(o)}),o.command("guide").argument("[comp]","competition id").description("Show the competition walkthrough (3 steps + AI cockpit)").action(async o=>{await runKaggleGuide(o)})}
@@ -1 +1 @@
1
- import chalk from"chalk";import{Interface as o,createInterface as e}from"node:readline";import{execSync as r,spawn as n}from"node:child_process";import{getMainRl as t}from"../lib/main-rl.js";import{ai4ioaiPromptLabel as l,handleAi4ioaiMessage as a,startAi4ioaiChat as s}from"./ai4ioai.js";import{existsSync as i}from"node:fs";import{dirname as c,join as u}from"node:path";import{fileURLToPath as d}from"node:url";import{loadCurriculumById as g,validateEAToken as m,syncProgress as y,syncCardFeedback as h}from"../lib/learn-curricula.js";import{normalizeTokenBody as f}from"../lib/token-format.js";import{streamLearnTutor as p,submitPqs as w,viewPqsTop as b,viewHonors as k}from"../lib/learn-ai.js";import{getConfig as v,saveConfig as A}from"../lib/config.js";import{loadLearnState as C,saveLearnState as I,newLearnState as $,updateStreak as E,markCardComplete as T,recordMCQ as _,recordCheck as x,markPracticalComplete as M,addAchievement as P}from"../lib/learn-state.js";import{renderWelcome as O,renderKnowledgeCard as L,renderMCQCard as D,renderMCQFeedback as S,renderPracticalCard as q,renderPracticalSuccess as j,renderSimDemoCard as N,renderMilestone as R,renderArenaTaskCard as W,renderComingSoonCard as F,renderStatus as B,renderPhaseComplete as z,renderCurriculumComplete as U,setLearnAiEnabled as J,setLearnPqsViewCards as Q,renderHonorWall as V}from"../lib/learn-render.js";import{printError as Y}from"../lib/ui.js";export function registerLearnCommand(H){H.command("learn [token]").description("Enter learn mode (free demo, or team-issued EA/EI/AC/CA/IO/IA token for full curriculum)").action(async H=>{H&&H.trim()||(console.log(),console.log(chalk.gray(" No token given — starting free 11-card demo (")+chalk.bold.green("LEARNDEMO01")+chalk.gray(").")),console.log(chalk.gray(" Full curriculum: ")+chalk.bold.yellow("learn EA|EI|AC|CA|IO|IA + 8 chars")+chalk.gray(" — token from your country team leader.")),console.log(),H="LEARNDEMO01");let K=H.trim().toUpperCase(),X=null;const Z=/^(LEARNDEMO01|AI4CTFDEMO01|CTF4AIDEMO01)$/i.test(K),G=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(K);let oo=!1;if(Z)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),X=await g(K,K);else if(G){console.log(),console.log(chalk.gray(" Validating token..."));let o=await m(K);if(!o.ok){const e=f(K);if(e!==K){const r=await m(e);r.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${K} → ${e}`)),o=r,K=e)}}if(!o.ok)return Y(`Token validation failed: ${o.message}`),console.log(),"device_bound"===o.code?(console.log(chalk.gray(" This learn token is bound to the first computer it was used on,")),console.log(chalk.gray(" and this is a different computer.")),console.log(),console.log(chalk.gray(" If you changed computers or reinstalled, ask the coordinator who")),console.log(chalk.gray(" issued your token to move it to this device, then try again."))):(console.log(chalk.gray(" Possible causes:")),console.log(chalk.gray(" · Token expired or revoked")),console.log(chalk.gray(" · Network down (check connection)")),console.log(chalk.gray(" · Typo in token (check 0/O, 1/I/L, V/U)"))),void console.log();if(console.log(chalk.green(` ✓ Token valid · curriculum: ${o.curriculumId} · status: ${o.status}`)+(!0===o.aiEnabled?chalk.bold.magenta(" · ⭐ AI tutor"):"")),oo=!0===o.aiEnabled,console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),X=await g(o.curriculumId||"LEARNDEMO01",K),!X)return Y(`Could not open a learn curriculum for token '${K}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${K}`)+chalk.gray(" instead.")),console.log(chalk.gray(" Otherwise: the full curriculum is ~3 MB; on a slow link the download")),console.log(chalk.gray(" can take a while — stay on a stable connection and run ")+chalk.bold.yellow(`learn ${K}`)+chalk.gray(" again")),console.log(chalk.gray(" (it caches after the first load). If it keeps failing, check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()}if(!X)return Y(`Unknown learn token: ${K}`),console.log(),console.log(chalk.gray(" Available tokens:")),console.log(chalk.gray(" ")+chalk.bold.green("LEARNDEMO01")+chalk.gray(" free 11-card demo (anyone can use)")),console.log(chalk.gray(" ")+chalk.bold.yellow("EA|EI|AC|CA|IO|IA")+chalk.gray(" + 8 chars full curriculum (issued by team leader)")),console.log(),console.log(chalk.gray(" Tracks: ")+chalk.cyan("EA")+chalk.gray("=ctf4eai · ")+chalk.cyan("AC")+chalk.gray("=ai4ctf · ")+chalk.cyan("CA")+chalk.gray("=ctf4ai · ")+chalk.cyan("IO")+chalk.gray("=ioai · ")+chalk.cyan("IA")+chalk.gray("=iaio")),console.log(),console.log(chalk.gray(" To get a full curriculum, email ")),console.log(chalk.gray(" ")+chalk.cyan("australia@icoa2026.au")+chalk.gray(" or ask your country's team leader.")),void console.log();let eo=C(),ro=!1;try{eo&&eo.token===K?E(eo):(eo=$(K,X.id,X.totalCards),ro=!0),I(eo),O(X,eo,ro)}catch{return Y("Could not open this curriculum — it may be malformed or not a learn curriculum."),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${K}`)+chalk.gray(".")),void console.log()}const no=t(),to=null!==no,lo=to?no.listeners("line").slice():[];to&&no.removeAllListeners("line");const ao=to?no:e({input:process.stdin,output:process.stdout,terminal:!0}),so=to?ao.prompt:null;to&&(ao.prompt=o.prototype.prompt);const io=()=>{to&&so&&(ao.prompt=so)},co=()=>{ao.setPrompt(po?chalk.bold.green(`icoa ${l()}> `):chalk.bold.cyan(ho?"icoa learn ai> ":"icoa learn> ")),ao.prompt()};let uo=null,go=null,mo=null,yo=null,ho=!1,fo=!1,po=!1;const wo=new Map,bo=()=>{let o=wo.get(eo.currentCard);return o||(o=[],wo.set(eo.currentCard,o)),o};let ko=!1;const vo=new Set;let Ao=!1,Co=0;const Io=(v().language||"en").toLowerCase().startsWith("zh");J(oo),Q(vo);const $o=[];let Eo=null;const To=new Promise(o=>{Eo=o}),_o=()=>{const o=Eo;Eo=null,o?.()},xo="1"===process.env.ICOA_LEARN_EMBEDDED,Mo=o=>X.cards.find(e=>e.number===o),Po=o=>{const e=X.modules.find(e=>e.cardRange[1]===o);if(!e)return!1;const r=X.modules.find(o=>o.number===e.number+1);return z(X,eo,e,r),!0},Oo=()=>{Ao=!0,console.log(chalk.gray(Io?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},Lo=()=>{const o=Mo(eo.currentCard);if(!o)return console.log(),console.log(chalk.gray(" No more cards in this curriculum.")),console.log(chalk.gray(" Type ")+chalk.bold.green("status")+chalk.gray(" for the dashboard or ")+chalk.bold.green("quit")+chalk.gray(" to exit.")),void console.log();switch(o.type){case"knowledge":L(o,X),o.check?(mo=o.number,Co=Date.now()):(T(eo,o.number),I(eo));break;case"mcq":D(o,X),uo=o.number;break;case"practical":q(o,X),go=o.number;break;case"sim_demo":N(o,X),T(eo,o.number),I(eo);break;case"milestone":R(o,X),P(eo,o.badge),T(eo,o.number),I(eo);break;case"arena_task":W(o,X),T(eo,o.number),I(eo);break;case"coming_soon":F(o,X),T(eo,o.number),I(eo)}},Do=()=>{K.endsWith("DEMO01")?console.log(chalk.yellow(Io?" AI 导师需要开通 AI 的正式课程 token(demo 是共享的,没有 AI 额度)。":" The AI tutor needs an AI-enabled curriculum token — demos are shared and carry no AI budget.")):(console.log(chalk.yellow(Io?" 此 token 未开通 AI 导师(高级功能)。":" This token does not include the AI tutor (premium).")),console.log(chalk.gray(Io?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},So=async(o,e)=>{if(oo){fo=!0;try{console.log(),console.log(chalk.gray("deep"===e?Io?" 🤖 AI 导师(深度思考中,思考过程为灰色小字)…":" 🤖 AI tutor (deepthink — reasoning shown in gray)…":Io?" 🤖 AI 导师(快速模式)…":" 🤖 AI tutor (quick mode)…")),console.log();let r=!1,n=!1;const t=await p({token:K,cardNumber:eo.currentCard,question:o,mode:e,history:bo().slice(-8)},o=>{"reasoning"===o.kind?(r||(process.stdout.write(" "),r=!0),process.stdout.write(chalk.dim(o.text.replace(/\n/g,"\n ")))):(n||(process.stdout.write(r?"\n\n ":" "),n=!0),process.stdout.write(chalk.white(o.text.replace(/\n/g,"\n "))))});(r||n)&&console.log(),t.ok?t.offtopic?(console.log(),console.log(chalk.yellow(Io?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(bo().push({role:"user",content:o},{role:"assistant",content:t.answer}),null!=t.spent&&null!=t.cap&&t.spent/t.cap>.8&&console.log(chalk.gray(` (${Io?"AI 额度":"AI budget"}: ${Math.round(t.spent/1e3)}k / ${Math.round(t.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${t.message||(Io?"AI 导师暂不可用。":"AI tutor unavailable.")}`))),null!==mo&&console.log(chalk.gray(Io?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{fo=!1}}else Do()},qo=o=>o.match(/.{1,64}(\s|$)/g)?.map(o=>o.trim())??[o],jo=async o=>{const e=o.trim().toLowerCase();if(!fo){if(null!==yo){const e=o.trim(),r=yo;if(yo=null,""===e)console.log(chalk.gray(Io?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else{const o=Co>0?Date.now()-Co:void 0;await h(K,{curriculum_id:X.id,card_number:r,feedback_text:e,time_on_card_ms:o})?console.log(chalk.green(Io?" ✓ 已收到,谢谢帮助完善这张卡。":" ✓ Thanks — your report was recorded.")):console.log(chalk.yellow(Io?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}return console.log(),void co()}if(ko){ko=!1;const e=o.trim().toLowerCase();return"y"===e||"yes"===e?await(async()=>{fo=!0;try{console.log(),console.log(chalk.gray(Io?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const o=await w({token:K,cardNumber:eo.currentCard});if(console.log(),!o.ok)return console.log(chalk.yellow(` ${o.message||(Io?"评审暂不可用。":"Review unavailable.")}`)),void console.log();(o=>{const e="green"===o.tier?chalk.bold.green:"blue"===o.tier?chalk.bold.cyan:"yellow"===o.tier?chalk.bold.yellow:chalk.bold.red;if(console.log(chalk.gray(" ─────────────────────────────────────────")),console.log(chalk.white(Io?" 提问评分 ":" Prompt score ")+e(`${o.score??0} / 100`)+chalk.gray(" "+(o=>{switch(o){case"green":return"🟢 "+(Io?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(Io?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(Io?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(Io?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(o.tier))),o.manipulation&&console.log(chalk.red(Io?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ an attempt to manipulate the score was detected — the score was reduced sharply")),null!=o.rank&&null!=o.entrants){const e=!0===o.inTop3,r=Io?` 本卡排名 #${o.rank} / ${o.entrants}`:` Rank on this card: #${o.rank} of ${o.entrants}`;console.log((e?chalk.bold.green(r):chalk.white(r))+(e?chalk.bold.magenta(Io?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(Io?` 第 ${o.submissionIndex??"?"} / 2 次提交 · 剩余 ${o.submissionsLeft??0} 次(可先追加 /ai 对话再交)`:` Attempt ${o.submissionIndex??"?"} of 2 · ${o.submissionsLeft??0} left (extend the /ai conversation before your next one)`)),o.feedback){console.log();for(const e of qo(o.feedback))console.log(chalk.white(" "+e))}o.improve&&(console.log(),console.log(chalk.cyan(Io?" 改进提问: ":" Ask better: ")+chalk.gray(o.improve))),console.log(chalk.gray(" ─────────────────────────────────────────")),null!=o.spent&&null!=o.cap&&o.spent/o.cap>.8&&console.log(chalk.gray(` (${Io?"AI 额度":"AI budget"}: ${Math.round(o.spent/1e3)}k / ${Math.round(o.cap/1e3)}k tokens)`)),console.log()})(o),!0===o.inTop3?vo.add(eo.currentCard):vo.delete(eo.currentCard);const e=await k({token:K,curriculumId:X.id,cardNumber:eo.currentCard});e.ok&&e.totals&&e.chapters&&(V({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log())}finally{fo=!1}})():(console.log(chalk.gray(Io?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==mo&&(console.log(chalk.gray(Io?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void co()}if(Ao)return Ao=!1,Lo(),void co();if(e){if(po)return"exit"===await a(o.trim())&&(po=!1),void co();if(ho){if(["q","quit","exit","back","b","menu"].includes(e))return ho=!1,console.log(chalk.gray(Io?" 已退出 AI 导师,回到卡片。":" Left the AI tutor — back to the card.")),console.log(),void co();const r=o.trim().startsWith("!"),n=r?o.trim().slice(1).trim():o.trim();return n&&await So(n,r?"fast":"deep"),void co()}if("tmux"===e||e.startsWith("tmux ")){try{r("command -v tmux",{stdio:"ignore"})}catch{return console.log(chalk.yellow(" tmux is not installed yet.")),console.log(chalk.gray(" Install it with ")+chalk.bold.cyan("darwin"===process.platform?"brew install tmux":"sudo apt install tmux")+chalk.gray(Io?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void co()}return await new Promise(e=>{const r=process.stdin,t=!!r.isTTY&&!!r.isRaw;if(ao.pause(),r.isTTY&&"function"==typeof r.setRawMode)try{r.setRawMode(!1)}catch{}const l=n(o.trim(),{shell:!0,stdio:"inherit"}),a=()=>{if(r.isTTY&&"function"==typeof r.setRawMode&&t)try{r.setRawMode(!0)}catch{}ao.resume(),e()};l.on("close",a),l.on("error",a)}),console.log(),void co()}if("ai4ioai"===e||"/ai4ioai"===e)return await s()&&(po=!0),void co();if("/ai"===e||"/ai!"===e||e.startsWith("/ai ")||e.startsWith("/ai! ")){if(!oo)return Do(),void co();const r=e.startsWith("/ai!"),n=o.trim().slice(r?4:3).trim();if(!n){ho=!0;const o=Mo(eo.currentCard),e=o?o.title??o.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(Io?"AI 导师":"AI tutor")+(e?chalk.gray(Io?` — 主题「${e}」`:` — topic “${e}”`):"")),console.log(chalk.gray(Io?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void co()}return await So(n,r?"fast":"deep"),void co()}if("/submit"===e||e.startsWith("/submit ")||"/research"===e||e.startsWith("/research ")){if(!oo)return Do(),void co();const o=Mo(eo.currentCard),e=o?o.title??o.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(Io?"Panda 提问评审":"Panda's prompt review")+(e?chalk.gray(Io?` — 主题「${e}」`:` — topic “${e}”`):"")),console.log(chalk.gray(Io?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(Io?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(Io?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(Io?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(Io?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),ko=!0,void co()}if("/view"===e)return oo?(await(async()=>{fo=!0;try{console.log();const o=await b({token:K,cardNumber:eo.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(Io?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&vo.delete(eo.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&vo.add(eo.currentCard),console.log(chalk.bold.white(Io?` 🏆 本卡 Top-3 提问 — 第 ${eo.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 Top-3 prompts — card ${eo.currentCard} · ${o.entrants??0} entrant(s)`));for(const e of o.top3??[]){const o="green"===e.tier?"🟢":"blue"===e.tier?"🔵":"yellow"===e.tier?"🟡":"🔴";console.log(),console.log(chalk.bold.cyan(` ── Rank ${e.rank}`)+(e.me?chalk.bold.magenta(" (me)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((o,e)=>{const r=qo(o);console.log(chalk.gray(` Q${e+1} `)+chalk.white(r[0]??""));for(const o of r.slice(1))console.log(chalk.white(" "+o))}),0===e.questions.length&&console.log(chalk.gray(Io?" (无可显示的提问)":" (no questions to show)"))}console.log()}finally{fo=!1}})(),void co()):(Do(),void co());if("/honors"===e||"honors"===e)return Z?(console.log(),console.log(chalk.gray(Io?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void co()):(await(async()=>{fo=!0;try{console.log();const o=await k({token:K,curriculumId:X.id,cardNumber:eo.currentCard});if(!o.ok||!o.totals||!o.chapters)return console.log(chalk.yellow(` ${o.message||(Io?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(Io?` 🏆 本卡实时 Top-3 — 第 ${eo.currentCard} 张`:` 🏆 Live top-3 — card ${eo.currentCard}`)),o.board&&0!==o.board.length)for(const e of o.board){const o="green"===e.tier?"🟢":"blue"===e.tier?"🔵":"yellow"===e.tier?"🟡":"🔴";console.log(chalk.white(` ${e.icon} `)+chalk.bold.cyan(`#${e.rank}`)+chalk.white(` · ${e.score} `)+o+(e.me?chalk.bold.magenta(" (me)"):""))}else console.log(chalk.gray(Io?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));console.log(),V({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()}finally{fo=!1}})(),void co());if("menu"!==e&&"menu confirm"!==e)if("quit"!==e&&"exit"!==e&&"q"!==e){if("status"===e)return B(X,eo),void co();if("lang"===e||e.startsWith("lang ")){const o=e.slice(4).trim();if(!o)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(v().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void co();const r=X.cards.some(o=>null!=o._zh),n=o.toLowerCase().startsWith("zh")?"zh":o.toLowerCase(),t="en"===n||"zh"===n&&r,l=t?n:"en";return A({language:l}),t?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${o} 本课暂无翻译,已用英文 / not available — using English`)),mo=null,uo=null,go=null,yo=null,Ao=!1,ko=!1,Lo(),void co()}if("sim"===e){const o=Mo(eo.currentCard);return o&&"sim_demo"===o.type?(function(o){const e=function(){const o=c(d(import.meta.url)),e=[u(o,"..","..","panda","mujoco-launcher.py"),u(o,"..","..","..","panda","mujoco-launcher.py")];for(const o of e)if(i(o))return o;return null}();if(!e)return console.log(chalk.yellow(" MuJoCo launcher not found.")),console.log(chalk.gray(" Get it from: https://github.com/newaipanda/ICOA_CLI/blob/main/panda/mujoco-launcher.py")),void console.log(chalk.gray(" Or use the sandbox-vla docker image (Phase 3)."));const r={baseline:"baseline",prompt_injected:"prompt_inj",patch_attacked:"patch",modality_confused:"confused"}[o]||"baseline";console.log(chalk.gray(` Launching MuJoCo viewer (scenario: ${r})...`)),console.log(chalk.gray(" Close the window or press ESC to return to learn mode.")),n("python3",[e,r,"--seconds","5"],{stdio:"inherit"}).on("exit",o=>{0!==o?console.log(chalk.yellow(` MuJoCo exited with code ${o} (install: pip install mujoco)`)):console.log(chalk.gray(" Returned from sim."))})}(o.simAction),void co()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void co())}if("bookmark"===e){const o=eo.currentCard;return eo.bookmarks.includes(o)||eo.bookmarks.push(o),I(eo),console.log(chalk.gray(` ✓ Card ${o} bookmarked.`)),void co()}if("e"===e)return yo=eo.currentCard,console.log(chalk.gray(Io?" 描述问题(回车提交 / 空行取消):":" Describe the issue (Enter to submit / blank to cancel):")),void co();if("back"===e||"b"===e)return eo.currentCard>1&&(eo.currentCard-=1),uo=null,go=null,mo=null,I(eo),Lo(),void co();if(e.startsWith("card ")){const o=e.slice(5).trim(),r=parseInt(o,10);return!Number.isInteger(r)||r<1||r>X.totalCards?(console.log(chalk.yellow(` Card number must be 1..${X.totalCards}. Try: `)+chalk.bold.green("card 1")),void co()):(eo.currentCard=r,uo=null,go=null,mo=null,I(eo),Lo(),void co())}if(null!==mo&&["y","yes","n","no"].includes(e)){const o=Mo(mo);if(o&&"knowledge"===o.type&&o.check){const r=e.startsWith("y")?"y":"n",n=r===o.check.answer,t=Date.now()-Co;T(eo,o.number),x(eo,o.number,{answer:r,correct:n,submittedAt:(new Date).toISOString()}),I(eo);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(o,r,n,!1),$o.push(y(K,{card_number:o.number,event_type:"check_answered",check_answer:r,check_correct:n,time_on_card_ms:t}).catch(()=>{})),mo=null,o.solution&&o.solution.length>0)return void co();if(eo.currentCard<X.totalCards){const o=eo.currentCard;eo.currentCard+=1,I(eo),Po(o)?Oo():Lo(),co()}else U(X,eo),co();return}}if(null!==uo&&["a","b","c","d"].includes(e)){const o=Mo(uo);if(o&&"mcq"===o.type){const r=e.toUpperCase(),n=r===o.answer;return _(eo,o.number,{answer:r,correct:n,submittedAt:(new Date).toISOString()}),T(eo,o.number),I(eo),S(o,r,n,eo),$o.push(y(K,{card_number:o.number,event_type:"mcq_answered",mcq_answer:r,mcq_correct:n}).catch(()=>{})),uo=null,void(n?eo.currentCard<X.totalCards?(eo.currentCard+=1,I(eo),Lo()):(U(X,eo),co()):co())}}if(null!==go){if("done"===e){const o=Mo(go);if(o&&"practical"===o.type)return M(eo,o.number),T(eo,o.number),I(eo),j(o),go=null,void co()}if("skip"===e)return T(eo,go),I(eo),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),go=null,void co()}if("ok"===e||"next"===e||"continue"===e||"n"===e){if(null!==uo)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void co();if(null!==go)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void co();if(null!==mo)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void co();const o=eo.currentCard;return eo.currentCard+=1,I(eo),eo.currentCard>X.totalCards?U(X,eo):Po(o)?Oo():Lo(),void co()}if(null!==mo)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void co();if(null!==uo)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void co();if(null!==go)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void co();console.log(chalk.gray(" Unknown command. Try: ")+chalk.white("ok")+chalk.gray(" / ")+chalk.white("status")+chalk.gray(" / ")+chalk.white("card N")+chalk.gray(" / ")+chalk.white("/ai")+chalk.gray(" / ")+chalk.white("quit")),co()}else if($o.length>0&&await Promise.race([Promise.allSettled($o),new Promise(o=>setTimeout(o,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${eo.streakDays} day(s)`)),console.log(),to){ao.removeAllListeners("line"),io();for(const o of lo)ao.on("line",o);ao.prompt(),_o()}else ao.removeAllListeners("line"),ao.close();else if($o.length>0&&await Promise.race([Promise.allSettled($o),new Promise(o=>setTimeout(o,3e3))]),ao.removeAllListeners("line"),io(),to||!xo){const{returnToMainMenu:o}=await import("../lib/menu-nav.js");o(to?ao:void 0),_o()}else ao.close()}else co()}};ao.on("line",o=>{jo(o).catch(o=>{console.log(),console.log(chalk.red(" ⚠ Something went wrong handling that input.")),console.log(chalk.gray(` ${o instanceof Error?o.message:String(o)}`)),console.log(chalk.gray(" Progress is saved. Type ")+chalk.bold.green("ok")+chalk.gray(" to continue or ")+chalk.bold.green("quit")+chalk.gray(" to exit.")),co()})}),to||ao.on("close",async()=>{$o.length>0&&await Promise.race([Promise.allSettled($o),new Promise(o=>setTimeout(o,5e3))]),xo?_o():process.exit(0)});try{Lo(),co()}catch{if(Y("Could not render this card — the curriculum may be malformed."),to){ao.removeAllListeners("line"),io();for(const o of lo)ao.on("line",o);ao.prompt()}else ao.close();_o()}await To}),H.command("learn-pull [id]").description("Pre-download learn curricula to ~/.icoa/learn-cache/ for offline use (default: all)").action(async o=>{const e=o?[o.trim()]:["LEARNDEMO01","AI4CTFDEMO01","CTF4AIDEMO01","ai4ctf-96","ai4ctf-360","ctf4ai-96","ctf4ai-360","ctf4eai-96","ctf4eai-360","embodied-ai-100","embodied-ai-480"];console.log(),console.log(chalk.bold.cyan(" ICOA learn-pull — fetching curricula for offline use")),console.log(chalk.gray(" Server: https://practice.icoa2026.au")),console.log();let r=0,n=0,t=0;for(const o of e){process.stdout.write(` ${o.padEnd(22)} `);const e=Date.now(),l=await g(o),a=Date.now()-e;if(l){const o=l.cards,e=Array.isArray(o)?o.length:0,n=JSON.stringify(l).length;t+=n,console.log(chalk.green("✓ ")+chalk.gray(`${e.toString().padStart(3)} cards · ${(n/1024).toFixed(1).padStart(6)} KB · ${a.toString().padStart(4)} ms`)),r++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),n++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${r} cached`)+chalk.gray(` · ${n} failed · total ${(t/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}
1
+ import chalk from"chalk";import{Interface as e,createInterface as o}from"node:readline";import{execSync as r,spawn as n}from"node:child_process";import{getMainRl as t}from"../lib/main-rl.js";import{ai4ioaiPromptLabel as l,handleAi4ioaiMessage as a,startAi4ioaiChat as s}from"./ai4ioai.js";import{existsSync as i}from"node:fs";import{dirname as c,join as u}from"node:path";import{fileURLToPath as d}from"node:url";import{loadCurriculumById as g,validateEAToken as m,syncProgress as y,syncCardFeedback as h}from"../lib/learn-curricula.js";import{normalizeTokenBody as f}from"../lib/token-format.js";import{streamLearnTutor as p,submitPqs as w,viewPqsTop as b,viewHonors as k}from"../lib/learn-ai.js";import{getConfig as v,saveConfig as C}from"../lib/config.js";import{loadLearnState as A,saveLearnState as $,newLearnState as I,updateStreak as T,markCardComplete as E,recordMCQ as _,recordCheck as x,markPracticalComplete as M,addAchievement as P}from"../lib/learn-state.js";import{renderWelcome as L,renderKnowledgeCard as D,renderMCQCard as S,renderMCQFeedback as q,renderPracticalCard as O,renderPracticalSuccess as R,renderSimDemoCard as j,renderMilestone as N,renderArenaTaskCard as W,renderComingSoonCard as B,renderStatus as F,renderPhaseComplete as z,renderCurriculumComplete as U,setLearnAiEnabled as J,setLearnPqsViewCards as K,renderHonorWall as Q}from"../lib/learn-render.js";import{printError as V}from"../lib/ui.js";export function registerLearnCommand(Y){Y.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async Y=>{Y&&Y.trim()||(console.log(),console.log(chalk.gray(" No token given — starting free 11-card demo (")+chalk.bold.green("LEARNDEMO01")+chalk.gray(").")),console.log(chalk.gray(" Full curriculum: ")+chalk.bold.yellow("learn <your token>")+chalk.gray(" (2 letters + 8 chars) — from your country team leader.")),console.log(),Y="LEARNDEMO01");let Z=Y.trim().toUpperCase(),H=null;const X=/^[A-Z0-9]+DEMO01$/i.test(Z),G=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Z);let ee=!1;if(X)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),H=await g(Z,Z);else if(G){console.log(),console.log(chalk.gray(" Validating token..."));let e=await m(Z);if(!e.ok){const o=f(Z);if(o!==Z){const r=await m(o);r.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${Z} → ${o}`)),e=r,Z=o)}}if(!e.ok)return V(`Token validation failed: ${e.message}`),console.log(),"device_bound"===e.code?(console.log(chalk.gray(" This learn token is bound to the first computer it was used on,")),console.log(chalk.gray(" and this is a different computer.")),console.log(),console.log(chalk.gray(" If you changed computers or reinstalled, ask the coordinator who")),console.log(chalk.gray(" issued your token to move it to this device, then try again."))):(console.log(chalk.gray(" Possible causes:")),console.log(chalk.gray(" · Token expired or revoked")),console.log(chalk.gray(" · Network down (check connection)")),console.log(chalk.gray(" · Typo in token (check 0/O, 1/I/L, V/U)"))),void console.log();if(console.log(chalk.green(` ✓ Token valid · curriculum: ${e.curriculumId} · status: ${e.status}`)+(!0===e.aiEnabled?chalk.bold.magenta(" · ⭐ AI tutor"):"")),ee=!0===e.aiEnabled,console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),H=await g(e.curriculumId||"LEARNDEMO01",Z),!H)return V(`Could not open a learn curriculum for token '${Z}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${Z}`)+chalk.gray(" instead.")),console.log(chalk.gray(" Otherwise: the full curriculum is ~3 MB; on a slow link the download")),console.log(chalk.gray(" can take a while — stay on a stable connection and run ")+chalk.bold.yellow(`learn ${Z}`)+chalk.gray(" again")),console.log(chalk.gray(" (it caches after the first load). If it keeps failing, check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()}if(!H)return V(`Unknown learn token: ${Z}`),console.log(),console.log(chalk.gray(" Available tokens:")),console.log(chalk.gray(" ")+chalk.bold.green("<TRACK>DEMO01")+chalk.gray(" free demo, anyone can use — e.g. ")+chalk.bold.green("LEARNDEMO01")),console.log(chalk.gray(" ")+chalk.bold.yellow("2 letters + 8 chars")+chalk.gray(" full curriculum (issued by team leader)")),console.log(),console.log(chalk.gray(" Every track has a free demo — ask for its name if you were not given one.")),console.log(),console.log(chalk.gray(" To get a full curriculum, email ")),console.log(chalk.gray(" ")+chalk.cyan("australia@icoa2026.au")+chalk.gray(" or ask your country's team leader.")),void console.log();let oe=A(),re=!1;try{oe&&oe.token===Z?T(oe):(oe=I(Z,H.id,H.totalCards),re=!0),$(oe),L(H,oe,re)}catch{return V("Could not open this curriculum — it may be malformed or not a learn curriculum."),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${Z}`)+chalk.gray(".")),void console.log()}const ne=t(),te=null!==ne,le=te?ne.listeners("line").slice():[];te&&ne.removeAllListeners("line");const ae=te?ne:o({input:process.stdin,output:process.stdout,terminal:!0}),se=te?ae.prompt:null;te&&(ae.prompt=e.prototype.prompt);const ie=()=>{te&&se&&(ae.prompt=se)},ce=()=>{ae.setPrompt(fe?chalk.bold.green(`icoa ${l()}> `):chalk.bold.cyan(ye?"icoa learn ai> ":"icoa learn> ")),ae.prompt()};let ue=null,de=null,ge=null,me=null,ye=!1,he=!1,fe=!1;const pe=new Map,we=()=>{let e=pe.get(oe.currentCard);return e||(e=[],pe.set(oe.currentCard,e)),e};let be=!1;const ke=new Set;let ve=!1,Ce=0;const Ae=(v().language||"en").toLowerCase().startsWith("zh");J(ee),K(ke);const $e=[];let Ie=null;const Te=new Promise(e=>{Ie=e}),Ee=()=>{const e=Ie;Ie=null,e?.()},_e="1"===process.env.ICOA_LEARN_EMBEDDED,xe=e=>H.cards.find(o=>o.number===e),Me=e=>{const o=H.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const r=H.modules.find(e=>e.number===o.number+1);return z(H,oe,o,r),!0},Pe=()=>{ve=!0,console.log(chalk.gray(Ae?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},Le=()=>{const e=xe(oe.currentCard);if(!e)return console.log(),console.log(chalk.gray(" No more cards in this curriculum.")),console.log(chalk.gray(" Type ")+chalk.bold.green("status")+chalk.gray(" for the dashboard or ")+chalk.bold.green("quit")+chalk.gray(" to exit.")),void console.log();switch(e.type){case"knowledge":D(e,H),e.check?(ge=e.number,Ce=Date.now()):(E(oe,e.number),$(oe));break;case"mcq":S(e,H),ue=e.number;break;case"practical":O(e,H),de=e.number;break;case"sim_demo":j(e,H),E(oe,e.number),$(oe);break;case"milestone":N(e,H),P(oe,e.badge),E(oe,e.number),$(oe);break;case"arena_task":W(e,H),E(oe,e.number),$(oe);break;case"coming_soon":B(e,H),E(oe,e.number),$(oe)}},De=()=>{Z.endsWith("DEMO01")?console.log(chalk.yellow(Ae?" AI 导师需要开通 AI 的正式课程 token(demo 是共享的,没有 AI 额度)。":" The AI tutor needs an AI-enabled curriculum token — demos are shared and carry no AI budget.")):(console.log(chalk.yellow(Ae?" 此 token 未开通 AI 导师(高级功能)。":" This token does not include the AI tutor (premium).")),console.log(chalk.gray(Ae?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},Se=async(e,o)=>{if(ee){he=!0;try{console.log(),console.log(chalk.gray("deep"===o?Ae?" 🤖 AI 导师(深度思考中,思考过程为灰色小字)…":" 🤖 AI tutor (deepthink — reasoning shown in gray)…":Ae?" 🤖 AI 导师(快速模式)…":" 🤖 AI tutor (quick mode)…")),console.log();let r=!1,n=!1;const t=await p({token:Z,cardNumber:oe.currentCard,question:e,mode:o,history:we().slice(-8)},e=>{"reasoning"===e.kind?(r||(process.stdout.write(" "),r=!0),process.stdout.write(chalk.dim(e.text.replace(/\n/g,"\n ")))):(n||(process.stdout.write(r?"\n\n ":" "),n=!0),process.stdout.write(chalk.white(e.text.replace(/\n/g,"\n "))))});(r||n)&&console.log(),t.ok?t.offtopic?(console.log(),console.log(chalk.yellow(Ae?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(we().push({role:"user",content:e},{role:"assistant",content:t.answer}),null!=t.spent&&null!=t.cap&&t.spent/t.cap>.8&&console.log(chalk.gray(` (${Ae?"AI 额度":"AI budget"}: ${Math.round(t.spent/1e3)}k / ${Math.round(t.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${t.message||(Ae?"AI 导师暂不可用。":"AI tutor unavailable.")}`))),null!==ge&&console.log(chalk.gray(Ae?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{he=!1}}else De()},qe=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],Oe=async e=>{const o=e.trim().toLowerCase();if(!he){if(null!==me){const o=e.trim(),r=me;if(me=null,""===o)console.log(chalk.gray(Ae?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else{const e=Ce>0?Date.now()-Ce:void 0;await h(Z,{curriculum_id:H.id,card_number:r,feedback_text:o,time_on_card_ms:e})?console.log(chalk.green(Ae?" ✓ 已收到,谢谢帮助完善这张卡。":" ✓ Thanks — your report was recorded.")):console.log(chalk.yellow(Ae?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}return console.log(),void ce()}if(be){be=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{he=!0;try{console.log(),console.log(chalk.gray(Ae?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await w({token:Z,cardNumber:oe.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(Ae?"评审暂不可用。":"Review unavailable.")}`)),void console.log();(e=>{const o="green"===e.tier?chalk.bold.green:"blue"===e.tier?chalk.bold.cyan:"yellow"===e.tier?chalk.bold.yellow:chalk.bold.red;if(console.log(chalk.gray(" ─────────────────────────────────────────")),console.log(chalk.white(Ae?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(" "+(e=>{switch(e){case"green":return"🟢 "+(Ae?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(Ae?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(Ae?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(Ae?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier))),e.manipulation&&console.log(chalk.red(Ae?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ an attempt to manipulate the score was detected — the score was reduced sharply")),null!=e.rank&&null!=e.entrants){const o=!0===e.inTop3,r=Ae?` 本卡排名 #${e.rank} / ${e.entrants}`:` Rank on this card: #${e.rank} of ${e.entrants}`;console.log((o?chalk.bold.green(r):chalk.white(r))+(o?chalk.bold.magenta(Ae?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(Ae?` 第 ${e.submissionIndex??"?"} / 2 次提交 · 剩余 ${e.submissionsLeft??0} 次(可先追加 /ai 对话再交)`:` Attempt ${e.submissionIndex??"?"} of 2 · ${e.submissionsLeft??0} left (extend the /ai conversation before your next one)`)),e.feedback){console.log();for(const o of qe(e.feedback))console.log(chalk.white(" "+o))}e.improve&&(console.log(),console.log(chalk.cyan(Ae?" 改进提问: ":" Ask better: ")+chalk.gray(e.improve))),console.log(chalk.gray(" ─────────────────────────────────────────")),null!=e.spent&&null!=e.cap&&e.spent/e.cap>.8&&console.log(chalk.gray(` (${Ae?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?ke.add(oe.currentCard):ke.delete(oe.currentCard);const o=await k({token:Z,curriculumId:H.id,cardNumber:oe.currentCard});o.ok&&o.totals&&o.chapters&&(Q({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log())}finally{he=!1}})():(console.log(chalk.gray(Ae?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==ge&&(console.log(chalk.gray(Ae?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void ce()}if(ve)return ve=!1,Le(),void ce();if(o){if(fe)return"exit"===await a(e.trim())&&(fe=!1),void ce();if(ye){if(["q","quit","exit","back","b","menu"].includes(o))return ye=!1,console.log(chalk.gray(Ae?" 已退出 AI 导师,回到卡片。":" Left the AI tutor — back to the card.")),console.log(),void ce();const r=e.trim().startsWith("!"),n=r?e.trim().slice(1).trim():e.trim();return n&&await Se(n,r?"fast":"deep"),void ce()}if("tmux"===o||o.startsWith("tmux ")){try{r("command -v tmux",{stdio:"ignore"})}catch{return console.log(chalk.yellow(" tmux is not installed yet.")),console.log(chalk.gray(" Install it with ")+chalk.bold.cyan("darwin"===process.platform?"brew install tmux":"sudo apt install tmux")+chalk.gray(Ae?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void ce()}return await new Promise(o=>{const r=process.stdin,t=!!r.isTTY&&!!r.isRaw;if(ae.pause(),r.isTTY&&"function"==typeof r.setRawMode)try{r.setRawMode(!1)}catch{}const l=n(e.trim(),{shell:!0,stdio:"inherit"}),a=()=>{if(r.isTTY&&"function"==typeof r.setRawMode&&t)try{r.setRawMode(!0)}catch{}ae.resume(),o()};l.on("close",a),l.on("error",a)}),console.log(),void ce()}if("ai4ioai"===o||"/ai4ioai"===o)return await s()&&(fe=!0),void ce();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!ee)return De(),void ce();const r=o.startsWith("/ai!"),n=e.trim().slice(r?4:3).trim();if(!n){ye=!0;const e=xe(oe.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(Ae?"AI 导师":"AI tutor")+(o?chalk.gray(Ae?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Ae?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void ce()}return await Se(n,r?"fast":"deep"),void ce()}if("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research ")){if(!ee)return De(),void ce();const e=xe(oe.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(Ae?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(Ae?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Ae?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(Ae?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(Ae?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(Ae?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(Ae?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),be=!0,void ce()}if("/view"===o)return ee?(await(async()=>{he=!0;try{console.log();const e=await b({token:Z,cardNumber:oe.currentCard});if(!e.ok)return console.log(chalk.yellow(` ${e.message||(Ae?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===e.code&&ke.delete(oe.currentCard),void console.log();null!=e.myRank&&e.myRank<=3&&ke.add(oe.currentCard),console.log(chalk.bold.white(Ae?` 🏆 本卡 Top-3 提问 — 第 ${oe.currentCard} 张 · ${e.entrants??0} 人上榜`:` 🏆 Top-3 prompts — card ${oe.currentCard} · ${e.entrants??0} entrant(s)`));for(const o of e.top3??[]){const e="green"===o.tier?"🟢":"blue"===o.tier?"🔵":"yellow"===o.tier?"🟡":"🔴";console.log(),console.log(chalk.bold.cyan(` ── Rank ${o.rank}`)+(o.me?chalk.bold.magenta(" (me)"):"")+chalk.white(` · ${o.score}`)+` ${e}`),o.questions.forEach((e,o)=>{const r=qe(e);console.log(chalk.gray(` Q${o+1} `)+chalk.white(r[0]??""));for(const e of r.slice(1))console.log(chalk.white(" "+e))}),0===o.questions.length&&console.log(chalk.gray(Ae?" (无可显示的提问)":" (no questions to show)"))}console.log()}finally{he=!1}})(),void ce()):(De(),void ce());if("/honors"===o||"honors"===o)return X?(console.log(),console.log(chalk.gray(Ae?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void ce()):(await(async()=>{he=!0;try{console.log();const e=await k({token:Z,curriculumId:H.id,cardNumber:oe.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(Ae?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(Ae?` 🏆 本卡实时 Top-3 — 第 ${oe.currentCard} 张`:` 🏆 Live top-3 — card ${oe.currentCard}`)),e.board&&0!==e.board.length)for(const o of e.board){const e="green"===o.tier?"🟢":"blue"===o.tier?"🔵":"yellow"===o.tier?"🟡":"🔴";console.log(chalk.white(` ${o.icon} `)+chalk.bold.cyan(`#${o.rank}`)+chalk.white(` · ${o.score} `)+e+(o.me?chalk.bold.magenta(" (me)"):""))}else console.log(chalk.gray(Ae?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));console.log(),Q({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log()}finally{he=!1}})(),void ce());if("menu"!==o&&"menu confirm"!==o)if("quit"!==o&&"exit"!==o&&"q"!==o){if("status"===o)return F(H,oe),void ce();if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(v().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void ce();const r=H.cards.some(e=>null!=e._zh),n=e.toLowerCase().startsWith("zh")?"zh":e.toLowerCase(),t="en"===n||"zh"===n&&r,l=t?n:"en";return C({language:l}),t?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),ge=null,ue=null,de=null,me=null,ve=!1,be=!1,Le(),void ce()}if("sim"===o){const e=xe(oe.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=c(d(import.meta.url)),o=[u(e,"..","..","panda","mujoco-launcher.py"),u(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(i(e))return e;return null}();if(!o)return console.log(chalk.yellow(" MuJoCo launcher not found.")),console.log(chalk.gray(" Get it from: https://github.com/newaipanda/ICOA_CLI/blob/main/panda/mujoco-launcher.py")),void console.log(chalk.gray(" Or use the sandbox-vla docker image (Phase 3)."));const r={baseline:"baseline",prompt_injected:"prompt_inj",patch_attacked:"patch",modality_confused:"confused"}[e]||"baseline";console.log(chalk.gray(` Launching MuJoCo viewer (scenario: ${r})...`)),console.log(chalk.gray(" Close the window or press ESC to return to learn mode.")),n("python3",[o,r,"--seconds","5"],{stdio:"inherit"}).on("exit",e=>{0!==e?console.log(chalk.yellow(` MuJoCo exited with code ${e} (install: pip install mujoco)`)):console.log(chalk.gray(" Returned from sim."))})}(e.simAction),void ce()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void ce())}if("bookmark"===o){const e=oe.currentCard;return oe.bookmarks.includes(e)||oe.bookmarks.push(e),$(oe),console.log(chalk.gray(` ✓ Card ${e} bookmarked.`)),void ce()}if("e"===o)return me=oe.currentCard,console.log(chalk.gray(Ae?" 描述问题(回车提交 / 空行取消):":" Describe the issue (Enter to submit / blank to cancel):")),void ce();if("back"===o||"b"===o)return oe.currentCard>1&&(oe.currentCard-=1),ue=null,de=null,ge=null,$(oe),Le(),void ce();if(o.startsWith("card ")){const e=o.slice(5).trim(),r=parseInt(e,10);return!Number.isInteger(r)||r<1||r>H.totalCards?(console.log(chalk.yellow(` Card number must be 1..${H.totalCards}. Try: `)+chalk.bold.green("card 1")),void ce()):(oe.currentCard=r,ue=null,de=null,ge=null,$(oe),Le(),void ce())}if(null!==ge&&["y","yes","n","no"].includes(o)){const e=xe(ge);if(e&&"knowledge"===e.type&&e.check){const r=o.startsWith("y")?"y":"n",n=r===e.check.answer,t=Date.now()-Ce;E(oe,e.number),x(oe,e.number,{answer:r,correct:n,submittedAt:(new Date).toISOString()}),$(oe);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,r,n,!1),$e.push(y(Z,{card_number:e.number,event_type:"check_answered",check_answer:r,check_correct:n,time_on_card_ms:t}).catch(()=>{})),ge=null,e.solution&&e.solution.length>0)return void ce();if(oe.currentCard<H.totalCards){const e=oe.currentCard;oe.currentCard+=1,$(oe),Me(e)?Pe():Le(),ce()}else U(H,oe),ce();return}}if(null!==ue&&["a","b","c","d"].includes(o)){const e=xe(ue);if(e&&"mcq"===e.type){const r=o.toUpperCase(),n=r===e.answer;return _(oe,e.number,{answer:r,correct:n,submittedAt:(new Date).toISOString()}),E(oe,e.number),$(oe),q(e,r,n,oe),$e.push(y(Z,{card_number:e.number,event_type:"mcq_answered",mcq_answer:r,mcq_correct:n}).catch(()=>{})),ue=null,void(n?oe.currentCard<H.totalCards?(oe.currentCard+=1,$(oe),Le()):(U(H,oe),ce()):ce())}}if(null!==de){if("done"===o){const e=xe(de);if(e&&"practical"===e.type)return M(oe,e.number),E(oe,e.number),$(oe),R(e),de=null,void ce()}if("skip"===o)return E(oe,de),$(oe),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),de=null,void ce()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==ue)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void ce();if(null!==de)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void ce();if(null!==ge)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void ce();const e=oe.currentCard;return oe.currentCard+=1,$(oe),oe.currentCard>H.totalCards?U(H,oe):Me(e)?Pe():Le(),void ce()}if(null!==ge)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void ce();if(null!==ue)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void ce();if(null!==de)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void ce();console.log(chalk.gray(" Unknown command. Try: ")+chalk.white("ok")+chalk.gray(" / ")+chalk.white("status")+chalk.gray(" / ")+chalk.white("card N")+chalk.gray(" / ")+chalk.white("/ai")+chalk.gray(" / ")+chalk.white("quit")),ce()}else if($e.length>0&&await Promise.race([Promise.allSettled($e),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${oe.streakDays} day(s)`)),console.log(),te){ae.removeAllListeners("line"),ie();for(const e of le)ae.on("line",e);ae.prompt(),Ee()}else ae.removeAllListeners("line"),ae.close();else if($e.length>0&&await Promise.race([Promise.allSettled($e),new Promise(e=>setTimeout(e,3e3))]),ae.removeAllListeners("line"),ie(),te||!_e){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(te?ae:void 0),Ee()}else ae.close()}else ce()}};ae.on("line",e=>{Oe(e).catch(e=>{console.log(),console.log(chalk.red(" ⚠ Something went wrong handling that input.")),console.log(chalk.gray(` ${e instanceof Error?e.message:String(e)}`)),console.log(chalk.gray(" Progress is saved. Type ")+chalk.bold.green("ok")+chalk.gray(" to continue or ")+chalk.bold.green("quit")+chalk.gray(" to exit.")),ce()})}),te||ae.on("close",async()=>{$e.length>0&&await Promise.race([Promise.allSettled($e),new Promise(e=>setTimeout(e,5e3))]),_e?Ee():process.exit(0)});try{Le(),ce()}catch{if(V("Could not render this card — the curriculum may be malformed."),te){ae.removeAllListeners("line"),ie();for(const e of le)ae.on("line",e);ae.prompt()}else ae.close();Ee()}await Te}),Y.command("learn-pull [id]").description("Pre-download learn curricula to ~/.icoa/learn-cache/ for offline use (default: all)").action(async e=>{const o=e?[e.trim()]:["LEARNDEMO01","AI4CTFDEMO01","CTF4AIDEMO01","ai4ctf-96","ai4ctf-360","ctf4ai-96","ctf4ai-360","ctf4eai-96","ctf4eai-360","embodied-ai-100","embodied-ai-480"];console.log(),console.log(chalk.bold.cyan(" ICOA learn-pull — fetching curricula for offline use")),console.log(chalk.gray(" Server: https://practice.icoa2026.au")),console.log();let r=0,n=0,t=0;for(const e of o){process.stdout.write(` ${e.padEnd(22)} `);const o=Date.now(),l=await g(e),a=Date.now()-o;if(l){const e=l.cards,o=Array.isArray(e)?e.length:0,n=JSON.stringify(l).length;t+=n,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(n/1024).toFixed(1).padStart(6)} KB · ${a.toString().padStart(4)} ms`)),r++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),n++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${r} cached`)+chalk.gray(` · ${n} failed · total ${(t/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}
@@ -1 +1 @@
1
- const t={ai4ctf:"AI4CTFDEMO01",ctf4ai:"CTF4AIDEMO01",ctf4eai:"LEARNDEMO01","ai4ctf-12":"AI4CTFDEMO01","ctf4ai-12":"CTF4AIDEMO01","ctf4eai-12":"LEARNDEMO01",ctf4vla:"LEARNDEMO01",vla:"LEARNDEMO01",embodied:"LEARNDEMO01",ai4ctfdemo:"AI4CTFDEMO01",ctf4aidemo:"CTF4AIDEMO01",learndemo:"LEARNDEMO01"},e={1:"AI4CTFDEMO01",2:"CTF4AIDEMO01",3:"LEARNDEMO01"},o=/^[A-Z]{2}[A-Z0-9]{6,}$/,n=/^(AI4CTFDEMO\d+|CTF4AIDEMO\d+|LEARNDEMO\d+)$/;export function resolveLearnInput(i){const r=i.trim();if(!r)return{kind:"back"};const a=r.replace(/^\s*(?:[/>])?\s*(?:icoa\s+)?learn\s+/i,"").trim();if(!a)return{kind:"ambiguous",hint:"Type just the token (e.g. LEARNDEMO01) or one of: ai4ctf / ctf4ai / ctf4eai"};if(e[a])return{kind:"token",token:e[a]};const c=a.toLowerCase();if(t[c])return{kind:"token",token:t[c]};if("demo"===c||"demos"===c)return{kind:"ambiguous",hint:"Which demo? Type: 1 (ai4ctf) / 2 (ctf4ai) / 3 (ctf4eai)"};if(/\s/.test(a))return{kind:"unknown",hint:`Don't recognize "${r}". Try one of: ai4ctf / ctf4ai / ctf4eai (for the free demos), 1/2/3, or paste your AC/CA/EA/EI/IO/IA + 8 chars cohort token. Blank to go back.`};const f=a.toUpperCase();return n.test(f)||o.test(f)||/^[A-Z0-9]{8,}$/.test(f)?{kind:"token",token:f}:{kind:"unknown",hint:`Don't recognize "${r}". Try one of: ai4ctf / ctf4ai / ctf4eai (for the free demos), 1/2/3, or paste your AC/CA/EA/EI/IO/IA + 8 chars cohort token. Blank to go back.`}}
1
+ const t={ai4ctf:"AI4CTFDEMO01",ctf4ai:"CTF4AIDEMO01",ctf4eai:"LEARNDEMO01","ai4ctf-12":"AI4CTFDEMO01","ctf4ai-12":"CTF4AIDEMO01","ctf4eai-12":"LEARNDEMO01","ioai-jr":"IOAIJRDEMO01","ioai-jr-48":"IOAIJRDEMO01",ioaijr:"IOAIJRDEMO01",junior:"IOAIJRDEMO01",jr:"IOAIJRDEMO01",ioaijrdemo:"IOAIJRDEMO01",ctf4vla:"LEARNDEMO01",vla:"LEARNDEMO01",embodied:"LEARNDEMO01",ai4ctfdemo:"AI4CTFDEMO01",ctf4aidemo:"CTF4AIDEMO01",learndemo:"LEARNDEMO01"},e={1:"AI4CTFDEMO01",2:"CTF4AIDEMO01",3:"LEARNDEMO01"},i=/^[A-Z]{2}[A-Z0-9]{6,}$/,o=/^(AI4CTFDEMO\d+|CTF4AIDEMO\d+|LEARNDEMO\d+)$/;export function resolveLearnInput(n){const a=n.trim();if(!a)return{kind:"back"};const r=a.replace(/^\s*(?:[/>])?\s*(?:icoa\s+)?learn\s+/i,"").trim();if(!r)return{kind:"ambiguous",hint:"Type just the token (e.g. LEARNDEMO01) or one of: ai4ctf / ctf4ai / ctf4eai"};if(e[r])return{kind:"token",token:e[r]};const c=r.toLowerCase();if(t[c])return{kind:"token",token:t[c]};if("demo"===c||"demos"===c)return{kind:"ambiguous",hint:"Which demo? Type: 1 (ai4ctf) / 2 (ctf4ai) / 3 (ctf4eai)"};if(/\s/.test(r))return{kind:"unknown",hint:`Don't recognize "${a}". Try a track name (ai4ctf / ctf4ai / ctf4eai / junior), 1/2/3, a demo id like LEARNDEMO01, or paste your token (2 letters + 8 chars). Blank to go back.`};const E=r.toUpperCase();return o.test(E)||i.test(E)||/^[A-Z0-9]{8,}$/.test(E)?{kind:"token",token:E}:{kind:"unknown",hint:`Don't recognize "${a}". Try one of: ai4ctf / ctf4ai / ctf4eai (for the free demos), 1/2/3, or paste your AC/CA/EA/EI/IO/IA + 8 chars cohort token. Blank to go back.`}}