icoa-cli 2.19.381 → 2.19.383

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 r}from"node:os";import{Interface as t,createInterface as c}from"node:readline";import{isAbsolute as a,join as s,resolve as i}from"node:path";import chalk from"chalk";import{aienvPaths as y}from"../lib/aienv.js";import{editTextInEditor as d}from"../lib/editor-spawn.js";import{shouldExecuteCell as g}from"../lib/ipynb-input.js";import{looksLikeMarkdown as u,renderMarkdown as p}from"../lib/md-term.js";import{NotebookKernel as m}from"../lib/kernel.js";import{getMainRl as h}from"../lib/main-rl.js";import{cellPreview as f,parseIpynb as w,parsePercentPy as v,parseRunRange as k,serializeIpynb as b,statusChar as $}from"../lib/notebook-doc.js";import{openFile as x}from"../lib/open-file.js";const N=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");export function registerIpynbCommand(o){o.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 o=>{await async function(o){const N=y(r()),P=s(r(),".icoa","ipynb-out");if(E(),!e(N.python))return console.log(chalk.yellow(" The AI/ML environment is not set up yet.")),console.log(chalk.gray(" Run ")+chalk.bold.cyan("aienv setup")+chalk.gray(" first (one-time, ~300 MB).")),void console.log();const j=o?function(o){const l=a(o)?o:i(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")?w(e):v(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.")}}}(o):null,S=j?j.doc:{cells:[],path:null,dirty:!1},L=new m({venvPython:N.python,venvRoot:N.root});process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await L.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.gray(" Type Python and press Enter. Blocks (def/for/…) continue until a blank line.")),console.log(chalk.gray(" Cells: ")+chalk.cyan("cells")+chalk.gray(" list · ")+chalk.cyan("edit N")+chalk.gray(" edit in $EDITOR · ")+chalk.cyan("run N")+chalk.gray(" / ")+chalk.cyan("run all")+chalk.gray(" · ")+chalk.cyan("add md")+chalk.gray(" notes · ")+chalk.cyan("save")+chalk.gray(" · ")+chalk.cyan("help")+chalk.gray(" · ")+chalk.cyan("quit")),console.log();const O=h(),q=null!==O,R=q?O.listeners("line").slice():[];q&&O.removeAllListeners("line");const A=q?O:c({input:process.stdin,output:process.stdout,terminal:!0}),T=q?A.prompt:null;q&&(A.prompt=t.prototype.prompt);const M=[];let B=!1,D=!1;const K=()=>{A.setPrompt(chalk.bold.cyan(M.length?"icoa ipynb ...> ":"icoa ipynb> ")),A.prompt()};let W=()=>{};const F=new Promise(e=>{W=e}),z=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>S.cells.length?(console.log(0===S.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${S.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:S.cells[o-1],idx:o}},G=(e,o)=>{e.result&&!e.result.ok&&e.result.outputs.some(e=>"error"===e.kind&&"SyntaxError"===e.ename)&&u(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(")."))},H=async e=>{if(B)return void(e.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));const o=e.trim();if(0===M.length){const e=o.split(/\s+/),n=(e[0]??"").toLowerCase(),r=o.slice(e[0]?.length??0).trim();if("quit"!==n&&"exit"!==n&&"q"!==n&&(D=!1),"quit"===n||"exit"===n||"back"===n||"q"===n)return S.dirty&&!D?(D=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void K()):void await(async()=>{if(A.removeAllListeners("line"),console.log(),console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await L.shutdown().catch(()=>{}),q){T&&(A.prompt=T);for(const e of R)A.on("line",e);A.prompt(),W()}else W(),A.close()})();if("clear"===n||"cls"===n)return console.clear(),E(),void K();if("restart"===n)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await L.shutdown().catch(()=>{});try{await L.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 K();if("help"===n||"?"===n)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(" 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 K();if("open"===n)return C&&x(C)?console.log(chalk.gray(" reopening ")+chalk.cyan(C)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void K();if("cells"===n||"ls"===n)return(()=>{if(0===S.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);S.cells.forEach((o,n)=>{const l=$(o),r="✓"===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))} ${r} ${chalk.white(f(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 K();if("show"===n)return(e=>{const o=z(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 p(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 ──")),I(o.cell.result,P)),console.log()}})(r),void K();if("edit"===n)return(e=>{const o=z(e);if(!o)return;A.pause();const n=d(o.cell.source,"markdown"===o.cell.kind?".md":".py");if(A.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,S.dirty=!0,console.log(chalk.green(` ✓ cell ${o.idx} updated`)+chalk.gray(" — ")+chalk.cyan(`run ${o.idx}`)+chalk.gray(" to execute."))):console.log(chalk.gray(" no changes."))})(r),void K();if("add"===n)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)"));A.pause();const l=d(n?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",n?".md":".py");A.resume();const r=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");r?(S.cells.push({kind:n?"markdown":"code",source:r,result:null}),S.dirty=!0,console.log(chalk.green(` ✓ added ${n?"markdown ":""}cell ${S.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${S.cells.length}`)+chalk.gray(n?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(r),void K();if("del"===n||"delete"===n)return(e=>{const o=z(e);o&&(S.cells.splice(o.idx-1,1),S.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${S.cells.length} left.`)))})(r),void K();if(("md"===n||"py"===n)&&/^\d+$/.test(r))return((e,o)=>{const n=z(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,S.dirty=!0,console.log(chalk.green(` ✓ cell ${n.idx} → ${l}`)+chalk.gray(" — ")+chalk.cyan(`run ${n.idx}`)+chalk.gray("markdown"===o?" to render it.":" to execute."))):console.log(chalk.gray(` cell ${n.idx} is already ${l}.`))})(r,"md"===n?"markdown":"code"),void K();if("run"===n)return B=!0,await(async e=>{const o=k(e,S.cells.length);if(o)for(const e of o){const n=S.cells[e-1];if("markdown"!==n.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(f(n,50))+chalk.gray(" ──"));try{n.result=await L.execute(n.source)}catch(e){return void console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e)))}if(S.dirty=!0,I(n.result,P),G(n,e),!n.result.ok)return void(e!==o[o.length-1]&&console.log(chalk.yellow(` ✗ cell ${e} raised — stopping here.`)+chalk.gray(" Fix it (")+chalk.cyan(`edit ${e}`)+chalk.gray(") and re-run.")))}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of p(n.source))console.log(e);console.log()}}else console.log(0===S.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(" usage: ")+chalk.cyan("run 3")+chalk.yellow(" · ")+chalk.cyan("run 1-5")+chalk.yellow(" · ")+chalk.cyan("run all"))})(r),B=!1,void K();if("save"===n)return(e=>{if(0===S.cells.length)return void console.log(chalk.yellow(" nothing to save — the notebook is empty."));let o;o=e.trim()?a(e.trim())?e.trim():i(process.cwd(),e.trim()):S.path?S.path.endsWith(".ipynb")?S.path:`${S.path.replace(/\.[^./]+$/,"")}.ipynb`:i(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");try{l(o,b(S.cells)),S.path=o,S.dirty=!1,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${S.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(r),void K();if(""===o)return void K()}if(M.push(e),!g(M))return void K();const n=M.join("\n").replace(/\s+$/,"");if(M.length=0,""!==n.trim()){B=!0;try{const e=await L.execute(n);S.cells.push({kind:"code",source:n,result:e}),S.dirty=!0,I(e,P),G(S.cells[S.cells.length-1],S.cells.length)}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e)))}B=!1,K()}else K()};A.on("line",e=>{H(e)}),q||A.on("close",async()=>{await L.shutdown().catch(()=>{}),process.exit(0)}),K(),await F}(o)})}function E(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}let P=0,C=null;function I(e,o){for(const n of e.outputs)if("stream"===n.kind){const e=n.text.replace(/\n$/,"");if(0===e.length)continue;console.log("stderr"===n.name?chalk.yellow(e):chalk.white(e))}else if("result"===n.kind)console.log(chalk.cyan(` Out[${e.execCount??"*"}]: `)+chalk.white(n.text));else if("error"===n.kind){console.log(chalk.bold.red(` ${n.ename}: ${n.evalue}`));for(const e of n.traceback)console.log(chalk.gray(` ${e.replace(N,"")}`))}else"display"===n.kind&&j(n.data,o)}function j(e,n){if(e["image/png"])try{o(n,{recursive:!0}),P+=1;const r=s(n,`figure-${P}.png`);return l(r,Buffer.from(e["image/png"],"base64")),C=r,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(r)),void(x(r)?console.log(chalk.gray(" opening in your image viewer… (type ")+chalk.cyan("open")+chalk.gray(" to reopen)")):console.log(chalk.gray(" open it with your file browser (inline images need a graphical viewer).")))}catch{}e["text/plain"]&&console.log(chalk.white(` ${e["text/plain"]}`))}
1
+ import{existsSync as e,mkdirSync as o,readFileSync as n,writeFileSync as l}from"node:fs";import{homedir as t}from"node:os";import{Interface as r,createInterface as a}from"node:readline";import{basename as s,isAbsolute as c,join as i,resolve as y}from"node:path";import chalk from"chalk";import{aienvPaths as g}from"../lib/aienv.js";import{editTextInEditor as d}from"../lib/editor-spawn.js";import{buildSshArgs as u,leaseConnectProblems as p,parseLeaseResponse as h,queueLine as m}from"../lib/gpu.js";import{shouldExecuteCell as w}from"../lib/ipynb-input.js";import{looksLikeMarkdown as f,renderMarkdown as v}from"../lib/md-term.js";import{NotebookKernel as k,buildRemoteBridgeCommand as b}from"../lib/kernel.js";import{getMainRl as $}from"../lib/main-rl.js";import{cellPreview as x,parseIpynb as P,parsePercentPy as E,parseRunRange as G,serializeIpynb as C,statusChar as U}from"../lib/notebook-doc.js";import{openFile as N}from"../lib/open-file.js";const S=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");export function registerIpynbCommand(h){h.command("ipynb").argument("[file]","notebook (.ipynb) or script (.py, split on # %%) to open").description("Open an in-terminal Python notebook (AI/ML — needs `aienv setup`)").action(async h=>{await async function(h){const S=g(t()),O=i(t(),".icoa","ipynb-out");if(A(),!e(S.python))return console.log(chalk.yellow(" The AI/ML environment is not set up yet.")),console.log(chalk.gray(" Run ")+chalk.bold.cyan("aienv setup")+chalk.gray(" first (one-time, ~300 MB).")),void console.log();const _=h?function(o){const l=c(o)?o:y(process.cwd(),o);if(!e(l))return{doc:{cells:[],path:l,dirty:!1},note:chalk.gray(" new notebook — will be created on ")+chalk.cyan("save")};try{const e=n(l,"utf8"),o=l.endsWith(".ipynb")?P(e):E(e);return{doc:{cells:o,path:l,dirty:!1},note:chalk.gray(" loaded ")+chalk.cyan(l)+chalk.gray(` — ${o.length} cell${1===o.length?"":"s"}. Type `)+chalk.cyan("cells")+chalk.gray(" to list them.")}}catch(e){return{doc:{cells:[],path:null,dirty:!1},note:chalk.yellow(` could not open ${l}: ${e instanceof Error?e.message:String(e)}`)+chalk.gray(" — starting an empty notebook.")}}}(h):null,K=_?_.doc:{cells:[],path:null,dirty:!1};let D=new k({venvPython:S.python,venvRoot:S.root}),M=null,W=q(K.path);process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await D.start()}catch{return console.log(chalk.red(" failed.")),console.log(chalk.gray(" Check the environment: ")+chalk.cyan("aienv status")),void console.log()}console.log(chalk.green(" ready.")),_&&console.log(_.note),console.log(chalk.gray(" Type Python and press Enter. Blocks (def/for/…) continue until a blank line.")),console.log(chalk.gray(" Cells: ")+chalk.cyan("cells")+chalk.gray(" list · ")+chalk.cyan("edit N")+chalk.gray(" edit in $EDITOR · ")+chalk.cyan("run N")+chalk.gray(" / ")+chalk.cyan("run all")+chalk.gray(" · ")+chalk.cyan("add md")+chalk.gray(" notes · ")+chalk.cyan("save")+chalk.gray(" · ")+chalk.cyan("help")+chalk.gray(" · ")+chalk.cyan("quit")),console.log();const V=$(),B=null!==V,F=B?V.listeners("line").slice():[];B&&V.removeAllListeners("line");const Y=B?V:a({input:process.stdin,output:process.stdout,terminal:!0}),z=B?Y.prompt:null;B&&(Y.prompt=r.prototype.prompt);const J=[];let H=!1,Q=!1;const X=()=>{const e=M?"icoa ipynb ⚡gpu":"icoa ipynb";Y.setPrompt(chalk.bold.cyan(J.length?`${e} ...> `:`${e}> `)),Y.prompt()};let Z=()=>{};const ee=new Promise(e=>{Z=e}),oe=async()=>{if(!M)return void console.log(chalk.gray(" not on a GPU kernel."));const e=R();await D.shutdown().catch(()=>{}),e&&await j("release",e),M=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped.")),await(async()=>{D=new k({venvPython:S.python,venvRoot:S.root}),process.stdout.write(chalk.gray(" Starting local kernel…"));try{await D.start(),console.log(chalk.green(" ready.")+chalk.gray(" (local CPU — variables were reset)"))}catch{console.log(chalk.red(" failed.")+chalk.gray(" Check ")+chalk.cyan("aienv status"))}})()},ne=async e=>{const[n,...r]=e.trim().split(/\s+/),a=(n??"").toLowerCase();"on"===a||"connect"===a?await(async()=>{if(M)return void console.log(chalk.gray(" already on the GPU kernel — ")+chalk.cyan("gpu status")+chalk.gray(" for time left."));const e=R();if(!e)return console.log(chalk.yellow(" No GPU access key found.")),void console.log(chalk.gray(" Save yours once with ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" (issued by your coach/ICOA)."));W||(W=q(K.path)),process.stdout.write(chalk.gray(" Requesting a GPU box…"));let n=await j("lease",e,W??void 0),r=0;for(;"queued"===n.state&&r<24;)0===r&&console.log(),process.stdout.write(`\r ${chalk.yellow(m(n))} `),await new Promise(e=>setTimeout(e,5e3)),n=await j("status",e),r++;if("queued"===n.state)return console.log(),console.log(chalk.yellow(" Still queued — your place is held server-side.")),void console.log(chalk.gray(" Keep working locally; ")+chalk.cyan("gpu on")+chalk.gray(" again in a few minutes."));if("ready"!==n.state)return void console.log(chalk.red(" failed.")+chalk.gray(` ${n.message??"no lease granted"}`));const a=p(n);if("local"!==n.transport||process.env.ICOA_GPU_SERVER||a.push("local transport from a non-dev broker"),a.length>0)return console.log(chalk.red(" rejected: ")+chalk.gray(a.join(", "))),void await j("release",e);const s=W?`${n.dataRoot}/${W}`:n.dataRoot,c=b(n.python,{ICOA_KAGGLE_DATA:s,ICOA_KAGGLE_OUT:n.outDir},n.outDir);let y;if("local"===n.transport)y={command:"/bin/sh",args:["-c",c]};else{const r=i(t(),".icoa","gpu","lease-key");try{o(i(t(),".icoa","gpu"),{recursive:!0}),l(r,n.keyPem,{mode:384})}catch{return console.log(chalk.red(" could not write the ssh key locally.")),void await j("release",e)}y={command:"ssh",args:u(n,r,c)}}const g=new k({spawnSpec:y,readyTimeoutMs:9e4});process.stdout.write(chalk.gray(" connecting…"));try{await g.start()}catch(o){return console.log(chalk.red(" connect failed.")),console.log(chalk.gray(` ${o instanceof Error?o.message:String(o)}`)),void await j("release",e)}await D.shutdown().catch(()=>{}),D=g,M=n;const d=Math.round((n.timeLeftSec??0)/60);console.log(chalk.bold.green(" ⚡ GPU connected.")),console.log(chalk.gray(` Cells now run on the GPU box · ${d}m left on this lease.`)),console.log(chalk.gray(" Variables were reset — ")+chalk.cyan("run all")+chalk.gray(" to retrain there.")),W&&console.log(chalk.gray(` Dataset is already on the box (${W}) — same cells, no edits.`)),console.log(chalk.gray(" When done: ")+chalk.cyan("download")+chalk.gray(" your submission, then ")+chalk.cyan("gpu off")+chalk.gray("."))})():"off"===a||"disconnect"===a?await oe():"status"===a||""===a?await(async()=>{const e=R();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const o=await j("status",e);if("ready"===o.state){const e=Math.round((o.timeLeftSec??0)/60);console.log(chalk.green(` ⚡ GPU lease active · ${e}m left`)+chalk.gray(M?" (this notebook is connected)":" (not connected here — gpu on)"))}else"queued"===o.state?console.log(chalk.yellow(` ${m(o)}`)):"none"===o.state?console.log(chalk.gray(" no GPU lease — ")+chalk.cyan("gpu on")+chalk.gray(" to request one.")):console.log(chalk.yellow(` ${o.message??"GPU broker not reachable"}`))})():"key"===a?(e=>{const n=e.trim();if(n)try{o(i(t(),".icoa"),{recursive:!0}),l(I(),`${n}\n`,{mode:384}),console.log(chalk.green(" ✓ GPU key saved")+chalk.gray(" — ")+chalk.cyan("gpu on")+chalk.gray(" when you need the box."))}catch{console.log(chalk.red(" could not save the key")+chalk.gray(` (${I()})`))}else console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu key <your-key>"))})(r.join(" ")):console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu on")+chalk.yellow(" · ")+chalk.cyan("gpu off")+chalk.yellow(" · ")+chalk.cyan("gpu status")+chalk.yellow(" · ")+chalk.cyan("gpu key <k>"))},le=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>K.cells.length?(console.log(0===K.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${K.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:K.cells[o-1],idx:o}},te=(e,o)=>{e.result&&!e.result.ok&&e.result.outputs.some(e=>"error"===e.kind&&"SyntaxError"===e.ename)&&f(e.source)&&console.log(chalk.gray(" ✎ looks like text/markdown, not Python — ")+chalk.cyan(`md ${o}`)+chalk.gray(" converts this cell to markdown (new note: ")+chalk.cyan("add md")+chalk.gray(")."))},re=async e=>{if(H)return void(e.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));const n=e.trim();if(0===J.length){const e=n.split(/\s+/),t=(e[0]??"").toLowerCase(),r=n.slice(e[0]?.length??0).trim();if("quit"!==t&&"exit"!==t&&"q"!==t&&(Q=!1),"quit"===t||"exit"===t||"back"===t||"q"===t)return K.dirty&&!Q?(Q=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void X()):void await(async()=>{if(Y.removeAllListeners("line"),console.log(),M){const e=R();e&&await j("release",e),M=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await D.shutdown().catch(()=>{}),B){z&&(Y.prompt=z);for(const e of F)Y.on("line",e);Y.prompt(),Z()}else Z(),Y.close()})();if("clear"===t||"cls"===t)return console.clear(),A(),void X();if("restart"===t)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await D.shutdown().catch(()=>{});try{await D.start(),console.log(chalk.green(" fresh kernel ready.")+chalk.gray(" (all variables cleared)"))}catch{console.log(chalk.red(" restart failed.")+chalk.gray(" Leave and re-enter the notebook."))}})(),void X();if("help"===t||"?"===t)return console.log(),console.log(chalk.bold.white(" Notebook commands")),console.log(chalk.cyan(" cells")+chalk.gray(" list cells (○ not run · ✓ ok · ✗ error)")),console.log(chalk.cyan(" show N")+chalk.gray(" print cell N source + outputs")),console.log(chalk.cyan(" edit N")+chalk.gray(" edit cell N in your editor ($EDITOR, default vi)")),console.log(chalk.cyan(" add")+chalk.gray(" write a new Python cell in your editor")),console.log(chalk.cyan(" add md")+chalk.gray(" write a markdown/text cell (notes, headings)")),console.log(chalk.cyan(" md N / py N")+chalk.gray(" convert cell N to markdown / Python")),console.log(chalk.cyan(" del N")+chalk.gray(" delete cell N")),console.log(chalk.cyan(" run N")+chalk.gray(" run cell N — markdown cells render (also: run 2-5, run all)")),console.log(chalk.cyan(" save [file]")+chalk.gray(" save as a real .ipynb")),console.log(chalk.cyan(" restart")+chalk.gray(" restart the kernel (wipes all variables)")),console.log(chalk.cyan(" gpu on/off")+chalk.gray(" run cells on a leased GPU box (dataset pre-mounted)")),console.log(chalk.cyan(" gpu status")+chalk.gray(" lease/queue state · ")+chalk.cyan("gpu key <k>")+chalk.gray(" save your access key")),console.log(chalk.cyan(" download")+chalk.gray(" pull submission.csv from the GPU box to this machine")),console.log(chalk.cyan(" open")+chalk.gray(" reopen the last figure in your image viewer")),console.log(chalk.cyan(" clear")+chalk.gray(" clear the screen · ")+chalk.cyan("quit")+chalk.gray(" leave")),console.log(chalk.gray(" Everything else runs as Python in the persistent kernel (and is appended as a cell).")),console.log(),void X();if("open"===t)return L&&N(L)?console.log(chalk.gray(" reopening ")+chalk.cyan(L)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void X();if("cells"===t||"ls"===t)return(()=>{if(0===K.cells.length)return void console.log(chalk.gray(" no cells yet — type Python, or ")+chalk.cyan("add")+chalk.gray(" to write one in your editor."));console.log();const e=Math.max(20,(process.stdout.columns??80)-12);K.cells.forEach((o,n)=>{const l=U(o),t="✓"===l?chalk.green(l.padEnd(2)):"✗"===l?chalk.red(l.padEnd(2)):"md"===l?chalk.magenta(l.padEnd(2)):chalk.gray(l.padEnd(2));console.log(`${chalk.cyan(String(n+1).padStart(4))} ${t} ${chalk.white(x(o,e))}`)}),console.log(),console.log(chalk.gray(" ")+chalk.cyan("show N")+chalk.gray(" · ")+chalk.cyan("edit N")+chalk.gray(" · ")+chalk.cyan("run N")+chalk.gray(" · ")+chalk.cyan("run all"))})(),void X();if("show"===t)return(e=>{const o=le(e);if(o){if(console.log(),console.log(chalk.gray(` ── cell ${o.idx} ${"markdown"===o.cell.kind?"(markdown) ":""}──`)),"markdown"===o.cell.kind){for(const e of v(o.cell.source))console.log(e);console.log(chalk.gray(" (rendered — ")+chalk.cyan(`edit ${o.idx}`)+chalk.gray(" for the raw source)"))}else for(const e of o.cell.source.split("\n"))console.log(chalk.white(` ${e}`));o.cell.result&&(console.log(chalk.gray(" ── output ──")),T(o.cell.result,O)),console.log()}})(r),void X();if("edit"===t)return(e=>{const o=le(e);if(!o)return;Y.pause();const n=d(o.cell.source,"markdown"===o.cell.kind?".md":".py");if(Y.resume(),null===n)return void console.log(chalk.yellow(" editor cancelled or failed — cell unchanged.")+chalk.gray(" (set $EDITOR to choose your editor)"));const l=n.replace(/\s+$/,"");l!==o.cell.source?(o.cell.source=l,o.cell.result=null,o.cell.rawOutputs=void 0,o.cell.rawExecCount=void 0,K.dirty=!0,console.log(chalk.green(` ✓ cell ${o.idx} updated`)+chalk.gray(" — ")+chalk.cyan(`run ${o.idx}`)+chalk.gray(" to execute."))):console.log(chalk.gray(" no changes."))})(r),void X();if("add"===t)return(e=>{const o=e.trim().toLowerCase(),n="md"===o||"markdown"===o||"text"===o||"txt"===o;if(o&&!n&&"py"!==o&&"code"!==o&&"python"!==o)return void console.log(chalk.yellow(" usage: ")+chalk.cyan("add")+chalk.yellow(" (Python cell) · ")+chalk.cyan("add md")+chalk.yellow(" (markdown/text cell)"));Y.pause();const l=d(n?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",n?".md":".py");Y.resume();const t=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");t?(K.cells.push({kind:n?"markdown":"code",source:t,result:null}),K.dirty=!0,console.log(chalk.green(` ✓ added ${n?"markdown ":""}cell ${K.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${K.cells.length}`)+chalk.gray(n?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(r),void X();if("del"===t||"delete"===t)return(e=>{const o=le(e);o&&(K.cells.splice(o.idx-1,1),K.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${K.cells.length} left.`)))})(r),void X();if(("md"===t||"py"===t)&&/^\d+$/.test(r))return((e,o)=>{const n=le(e);if(!n)return;const l="markdown"===o?"markdown":"Python";n.cell.kind!==o?(n.cell.kind=o,n.cell.result=null,n.cell.rawOutputs=void 0,n.cell.rawExecCount=void 0,K.dirty=!0,console.log(chalk.green(` ✓ cell ${n.idx} → ${l}`)+chalk.gray(" — ")+chalk.cyan(`run ${n.idx}`)+chalk.gray("markdown"===o?" to render it.":" to execute."))):console.log(chalk.gray(` cell ${n.idx} is already ${l}.`))})(r,"md"===t?"markdown":"code"),void X();if("gpu"===t)return H=!0,await ne(r),H=!1,void X();if("download"===t||"dl"===t)return H=!0,await(async e=>{if(!M)return void console.log(chalk.gray(" local kernel — your files are already on this machine (no download needed)."));const n=e.trim()||"submission.csv",t=n.startsWith("/")?n:`${M.outDir}/${n}`;let r;try{r=await D.fetchFile(t)}catch(e){return console.log(chalk.yellow(` could not fetch ${t}: `)+chalk.gray(e instanceof Error?e.message:String(e))),void console.log(chalk.gray(" (run the submission cell first — it writes into the GPU workspace)"))}const a=W?i(process.cwd(),"icoa-kaggle",W):process.cwd(),c=i(a,s(n));try{o(a,{recursive:!0}),l(c,r)}catch{return void console.log(chalk.yellow(" could not write the file here — check directory permissions."))}console.log(chalk.green(" ✓ downloaded ")+chalk.white(c)+chalk.gray(` (${r.length} bytes)`)),W&&"submission.csv"===s(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${W}`)+chalk.gray(" — then upload on Kaggle yourself."))})(r),H=!1,void X();if("run"===t)return H=!0,await(async e=>{const o=G(e,K.cells.length);if(o)for(const e of o){const n=K.cells[e-1];if("markdown"!==n.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(x(n,50))+chalk.gray(" ──"));try{n.result=await D.execute(n.source)}catch(e){return void console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e)))}if(K.dirty=!0,T(n.result,O),te(n,e),!n.result.ok)return void(e!==o[o.length-1]&&console.log(chalk.yellow(` ✗ cell ${e} raised — stopping here.`)+chalk.gray(" Fix it (")+chalk.cyan(`edit ${e}`)+chalk.gray(") and re-run.")))}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of v(n.source))console.log(e);console.log()}}else console.log(0===K.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(" usage: ")+chalk.cyan("run 3")+chalk.yellow(" · ")+chalk.cyan("run 1-5")+chalk.yellow(" · ")+chalk.cyan("run all"))})(r),H=!1,void X();if("save"===t)return(e=>{if(0===K.cells.length)return void console.log(chalk.yellow(" nothing to save — the notebook is empty."));let o;o=e.trim()?c(e.trim())?e.trim():y(process.cwd(),e.trim()):K.path?K.path.endsWith(".ipynb")?K.path:`${K.path.replace(/\.[^./]+$/,"")}.ipynb`:y(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");try{l(o,C(K.cells)),K.path=o,K.dirty=!1,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${K.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(r),void X();if(""===n)return void X()}if(J.push(e),!w(J))return void X();const t=J.join("\n").replace(/\s+$/,"");if(J.length=0,""!==t.trim()){H=!0;try{const e=await D.execute(t);K.cells.push({kind:"code",source:t,result:e}),K.dirty=!0,T(e,O),te(K.cells[K.cells.length-1],K.cells.length)}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e)))}H=!1,X()}else X()};Y.on("line",e=>{re(e)}),B||Y.on("close",async()=>{await D.shutdown().catch(()=>{}),process.exit(0)}),X(),await ee}(h)})}function A(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}const O="https://practice.icoa2026.au";function I(){return i(t(),".icoa","gpu-key")}function R(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return n(I(),"utf-8").trim()||null}catch{return null}}async function j(e,o,n){try{const l=await fetch(`${process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):O}/api/icoa/gpu/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n?{key:o,task:n}:{key:o}),signal:AbortSignal.timeout(2e4)});return h(await l.json())}catch{return{state:"error",message:"GPU broker not reachable"}}}function q(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let _=0,L=null;function T(e,o){for(const n of e.outputs)if("stream"===n.kind){const e=n.text.replace(/\n$/,"");if(0===e.length)continue;console.log("stderr"===n.name?chalk.yellow(e):chalk.white(e))}else if("result"===n.kind)console.log(chalk.cyan(` Out[${e.execCount??"*"}]: `)+chalk.white(n.text));else if("error"===n.kind){console.log(chalk.bold.red(` ${n.ename}: ${n.evalue}`));for(const e of n.traceback)console.log(chalk.gray(` ${e.replace(S,"")}`))}else"display"===n.kind&&K(n.data,o)}function K(e,n){if(e["image/png"])try{o(n,{recursive:!0}),_+=1;const t=i(n,`figure-${_}.png`);return l(t,Buffer.from(e["image/png"],"base64")),L=t,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(t)),void(N(t)?console.log(chalk.gray(" opening in your image viewer… (type ")+chalk.cyan("open")+chalk.gray(" to reopen)")):console.log(chalk.gray(" open it with your file browser (inline images need a graphical viewer).")))}catch{}e["text/plain"]&&console.log(chalk.white(` ${e["text/plain"]}`))}
@@ -1,4 +1,8 @@
1
1
  import type { Command } from 'commander';
2
2
  export declare function runKaggle(compArg?: string): Promise<void>;
3
3
  export declare function runKaggleCheck(compArg?: string): Promise<void>;
4
+ /** `icoa kaggle submit [comp]` — M2.5: ICOA-judged comps only. Validates
5
+ * locally first (fail fast), then the server scores submission.csv against the
6
+ * secret test labels and the result lands on the live board. */
7
+ export declare function runKaggleSubmit(compArg?: string): Promise<void>;
4
8
  export declare function registerKaggleCommand(program: Command): void;
@@ -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 i}from"../lib/repl-asker.js";import{openFile as a}from"../lib/open-file.js";import{serializeIpynb as c}from"../lib/notebook-doc.js";import{buildStarterCells as r,parseKaggleTaskList as g,validateSubmissionText as u}from"../lib/kaggle.js";async function m(o){try{const e=await fetch((process.env.ICOA_KAGGLE_SERVER?process.env.ICOA_KAGGLE_SERVER.replace(/\/$/,""):"https://practice.icoa2026.au")+o,{signal:AbortSignal.timeout(3e4)});return await e.json()}catch{return null}}function y(){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 p(o){return s(process.cwd(),"icoa-kaggle",o)}function d(o){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=i(),a=async o=>await l.ask(o)??"";try{console.log(),console.log(chalk.bold.cyan(" 📊 KAGGLE PRACTICE")+chalk.gray(" · train locally · submit on Kaggle yourself")),console.log(chalk.gray(" Small real-format datasets, a runnable starter notebook, your own CPU.")),console.log();const l=await m("/api/icoa/kaggle/tasks");if(!l)return y();const i=g(l);if(0===i.length)return console.log(chalk.yellow(" No practice competitions are live yet — check back soon.")),void console.log();let u=n?i.find(o=>o.comp_id===n):void 0;if(n&&!u&&console.log(chalk.yellow(` No competition called "${n}".`)),!u){console.log(chalk.white(" Live practice competitions:")),i.forEach((o,e)=>{console.log(chalk.gray(` ${e+1}. `)+chalk.cyan(o.comp_id)+chalk.gray(` — ${o.title} · ${o.metric}`))});for(let o=0;o<3&&!u;o++){const o=(await a(chalk.cyan(" Pick one (number or id): "))).trim();if(!o)return;const e=Number(o);u=!Number.isNaN(e)&&i[e-1]||i.find(e=>e.comp_id===o.toLowerCase())||void 0,u||console.log(chalk.gray(` Try a number 1-${i.length} or an id like "${i[0].comp_id}".`))}if(!u)return}const b=u.comp_id;console.log(),console.log(chalk.white(` ${u.title}`)+chalk.gray(` · ${u.metric}`)),console.log(chalk.gray(" Downloading data…"));const f=await m(`/api/icoa/kaggle/${b}/data`),h=f?.data??f;if(!h?.train||!h?.test||!h?.sample_submission)return y();const w=p(b),k={...u,...h.meta??{}};try{e(w,{recursive:!0}),t(s(w,"train.csv"),h.train),t(s(w,"test.csv"),h.test),t(s(w,"sample_submission.csv"),h.sample_submission),t(s(w,"meta.json"),`${JSON.stringify(k,null,2)}\n`)}catch{return void console.log(chalk.yellow(" Could not write the data files here — check directory permissions."))}const v=s(w,"starter.ipynb");let $=!1;o(v)?$=!0:t(v,c(r(w,k)));const _="number"==typeof k.n_train?`${k.n_train} rows`:"labelled",K="number"==typeof k.n_test?`${k.n_test} rows`:"predict these";console.log(chalk.green(" ✓ train: ")+chalk.white(s(w,"train.csv"))+chalk.gray(` (${_})`)),console.log(chalk.green(" ✓ test: ")+chalk.white(s(w,"test.csv"))+chalk.gray(` (${K})`)),console.log(chalk.green(" ✓ format: ")+chalk.white(s(w,"sample_submission.csv"))),console.log(chalk.green(" ✓ notebook: ")+chalk.white(v)+chalk.gray($?" (kept your existing one)":" (runnable baseline inside)")),(k.licence||k.attribution)&&console.log(chalk.gray(` licence: ${k.licence??"—"} · ${k.attribution??""}`)),console.log(),console.log(chalk.bold.white(" Your move — 3 steps:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${v}`)+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 ${b}`)),console.log(chalk.gray(" 3. upload it on Kaggle yourself — then beat the baseline.")),console.log(),d(k),console.log()}finally{l.close()}}export async function runKaggleCheck(e){console.log();let t=e;if(!t){const e=s(process.cwd(),"icoa-kaggle"),n=o(e)?l(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&o(s(e,n.name,"sample_submission.csv"))).map(o=>o.name):[];if(1!==n.length){if(0===n.length)return console.log(chalk.yellow(" No downloaded competition found here — run ")+chalk.cyan("kaggle")+chalk.yellow(" first.")),void console.log();console.log(chalk.white(" Several competitions downloaded — pick one:"));for(const o of n)console.log(chalk.gray(" kaggle check ")+chalk.cyan(o));return void console.log()}t=n[0]}const i=p(t),c=s(i,"submission.csv"),r=s(i,"sample_submission.csv");if(!o(r))return console.log(chalk.yellow(` No data for "${t}" here — run `)+chalk.cyan(`kaggle ${t}`)+chalk.yellow(" first.")),void console.log();if(!o(c))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(i,"starter.ipynb")}`)),void console.log();const g=u(n(c,"utf-8"),n(r,"utf-8"));let m=null;try{m=JSON.parse(n(s(i,"meta.json"),"utf-8"))}catch{m=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(c)),console.log(),d(m),a(i);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 function registerKaggleCommand(o){o.command("kaggle").argument("[action]",'competition id, or "check" to validate submission.csv').argument("[comp]",'competition id (with "check")').description("Kaggle-style ML practice — dataset + starter notebook, submit on Kaggle yourself").action(async(o,e)=>{"check"===o?await runKaggleCheck(e):await runKaggle(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 i}from"../lib/repl-asker.js";import{openFile as r}from"../lib/open-file.js";import{serializeIpynb as a}from"../lib/notebook-doc.js";import{loadLearnState as c}from"../lib/learn-state.js";import{buildStarterCells as g,dataFileUrls as u,parseKaggleTaskList as d,parseSubmitResponse as y,validateSubmissionText as m}from"../lib/kaggle.js";function b(){return process.env.ICOA_KAGGLE_SERVER?process.env.ICOA_KAGGLE_SERVER.replace(/\/$/,""):"https://practice.icoa2026.au"}async function h(o){try{const e=await fetch(b()+o,{signal:AbortSignal.timeout(3e4)});return await e.json()}catch{return null}}async function p(o){try{const e=await fetch(o,{signal:AbortSignal.timeout(6e4)});return e.ok?await e.text():null}catch{return null}}function f(){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 k(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=i(),r=async o=>await l.ask(o)??"";try{console.log(),console.log(chalk.bold.cyan(" 📊 KAGGLE PRACTICE")+chalk.gray(" · train locally · submit on Kaggle yourself")),console.log(chalk.gray(" Small real-format datasets, a runnable starter notebook, your own CPU.")),console.log();const l=await h("/api/icoa/kaggle/tasks");if(!l)return f();const i=d(l);if(0===i.length)return console.log(chalk.yellow(" No practice competitions are live yet — check back soon.")),void console.log();let c=n?i.find(o=>o.comp_id===n):void 0;if(n&&!c&&console.log(chalk.yellow(` No competition called "${n}".`)),!c){console.log(chalk.white(" Live practice competitions:")),i.forEach((o,e)=>{console.log(chalk.gray(` ${e+1}. `)+chalk.cyan(o.comp_id)+chalk.gray(` — ${o.title} · ${o.metric}`))});for(let o=0;o<3&&!c;o++){const o=(await r(chalk.cyan(" Pick one (number or id): "))).trim();if(!o)return;const e=Number(o);c=!Number.isNaN(e)&&i[e-1]||i.find(e=>e.comp_id===o.toLowerCase())||void 0,c||console.log(chalk.gray(` Try a number 1-${i.length} or an id like "${i[0].comp_id}".`))}if(!c)return}const y=c.comp_id;console.log(),console.log(chalk.white(` ${c.title}`)+chalk.gray(` · ${c.metric}`)),console.log(chalk.gray(" Downloading data…"));let m=null;const b=u(c);if(b){const[o,e,n]=await Promise.all([p(b.train),p(b.test),p(b.sample_submission)]);o&&e&&n&&(m={train:o,test:e,sample_submission:n})}if(!m){const o=await h(`/api/icoa/kaggle/${y}/data`);m=o?.data??o}if(!m?.train||!m?.test||!m?.sample_submission)return f();const v=w(y),$={...c,...m.meta??{}};try{e(v,{recursive:!0}),t(s(v,"train.csv"),m.train),t(s(v,"test.csv"),m.test),t(s(v,"sample_submission.csv"),m.sample_submission),t(s(v,"meta.json"),`${JSON.stringify($,null,2)}\n`)}catch{return void console.log(chalk.yellow(" Could not write the data files here — check directory permissions."))}const _=s(v,"starter.ipynb");let j=!1;o(_)?j=!0:t(_,a(g(v,$)));const S="number"==typeof $.n_train?`${$.n_train} rows`:"labelled",K="number"==typeof $.n_test?`${$.n_test} rows`:"predict these";console.log(chalk.green(" ✓ train: ")+chalk.white(s(v,"train.csv"))+chalk.gray(` (${S})`)),console.log(chalk.green(" ✓ test: ")+chalk.white(s(v,"test.csv"))+chalk.gray(` (${K})`)),console.log(chalk.green(" ✓ format: ")+chalk.white(s(v,"sample_submission.csv"))),console.log(chalk.green(" ✓ notebook: ")+chalk.white(_)+chalk.gray(j?" (kept your existing one)":" (runnable baseline inside)")),($.licence||$.attribution)&&console.log(chalk.gray(` licence: ${$.licence??"—"} · ${$.attribution??""}`)),console.log(),console.log(chalk.bold.white(" Your move — 3 steps:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${_}`)+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 ${y}`)),"icoa-holdout"===$.judge?console.log(chalk.gray(" 3. ")+chalk.bold.cyan(`kaggle submit ${y}`)+chalk.gray(" → scored + ranked live.")):console.log(chalk.gray(" 3. upload it on Kaggle yourself — then beat the baseline.")),console.log(),k($),console.log()}finally{l.close()}}function v(e,n){if(e)return e;const t=s(process.cwd(),"icoa-kaggle"),i=o(t)?l(t,{withFileTypes:!0}).filter(e=>e.isDirectory()&&o(s(t,e.name,"sample_submission.csv"))).map(o=>o.name):[];if(1===i.length)return i[0];if(0===i.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 i)console.log(chalk.gray(` kaggle ${n} `)+chalk.cyan(o));return console.log(),null}export async function runKaggleCheck(e){console.log();const l=v(e,"check");if(!l)return;const t=w(l),i=s(t,"submission.csv"),a=s(t,"sample_submission.csv");if(!o(a))return console.log(chalk.yellow(` No data for "${l}" here — run `)+chalk.cyan(`kaggle ${l}`)+chalk.yellow(" first.")),void console.log();if(!o(i))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 c=m(n(i,"utf-8"),n(a,"utf-8"));let g=null;try{g=JSON.parse(n(s(t,"meta.json"),"utf-8"))}catch{g=null}if(c.ok)console.log(chalk.bold.green(" ✓ submission.csv is Kaggle-ready")+chalk.gray(" (matches sample_submission.csv)")),console.log(chalk.gray(" ")+chalk.white(i)),console.log(),k(g),r(t);else{console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of c.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=v(e,"submit");if(!l)return;const t=w(l),r=s(t,"submission.csv"),a=s(t,"sample_submission.csv");let g=null;try{g=JSON.parse(n(s(t,"meta.json"),"utf-8"))}catch{g=null}if(!g||!o(a))return console.log(chalk.yellow(` No data for "${l}" here — run `)+chalk.cyan(`kaggle ${l}`)+chalk.yellow(" first.")),void console.log();if("icoa-holdout"!==g.judge)return console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here.")),console.log(),k(g),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 u=n(r,"utf-8"),d=m(u,n(a,"utf-8"));if(!d.ok){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 h=c()?.token??"";if(!h){const o=i();try{h=(await o.ask(chalk.cyan(" Your learn token: "))??"").trim()}finally{o.close()}if(!h)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 p=await async function(o,e){try{const n=await fetch(b()+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:h,submission_csv:u}),f=y(p);if(console.log(),f.ok){const o=`${f.metric}: ${Number(f.score).toFixed(4).replace(/\.?0+$/,"")}`;f.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 f.rank&&"number"==typeof f.fieldSize&&console.log(chalk.bold.white(` 🏁 board rank #${f.rank}`)+chalk.gray(` of ${f.fieldSize}`))),f.boardEvent&&console.log(chalk.gray(" standings: ")+chalk.cyan(`board ${f.boardEvent} ${l}`))}else switch(f.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 f.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):await runKaggle(o)})}
@@ -1 +1 @@
1
- import chalk from"chalk";import{Interface as e,createInterface as o}from"node:readline";import{spawn as r}from"node:child_process";import{getMainRl as n}from"../lib/main-rl.js";import{ai4ioaiPromptLabel as t,handleAi4ioaiMessage as l,startAi4ioaiChat as a}from"./ai4ioai.js";import{existsSync as s}from"node:fs";import{dirname as i,join as c}from"node:path";import{fileURLToPath as u}from"node:url";import{loadCurriculumById as d,validateEAToken as g,syncProgress as m,syncCardFeedback as y}from"../lib/learn-curricula.js";import{normalizeTokenBody as h}from"../lib/token-format.js";import{streamLearnTutor as f,submitPqs as p,viewPqsTop as w,viewHonors as b}from"../lib/learn-ai.js";import{getConfig as k,saveConfig as v}from"../lib/config.js";import{loadLearnState as A,saveLearnState as C,newLearnState as I,updateStreak as $,markCardComplete as E,recordMCQ as _,recordCheck as T,markPracticalComplete as M,addAchievement as P}from"../lib/learn-state.js";import{renderWelcome as x,renderKnowledgeCard as L,renderMCQCard as O,renderMCQFeedback as D,renderPracticalCard as S,renderPracticalSuccess as q,renderSimDemoCard as j,renderMilestone as N,renderArenaTaskCard as R,renderComingSoonCard as W,renderStatus as F,renderPhaseComplete as B,renderCurriculumComplete as z,setLearnAiEnabled as U,setLearnPqsViewCards as J,renderHonorWall as Q}from"../lib/learn-render.js";import{printError as V}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 Y=!1;if(Z)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),X=await d(K,K);else if(G){console.log(),console.log(chalk.gray(" Validating token..."));let e=await g(K);if(!e.ok){const o=h(K);if(o!==K){const r=await g(o);r.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${K} → ${o}`)),e=r,K=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"):"")),Y=!0===e.aiEnabled,console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),X=await d(e.curriculumId||"LEARNDEMO01",K),!X)return V(`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 V(`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 ee=A(),oe=!1;try{ee&&ee.token===K?$(ee):(ee=I(K,X.id,X.totalCards),oe=!0),C(ee),x(X,ee,oe)}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 ${K}`)+chalk.gray(".")),void console.log()}const re=n(),ne=null!==re,te=ne?re.listeners("line").slice():[];ne&&re.removeAllListeners("line");const le=ne?re:o({input:process.stdin,output:process.stdout,terminal:!0}),ae=ne?le.prompt:null;ne&&(le.prompt=e.prototype.prompt);const se=()=>{ne&&ae&&(le.prompt=ae)},ie=()=>{le.setPrompt(he?chalk.bold.green(`icoa ${t()}> `):chalk.bold.cyan(me?"icoa learn ai> ":"icoa learn> ")),le.prompt()};let ce=null,ue=null,de=null,ge=null,me=!1,ye=!1,he=!1;const fe=new Map,pe=()=>{let e=fe.get(ee.currentCard);return e||(e=[],fe.set(ee.currentCard,e)),e};let we=!1;const be=new Set;let ke=!1,ve=0;const Ae=(k().language||"en").toLowerCase().startsWith("zh");U(Y),J(be);const Ce=[];let Ie=null;const $e=new Promise(e=>{Ie=e}),Ee=()=>{const e=Ie;Ie=null,e?.()},_e="1"===process.env.ICOA_LEARN_EMBEDDED,Te=e=>X.cards.find(o=>o.number===e),Me=e=>{const o=X.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const r=X.modules.find(e=>e.number===o.number+1);return B(X,ee,o,r),!0},Pe=()=>{ke=!0,console.log(chalk.gray(Ae?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},xe=()=>{const e=Te(ee.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":L(e,X),e.check?(de=e.number,ve=Date.now()):(E(ee,e.number),C(ee));break;case"mcq":O(e,X),ce=e.number;break;case"practical":S(e,X),ue=e.number;break;case"sim_demo":j(e,X),E(ee,e.number),C(ee);break;case"milestone":N(e,X),P(ee,e.badge),E(ee,e.number),C(ee);break;case"arena_task":R(e,X),E(ee,e.number),C(ee);break;case"coming_soon":W(e,X),E(ee,e.number),C(ee)}},Le=()=>{K.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()},Oe=async(e,o)=>{if(Y){ye=!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 f({token:K,cardNumber:ee.currentCard,question:e,mode:o,history:pe().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)"))):(pe().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!==de&&console.log(chalk.gray(Ae?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{ye=!1}}else Le()},De=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],Se=async e=>{const o=e.trim().toLowerCase();if(!ye){if(null!==ge){const o=e.trim(),r=ge;if(ge=null,""===o)console.log(chalk.gray(Ae?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else{const e=ve>0?Date.now()-ve:void 0;Ce.push(y(K,{curriculum_id:X.id,card_number:r,feedback_text:o,time_on_card_ms:e}).catch(()=>{})),console.log(chalk.green(Ae?" ✓ 已收到,谢谢帮助完善这张卡。":" ✓ Thanks — your report was recorded."))}return console.log(),void ie()}if(we){we=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{ye=!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 p({token:K,cardNumber:ee.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 De(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?be.add(ee.currentCard):be.delete(ee.currentCard);const o=await b({token:K,curriculumId:X.id,cardNumber:ee.currentCard});o.ok&&o.totals&&o.chapters&&(Q({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log())}finally{ye=!1}})():(console.log(chalk.gray(Ae?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==de&&(console.log(chalk.gray(Ae?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void ie()}if(ke)return ke=!1,xe(),void ie();if(o){if(he)return"exit"===await l(e.trim())&&(he=!1),void ie();if(me){if(["q","quit","exit","back","b","menu"].includes(o))return me=!1,console.log(chalk.gray(Ae?" 已退出 AI 导师,回到卡片。":" Left the AI tutor — back to the card.")),console.log(),void ie();const r=e.trim().startsWith("!"),n=r?e.trim().slice(1).trim():e.trim();return n&&await Oe(n,r?"fast":"deep"),void ie()}if("ai4ioai"===o||"/ai4ioai"===o)return await a()&&(he=!0),void ie();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!Y)return Le(),void ie();const r=o.startsWith("/ai!"),n=e.trim().slice(r?4:3).trim();if(!n){me=!0;const e=Te(ee.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 ie()}return await Oe(n,r?"fast":"deep"),void ie()}if("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research ")){if(!Y)return Le(),void ie();const e=Te(ee.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(),we=!0,void ie()}if("/view"===o)return Y?(await(async()=>{ye=!0;try{console.log();const e=await w({token:K,cardNumber:ee.currentCard});if(!e.ok)return console.log(chalk.yellow(` ${e.message||(Ae?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===e.code&&be.delete(ee.currentCard),void console.log();null!=e.myRank&&e.myRank<=3&&be.add(ee.currentCard),console.log(chalk.bold.white(Ae?` 🏆 本卡 Top-3 提问 — 第 ${ee.currentCard} 张 · ${e.entrants??0} 人上榜`:` 🏆 Top-3 prompts — card ${ee.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=De(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{ye=!1}})(),void ie()):(Le(),void ie());if("/honors"===o||"honors"===o)return Z?(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 ie()):(await(async()=>{ye=!0;try{console.log();const e=await b({token:K,curriculumId:X.id,cardNumber:ee.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 — 第 ${ee.currentCard} 张`:` 🏆 Live top-3 — card ${ee.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{ye=!1}})(),void ie());if("menu"!==o&&"menu confirm"!==o)if("quit"!==o&&"exit"!==o&&"q"!==o){if("status"===o)return F(X,ee),void ie();if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(k().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void ie();const r=X.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 v({language:l}),t?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),de=null,ce=null,ue=null,ge=null,ke=!1,we=!1,xe(),void ie()}if("sim"===o){const e=Te(ee.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=i(u(import.meta.url)),o=[c(e,"..","..","panda","mujoco-launcher.py"),c(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(s(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 n={baseline:"baseline",prompt_injected:"prompt_inj",patch_attacked:"patch",modality_confused:"confused"}[e]||"baseline";console.log(chalk.gray(` Launching MuJoCo viewer (scenario: ${n})...`)),console.log(chalk.gray(" Close the window or press ESC to return to learn mode.")),r("python3",[o,n,"--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 ie()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void ie())}if("bookmark"===o){const e=ee.currentCard;return ee.bookmarks.includes(e)||ee.bookmarks.push(e),C(ee),console.log(chalk.gray(` ✓ Card ${e} bookmarked.`)),void ie()}if("e"===o)return ge=ee.currentCard,console.log(chalk.gray(Ae?" 描述问题(回车提交 / 空行取消):":" Describe the issue (Enter to submit / blank to cancel):")),void ie();if("back"===o||"b"===o)return ee.currentCard>1&&(ee.currentCard-=1),ce=null,ue=null,de=null,C(ee),xe(),void ie();if(o.startsWith("card ")){const e=o.slice(5).trim(),r=parseInt(e,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 ie()):(ee.currentCard=r,ce=null,ue=null,de=null,C(ee),xe(),void ie())}if(null!==de&&["y","yes","n","no"].includes(o)){const e=Te(de);if(e&&"knowledge"===e.type&&e.check){const r=o.startsWith("y")?"y":"n",n=r===e.check.answer,t=Date.now()-ve;E(ee,e.number),T(ee,e.number,{answer:r,correct:n,submittedAt:(new Date).toISOString()}),C(ee);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,r,n,!1),Ce.push(m(K,{card_number:e.number,event_type:"check_answered",check_answer:r,check_correct:n,time_on_card_ms:t}).catch(()=>{})),de=null,e.solution&&e.solution.length>0)return void ie();if(ee.currentCard<X.totalCards){const e=ee.currentCard;ee.currentCard+=1,C(ee),Me(e)?Pe():xe(),ie()}else z(X,ee),ie();return}}if(null!==ce&&["a","b","c","d"].includes(o)){const e=Te(ce);if(e&&"mcq"===e.type){const r=o.toUpperCase(),n=r===e.answer;return _(ee,e.number,{answer:r,correct:n,submittedAt:(new Date).toISOString()}),E(ee,e.number),C(ee),D(e,r,n,ee),Ce.push(m(K,{card_number:e.number,event_type:"mcq_answered",mcq_answer:r,mcq_correct:n}).catch(()=>{})),ce=null,void(n?ee.currentCard<X.totalCards?(ee.currentCard+=1,C(ee),xe()):(z(X,ee),ie()):ie())}}if(null!==ue){if("done"===o){const e=Te(ue);if(e&&"practical"===e.type)return M(ee,e.number),E(ee,e.number),C(ee),q(e),ue=null,void ie()}if("skip"===o)return E(ee,ue),C(ee),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),ue=null,void ie()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==ce)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void ie();if(null!==ue)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void ie();if(null!==de)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void ie();const e=ee.currentCard;return ee.currentCard+=1,C(ee),ee.currentCard>X.totalCards?z(X,ee):Me(e)?Pe():xe(),void ie()}if(null!==de)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void ie();if(null!==ce)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void ie();if(null!==ue)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void ie();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")),ie()}else if(Ce.length>0&&await Promise.race([Promise.allSettled(Ce),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${ee.streakDays} day(s)`)),console.log(),ne){le.removeAllListeners("line"),se();for(const e of te)le.on("line",e);le.prompt(),Ee()}else le.removeAllListeners("line"),le.close();else if(Ce.length>0&&await Promise.race([Promise.allSettled(Ce),new Promise(e=>setTimeout(e,3e3))]),le.removeAllListeners("line"),se(),ne||!_e){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(ne?le:void 0),Ee()}else le.close()}else ie()}};le.on("line",e=>{Se(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.")),ie()})}),ne||le.on("close",async()=>{Ce.length>0&&await Promise.race([Promise.allSettled(Ce),new Promise(e=>setTimeout(e,5e3))]),_e?Ee():process.exit(0)});try{xe(),ie()}catch{if(V("Could not render this card — the curriculum may be malformed."),ne){le.removeAllListeners("line"),se();for(const e of te)le.on("line",e);le.prompt()}else le.close();Ee()}await $e}),H.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 d(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
+ import chalk from"chalk";import{Interface as e,createInterface as o}from"node:readline";import{spawn as r}from"node:child_process";import{getMainRl as n}from"../lib/main-rl.js";import{ai4ioaiPromptLabel as t,handleAi4ioaiMessage as l,startAi4ioaiChat as a}from"./ai4ioai.js";import{existsSync as s}from"node:fs";import{dirname as i,join as c}from"node:path";import{fileURLToPath as u}from"node:url";import{loadCurriculumById as d,validateEAToken as g,syncProgress as m,syncCardFeedback as y}from"../lib/learn-curricula.js";import{normalizeTokenBody as h}from"../lib/token-format.js";import{streamLearnTutor as f,submitPqs as p,viewPqsTop as w,viewHonors as b}from"../lib/learn-ai.js";import{getConfig as k,saveConfig as v}from"../lib/config.js";import{loadLearnState as A,saveLearnState as C,newLearnState as I,updateStreak as $,markCardComplete as E,recordMCQ as T,recordCheck as _,markPracticalComplete as M,addAchievement as P}from"../lib/learn-state.js";import{renderWelcome as x,renderKnowledgeCard as O,renderMCQCard as L,renderMCQFeedback as D,renderPracticalCard as S,renderPracticalSuccess as q,renderSimDemoCard as j,renderMilestone as N,renderArenaTaskCard as R,renderComingSoonCard as W,renderStatus as F,renderPhaseComplete as B,renderCurriculumComplete as z,setLearnAiEnabled as U,setLearnPqsViewCards as J,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 demo, or team-issued EA/EI/AC/CA/IO/IA 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 EA|EI|AC|CA|IO|IA + 8 chars")+chalk.gray(" — token from your country team leader.")),console.log(),Y="LEARNDEMO01");let H=Y.trim().toUpperCase(),K=null;const X=/^(LEARNDEMO01|AI4CTFDEMO01|CTF4AIDEMO01)$/i.test(H),Z=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(H);let G=!1;if(X)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),K=await d(H,H);else if(Z){console.log(),console.log(chalk.gray(" Validating token..."));let e=await g(H);if(!e.ok){const o=h(H);if(o!==H){const r=await g(o);r.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${H} → ${o}`)),e=r,H=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"):"")),G=!0===e.aiEnabled,console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),K=await d(e.curriculumId||"LEARNDEMO01",H),!K)return V(`Could not open a learn curriculum for token '${H}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${H}`)+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 ${H}`)+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(!K)return V(`Unknown learn token: ${H}`),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 ee=A(),oe=!1;try{ee&&ee.token===H?$(ee):(ee=I(H,K.id,K.totalCards),oe=!0),C(ee),x(K,ee,oe)}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 ${H}`)+chalk.gray(".")),void console.log()}const re=n(),ne=null!==re,te=ne?re.listeners("line").slice():[];ne&&re.removeAllListeners("line");const le=ne?re:o({input:process.stdin,output:process.stdout,terminal:!0}),ae=ne?le.prompt:null;ne&&(le.prompt=e.prototype.prompt);const se=()=>{ne&&ae&&(le.prompt=ae)},ie=()=>{le.setPrompt(he?chalk.bold.green(`icoa ${t()}> `):chalk.bold.cyan(me?"icoa learn ai> ":"icoa learn> ")),le.prompt()};let ce=null,ue=null,de=null,ge=null,me=!1,ye=!1,he=!1;const fe=new Map,pe=()=>{let e=fe.get(ee.currentCard);return e||(e=[],fe.set(ee.currentCard,e)),e};let we=!1;const be=new Set;let ke=!1,ve=0;const Ae=(k().language||"en").toLowerCase().startsWith("zh");U(G),J(be);const Ce=[];let Ie=null;const $e=new Promise(e=>{Ie=e}),Ee=()=>{const e=Ie;Ie=null,e?.()},Te="1"===process.env.ICOA_LEARN_EMBEDDED,_e=e=>K.cards.find(o=>o.number===e),Me=e=>{const o=K.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const r=K.modules.find(e=>e.number===o.number+1);return B(K,ee,o,r),!0},Pe=()=>{ke=!0,console.log(chalk.gray(Ae?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},xe=()=>{const e=_e(ee.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":O(e,K),e.check?(de=e.number,ve=Date.now()):(E(ee,e.number),C(ee));break;case"mcq":L(e,K),ce=e.number;break;case"practical":S(e,K),ue=e.number;break;case"sim_demo":j(e,K),E(ee,e.number),C(ee);break;case"milestone":N(e,K),P(ee,e.badge),E(ee,e.number),C(ee);break;case"arena_task":R(e,K),E(ee,e.number),C(ee);break;case"coming_soon":W(e,K),E(ee,e.number),C(ee)}},Oe=()=>{H.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()},Le=async(e,o)=>{if(G){ye=!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 f({token:H,cardNumber:ee.currentCard,question:e,mode:o,history:pe().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)"))):(pe().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!==de&&console.log(chalk.gray(Ae?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{ye=!1}}else Oe()},De=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],Se=async e=>{const o=e.trim().toLowerCase();if(!ye){if(null!==ge){const o=e.trim(),r=ge;if(ge=null,""===o)console.log(chalk.gray(Ae?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else{const e=ve>0?Date.now()-ve:void 0;await y(H,{curriculum_id:K.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 ie()}if(we){we=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{ye=!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 p({token:H,cardNumber:ee.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 De(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?be.add(ee.currentCard):be.delete(ee.currentCard);const o=await b({token:H,curriculumId:K.id,cardNumber:ee.currentCard});o.ok&&o.totals&&o.chapters&&(Q({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log())}finally{ye=!1}})():(console.log(chalk.gray(Ae?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==de&&(console.log(chalk.gray(Ae?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void ie()}if(ke)return ke=!1,xe(),void ie();if(o){if(he)return"exit"===await l(e.trim())&&(he=!1),void ie();if(me){if(["q","quit","exit","back","b","menu"].includes(o))return me=!1,console.log(chalk.gray(Ae?" 已退出 AI 导师,回到卡片。":" Left the AI tutor — back to the card.")),console.log(),void ie();const r=e.trim().startsWith("!"),n=r?e.trim().slice(1).trim():e.trim();return n&&await Le(n,r?"fast":"deep"),void ie()}if("tmux"===o||o.startsWith("tmux "))return await new Promise(o=>{const n=process.stdin,t=!!n.isTTY&&!!n.isRaw;if(le.pause(),n.isTTY&&"function"==typeof n.setRawMode)try{n.setRawMode(!1)}catch{}const l=r(e.trim(),{shell:!0,stdio:"inherit"}),a=()=>{if(n.isTTY&&"function"==typeof n.setRawMode&&t)try{n.setRawMode(!0)}catch{}le.resume(),o()};l.on("close",a),l.on("error",a)}),console.log(),void ie();if("ai4ioai"===o||"/ai4ioai"===o)return await a()&&(he=!0),void ie();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!G)return Oe(),void ie();const r=o.startsWith("/ai!"),n=e.trim().slice(r?4:3).trim();if(!n){me=!0;const e=_e(ee.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 ie()}return await Le(n,r?"fast":"deep"),void ie()}if("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research ")){if(!G)return Oe(),void ie();const e=_e(ee.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(),we=!0,void ie()}if("/view"===o)return G?(await(async()=>{ye=!0;try{console.log();const e=await w({token:H,cardNumber:ee.currentCard});if(!e.ok)return console.log(chalk.yellow(` ${e.message||(Ae?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===e.code&&be.delete(ee.currentCard),void console.log();null!=e.myRank&&e.myRank<=3&&be.add(ee.currentCard),console.log(chalk.bold.white(Ae?` 🏆 本卡 Top-3 提问 — 第 ${ee.currentCard} 张 · ${e.entrants??0} 人上榜`:` 🏆 Top-3 prompts — card ${ee.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=De(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{ye=!1}})(),void ie()):(Oe(),void ie());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 ie()):(await(async()=>{ye=!0;try{console.log();const e=await b({token:H,curriculumId:K.id,cardNumber:ee.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 — 第 ${ee.currentCard} 张`:` 🏆 Live top-3 — card ${ee.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{ye=!1}})(),void ie());if("menu"!==o&&"menu confirm"!==o)if("quit"!==o&&"exit"!==o&&"q"!==o){if("status"===o)return F(K,ee),void ie();if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(k().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void ie();const r=K.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 v({language:l}),t?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),de=null,ce=null,ue=null,ge=null,ke=!1,we=!1,xe(),void ie()}if("sim"===o){const e=_e(ee.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=i(u(import.meta.url)),o=[c(e,"..","..","panda","mujoco-launcher.py"),c(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(s(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 n={baseline:"baseline",prompt_injected:"prompt_inj",patch_attacked:"patch",modality_confused:"confused"}[e]||"baseline";console.log(chalk.gray(` Launching MuJoCo viewer (scenario: ${n})...`)),console.log(chalk.gray(" Close the window or press ESC to return to learn mode.")),r("python3",[o,n,"--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 ie()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void ie())}if("bookmark"===o){const e=ee.currentCard;return ee.bookmarks.includes(e)||ee.bookmarks.push(e),C(ee),console.log(chalk.gray(` ✓ Card ${e} bookmarked.`)),void ie()}if("e"===o)return ge=ee.currentCard,console.log(chalk.gray(Ae?" 描述问题(回车提交 / 空行取消):":" Describe the issue (Enter to submit / blank to cancel):")),void ie();if("back"===o||"b"===o)return ee.currentCard>1&&(ee.currentCard-=1),ce=null,ue=null,de=null,C(ee),xe(),void ie();if(o.startsWith("card ")){const e=o.slice(5).trim(),r=parseInt(e,10);return!Number.isInteger(r)||r<1||r>K.totalCards?(console.log(chalk.yellow(` Card number must be 1..${K.totalCards}. Try: `)+chalk.bold.green("card 1")),void ie()):(ee.currentCard=r,ce=null,ue=null,de=null,C(ee),xe(),void ie())}if(null!==de&&["y","yes","n","no"].includes(o)){const e=_e(de);if(e&&"knowledge"===e.type&&e.check){const r=o.startsWith("y")?"y":"n",n=r===e.check.answer,t=Date.now()-ve;E(ee,e.number),_(ee,e.number,{answer:r,correct:n,submittedAt:(new Date).toISOString()}),C(ee);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,r,n,!1),Ce.push(m(H,{card_number:e.number,event_type:"check_answered",check_answer:r,check_correct:n,time_on_card_ms:t}).catch(()=>{})),de=null,e.solution&&e.solution.length>0)return void ie();if(ee.currentCard<K.totalCards){const e=ee.currentCard;ee.currentCard+=1,C(ee),Me(e)?Pe():xe(),ie()}else z(K,ee),ie();return}}if(null!==ce&&["a","b","c","d"].includes(o)){const e=_e(ce);if(e&&"mcq"===e.type){const r=o.toUpperCase(),n=r===e.answer;return T(ee,e.number,{answer:r,correct:n,submittedAt:(new Date).toISOString()}),E(ee,e.number),C(ee),D(e,r,n,ee),Ce.push(m(H,{card_number:e.number,event_type:"mcq_answered",mcq_answer:r,mcq_correct:n}).catch(()=>{})),ce=null,void(n?ee.currentCard<K.totalCards?(ee.currentCard+=1,C(ee),xe()):(z(K,ee),ie()):ie())}}if(null!==ue){if("done"===o){const e=_e(ue);if(e&&"practical"===e.type)return M(ee,e.number),E(ee,e.number),C(ee),q(e),ue=null,void ie()}if("skip"===o)return E(ee,ue),C(ee),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),ue=null,void ie()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==ce)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void ie();if(null!==ue)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void ie();if(null!==de)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void ie();const e=ee.currentCard;return ee.currentCard+=1,C(ee),ee.currentCard>K.totalCards?z(K,ee):Me(e)?Pe():xe(),void ie()}if(null!==de)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void ie();if(null!==ce)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void ie();if(null!==ue)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void ie();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")),ie()}else if(Ce.length>0&&await Promise.race([Promise.allSettled(Ce),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${ee.streakDays} day(s)`)),console.log(),ne){le.removeAllListeners("line"),se();for(const e of te)le.on("line",e);le.prompt(),Ee()}else le.removeAllListeners("line"),le.close();else if(Ce.length>0&&await Promise.race([Promise.allSettled(Ce),new Promise(e=>setTimeout(e,3e3))]),le.removeAllListeners("line"),se(),ne||!Te){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(ne?le:void 0),Ee()}else le.close()}else ie()}};le.on("line",e=>{Se(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.")),ie()})}),ne||le.on("close",async()=>{Ce.length>0&&await Promise.race([Promise.allSettled(Ce),new Promise(e=>setTimeout(e,5e3))]),Te?Ee():process.exit(0)});try{xe(),ie()}catch{if(V("Could not render this card — the curriculum may be malformed."),ne){le.removeAllListeners("line"),se();for(const e of te)le.on("line",e);le.prompt()}else le.close();Ee()}await $e}),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 d(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
- import{createHash as t}from"node:crypto";import{execSync as e}from"node:child_process";import{platform as n}from"node:os";import{getConfig as r,saveConfig as i,getIcoaDir as o,getInstallSalt as s}from"./config.js";import{readFileSync as c,existsSync as a}from"node:fs";import{join as u}from"node:path";import{deriveFileKey as d,readSignedFile as p,writeSignedFile as f,recordVerdict as m}from"./secure-store.js";const l=/^ICOA-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/;export function isFirstRunOrUpgrade(t){return r().lastVersion!==t}export function markVersionSeen(t){i({lastVersion:t})}const g=new Set(["ref","help","exit","quit","q","clear","cls","activate","doctor","aienv","ipynb","kaggle"]);export function isActivated(){return!!r().accessToken}export function getDeviceFingerprint(){const i=r();if(i.deviceFingerprint)return i.deviceFingerprint;const o=s(),u=function(){try{if("darwin"===n()){const t=e("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf-8"}).match(/"([A-F0-9-]+)"/);if(t)return t[1]}else if("linux"===n()){if(a("/etc/machine-id"))return c("/etc/machine-id","utf-8").trim()}else if("win32"===n())return e('powershell -Command "(Get-CimInstance Win32_ComputerSystemProduct).UUID"',{encoding:"utf-8"}).trim()}catch{}return""}();return t("sha256").update(`${u}|${o}`).digest("hex")}const x="token-bindings";export function activateToken(e){if(!function(t){return l.test(t.trim().toUpperCase())}(e))return"invalid";const n=getDeviceFingerprint(),r=u(o(),"token-bindings.json"),c=d(s(),x),{data:a,verdict:g}=p(r,c);m(x,g);const v=a||{},h=function(e){return t("sha256").update(e.trim().toUpperCase()).digest("hex")}(e),A=v[h];return A&&A!==n?"already_bound":(v[h]=n,f(r,v,c),i({accessToken:e.trim().toUpperCase(),deviceFingerprint:n}),"ok")}export function isDeviceMatch(){const t=r();return!t.deviceFingerprint||t.deviceFingerprint===getDeviceFingerprint()}export function isFreeCommand(t){return g.has(t.toLowerCase())}const v=()=>u(o(),"session-state.json"),h="session-state";function A(){return d(s(),h)}function w(){return{startedAt:(new Date).toISOString(),lastExitAt:null,lastResumeAt:null,exitCount:0,totalAwaySeconds:0}}function C(){const{data:t,verdict:e}=p(v(),A());return m(h,e),t?{...w(),...t}:w()}function D(t){const e={...C(),...t};f(v(),e,A())}export function recordExit(){const t=C();t.lastExitAt=(new Date).toISOString(),t.exitCount++,D(t)}export function recordResume(){const t=C();if(!t.lastExitAt)return null;const e=new Date(t.lastExitAt).getTime(),n=Date.now(),r=Math.round((n-e)/1e3);return t.lastResumeAt=(new Date).toISOString(),t.totalAwaySeconds+=r,D(t),{awaySeconds:r,exitCount:t.exitCount}}
1
+ import{createHash as t}from"node:crypto";import{execSync as e}from"node:child_process";import{platform as n}from"node:os";import{getConfig as r,saveConfig as i,getIcoaDir as o,getInstallSalt as s}from"./config.js";import{readFileSync as c,existsSync as a}from"node:fs";import{join as u}from"node:path";import{deriveFileKey as d,readSignedFile as p,writeSignedFile as f,recordVerdict as m}from"./secure-store.js";const l=/^ICOA-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/;export function isFirstRunOrUpgrade(t){return r().lastVersion!==t}export function markVersionSeen(t){i({lastVersion:t})}const g=new Set(["ref","help","exit","quit","q","clear","cls","activate","doctor","aienv","ipynb","kaggle","tmux"]);export function isActivated(){return!!r().accessToken}export function getDeviceFingerprint(){const i=r();if(i.deviceFingerprint)return i.deviceFingerprint;const o=s(),u=function(){try{if("darwin"===n()){const t=e("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf-8"}).match(/"([A-F0-9-]+)"/);if(t)return t[1]}else if("linux"===n()){if(a("/etc/machine-id"))return c("/etc/machine-id","utf-8").trim()}else if("win32"===n())return e('powershell -Command "(Get-CimInstance Win32_ComputerSystemProduct).UUID"',{encoding:"utf-8"}).trim()}catch{}return""}();return t("sha256").update(`${u}|${o}`).digest("hex")}const x="token-bindings";export function activateToken(e){if(!function(t){return l.test(t.trim().toUpperCase())}(e))return"invalid";const n=getDeviceFingerprint(),r=u(o(),"token-bindings.json"),c=d(s(),x),{data:a,verdict:g}=p(r,c);m(x,g);const v=a||{},h=function(e){return t("sha256").update(e.trim().toUpperCase()).digest("hex")}(e),A=v[h];return A&&A!==n?"already_bound":(v[h]=n,f(r,v,c),i({accessToken:e.trim().toUpperCase(),deviceFingerprint:n}),"ok")}export function isDeviceMatch(){const t=r();return!t.deviceFingerprint||t.deviceFingerprint===getDeviceFingerprint()}export function isFreeCommand(t){return g.has(t.toLowerCase())}const v=()=>u(o(),"session-state.json"),h="session-state";function A(){return d(s(),h)}function w(){return{startedAt:(new Date).toISOString(),lastExitAt:null,lastResumeAt:null,exitCount:0,totalAwaySeconds:0}}function C(){const{data:t,verdict:e}=p(v(),A());return m(h,e),t?{...w(),...t}:w()}function D(t){const e={...C(),...t};f(v(),e,A())}export function recordExit(){const t=C();t.lastExitAt=(new Date).toISOString(),t.exitCount++,D(t)}export function recordResume(){const t=C();if(!t.lastExitAt)return null;const e=new Date(t.lastExitAt).getTime(),n=Date.now(),r=Math.round((n-e)/1e3);return t.lastResumeAt=(new Date).toISOString(),t.totalAwaySeconds+=r,D(t),{awaySeconds:r,exitCount:t.exitCount}}
@@ -0,0 +1,51 @@
1
+ /**
2
+ * gpu — pure core of the M2 GPU-lease client (Kaggle practice arena).
3
+ *
4
+ * The control plane is server-authoritative (design §5): the CLI POSTs
5
+ * lease/status/release and renders what it gets back; quota, max-1 and
6
+ * timeout-kill all live server-side (panda/kaggle/gpu_api.py). This module is
7
+ * the pure part — response parsing, connect-field validation, ssh arg
8
+ * building — so the trust boundary is unit-tested: a lease response can NEVER
9
+ * smuggle shell into the ssh command (every field is format-whitelisted and
10
+ * the remote command string is built by buildRemoteBridgeCommand's quoting).
11
+ *
12
+ * Transports: 'ssh' (real GPU box) and 'local' (dev loop — spawns the bridge
13
+ * under a local shell; the command layer only honours it when the student
14
+ * explicitly pointed ICOA_GPU_SERVER at a dev broker, so a hostile prod
15
+ * response cannot make the CLI spawn local processes).
16
+ */
17
+ export interface GpuLease {
18
+ state: 'ready' | 'queued' | 'none' | 'error';
19
+ transport?: 'ssh' | 'local';
20
+ host?: string;
21
+ port?: number;
22
+ user?: string;
23
+ /** Remote venv python that runs the kernel bridge. */
24
+ python?: string;
25
+ /** Fixed dataset mount root on the box (design §4: /data/kaggle). */
26
+ dataRoot?: string;
27
+ /** Per-session workspace on the box (submission.csv lands here). */
28
+ outDir?: string;
29
+ /** SSH private key for this lease (PEM, from the broker). */
30
+ keyPem?: string;
31
+ timeLeftSec?: number;
32
+ queuePosition?: number;
33
+ estimatedWaitSec?: number;
34
+ message?: string;
35
+ }
36
+ /** Parse a broker response ({success,data:{...}} or bare) into a GpuLease. */
37
+ export declare function parseLeaseResponse(resp: unknown): GpuLease;
38
+ /**
39
+ * Trust boundary: a ready lease's connect fields must be plainly-shaped
40
+ * before they go anywhere near a spawn. Returns the list of problems
41
+ * (empty = safe to connect).
42
+ */
43
+ export declare function leaseConnectProblems(l: GpuLease): string[];
44
+ /**
45
+ * ssh argv for a validated lease (spawn-array — no local shell ever parses
46
+ * any of this). `remoteCommand` is the single bridge command from
47
+ * buildRemoteBridgeCommand; `keyPath` is where the caller wrote keyPem (0600).
48
+ */
49
+ export declare function buildSshArgs(l: GpuLease, keyPath: string, remoteCommand: string): string[];
50
+ /** `⏳ GPU queue: #3 · ~6 min` — the student-facing queue line (design §5). */
51
+ export declare function queueLine(l: GpuLease): string;
@@ -0,0 +1 @@
1
+ const t=/^[a-zA-Z0-9][a-zA-Z0-9.-]*$/,e=/^[a-z_][a-z0-9_-]*$/,o=/^\/[A-Za-z0-9._/-]*$/;function s(t,e){return"string"==typeof t[e]&&""!==t[e]?t[e]:void 0}function r(t,e){return"number"==typeof t[e]&&Number.isFinite(t[e])?t[e]:void 0}export function parseLeaseResponse(t){const e=t??{},o=e.data??e,a=s(o,"state");return"ready"!==a&&"queued"!==a&&"none"!==a?{state:"error",message:s(o,"error")??s(o,"message")??"unexpected broker response"}:{state:a,transport:"local"===o.transport?"local":"ssh"===o.transport?"ssh":void 0,host:s(o,"host"),port:r(o,"port"),user:s(o,"user"),python:s(o,"python"),dataRoot:s(o,"data_root"),outDir:s(o,"out_dir"),keyPem:s(o,"key_pem"),timeLeftSec:r(o,"time_left_sec"),queuePosition:r(o,"queue_position"),estimatedWaitSec:r(o,"estimated_wait_sec"),message:s(o,"message")}}export function leaseConnectProblems(s){const r=[];return"ready"!==s.state&&r.push("lease is not ready"),s.python&&o.test(s.python)||r.push("bad python path"),s.dataRoot&&o.test(s.dataRoot)||r.push("bad data_root"),s.outDir&&o.test(s.outDir)||r.push("bad out_dir"),"ssh"===s.transport?(s.host&&t.test(s.host)||r.push("bad host"),s.user&&e.test(s.user)||r.push("bad user"),void 0!==s.port&&(!Number.isInteger(s.port)||s.port<1||s.port>65535)&&r.push("bad port"),s.keyPem||r.push("missing ssh key")):"local"!==s.transport&&r.push("unknown transport"),r}export function buildSshArgs(t,e,o){return["-i",e,"-p",String(t.port??22),"-o","StrictHostKeyChecking=accept-new","-o","ConnectTimeout=15","-o","BatchMode=yes","-T",`${t.user}@${t.host}`,o]}export function queueLine(t){return`⏳ GPU queue: #${t.queuePosition??0}${t.estimatedWaitSec?` · ~${Math.max(1,Math.round(t.estimatedWaitSec/60))} min`:""}`}
@@ -22,15 +22,34 @@ export interface KaggleTask {
22
22
  kaggle_url?: string | null;
23
23
  licence?: string;
24
24
  attribution?: string;
25
- }
26
- export interface KaggleMeta extends KaggleTask {
25
+ /** M1: base URL of this competition's public Object-Storage prefix. When
26
+ * present the client fetches the CSVs straight from the bucket (practice
27
+ * serves only this pointer); absent → M0 fallback via the /data bundle. */
28
+ data_base?: string | null;
27
29
  id_col?: string;
28
30
  target_col?: string;
29
31
  n_train?: number;
30
32
  n_test?: number;
33
+ /** M2.5 (one engine, two judges): absent/"kaggle" → manual kaggle.com upload;
34
+ * "icoa-holdout" → `kaggle submit` scores server-side vs secret labels and
35
+ * lands on the ICOA Board. */
36
+ judge?: string;
37
+ /** Board event this competition's submissions are recorded under. */
38
+ board_event?: string | null;
31
39
  }
40
+ export type KaggleMeta = KaggleTask;
32
41
  /** Extract the task list from a server response ({success,data:{tasks}} or bare). */
33
42
  export declare function parseKaggleTaskList(resp: unknown): KaggleTask[];
43
+ export interface DataFileUrls {
44
+ train: string;
45
+ test: string;
46
+ sample_submission: string;
47
+ }
48
+ /** The three CSV URLs under a competition's bucket prefix, or null when the
49
+ * server advertised no bucket (client then falls back to the /data bundle). */
50
+ export declare function dataFileUrls(task: {
51
+ data_base?: string | null;
52
+ }): DataFileUrls | null;
34
53
  /**
35
54
  * Build the starter notebook cells for a competition. The data dir is baked in
36
55
  * as an absolute path so the notebook runs from anywhere; the submission cell
@@ -38,6 +57,22 @@ export declare function parseKaggleTaskList(resp: unknown): KaggleTask[];
38
57
  * sample_submission.csv byte-for-byte in shape.
39
58
  */
40
59
  export declare function buildStarterCells(dir: string, meta: KaggleMeta): NbCell[];
60
+ export interface SubmitOutcome {
61
+ ok: boolean;
62
+ score?: number;
63
+ metric?: string;
64
+ rank?: number | null;
65
+ fieldSize?: number | null;
66
+ deduped?: boolean;
67
+ boardEvent?: string | null;
68
+ /** machine-readable failure: network · bad_token · format · kaggle_judged ·
69
+ * event_closed · outside_window · cap_reached · judge_unavailable · … */
70
+ reason?: string;
71
+ error?: string;
72
+ problems?: string[];
73
+ }
74
+ /** Unwrap the server's judge response ({success,data} envelope or bare). */
75
+ export declare function parseSubmitResponse(resp: unknown): SubmitOutcome;
41
76
  export interface SubmissionVerdict {
42
77
  ok: boolean;
43
78
  problems: string[];
@@ -1 +1 @@
1
- export function parseKaggleTaskList(e){const t=e??{},i=(t.data??t).tasks;if(!Array.isArray(i))return[];const r=[];for(const e of i){if(!e||"object"!=typeof e)continue;const t=e;"string"==typeof t.comp_id&&""!==t.comp_id&&r.push({comp_id:t.comp_id,title:"string"==typeof t.title?t.title:t.comp_id,metric:"string"==typeof t.metric?t.metric:"accuracy",kaggle_url:"string"==typeof t.kaggle_url?t.kaggle_url:null,licence:"string"==typeof t.licence?t.licence:void 0,attribution:"string"==typeof t.attribution?t.attribution:void 0})}return r}export function buildStarterCells(e,t){const i=t.id_col??"id",r=t.target_col??"target",a=(s=t.metric,/rmse|mse|mae|error/i.test(s));var s;const o=e=>({kind:"markdown",source:e,result:null}),n=e=>({kind:"code",source:e.join("\n"),result:null}),l=[`# ${t.title}`,"",`Kaggle-style practice — metric: **${t.metric}**.`,"","- `train.csv` — labelled training data",`- \`test.csv\` — rows to predict (no \`${r}\` column)`,"- `sample_submission.csv` — the exact format Kaggle expects","","Run all cells top to bottom: a baseline model trains on your CPU and","`submission.csv` appears next to the data. Then improve the model cell","and re-run — your score is whatever Kaggle says it is.",...t.licence?["",`**Data licence:** ${t.licence}`]:[],...t.attribution?[`**Attribution:** ${t.attribution}`]:[]].join("\n"),c=n(["# setup — load the data (leave as is)","import pandas as pd","from sklearn.model_selection import train_test_split",a?"from sklearn.metrics import mean_squared_error":"from sklearn.metrics import accuracy_score","",`DIR = r"${e}"`,'train = pd.read_csv(DIR + "/train.csv")','test = pd.read_csv(DIR + "/test.csv")',`features = [c for c in train.columns if c not in ("${i}", "${r}")]`,`X, y = train[features], train["${r}"]`,"X_test = test[features]","X_tr, X_val, y_tr, y_val = train_test_split(X, y, test_size=0.2, random_state=0)",'print(f"train {train.shape} · test {test.shape} · {len(features)} features")']),m=n(a?["# MODEL — a working baseline. Improve THIS cell to climb the Kaggle board.","from sklearn.linear_model import Ridge","model = Ridge()"]:["# MODEL — a working baseline. Improve THIS cell to climb the Kaggle board.","from sklearn.linear_model import LogisticRegression","model = LogisticRegression(max_iter=2000)"]),u=n(["# validate — quick local score on a held-out fifth of train","model.fit(X_tr, y_tr)",a?'print("val RMSE:", round(mean_squared_error(y_val, model.predict(X_val)) ** 0.5, 4))':'print("val accuracy:", round(accuracy_score(y_val, model.predict(X_val)), 4))']),p=n(["# submission — retrain on ALL data, write submission.csv (Kaggle format)","model.fit(X, y)","pred = model.predict(X_test)",'out = DIR + "/submission.csv"',`pd.DataFrame({"${i}": test["${i}"], "${r}": pred}).to_csv(out, index=False)`,'print("wrote", out)','print("format check: icoa kaggle check")']),d=t.kaggle_url?["## Submit on Kaggle (manual, your own account)","",`1. Open ${t.kaggle_url}`,"2. **Submit Predictions** → upload `submission.csv`","3. Read your leaderboard score, come back, improve the MODEL cell, repeat."]:["## Submit on Kaggle (manual, your own account)","","_This is a placeholder practice dataset — it has no live Kaggle page yet._","When the real competition dataset lands, this cell will link straight to","its Kaggle submission page. The loop is identical: upload `submission.csv`,","read the score, improve the MODEL cell, repeat."];return[o(l),c,m,u,p,o(d.join("\n"))]}export function validateSubmissionText(e,t){const i=[],r=e.trim().split(/\r?\n/),a=t.trim().split(/\r?\n/),s=r[0]??"",o=a[0]??"";s.trim()!==o.trim()&&i.push(`header mismatch: expected "${o}", got "${s}"`);const n=r.slice(1).filter(e=>""!==e.trim()),l=a.slice(1).filter(e=>""!==e.trim());n.length!==l.length&&i.push(`row count mismatch: expected ${l.length}, got ${n.length}`);const c=e=>new Set(e.map(e=>(e.split(",")[0]??"").trim())),m=c(n),u=c(l),p=[...u].filter(e=>!m.has(e)),d=[...m].filter(e=>!u.has(e));if(p.length>0||d.length>0){const e=[];p.length>0&&e.push(`${p.length} missing (e.g. ${p[0]})`),d.length>0&&e.push(`${d.length} unknown (e.g. ${d[0]})`),i.push(`id mismatch vs sample_submission: ${e.join(", ")}`)}for(let e=0;e<n.length;e++)if(n[e].split(",").some(e=>""===e.trim())){i.push(`empty cell in data row ${e+1}`);break}return{ok:0===i.length,problems:i}}
1
+ export function parseKaggleTaskList(e){const t=e??{},r=(t.data??t).tasks;if(!Array.isArray(r))return[];const o=[];for(const e of r){if(!e||"object"!=typeof e)continue;const t=e;"string"==typeof t.comp_id&&""!==t.comp_id&&o.push({comp_id:t.comp_id,title:"string"==typeof t.title?t.title:t.comp_id,metric:"string"==typeof t.metric?t.metric:"accuracy",kaggle_url:"string"==typeof t.kaggle_url?t.kaggle_url:null,licence:"string"==typeof t.licence?t.licence:void 0,attribution:"string"==typeof t.attribution?t.attribution:void 0,data_base:"string"==typeof t.data_base&&""!==t.data_base?t.data_base:null,id_col:"string"==typeof t.id_col?t.id_col:void 0,target_col:"string"==typeof t.target_col?t.target_col:void 0,n_train:"number"==typeof t.n_train?t.n_train:void 0,n_test:"number"==typeof t.n_test?t.n_test:void 0,judge:"string"==typeof t.judge&&""!==t.judge?t.judge:void 0,board_event:"string"==typeof t.board_event&&""!==t.board_event?t.board_event:null})}return o}export function dataFileUrls(e){const t=e.data_base;if("string"!=typeof t||""===t)return null;const r=t.replace(/\/$/,"");return{train:`${r}/train.csv`,test:`${r}/test.csv`,sample_submission:`${r}/sample_submission.csv`}}export function buildStarterCells(e,t){const r=t.id_col??"id",o=t.target_col??"target",i=(s=t.metric,/rmse|mse|mae|error/i.test(s));var s;const a="icoa-holdout"===t.judge,n=e=>({kind:"markdown",source:e,result:null}),l=e=>({kind:"code",source:e.join("\n"),result:null}),c=[`# ${t.title}`,"",`Kaggle-style practice — metric: **${t.metric}**.`,"","- `train.csv` — labelled training data",`- \`test.csv\` — rows to predict (no \`${o}\` column)`,"- `sample_submission.csv` — the exact format Kaggle expects","","Run all cells top to bottom: a baseline model trains on your CPU and","`submission.csv` appears next to the data. Then improve the model cell",...a?["and re-run — `icoa kaggle submit` scores it and ranks you on the board."]:["and re-run — your score is whatever Kaggle says it is."],...t.licence?["",`**Data licence:** ${t.licence}`]:[],...t.attribution?[`**Attribution:** ${t.attribution}`]:[]].join("\n"),d=l(["# setup — load the data (leave as is)","import os","import pandas as pd","from sklearn.model_selection import train_test_split",i?"from sklearn.metrics import mean_squared_error":"from sklearn.metrics import accuracy_score","","# same code everywhere: in a GPU session these env vars point at the","# box's own dataset copy + workspace — locally they are unset.",`DIR = os.environ.get("ICOA_KAGGLE_DATA") or r"${e}"`,'OUT = os.environ.get("ICOA_KAGGLE_OUT") or DIR',...t.data_base?[`DATA_BASE = "${t.data_base.replace(/\/$/,"")}"`,'if not os.path.exists(DIR + "/train.csv"):'," import urllib.request"," os.makedirs(DIR, exist_ok=True)",' for f in ("train.csv", "test.csv", "sample_submission.csv"):',' urllib.request.urlretrieve(DATA_BASE + "/" + f, DIR + "/" + f)']:[],'train = pd.read_csv(DIR + "/train.csv")','test = pd.read_csv(DIR + "/test.csv")',`features = [c for c in train.columns if c not in ("${r}", "${o}")]`,`X, y = train[features], train["${o}"]`,"X_test = test[features]","X_tr, X_val, y_tr, y_val = train_test_split(X, y, test_size=0.2, random_state=0)",'print(f"train {train.shape} · test {test.shape} · {len(features)} features")']),u=l(i?["# MODEL — a working baseline. Improve THIS cell to climb the Kaggle board.","from sklearn.linear_model import Ridge","model = Ridge()"]:["# MODEL — a working baseline. Improve THIS cell to climb the Kaggle board.","from sklearn.linear_model import LogisticRegression","model = LogisticRegression(max_iter=2000)"]),m=l(["# validate — quick local score on a held-out fifth of train","model.fit(X_tr, y_tr)",i?'print("val RMSE:", round(mean_squared_error(y_val, model.predict(X_val)) ** 0.5, 4))':'print("val accuracy:", round(accuracy_score(y_val, model.predict(X_val)), 4))']),p=l(["# submission — retrain on ALL data, write submission.csv (Kaggle format)","model.fit(X, y)","pred = model.predict(X_test)",'out = OUT + "/submission.csv"',`pd.DataFrame({"${r}": test["${r}"], "${o}": pred}).to_csv(out, index=False)`,'print("wrote", out)',a?`print("score it: icoa kaggle submit ${t.comp_id}")`:'print("format check: icoa kaggle check")']),g=a?["## Submit to ICOA (scored on the server)","",`1. In the ICOA CLI run \`icoa kaggle submit ${t.comp_id}\``,"2. The server scores `submission.csv` against the secret test labels"," and your rank lands on the live board (`icoa board`).","3. Improve the MODEL cell, re-run, submit again — best score counts."]:t.kaggle_url?["## Submit on Kaggle (manual, your own account)","",`1. Open ${t.kaggle_url}`,"2. **Submit Predictions** → upload `submission.csv`","3. Read your leaderboard score, come back, improve the MODEL cell, repeat."]:["## Submit on Kaggle (manual, your own account)","","_This is a placeholder practice dataset — it has no live Kaggle page yet._","When the real competition dataset lands, this cell will link straight to","its Kaggle submission page. The loop is identical: upload `submission.csv`,","read the score, improve the MODEL cell, repeat."];return[n(c),d,u,m,p,n(g.join("\n"))]}export function parseSubmitResponse(e){const t=e&&"object"==typeof e?e:{},r=t.data??t,o=r&&"object"==typeof r?r:{};return"number"==typeof o.score&&"string"==typeof o.metric?{ok:!0,score:o.score,metric:o.metric,rank:"number"==typeof o.rank_at_time?o.rank_at_time:null,fieldSize:"number"==typeof o.field_size?o.field_size:null,deduped:!0===o.deduped,boardEvent:"string"==typeof o.board_event?o.board_event:null}:"string"==typeof o.reason&&""!==o.reason?{ok:!1,reason:o.reason,error:"string"==typeof o.error?o.error:void 0,problems:Array.isArray(o.problems)?o.problems.filter(e=>"string"==typeof e):void 0}:{ok:!1,reason:"network"}}export function validateSubmissionText(e,t){const r=[],o=e.trim().split(/\r?\n/),i=t.trim().split(/\r?\n/),s=o[0]??"",a=i[0]??"";s.trim()!==a.trim()&&r.push(`header mismatch: expected "${a}", got "${s}"`);const n=o.slice(1).filter(e=>""!==e.trim()),l=i.slice(1).filter(e=>""!==e.trim());n.length!==l.length&&r.push(`row count mismatch: expected ${l.length}, got ${n.length}`);const c=e=>new Set(e.map(e=>(e.split(",")[0]??"").trim())),d=c(n),u=c(l),m=[...u].filter(e=>!d.has(e)),p=[...d].filter(e=>!u.has(e));if(m.length>0||p.length>0){const e=[];m.length>0&&e.push(`${m.length} missing (e.g. ${m[0]})`),p.length>0&&e.push(`${p.length} unknown (e.g. ${p[0]})`),r.push(`id mismatch vs sample_submission: ${e.join(", ")}`)}for(let e=0;e<n.length;e++)if(n[e].split(",").some(e=>""===e.trim())){r.push(`empty cell in data row ${e+1}`);break}return{ok:0===r.length,problems:r}}
@@ -36,6 +36,15 @@ export type KernelEvent = {
36
36
  type: 'done';
37
37
  id: number;
38
38
  count: number | null;
39
+ } | {
40
+ type: 'file';
41
+ id: number;
42
+ data: string;
43
+ size: number;
44
+ } | {
45
+ type: 'file_error';
46
+ id: number;
47
+ message: string;
39
48
  } | {
40
49
  type: 'fatal';
41
50
  message: string;
@@ -1 +1 @@
1
- const e=new Set(["ready","stream","result","display","error","done","fatal"]);export function parseKernelEvent(t){const a=t.trim();if(!a)return null;let r;try{r=JSON.parse(a)}catch{return null}if(!r||"object"!=typeof r)return null;const n=r.type;return"string"==typeof n&&e.has(n)?r:null}export function foldCellOutputs(e){const t=[];let a=!0,r=null;for(const n of e)switch(n.type){case"stream":{const e=t[t.length-1];e&&"stream"===e.kind&&e.name===n.name?e.text+=n.text:t.push({kind:"stream",name:n.name,text:n.text});break}case"result":t.push({kind:"result",text:n.text,...n.data?{data:n.data}:{}});break;case"display":t.push({kind:"display",data:n.data});break;case"error":a=!1,t.push({kind:"error",ename:n.ename,evalue:n.evalue,traceback:n.traceback});break;case"done":r=n.count;break;case"fatal":a=!1,t.push({kind:"error",ename:"KernelError",evalue:n.message,traceback:[n.message]})}return{outputs:t,ok:a,execCount:r}}
1
+ const e=new Set(["ready","stream","result","display","error","done","file","file_error","fatal"]);export function parseKernelEvent(t){const a=t.trim();if(!a)return null;let r;try{r=JSON.parse(a)}catch{return null}if(!r||"object"!=typeof r)return null;const n=r.type;return"string"==typeof n&&e.has(n)?r:null}export function foldCellOutputs(e){const t=[];let a=!0,r=null;for(const n of e)switch(n.type){case"stream":{const e=t[t.length-1];e&&"stream"===e.kind&&e.name===n.name?e.text+=n.text:t.push({kind:"stream",name:n.name,text:n.text});break}case"result":t.push({kind:"result",text:n.text,...n.data?{data:n.data}:{}});break;case"display":t.push({kind:"display",data:n.data});break;case"error":a=!1,t.push({kind:"error",ename:n.ename,evalue:n.evalue,traceback:n.traceback});break;case"done":r=n.count;break;case"file":case"file_error":default:break;case"fatal":a=!1,t.push({kind:"error",ename:"KernelError",evalue:n.message,traceback:[n.message]})}return{outputs:t,ok:a,execCount:r}}
@@ -17,14 +17,32 @@
17
17
  */
18
18
  import { type FoldedCell } from './kernel-protocol.js';
19
19
  export declare const KERNEL_BRIDGE_PY: string;
20
+ export interface KernelSpawnSpec {
21
+ command: string;
22
+ args: string[];
23
+ }
20
24
  export interface KernelStartOptions {
21
- /** Absolute path to the venv python (from aienvPaths().python). */
22
- venvPython: string;
23
- /** Directory to drop the bridge script in (the venv root). */
24
- venvRoot: string;
25
+ /** Local kernel: absolute path to the venv python (from aienvPaths().python). */
26
+ venvPython?: string;
27
+ /** Local kernel: directory to drop the bridge script in (the venv root). */
28
+ venvRoot?: string;
29
+ /** Remote kernel (M2 GPU sessions): spawn THIS instead of the local venv
30
+ * bridge — typically `ssh … <buildRemoteBridgeCommand(...)>`. The bridge
31
+ * rides inside the command itself, so the box needs no pre-provisioned
32
+ * bridge file; the wire protocol is identical to the local kernel. */
33
+ spawnSpec?: KernelSpawnSpec;
25
34
  /** Optional: max ms to wait for the kernel `ready` event. */
26
35
  readyTimeoutMs?: number;
27
36
  }
37
+ /**
38
+ * The single shell-command string that runs the bridge on a remote box (the
39
+ * one argument after `ssh user@host`). The bridge source travels as base64
40
+ * inside a `python -c exec(...)` so any box with the ML venv works — nothing
41
+ * to pre-install beyond the venv itself. `env` carries the fixed-path dataset
42
+ * pointers (ICOA_KAGGLE_DATA / ICOA_KAGGLE_OUT — the §4 UX invariant), `cwd`
43
+ * is the per-session workspace.
44
+ */
45
+ export declare function buildRemoteBridgeCommand(remotePython: string, env?: Record<string, string>, cwd?: string): string;
28
46
  /**
29
47
  * A live notebook kernel. Executes are serialized (one cell at a time, as a
30
48
  * notebook does) so the line-buffered output demux stays unambiguous.
@@ -32,9 +50,11 @@ export interface KernelStartOptions {
32
50
  export declare class NotebookKernel {
33
51
  private proc;
34
52
  private buf;
53
+ private errTail;
35
54
  private nextId;
36
55
  private ready;
37
56
  private pending;
57
+ private pendingFetch;
38
58
  private onReady;
39
59
  private onExit;
40
60
  private readonly opts;
@@ -48,6 +68,12 @@ export declare class NotebookKernel {
48
68
  start(): Promise<void>;
49
69
  /** Run one cell; resolves with its folded outputs after the `done` event. */
50
70
  execute(code: string): Promise<FoldedCell>;
71
+ /**
72
+ * Fetch one small file from the kernel's filesystem (local box or remote
73
+ * GPU box — same pipe either way). Resolves with the raw bytes; rejects on
74
+ * missing file or the bridge's 20MB artifact cap.
75
+ */
76
+ fetchFile(path: string): Promise<Buffer>;
51
77
  /** Ask the bridge to shut the kernel down; resolves when the process exits. */
52
78
  shutdown(): Promise<void>;
53
79
  private onStdout;
@@ -1,4 +1,4 @@
1
- import{spawn as e}from"node:child_process";import{writeFileSync as t}from"node:fs";import{join as i}from"node:path";import{foldCellOutputs as n,parseKernelEvent as r}from"./kernel-protocol.js";export const KERNEL_BRIDGE_PY=String.raw`import sys, os, json, queue
1
+ import{spawn as e}from"node:child_process";import{writeFileSync as t}from"node:fs";import{join as i}from"node:path";import{foldCellOutputs as r,parseKernelEvent as n}from"./kernel-protocol.js";export const KERNEL_BRIDGE_PY=String.raw`import sys, os, json, queue, base64
2
2
 
3
3
  def emit(o):
4
4
  sys.stdout.write(json.dumps(o) + "\n")
@@ -36,6 +36,20 @@ def main():
36
36
  continue
37
37
  if req.get("cmd") == "shutdown":
38
38
  break
39
+ if req.get("cmd") == "fetch":
40
+ # Artifact download over the same pipe (M2): small files only —
41
+ # the thin-client rule caps what crosses the student's downlink.
42
+ fid = req.get("id"); fpath = req.get("path", "")
43
+ try:
44
+ if os.path.getsize(fpath) > 20 * 1024 * 1024:
45
+ emit({"type": "file_error", "id": fid, "message": "file exceeds the 20MB artifact cap"})
46
+ else:
47
+ with open(fpath, "rb") as fh:
48
+ raw = fh.read()
49
+ emit({"type": "file", "id": fid, "data": base64.b64encode(raw).decode(), "size": len(raw)})
50
+ except Exception as e:
51
+ emit({"type": "file_error", "id": fid, "message": str(e)})
52
+ continue
39
53
  cid = req.get("id"); code = req.get("code", "")
40
54
  mid = kc.execute(code)
41
55
  count = None
@@ -78,4 +92,4 @@ def main():
78
92
  os._exit(0)
79
93
 
80
94
  main()
81
- `;export class NotebookKernel{proc=null;buf="";nextId=1;ready=!1;pending=null;onReady=null;onExit=null;opts;bridgePath;constructor(e){this.opts=e,this.bridgePath=i(e.venvRoot,"icoa-kernel-bridge.py")}start(){this.buf="",this.ready=!1,this.pending=null,this.nextId=1,t(this.bridgePath,KERNEL_BRIDGE_PY);const i=e(this.opts.venvPython,[this.bridgePath],{stdio:["pipe","pipe","pipe"]});this.proc=i,i.stdout.setEncoding("utf-8"),i.stdout.on("data",e=>this.onStdout(e)),i.on("exit",()=>{this.ready=!1,this.onExit?.()});const n=this.opts.readyTimeoutMs??6e4;return new Promise((e,t)=>{const i=setTimeout(()=>t(new Error("kernel did not become ready in time")),n);this.onReady=()=>{clearTimeout(i),e()},this.onExit=()=>{clearTimeout(i),this.ready||t(new Error("kernel process exited before ready"))}})}execute(e){if(!this.proc||!this.ready)return Promise.reject(new Error("kernel not ready"));if(this.pending)return Promise.reject(new Error("a cell is already executing"));const t=this.nextId++;return new Promise(i=>{this.pending={id:t,events:[],resolve:i},this.proc?.stdin.write(`${JSON.stringify({id:t,code:e})}\n`)})}shutdown(){const e=this.proc;return e?new Promise(t=>{this.onExit=()=>t();try{e.stdin.write(`${JSON.stringify({cmd:"shutdown"})}\n`)}catch{e.kill()}setTimeout(()=>{this.proc&&(this.proc.kill(),t())},5e3)}):Promise.resolve()}onStdout(e){this.buf+=e;let t=this.buf.indexOf("\n");for(;-1!==t;){const e=this.buf.slice(0,t);this.buf=this.buf.slice(t+1),this.handleEvent(r(e)),t=this.buf.indexOf("\n")}}handleEvent(e){if(!e)return;if("ready"===e.type)return this.ready=!0,void this.onReady?.();const t=this.pending;if(t){if("done"===e.type){if(e.id!==t.id)return;const i=n(t.events.concat(e));return this.pending=null,void t.resolve(i)}t.events.push(e)}}}
95
+ `;function s(e){return`'${e.replace(/'/g,"'\\''")}'`}export function buildRemoteBridgeCommand(e,t={},i){const r=Buffer.from(KERNEL_BRIDGE_PY,"utf-8").toString("base64"),n=["exec","env",...Object.entries(t).map(([e,t])=>`${e}=${s(t)}`),s(e),"-c",s(`exec(__import__("base64").b64decode("${r}").decode())`)].join(" ");return i?`mkdir -p ${s(i)} && cd ${s(i)} && ${n}`:n}export class NotebookKernel{proc=null;buf="";errTail="";nextId=1;ready=!1;pending=null;pendingFetch=null;onReady=null;onExit=null;opts;bridgePath;constructor(e){this.opts=e,this.bridgePath=e.venvRoot?i(e.venvRoot,"icoa-kernel-bridge.py"):null}start(){let i;if(this.buf="",this.errTail="",this.ready=!1,this.pending=null,this.pendingFetch=null,this.nextId=1,this.opts.spawnSpec)i=e(this.opts.spawnSpec.command,this.opts.spawnSpec.args,{stdio:["pipe","pipe","pipe"]});else{if(!this.opts.venvPython||!this.bridgePath)return Promise.reject(new Error("kernel needs venvPython+venvRoot or a spawnSpec"));t(this.bridgePath,KERNEL_BRIDGE_PY),i=e(this.opts.venvPython,[this.bridgePath],{stdio:["pipe","pipe","pipe"]})}this.proc=i,i.stdout.setEncoding("utf-8"),i.stdout.on("data",e=>this.onStdout(e)),i.stderr.setEncoding("utf-8"),i.stderr.on("data",e=>{this.errTail=(this.errTail+e).slice(-600)}),i.on("exit",()=>{this.ready=!1,this.onExit?.()}),i.on("error",()=>{this.ready=!1,this.proc=null,this.onExit?.()});const r=this.opts.readyTimeoutMs??6e4;return new Promise((e,t)=>{const i=e=>new Error(this.errTail?`${e} — ${this.errTail.trim()}`:e),n=setTimeout(()=>t(i("kernel did not become ready in time")),r);this.onReady=()=>{clearTimeout(n),e()},this.onExit=()=>{clearTimeout(n),this.ready||t(i("kernel process exited before ready"))}})}execute(e){if(!this.proc||!this.ready)return Promise.reject(new Error("kernel not ready"));if(this.pending)return Promise.reject(new Error("a cell is already executing"));const t=this.nextId++;return new Promise(i=>{this.pending={id:t,events:[],resolve:i},this.proc?.stdin.write(`${JSON.stringify({id:t,code:e})}\n`)})}fetchFile(e){if(!this.proc||!this.ready)return Promise.reject(new Error("kernel not ready"));if(this.pendingFetch)return Promise.reject(new Error("a fetch is already in flight"));const t=this.nextId++;return new Promise((i,r)=>{this.pendingFetch={id:t,resolve:i,reject:r},this.proc?.stdin.write(`${JSON.stringify({cmd:"fetch",id:t,path:e})}\n`)})}shutdown(){const e=this.proc;return e?new Promise(t=>{this.onExit=()=>t();try{e.stdin.write(`${JSON.stringify({cmd:"shutdown"})}\n`)}catch{e.kill()}setTimeout(()=>{this.proc&&(this.proc.kill(),t())},5e3)}):Promise.resolve()}onStdout(e){this.buf+=e;let t=this.buf.indexOf("\n");for(;-1!==t;){const e=this.buf.slice(0,t);this.buf=this.buf.slice(t+1),this.handleEvent(n(e)),t=this.buf.indexOf("\n")}}handleEvent(e){if(!e)return;if("ready"===e.type)return this.ready=!0,void this.onReady?.();if("file"===e.type||"file_error"===e.type){const t=this.pendingFetch;if(!t||e.id!==t.id)return;return this.pendingFetch=null,void("file"===e.type?t.resolve(Buffer.from(e.data,"base64")):t.reject(new Error(e.message)))}const t=this.pending;if(t){if("done"===e.type){if(e.id!==t.id)return;const i=r(t.events.concat(e));return this.pending=null,void t.resolve(i)}t.events.push(e)}}}