icoa-cli 2.19.442 → 2.19.444

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{existsSync as e,mkdirSync as o,readFileSync as n,writeFileSync as l}from"node:fs";import{homedir as t}from"node:os";import{Interface as r,createInterface as a}from"node:readline";import{basename as s,dirname as c,isAbsolute as i,join as y,resolve as g}from"node:path";import chalk from"chalk";import{aienvPaths as d}from"../lib/aienv.js";import{editTextInEditor as u}from"../lib/editor-spawn.js";import{buildSshArgs as p,leaseConnectProblems as h,parseLeaseResponse as m,queueLine as w}from"../lib/gpu.js";import{shouldExecuteCell as f}from"../lib/ipynb-input.js";import{looksLikeMarkdown as b,renderMarkdown as k}from"../lib/md-term.js";import{NotebookKernel as v,buildRemoteBridgeCommand as $}from"../lib/kernel.js";import{getMainRl as x}from"../lib/main-rl.js";import{logCommand as P}from"../lib/logger.js";import{startLogSync as E,stopLogSync as G}from"../lib/log-sync.js";import{cellPreview as S,parseIpynb as U,parsePercentPy as N,parseRunRange as q,serializeIpynb as C,statusChar as A}from"../lib/notebook-doc.js";import{openFile as O}from"../lib/open-file.js";const j=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");export function registerIpynbCommand(m){m.command("ipynb").argument("[file]","notebook (.ipynb) or script (.py, split on # %%) to open").description("Open an in-terminal Python notebook (AI/ML — needs `aienv setup`)").action(async m=>{await async function(m){const j=d(t()),T=y(t(),".icoa","ipynb-out");if(_(),!e(j.python))return console.log(chalk.yellow(" The AI/ML environment is not set up yet.")),console.log(chalk.gray(" Run ")+chalk.bold.cyan("aienv setup")+chalk.gray(" first (one-time, ~300 MB).")),void console.log();const J=m?function(o){const l=i(o)?o:g(process.cwd(),o);if(!e(l))return{doc:{cells:[],path:l,dirty:!1},note:chalk.gray(" new notebook — will be created on ")+chalk.cyan("save")};try{const e=n(l,"utf8"),o=l.endsWith(".ipynb")?U(e):N(e);return{doc:{cells:o,path:l,dirty:!1},note:chalk.gray(" loaded ")+chalk.cyan(l)+chalk.gray(` — ${o.length} cell${1===o.length?"":"s"}. Type `)+chalk.cyan("cells")+chalk.gray(" to list them.")}}catch(e){return{doc:{cells:[],path:null,dirty:!1},note:chalk.yellow(` could not open ${l}: ${e instanceof Error?e.message:String(e)}`)+chalk.gray(" — starting an empty notebook.")}}}(m):null,z=J?J.doc:{cells:[],path:null,dirty:!1};let B=new v({venvPython:j.python,venvRoot:j.root}),F=null,H=W(z.path);process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await B.start()}catch{return console.log(chalk.red(" failed.")),console.log(chalk.gray(" Check the environment: ")+chalk.cyan("aienv status")),void console.log()}console.log(chalk.green(" ready.")),J&&console.log(J.note),console.log(chalk.bold.white(" ▶ Start here: ")+chalk.bold.cyan("run all")+chalk.gray(" — runs every cell (trains the baseline, writes submission.csv).")),console.log(chalk.gray(" You are already inside the notebook — do ")+chalk.bold.red("not")+chalk.gray(" type ")+chalk.cyan("python file.ipynb")+chalk.gray(". Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(chalk.gray(" Then: ")+chalk.cyan("cells")+chalk.gray(" list · ")+chalk.cyan("edit N")+chalk.gray(" edit · ")+chalk.cyan("add")+chalk.gray(" new cell · ")+chalk.cyan("save")+chalk.gray(" · ")+chalk.cyan("help")+chalk.gray(" full · ")+chalk.cyan("quit")),console.log(chalk.gray(" Or just type Python and press Enter (blocks continue until a blank line).")),console.log(chalk.bold.yellow(" 🧭 Lost at any point? Type ")+chalk.bold.cyan("guide")+chalk.bold.yellow(" — the full walkthrough + where you are.")),console.log();const Q=x(),X=null!==Q,Z=X?Q.listeners("line").slice():[];X&&Q.removeAllListeners("line");const ee=X?Q:a({input:process.stdin,output:process.stdout,terminal:!0}),oe=X?ee.prompt:null;X&&(ee.prompt=r.prototype.prompt),X||E();const ne=[];let le=!1,te=!1,re=!1;const ae=()=>{const e=F?"icoa ipynb ⚡gpu":"icoa ipynb";ee.setPrompt(chalk.bold.cyan(ne.length?`${e} ...> `:`${e}> `)),ee.prompt()};let se=()=>{};const ce=new Promise(e=>{se=e}),ie=async()=>{if(!F)return void console.log(chalk.gray(" not on a GPU kernel."));const e=D();await B.shutdown().catch(()=>{}),e&&await K("release",e),F=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped.")),await(async()=>{B=new v({venvPython:j.python,venvRoot:j.root}),process.stdout.write(chalk.gray(" Starting local kernel…"));try{await B.start(),console.log(chalk.green(" ready.")+chalk.gray(" (local CPU — variables were reset)"))}catch{console.log(chalk.red(" failed.")+chalk.gray(" Check ")+chalk.cyan("aienv status"))}})()},ye=async e=>{const[n,...r]=e.trim().split(/\s+/),a=(n??"").toLowerCase();"on"===a||"connect"===a?await(async()=>{if(F)return void console.log(chalk.gray(" already on the GPU kernel — ")+chalk.cyan("gpu status")+chalk.gray(" for time left."));const e=D();if(!e)return console.log(chalk.yellow(" No GPU access key found.")),void console.log(chalk.gray(" Save yours once with ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" (issued by your coach/ICOA)."));H||(H=W(z.path)),process.stdout.write(chalk.gray(" Requesting a GPU box…"));let n=await K("lease",e,H??void 0),r=0;for(;"queued"===n.state&&r<24;)0===r&&console.log(),process.stdout.write(`\r ${chalk.yellow(w(n))} `),await new Promise(e=>setTimeout(e,5e3)),n=await K("status",e),r++;if("queued"===n.state)return console.log(),console.log(chalk.yellow(" Still queued — your place is held server-side.")),void console.log(chalk.gray(" Keep working locally; ")+chalk.cyan("gpu on")+chalk.gray(" again in a few minutes."));if("ready"!==n.state)return void console.log(chalk.red(" failed.")+chalk.gray(` ${n.message??"no lease granted"}`));const a=h(n);if("local"!==n.transport||process.env.ICOA_GPU_SERVER||a.push("local transport from a non-dev broker"),a.length>0)return console.log(chalk.red(" rejected: ")+chalk.gray(a.join(", "))),void await K("release",e);const s=H?`${n.dataRoot}/${H}`:n.dataRoot,c=$(n.python,{ICOA_KAGGLE_DATA:s,ICOA_KAGGLE_OUT:n.outDir},n.outDir);let i;if("local"===n.transport)i={command:"/bin/sh",args:["-c",c]};else{const r=y(t(),".icoa","gpu","lease-key");try{o(y(t(),".icoa","gpu"),{recursive:!0}),l(r,n.keyPem,{mode:384})}catch{return console.log(chalk.red(" could not write the ssh key locally.")),void await K("release",e)}i={command:"ssh",args:p(n,r,c)}}const g=new v({spawnSpec:i,readyTimeoutMs:9e4});process.stdout.write(chalk.gray(" connecting…"));try{await g.start()}catch(o){return console.log(chalk.red(" connect failed.")),console.log(chalk.gray(` ${o instanceof Error?o.message:String(o)}`)),void await K("release",e)}await B.shutdown().catch(()=>{}),B=g,F=n;const d=Math.round((n.timeLeftSec??0)/60);console.log(chalk.bold.green(" ⚡ GPU connected.")),console.log(chalk.gray(` Cells now run on the GPU box · ${d}m left on this lease.`)),console.log(chalk.gray(" Variables were reset — ")+chalk.cyan("run all")+chalk.gray(" to retrain there.")),H&&console.log(chalk.gray(` Dataset is already on the box (${H}) — same cells, no edits.`)),console.log(chalk.gray(" When done: ")+chalk.cyan("download")+chalk.gray(" your submission, then ")+chalk.cyan("gpu off")+chalk.gray("."))})():"off"===a||"disconnect"===a?await ie():"status"===a||""===a?await(async()=>{const e=D();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const o=await K("status",e);if("ready"===o.state){const e=Math.round((o.timeLeftSec??0)/60);console.log(chalk.green(` ⚡ GPU lease active · ${e}m left`)+chalk.gray(F?" (this notebook is connected)":" (not connected here — gpu on)"))}else"queued"===o.state?console.log(chalk.yellow(` ${w(o)}`)):"none"===o.state?console.log(chalk.gray(" no GPU lease — ")+chalk.cyan("gpu on")+chalk.gray(" to request one.")):console.log(chalk.yellow(` ${o.message??"GPU broker not reachable"}`))})():"queue"===a||"q"===a?await(async()=>{const e=D();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));let o=null;try{const n=await fetch(`${R()}/api/icoa/gpu/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)}),l=await n.json();o=l.data??l}catch{o=null}if(!o||"object"!=typeof o)return void console.log(chalk.yellow(" GPU queue not reachable right now — try again in a moment."));const n="number"==typeof o.boxes?o.boxes:0,l="number"==typeof o.free?o.free:0,t=Array.isArray(o.running)?o.running:[],r=Array.isArray(o.waiting)?o.waiting:[];console.log(),console.log(chalk.bold.cyan(" GPU queue")+chalk.gray(` · ${n} box${1===n?"":"es"} · ${l} free`)),console.log(chalk.bold.white(" ▶ running now:")),0===t.length&&console.log(chalk.gray(" (idle — gpu on takes a box immediately)"));for(const e of t){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.time_left_sec?e.time_left_sec:0,l=Math.floor(n/60),t=String(n%60).padStart(2,"0"),r=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(" ")+chalk.white(o.padEnd(8))+chalk.gray(` ${l}:${t} left`)+r)}console.log(chalk.bold.white(` ⏳ waiting (${r.length}):`)),0===r.length&&console.log(chalk.gray(" (nobody queued)"));for(const e of r){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.position?e.position:"?",l=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(` #${n} `)+chalk.white(o.padEnd(8))+l)}console.log()})():"key"===a?(e=>{const n=e.trim();if(n)try{o(y(t(),".icoa"),{recursive:!0}),l(M(),`${n}\n`,{mode:384}),console.log(chalk.green(" ✓ GPU key saved")+chalk.gray(" — ")+chalk.cyan("gpu on")+chalk.gray(" when you need the box."))}catch{console.log(chalk.red(" could not save the key")+chalk.gray(` (${M()})`))}else console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu key <your-key>"))})(r.join(" ")):console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu on")+chalk.yellow(" · ")+chalk.cyan("gpu off")+chalk.yellow(" · ")+chalk.cyan("gpu status")+chalk.yellow(" · ")+chalk.cyan("gpu queue")+chalk.yellow(" · ")+chalk.cyan("gpu key <k>"))},ge=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>z.cells.length?(console.log(0===z.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${z.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:z.cells[o-1],idx:o}},de=(e,o)=>!(!e.result||e.result.ok)&&!(!e.result.outputs.some(e=>"error"===e.kind&&"SyntaxError"===e.ename)||!b(e.source)||(console.log(chalk.gray(" ✎ looks like text/markdown, not Python — ")+chalk.cyan(`md ${o}`)+chalk.gray(" converts this cell to markdown (new note: ")+chalk.cyan("add md")+chalk.gray(").")),0)),ue=async t=>{if(t.trim()&&P(`ipynb: ${t.trim()}`),te)return void(t.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));let r=t.trim();if(0===ne.length&&/^icoa\s+[a-z/]/i.test(r)&&(r=r.replace(/^icoa\s+/i,"")),0===ne.length){const t=r.split(/\s+/),a=(t[0]??"").toLowerCase(),d=r.slice(t[0]?.length??0).trim();if("quit"!==a&&"exit"!==a&&"q"!==a&&(re=!1),"quit"===a||"exit"===a||"back"===a||"q"===a||"menu"===a)return z.dirty&&!re?(re=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void ae()):void await(async()=>{if(ee.removeAllListeners("line"),X||G(),console.log(),F){const e=D();e&&await K("release",e),F=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await B.shutdown().catch(()=>{}),X){oe&&(ee.prompt=oe);for(const e of Z)ee.on("line",e);ee.prompt(),se()}else se(),ee.close()})();if("clear"===a||"cls"===a)return console.clear(),_(),void ae();if("restart"===a)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await B.shutdown().catch(()=>{});try{await B.start(),console.log(chalk.green(" fresh kernel ready.")+chalk.gray(" (all variables cleared)"))}catch{console.log(chalk.red(" restart failed.")+chalk.gray(" Leave and re-enter the notebook."))}})(),void ae();if("help"===a||"?"===a)return console.log(),console.log(chalk.bold.white(" Notebook commands")),console.log(chalk.cyan(" cells")+chalk.gray(" list cells (○ not run · ✓ ok · ✗ error)")),console.log(chalk.cyan(" show N")+chalk.gray(" print cell N source + outputs")),console.log(chalk.cyan(" edit N")+chalk.gray(" edit cell N in your editor ($EDITOR, default vi)")),console.log(chalk.cyan(" add")+chalk.gray(" write a new Python cell in your editor")),console.log(chalk.cyan(" add md")+chalk.gray(" write a markdown/text cell (notes, headings)")),console.log(chalk.cyan(" md N / py N")+chalk.gray(" convert cell N to markdown / Python")),console.log(chalk.cyan(" del N")+chalk.gray(" delete cell N")),console.log(chalk.cyan(" run N")+chalk.gray(" run cell N — markdown cells render (also: run 2-5, run all)")),console.log(chalk.cyan(" save [file]")+chalk.gray(" save as a real .ipynb")),console.log(chalk.cyan(" restart")+chalk.gray(" restart the kernel (wipes all variables)")),console.log(chalk.cyan(" gpu on/off")+chalk.gray(" run cells on a leased GPU box (dataset pre-mounted)")),console.log(chalk.cyan(" gpu status")+chalk.gray(" your lease/queue · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on the GPU now")),console.log(chalk.cyan(" gpu key <k>")+chalk.gray(" save your access key")),console.log(chalk.cyan(" download")+chalk.gray(" pull submission.csv from the GPU box to this machine")),console.log(chalk.cyan(" open")+chalk.gray(" reopen the last figure in your image viewer")),console.log(chalk.cyan(" clear")+chalk.gray(" clear the screen · ")+chalk.cyan("quit")+chalk.gray(" leave")),console.log(chalk.gray(" Everything else runs as Python in the persistent kernel (and is appended as a cell).")),console.log(),void ae();if("guide"===a||"/guide"===a)return(()=>{const o=z.path?c(z.path):process.cwd(),l=W(z.path);let t="",r=!1;try{const e=JSON.parse(n(y(o,"meta.json"),"utf-8"));t=e.judge??"",r=!0===e.needs_gpu}catch{}const a=z.cells.filter(e=>null!==e.result).length,i=e(y(o,"submission.csv"));console.log(),console.log(chalk.bold.white(" ═══ 📖 Notebook guide ═══")),console.log(),console.log(chalk.gray(" Where you are: ")+chalk.white(z.path?s(z.path):"new empty notebook")+chalk.gray(` · ${z.cells.length} cells (${a} run) · submission.csv: `)+(i?chalk.green("written ✓"):chalk.yellow("not yet — run all"))),F?console.log(chalk.gray(" ⚡ GPU: ")+chalk.green("connected")+chalk.gray(" — ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on · ")+chalk.cyan("download <file>")+chalk.gray(" pull results")):r&&console.log(chalk.gray(" ⚡ GPU task, not connected — ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.cyan("gpu on")+chalk.gray(" · ")+chalk.cyan("gpu queue")+chalk.gray(" shows who is on")),console.log(),console.log(chalk.bold.white(" The loop:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan("run all")+chalk.gray(" — trains the baseline, writes submission.csv")),l&&"icoa-holdout"===t?(console.log(chalk.gray(" 2. ")+chalk.cyan("quit")+chalk.gray(", then ")+chalk.cyan(`kaggle submit ${l}`)+chalk.gray(" — scored + ranked on the live board")),console.log(chalk.gray(" 3. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat your score."))):l&&r?(console.log(chalk.gray(" 2. ")+chalk.cyan("download <file>")+chalk.gray(" — pull your results (submission.csv / predictions.zip) off the GPU box")),console.log(chalk.gray(" 3. submit on kaggle.com — the notebook's final cell has the exact steps")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):l?(console.log(chalk.gray(" 2. ")+chalk.cyan("quit")+chalk.gray(", then ")+chalk.cyan(`kaggle check ${l}`)+chalk.gray(" — verifies the file format")),console.log(chalk.gray(" 3. upload submission.csv on kaggle.com — read your public score")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):console.log(chalk.gray(" 2. edit cells (")+chalk.cyan("edit N")+chalk.gray("), re-run, ")+chalk.cyan("save")+chalk.gray(" — this is a free notebook.")),console.log(),console.log(chalk.bold.white(" If it looks stuck:")),console.log(chalk.gray(" · prompt shows ")+chalk.cyan("...>")+chalk.gray(" → you are inside a code block. Press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(".")),console.log(chalk.gray(" · never type ")+chalk.cyan("python file.ipynb")+chalk.gray(" here — you are already inside. Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(),console.log(chalk.bold.white(" 🤝 AI help: ")+chalk.gray("split the screen ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" · right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" then ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" — live Gemma 3")),console.log(chalk.gray(" All commands: ")+chalk.cyan("help")+chalk.gray(" · leave: ")+chalk.cyan("quit")),console.log()})(),void ae();if("python"===a||"python3"===a)return console.log(chalk.gray(" You're already inside the notebook kernel — no need to run python.")),console.log(chalk.gray(" Type ")+chalk.bold.cyan("run all")+chalk.gray(" to run every cell, or ")+chalk.cyan("guide")+chalk.gray(" for the basics.")),void ae();if("open"===a)return V&&O(V)?console.log(chalk.gray(" reopening ")+chalk.cyan(V)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void ae();if("cells"===a||"ls"===a)return(()=>{if(0===z.cells.length)return void console.log(chalk.gray(" no cells yet — type Python, or ")+chalk.cyan("add")+chalk.gray(" to write one in your editor."));console.log();const e=Math.max(20,(process.stdout.columns??80)-12);z.cells.forEach((o,n)=>{const l=A(o),t="✓"===l?chalk.green(l.padEnd(2)):"✗"===l?chalk.red(l.padEnd(2)):"md"===l?chalk.magenta(l.padEnd(2)):chalk.gray(l.padEnd(2));console.log(`${chalk.cyan(String(n+1).padStart(4))} ${t} ${chalk.white(S(o,e))}`)}),console.log(),console.log(chalk.gray(" ")+chalk.cyan("show N")+chalk.gray(" · ")+chalk.cyan("edit N")+chalk.gray(" · ")+chalk.cyan("run N")+chalk.gray(" · ")+chalk.cyan("run all"))})(),void ae();if("show"===a)return(e=>{const o=ge(e);if(o){if(console.log(),console.log(chalk.gray(` ── cell ${o.idx} ${"markdown"===o.cell.kind?"(markdown) ":""}──`)),"markdown"===o.cell.kind){for(const e of k(o.cell.source))console.log(e);console.log(chalk.gray(" (rendered — ")+chalk.cyan(`edit ${o.idx}`)+chalk.gray(" for the raw source)"))}else for(const e of o.cell.source.split("\n"))console.log(chalk.white(` ${e}`));o.cell.result&&(console.log(chalk.gray(" ── output ──")),Y(o.cell.result,T)),console.log()}})(d),void ae();if("edit"===a)return(e=>{const o=ge(e);if(!o)return;ee.pause();const n=u(o.cell.source,"markdown"===o.cell.kind?".md":".py");if(ee.resume(),null===n)return void console.log(chalk.yellow(" editor cancelled or failed — cell unchanged.")+chalk.gray(" (set $EDITOR to choose your editor)"));const l=n.replace(/\s+$/,"");l!==o.cell.source?(o.cell.source=l,o.cell.result=null,o.cell.rawOutputs=void 0,o.cell.rawExecCount=void 0,z.dirty=!0,console.log(chalk.green(` ✓ cell ${o.idx} updated`)+chalk.gray(" — ")+chalk.cyan(`run ${o.idx}`)+chalk.gray(" to execute."))):console.log(chalk.gray(" no changes."))})(d),void ae();if("add"===a)return(e=>{const o=e.trim().toLowerCase(),n="md"===o||"markdown"===o||"text"===o||"txt"===o;if(o&&!n&&"py"!==o&&"code"!==o&&"python"!==o)return void console.log(chalk.yellow(" usage: ")+chalk.cyan("add")+chalk.yellow(" (Python cell) · ")+chalk.cyan("add md")+chalk.yellow(" (markdown/text cell)"));ee.pause();const l=u(n?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",n?".md":".py");ee.resume();const t=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");t?(z.cells.push({kind:n?"markdown":"code",source:t,result:null}),z.dirty=!0,console.log(chalk.green(` ✓ added ${n?"markdown ":""}cell ${z.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${z.cells.length}`)+chalk.gray(n?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(d),void ae();if("del"===a||"delete"===a)return(e=>{const o=ge(e);o&&(z.cells.splice(o.idx-1,1),z.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${z.cells.length} left.`)+(o.idx<=z.cells.length?chalk.yellow(" ⚠ 后面的 cell 号已顺移")+chalk.gray(" — ")+chalk.cyan("cells")+chalk.gray(" 重看一眼"):"")))})(d),void ae();if(("md"===a||"py"===a)&&/^\d+$/.test(d))return((e,o)=>{const n=ge(e);if(!n)return;const l="markdown"===o?"markdown":"Python";n.cell.kind!==o?(n.cell.kind=o,n.cell.result=null,n.cell.rawOutputs=void 0,n.cell.rawExecCount=void 0,z.dirty=!0,console.log(chalk.green(` ✓ cell ${n.idx} → ${l}`)+chalk.gray(" — ")+chalk.cyan(`run ${n.idx}`)+chalk.gray("markdown"===o?" to render it.":" to execute."))):console.log(chalk.gray(` cell ${n.idx} is already ${l}.`))})(d,"md"===a?"markdown":"code"),void ae();if("gpu"===a)return te=!0,await ye(d),te=!1,void ae();if("download"===a||"dl"===a)return te=!0,await(async e=>{if(!F)return void console.log(chalk.gray(" local kernel — your files are already on this machine (no download needed)."));const n=e.trim()||"submission.csv",t=n.startsWith("/")?n:`${F.outDir}/${n}`;let r;try{r=await B.fetchFile(t)}catch(e){return console.log(chalk.yellow(` could not fetch ${t}: `)+chalk.gray(e instanceof Error?e.message:String(e))),void console.log(chalk.gray(" (run the submission cell first — it writes into the GPU workspace)"))}const a=H?y(process.cwd(),"icoa-kaggle",H):process.cwd(),c=y(a,s(n));try{o(a,{recursive:!0}),l(c,r)}catch{return void console.log(chalk.yellow(" could not write the file here — check directory permissions."))}console.log(chalk.green(" ✓ downloaded ")+chalk.white(c)+chalk.gray(` (${r.length} bytes)`)),H&&"submission.csv"===s(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${H}`)+chalk.gray(" — then upload on Kaggle yourself."))})(d),te=!1,void ae();if("run"===a)return te=!0,await(async e=>{const o=q(e,z.cells.length);if(o)for(const e of o){const n=z.cells[e-1];if("markdown"!==n.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(S(n,50))+chalk.gray(" ──"));try{n.result=await B.execute(n.source)}catch(e){return console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),void L()}if(z.dirty=!0,Y(n.result,T),de(n,e),!n.result.ok){const n=e!==o[o.length-1];return console.log(chalk.yellow(` ✗ cell ${e} raised${n?" — stopping here.":"."}`)+chalk.gray(" Fix it (")+chalk.cyan(`edit ${e}`)+chalk.gray(") and re-run.")),void L()}}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of k(n.source))console.log(e);console.log()}}else console.log(0===z.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(" usage: ")+chalk.cyan("run 3")+chalk.yellow(" · ")+chalk.cyan("run 1-5")+chalk.yellow(" · ")+chalk.cyan("run all"))})(d),te=!1,void ae();if("save"===a)return(e=>{if(0===z.cells.length)return void console.log(chalk.yellow(" nothing to save — the notebook is empty."));let o;o=e.trim()?i(e.trim())?e.trim():g(process.cwd(),e.trim()):z.path?z.path.endsWith(".ipynb")?z.path:`${z.path.replace(/\.[^./]+$/,"")}.ipynb`:g(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");try{l(o,C(z.cells)),z.path=o,z.dirty=!1,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${z.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(d),void ae();if(""===r)return void ae()}if(ne.length>0&&I.has(r.toLowerCase()))return console.log(chalk.gray(" (⏸ you are inside a multi-line block — press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(" to run it; then ")+chalk.cyan(r.toLowerCase().replace(/^\//,""))+chalk.gray(" will work. This line was not added to the block.)")),void ae();if(ne.push(t),!f(ne))return 1!==ne.length||le||(le=!0,console.log(chalk.gray(" (multi-line block started — keep typing; an empty line runs it)"))),void ae();const a=ne.join("\n").replace(/\s+$/,"");if(ne.length=0,""!==a.trim()){te=!0;try{const e=await B.execute(a);z.cells.push({kind:"code",source:a,result:e}),z.dirty=!0,Y(e,T);const o=de(z.cells[z.cells.length-1],z.cells.length);e.ok||o||L()}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),L()}te=!1,ae()}else ae()};ee.on("line",e=>{ue(e)}),X||ee.on("close",async()=>{await B.shutdown().catch(()=>{}),process.exit(0)}),ae(),await ce}(m)})}function _(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}const I=new Set(["guide","/guide","help","?","quit","exit","back","menu","cells","run all"]);function L(){console.log(chalk.gray(" 🧭 stuck? type ")+chalk.cyan("guide")+chalk.gray(" for the basics · ")+chalk.cyan("help")+chalk.gray(" for every command."))}const T="https://practice.icoa2026.au";function R(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):T}function M(){return y(t(),".icoa","gpu-key")}function D(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return n(M(),"utf-8").trim()||null}catch{return null}}async function K(e,o,n){try{const l=await fetch(`${R()}/api/icoa/gpu/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n?{key:o,task:n}:{key:o}),signal:AbortSignal.timeout(2e4)});return m(await l.json())}catch{return{state:"error",message:"GPU broker not reachable"}}}function W(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let J=0,V=null;function Y(e,o){for(const n of e.outputs)if("stream"===n.kind){const e=n.text.replace(/\n$/,"");if(0===e.length)continue;console.log("stderr"===n.name?chalk.yellow(e):chalk.white(e))}else if("result"===n.kind)console.log(chalk.cyan(` Out[${e.execCount??"*"}]: `)+chalk.white(n.text));else if("error"===n.kind){console.log(chalk.bold.red(` ${n.ename}: ${n.evalue}`));for(const e of n.traceback)console.log(chalk.gray(` ${e.replace(j,"")}`))}else"display"===n.kind&&z(n.data,o)}function z(e,n){if(e["image/png"])try{o(n,{recursive:!0}),J+=1;const t=y(n,`figure-${J}.png`);return l(t,Buffer.from(e["image/png"],"base64")),V=t,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(t)),void(O(t)?console.log(chalk.gray(" opening in your image viewer… (type ")+chalk.cyan("open")+chalk.gray(" to reopen)")):console.log(chalk.gray(" open it with your file browser (inline images need a graphical viewer).")))}catch{}e["text/plain"]&&console.log(chalk.white(` ${e["text/plain"]}`))}
1
+ import{existsSync as e,mkdirSync as o,readFileSync as n,writeFileSync as l}from"node:fs";import{homedir as t}from"node:os";import{Interface as r,createInterface as a}from"node:readline";import{basename as s,dirname as c,isAbsolute as i,join as g,resolve as y}from"node:path";import chalk from"chalk";import{aienvPaths as d}from"../lib/aienv.js";import{AI_MAX_INPUT_CHARS as u,askIoaiOneShot as h}from"./ai4ioai.js";import{getConfig as p}from"../lib/config.js";import{editTextInEditor as m}from"../lib/editor-spawn.js";import{buildSshArgs as f,leaseConnectProblems as w,parseLeaseResponse as b,queueLine as k}from"../lib/gpu.js";import{shouldExecuteCell as v}from"../lib/ipynb-input.js";import{looksLikeMarkdown as $,renderMarkdown as x}from"../lib/md-term.js";import{NotebookKernel as P,buildRemoteBridgeCommand as E}from"../lib/kernel.js";import{getMainRl as G}from"../lib/main-rl.js";import{logCommand as S}from"../lib/logger.js";import{startLogSync as A,stopLogSync as N}from"../lib/log-sync.js";import{cellPreview as j,parseIpynb as q,parsePercentPy as U,parseRunRange as I,serializeIpynb as O,statusChar as C}from"../lib/notebook-doc.js";import{openFile as _}from"../lib/open-file.js";const L=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");function T(){return(p().language||"en").toLowerCase().startsWith("zh")}export function registerIpynbCommand(p){p.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 p=>{await async function(p){const b=d(t()),K=g(t(),".icoa","ipynb-out");if(R(),!e(b.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 V=p?function(o){const l=i(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")?q(e):U(e);return{doc:{cells:o,path:l,dirty:!1},note:chalk.gray(" loaded ")+chalk.cyan(l)+chalk.gray(` — ${o.length} cell${1===o.length?"":"s"}. Type `)+chalk.cyan("cells")+chalk.gray(" to list them.")}}catch(e){return{doc:{cells:[],path:null,dirty:!1},note:chalk.yellow(` could not open ${l}: ${e instanceof Error?e.message:String(e)}`)+chalk.gray(" — starting an empty notebook.")}}}(p):null,Q=V?V.doc:{cells:[],path:null,dirty:!1};let X=new P({venvPython:b.python,venvRoot:b.root}),Z=null,ee=z(Q.path);process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await X.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.")),V&&console.log(V.note),console.log(chalk.bold.white(" ▶ Start here: ")+chalk.bold.cyan("run all")+chalk.gray(" — runs every cell (trains the baseline, writes submission.csv).")),console.log(chalk.gray(" You are already inside the notebook — do ")+chalk.bold.red("not")+chalk.gray(" type ")+chalk.cyan("python file.ipynb")+chalk.gray(". Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(chalk.gray(" Then: ")+chalk.cyan("cells")+chalk.gray(" list · ")+chalk.cyan("edit N")+chalk.gray(" edit · ")+chalk.cyan("add")+chalk.gray(" new cell · ")+chalk.cyan("save")+chalk.gray(" · ")+chalk.cyan("help")+chalk.gray(" full · ")+chalk.cyan("quit")),console.log(chalk.gray(" Or just type Python and press Enter (blocks continue until a blank line).")),console.log(chalk.bold.yellow(" 🧭 Lost at any point? Type ")+chalk.bold.cyan("guide")+chalk.bold.yellow(" — the full walkthrough + where you are.")),console.log();const oe=G(),ne=null!==oe,le=ne?oe.listeners("line").slice():[];ne&&oe.removeAllListeners("line");const te=ne?oe:a({input:process.stdin,output:process.stdout,terminal:!0}),re=ne?te.prompt:null;ne&&(te.prompt=r.prototype.prompt),ne||A();const ae=[];let se=!1,ce=!1,ie=!1;const ge=()=>{const e=Z?"icoa ipynb ⚡gpu":"icoa ipynb";te.setPrompt(chalk.bold.cyan(ae.length?`${e} ...> `:`${e}> `)),te.prompt()};let ye=()=>{};const de=new Promise(e=>{ye=e}),ue=async()=>{if(!Z)return void console.log(chalk.gray(" not on a GPU kernel."));const e=J();await X.shutdown().catch(()=>{}),e&&await Y("release",e),Z=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped.")),await(async()=>{X=new P({venvPython:b.python,venvRoot:b.root}),process.stdout.write(chalk.gray(" Starting local kernel…"));try{await X.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"))}})()},he=async e=>{const[n,...r]=e.trim().split(/\s+/),a=(n??"").toLowerCase();"on"===a||"connect"===a?await(async()=>{if(Z)return void console.log(chalk.gray(" already on the GPU kernel — ")+chalk.cyan("gpu status")+chalk.gray(" for time left."));const e=J();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)."));ee||(ee=z(Q.path)),process.stdout.write(chalk.gray(" Requesting a GPU box…"));let n=await Y("lease",e,ee??void 0),r=0;for(;"queued"===n.state&&r<24;)0===r&&console.log(),process.stdout.write(`\r ${chalk.yellow(k(n))} `),await new Promise(e=>setTimeout(e,5e3)),n=await Y("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=w(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 Y("release",e);const s=ee?`${n.dataRoot}/${ee}`:n.dataRoot,c=E(n.python,{ICOA_KAGGLE_DATA:s,ICOA_KAGGLE_OUT:n.outDir},n.outDir);let i;if("local"===n.transport)i={command:"/bin/sh",args:["-c",c]};else{const r=g(t(),".icoa","gpu","lease-key");try{o(g(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 Y("release",e)}i={command:"ssh",args:f(n,r,c)}}const y=new P({spawnSpec:i,readyTimeoutMs:9e4});process.stdout.write(chalk.gray(" connecting…"));try{await y.start()}catch(o){return console.log(chalk.red(" connect failed.")),console.log(chalk.gray(` ${o instanceof Error?o.message:String(o)}`)),void await Y("release",e)}await X.shutdown().catch(()=>{}),X=y,Z=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.")),ee&&console.log(chalk.gray(` Dataset is already on the box (${ee}) — 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 ue():"status"===a||""===a?await(async()=>{const e=J();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const o=await Y("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(Z?" (this notebook is connected)":" (not connected here — gpu on)"))}else"queued"===o.state?console.log(chalk.yellow(` ${k(o)}`)):"none"===o.state?console.log(chalk.gray(" no GPU lease — ")+chalk.cyan("gpu on")+chalk.gray(" to request one.")):console.log(chalk.yellow(` ${o.message??"GPU broker not reachable"}`))})():"queue"===a||"q"===a?await(async()=>{const e=J();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));let o=null;try{const n=await fetch(`${B()}/api/icoa/gpu/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)}),l=await n.json();o=l.data??l}catch{o=null}if(!o||"object"!=typeof o)return void console.log(chalk.yellow(" GPU queue not reachable right now — try again in a moment."));const n="number"==typeof o.boxes?o.boxes:0,l="number"==typeof o.free?o.free:0,t=Array.isArray(o.running)?o.running:[],r=Array.isArray(o.waiting)?o.waiting:[];console.log(),console.log(chalk.bold.cyan(" GPU queue")+chalk.gray(` · ${n} box${1===n?"":"es"} · ${l} free`)),console.log(chalk.bold.white(" ▶ running now:")),0===t.length&&console.log(chalk.gray(" (idle — gpu on takes a box immediately)"));for(const e of t){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.time_left_sec?e.time_left_sec:0,l=Math.floor(n/60),t=String(n%60).padStart(2,"0"),r=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(" ")+chalk.white(o.padEnd(8))+chalk.gray(` ${l}:${t} left`)+r)}console.log(chalk.bold.white(` ⏳ waiting (${r.length}):`)),0===r.length&&console.log(chalk.gray(" (nobody queued)"));for(const e of r){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.position?e.position:"?",l=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(` #${n} `)+chalk.white(o.padEnd(8))+l)}console.log()})():"key"===a?(e=>{const n=e.trim();if(n)try{o(g(t(),".icoa"),{recursive:!0}),l(W(),`${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(` (${W()})`))}else console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu key <your-key>"))})(r.join(" ")):console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu on")+chalk.yellow(" · ")+chalk.cyan("gpu off")+chalk.yellow(" · ")+chalk.cyan("gpu status")+chalk.yellow(" · ")+chalk.cyan("gpu queue")+chalk.yellow(" · ")+chalk.cyan("gpu key <k>"))},pe=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>Q.cells.length?(console.log(0===Q.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${Q.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:Q.cells[o-1],idx:o}},me=(e,o)=>{if(e.length<=o)return e;const n=Math.floor(.6*o);return`${e.slice(0,n)}\n…(${e.length-o} chars elided)…\n${e.slice(-(o-n))}`};let fe=!1;const we=async e=>{const o=e.trim().split(/\s+/).filter(Boolean),l=o.length>0&&/^\d+$/.test(o[0]),t=(l?o.slice(1):o).join(" ").trim(),r=l?Number(o[0]):(()=>{for(let e=Q.cells.length-1;e>=0;e--)if((Q.cells[e].result?.outputs??[]).some(e=>"error"===e.kind))return e+1;return null})()??Q.cells.length;if(0===Q.cells.length)return void console.log(chalk.yellow(" 还没有 cell —— 先写点代码,或用 ")+chalk.cyan("add"));const a=pe(String(r));if(!a)return;if("markdown"===a.cell.kind)return void console.log(chalk.yellow(` cell ${a.idx} 是 markdown —— 挑一个代码格,比如 `)+chalk.cyan("ai 2"));const s=(e=>{const o=[];for(const n of e.result?.outputs??[])"stream"===n.kind||"result"===n.kind?o.push(n.text):"error"===n.kind&&(o.push(`${n.ename}: ${n.evalue}`),o.push(n.traceback.map(e=>e.replace(L,"")).join("\n")));return o.join("\n").replace(L,"").replace(/\n{3,}/g,"\n\n").trim()})(a.cell),i=(()=>{if(!Q.path||!z(Q.path))return"";try{const e=JSON.parse(n(g(c(Q.path),"meta.json"),"utf-8")),o=[e.title,e.metric?`metric: ${e.metric}`:"",e.description].filter(Boolean).join("\n");return me(o,350)}catch{return""}})(),y=T(),d=y?"你在帮一个 IOAI 选手调试 notebook。先说清楚这一格为什么会这样,再给出最小改动。用中文回答,简洁,给可直接粘回去的代码。":"You are helping an IOAI contestant debug a notebook cell. Say why it behaves this way, then give the smallest fix. Be concise and give code that can be pasted straight back.",p=d.length+t.length+120,m=Math.max(400,u-p-i.length),f=me(a.cell.source,Math.floor(.6*m)),w=s?($=s,P=m-f.length,$.length<=P?$:`…(${$.length-P} chars elided)…\n${$.slice(-P)}`):"",b=[d,i?`\n[task]\n${i}`:"",`\n[cell ${a.idx} code]\n${f}`,w?`\n[cell ${a.idx} output]\n${w}`:"\n(this cell has not been run yet)",t?`\n[question]\n${t}`:""].filter(Boolean).join("\n"),k=b.includes("chars elided"),v=y;var $,P;console.log(),fe||(fe=!0,console.log(chalk.gray(" ")+chalk.bold.white("IOAI 2026 ")+chalk.white("Gemma 3n E4B")+chalk.gray(" (32k) · ")+chalk.white(T()?"单轮无记忆":"single-turn, no memory")+chalk.gray(" · ")+chalk.white(`${u} ${T()?"字符/条":"chars/message"}`)+chalk.gray(" · ")+chalk.white(T()?"1000 token/回复":"1000 tokens/reply")),console.log(chalk.gray(T()?" —— 现场就是这个模型和这几条上限,在这里练的手感能原样带过去。":" — the onsite model and the onsite limits, so the habit transfers as-is."))),console.log(chalk.gray(` → cell ${a.idx} · ${b.length}/${u} chars`)+chalk.gray(v?" · 单轮(竞赛档模型)":" · single-turn (contest model)")+(s?chalk.gray(v?" · 含输出":" · output included"):"")+(k?chalk.yellow(v?" ⚠ 上下文被裁过,加一句具体问题会更准":" ⚠ context trimmed — a specific question helps"):"")),S(`ipynb: ai ${a.idx}${t?` — ${t}`:""}`);const E=await h(b);if(console.log(),!E.ok)return console.log(chalk.yellow(" AI 现在连不上 —— ")+chalk.gray(E.text)),console.log(chalk.gray(" 过一会儿再试,或用 ")+chalk.cyan("ai4ioai")+chalk.gray(" 单开一个会话。")),void console.log();for(const e of x(E.text))console.log(e);console.log(),console.log(chalk.gray(" ")+chalk.cyan(`ai ${a.idx} ${v?"<你的问题>":"<your question>"}`)+chalk.gray(v?" 追问 · ":" follow up · ")+chalk.cyan(`edit ${a.idx}`)+chalk.gray(v?" 改这一格 · ":" edit it · ")+chalk.cyan(`run ${a.idx}`)+chalk.gray(v?" 再跑一次":" run it again")),console.log(chalk.gray(v?" 这是调试助手(超限自动裁剪);想练现场那堵墙用 ":" This is the debugging aid (it trims to fit). To train against the real wall: ")+chalk.cyan("ai4ioai")),console.log()},be=(e,o)=>!(!e.result||e.result.ok)&&!(!e.result.outputs.some(e=>"error"===e.kind&&"SyntaxError"===e.ename)||!$(e.source)||(console.log(chalk.gray(" ✎ looks like text/markdown, not Python — ")+chalk.cyan(`md ${o}`)+chalk.gray(" converts this cell to markdown (new note: ")+chalk.cyan("add md")+chalk.gray(").")),0)),ke=async t=>{if(t.trim()&&S(`ipynb: ${t.trim()}`),ce)return void(t.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));let r=t.trim();if(0===ae.length&&/^icoa\s+[a-z/]/i.test(r)&&(r=r.replace(/^icoa\s+/i,"")),0===ae.length){const t=r.split(/\s+/),a=(t[0]??"").toLowerCase(),d=r.slice(t[0]?.length??0).trim();if("quit"!==a&&"exit"!==a&&"q"!==a&&(ie=!1),"quit"===a||"exit"===a||"back"===a||"q"===a||"menu"===a)return Q.dirty&&!ie?(ie=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void ge()):void await(async()=>{if(te.removeAllListeners("line"),ne||N(),console.log(),Z){const e=J();e&&await Y("release",e),Z=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await X.shutdown().catch(()=>{}),ne){re&&(te.prompt=re);for(const e of le)te.on("line",e);te.prompt(),ye()}else ye(),te.close()})();if("clear"===a||"cls"===a)return console.clear(),R(),void ge();if("restart"===a)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await X.shutdown().catch(()=>{});try{await X.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 ge();if("help"===a||"?"===a)return console.log(),console.log(chalk.bold.white(" Notebook commands")),console.log(chalk.cyan(" cells")+chalk.gray(" list cells (○ not run · ✓ ok · ✗ error)")),console.log(chalk.cyan(" show N")+chalk.gray(" print cell N source + outputs")),console.log(chalk.cyan(" edit N")+chalk.gray(" edit cell N in your editor ($EDITOR, default vi)")),console.log(chalk.cyan(" add")+chalk.gray(" write a new Python cell in your editor")),console.log(chalk.cyan(" add md")+chalk.gray(" write a markdown/text cell (notes, headings)")),console.log(chalk.cyan(" md N / py N")+chalk.gray(" convert cell N to markdown / Python")),console.log(chalk.cyan(" del N")+chalk.gray(" delete cell N")),console.log(chalk.cyan(" run N")+chalk.gray(" run cell N — markdown cells render (also: run 2-5, run all)")),console.log(chalk.cyan(" ai [N] [问题]")+chalk.gray(T()?" 问 AI 这一格(默认最近报错的那格;带上代码和 traceback)":" ask the AI about a cell (defaults to the last one that errored)")),console.log(chalk.cyan(" save [file]")+chalk.gray(" save as a real .ipynb")),console.log(chalk.cyan(" restart")+chalk.gray(" restart the kernel (wipes all variables)")),console.log(chalk.cyan(" gpu on/off")+chalk.gray(" run cells on a leased GPU box (dataset pre-mounted)")),console.log(chalk.cyan(" gpu status")+chalk.gray(" your lease/queue · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on the GPU now")),console.log(chalk.cyan(" gpu key <k>")+chalk.gray(" save your access key")),console.log(chalk.cyan(" download")+chalk.gray(" pull submission.csv from the GPU box to this machine")),console.log(chalk.cyan(" open")+chalk.gray(" reopen the last figure in your image viewer")),console.log(chalk.cyan(" clear")+chalk.gray(" clear the screen · ")+chalk.cyan("quit")+chalk.gray(" leave")),console.log(chalk.gray(" Everything else runs as Python in the persistent kernel (and is appended as a cell).")),console.log(),void ge();if("guide"===a||"/guide"===a)return(()=>{const o=Q.path?c(Q.path):process.cwd(),l=z(Q.path);let t="",r=!1;try{const e=JSON.parse(n(g(o,"meta.json"),"utf-8"));t=e.judge??"",r=!0===e.needs_gpu}catch{}const a=Q.cells.filter(e=>null!==e.result).length,i=e(g(o,"submission.csv"));console.log(),console.log(chalk.bold.white(" ═══ 📖 Notebook guide ═══")),console.log(),console.log(chalk.gray(" Where you are: ")+chalk.white(Q.path?s(Q.path):"new empty notebook")+chalk.gray(` · ${Q.cells.length} cells (${a} run) · submission.csv: `)+(i?chalk.green("written ✓"):chalk.yellow("not yet — run all"))),Z?console.log(chalk.gray(" ⚡ GPU: ")+chalk.green("connected")+chalk.gray(" — ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on · ")+chalk.cyan("download <file>")+chalk.gray(" pull results")):r&&console.log(chalk.gray(" ⚡ GPU task, not connected — ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.cyan("gpu on")+chalk.gray(" · ")+chalk.cyan("gpu queue")+chalk.gray(" shows who is on")),console.log(),console.log(chalk.bold.white(" The loop:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan("run all")+chalk.gray(" — trains the baseline, writes submission.csv")),l&&"icoa-holdout"===t?(console.log(chalk.gray(" 2. ")+chalk.cyan("quit")+chalk.gray(", then ")+chalk.cyan(`kaggle submit ${l}`)+chalk.gray(" — scored + ranked on the live board")),console.log(chalk.gray(" 3. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat your score."))):l&&r?(console.log(chalk.gray(" 2. ")+chalk.cyan("download <file>")+chalk.gray(" — pull your results (submission.csv / predictions.zip) off the GPU box")),console.log(chalk.gray(" 3. submit on kaggle.com — the notebook's final cell has the exact steps")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):l?(console.log(chalk.gray(" 2. ")+chalk.cyan("quit")+chalk.gray(", then ")+chalk.cyan(`kaggle check ${l}`)+chalk.gray(" — verifies the file format")),console.log(chalk.gray(" 3. upload submission.csv on kaggle.com — read your public score")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):console.log(chalk.gray(" 2. edit cells (")+chalk.cyan("edit N")+chalk.gray("), re-run, ")+chalk.cyan("save")+chalk.gray(" — this is a free notebook.")),console.log(),console.log(chalk.bold.white(" If it looks stuck:")),console.log(chalk.gray(" · prompt shows ")+chalk.cyan("...>")+chalk.gray(" → you are inside a code block. Press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(".")),console.log(chalk.gray(" · never type ")+chalk.cyan("python file.ipynb")+chalk.gray(" here — you are already inside. Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(),console.log(chalk.bold.white(" 🤝 AI help: ")+chalk.gray("split the screen ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" · right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" then ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" — live Gemma 3")),console.log(chalk.gray(" All commands: ")+chalk.cyan("help")+chalk.gray(" · leave: ")+chalk.cyan("quit")),console.log()})(),void ge();if("python"===a||"python3"===a)return console.log(chalk.gray(" You're already inside the notebook kernel — no need to run python.")),console.log(chalk.gray(" Type ")+chalk.bold.cyan("run all")+chalk.gray(" to run every cell, or ")+chalk.cyan("guide")+chalk.gray(" for the basics.")),void ge();if("open"===a)return F&&_(F)?console.log(chalk.gray(" reopening ")+chalk.cyan(F)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void ge();if("cells"===a||"ls"===a)return(()=>{if(0===Q.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);Q.cells.forEach((o,n)=>{const l=C(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(j(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 ge();if("show"===a)return(e=>{const o=pe(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 x(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 ──")),H(o.cell.result,K)),console.log()}})(d),void ge();if("edit"===a)return(e=>{const o=pe(e);if(!o)return;te.pause();const n=m(o.cell.source,"markdown"===o.cell.kind?".md":".py");if(te.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,Q.dirty=!0,console.log(chalk.green(` ✓ cell ${o.idx} updated`)+chalk.gray(" — ")+chalk.cyan(`run ${o.idx}`)+chalk.gray(" to execute."))):console.log(chalk.gray(" no changes."))})(d),void ge();if("add"===a)return(e=>{const o=e.trim().toLowerCase(),n="md"===o||"markdown"===o||"text"===o||"txt"===o;if(o&&!n&&"py"!==o&&"code"!==o&&"python"!==o)return void console.log(chalk.yellow(" usage: ")+chalk.cyan("add")+chalk.yellow(" (Python cell) · ")+chalk.cyan("add md")+chalk.yellow(" (markdown/text cell)"));te.pause();const l=m(n?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",n?".md":".py");te.resume();const t=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");t?(Q.cells.push({kind:n?"markdown":"code",source:t,result:null}),Q.dirty=!0,console.log(chalk.green(` ✓ added ${n?"markdown ":""}cell ${Q.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${Q.cells.length}`)+chalk.gray(n?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(d),void ge();if("del"===a||"delete"===a)return(e=>{const o=pe(e);o&&(Q.cells.splice(o.idx-1,1),Q.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${Q.cells.length} left.`)+(o.idx<=Q.cells.length?chalk.yellow(" ⚠ 后面的 cell 号已顺移")+chalk.gray(" — ")+chalk.cyan("cells")+chalk.gray(" 重看一眼"):"")))})(d),void ge();if(("md"===a||"py"===a)&&/^\d+$/.test(d))return((e,o)=>{const n=pe(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,Q.dirty=!0,console.log(chalk.green(` ✓ cell ${n.idx} → ${l}`)+chalk.gray(" — ")+chalk.cyan(`run ${n.idx}`)+chalk.gray("markdown"===o?" to render it.":" to execute."))):console.log(chalk.gray(` cell ${n.idx} is already ${l}.`))})(d,"md"===a?"markdown":"code"),void ge();if("gpu"===a)return ce=!0,await he(d),ce=!1,void ge();if("download"===a||"dl"===a)return ce=!0,await(async e=>{if(!Z)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:`${Z.outDir}/${n}`;let r;try{r=await X.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=ee?g(process.cwd(),"icoa-kaggle",ee):process.cwd(),c=g(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)`)),ee&&"submission.csv"===s(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${ee}`)+chalk.gray(" — then upload on Kaggle yourself."))})(d),ce=!1,void ge();if("ai"===a||"/ai"===a)return ce=!0,await we(d),ce=!1,void ge();if("run"===a)return ce=!0,await(async e=>{const o=I(e,Q.cells.length);if(o)for(const e of o){const n=Q.cells[e-1];if("markdown"!==n.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(j(n,50))+chalk.gray(" ──"));try{n.result=await X.execute(n.source)}catch(e){return console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),void D()}if(Q.dirty=!0,H(n.result,K),be(n,e),!n.result.ok){const n=e!==o[o.length-1];return console.log(chalk.yellow(` ✗ cell ${e} raised${n?" — stopping here.":"."}`)+chalk.gray(" Fix it (")+chalk.cyan(`edit ${e}`)+chalk.gray(") and re-run.")),console.log(chalk.gray(T()?" 卡住了? ":" Stuck? ")+chalk.bold.cyan(`ai ${e}`)+chalk.gray(T()?" 把这一格的代码和报错一起问 AI(不用离开 notebook)":" sends this cell and its traceback to the AI — without leaving the notebook")),void D()}}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of x(n.source))console.log(e);console.log()}}else console.log(0===Q.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(" usage: ")+chalk.cyan("run 3")+chalk.yellow(" · ")+chalk.cyan("run 1-5")+chalk.yellow(" · ")+chalk.cyan("run all"))})(d),ce=!1,void ge();if("save"===a)return(e=>{if(0===Q.cells.length)return void console.log(chalk.yellow(" nothing to save — the notebook is empty."));let o;o=e.trim()?i(e.trim())?e.trim():y(process.cwd(),e.trim()):Q.path?Q.path.endsWith(".ipynb")?Q.path:`${Q.path.replace(/\.[^./]+$/,"")}.ipynb`:y(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");try{l(o,O(Q.cells)),Q.path=o,Q.dirty=!1,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${Q.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(d),void ge();if(""===r)return void ge()}if(ae.length>0&&M.has(r.toLowerCase()))return console.log(chalk.gray(" (⏸ you are inside a multi-line block — press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(" to run it; then ")+chalk.cyan(r.toLowerCase().replace(/^\//,""))+chalk.gray(" will work. This line was not added to the block.)")),void ge();if(ae.push(t),!v(ae))return 1!==ae.length||se||(se=!0,console.log(chalk.gray(" (multi-line block started — keep typing; an empty line runs it)"))),void ge();const a=ae.join("\n").replace(/\s+$/,"");if(ae.length=0,""!==a.trim()){ce=!0;try{const e=await X.execute(a);Q.cells.push({kind:"code",source:a,result:e}),Q.dirty=!0,H(e,K);const o=be(Q.cells[Q.cells.length-1],Q.cells.length);e.ok||o||D()}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),D()}ce=!1,ge()}else ge()};te.on("line",e=>{ke(e)}),ne||te.on("close",async()=>{await X.shutdown().catch(()=>{}),process.exit(0)}),ge(),await de}(p)})}function R(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}const M=new Set(["guide","/guide","help","?","quit","exit","back","menu","cells","run all"]);function D(){console.log(chalk.gray(" 🧭 stuck? type ")+chalk.cyan("guide")+chalk.gray(" for the basics · ")+chalk.cyan("help")+chalk.gray(" for every command."))}const K="https://practice.icoa2026.au";function B(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):K}function W(){return g(t(),".icoa","gpu-key")}function J(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return n(W(),"utf-8").trim()||null}catch{return null}}async function Y(e,o,n){try{const l=await fetch(`${B()}/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 b(await l.json())}catch{return{state:"error",message:"GPU broker not reachable"}}}function z(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let V=0,F=null;function H(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(L,"")}`))}else"display"===n.kind&&Q(n.data,o)}function Q(e,n){if(e["image/png"])try{o(n,{recursive:!0}),V+=1;const t=g(n,`figure-${V}.png`);return l(t,Buffer.from(e["image/png"],"base64")),F=t,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(t)),void(_(t)?console.log(chalk.gray(" opening in your image viewer… (type ")+chalk.cyan("open")+chalk.gray(" to reopen)")):console.log(chalk.gray(" open it with your file browser (inline images need a graphical viewer).")))}catch{}e["text/plain"]&&console.log(chalk.white(` ${e["text/plain"]}`))}
@@ -1 +1 @@
1
- import{existsSync as o,mkdirSync as e,readFileSync as n,readdirSync as l,writeFileSync as t}from"node:fs";import{join as s}from"node:path";import chalk from"chalk";import{makeReplAsker as a}from"../lib/repl-asker.js";import{logCommand as r}from"../lib/logger.js";import{openFile as i}from"../lib/open-file.js";import{serializeIpynb as c}from"../lib/notebook-doc.js";import{loadLearnState as g}from"../lib/learn-state.js";import{buildStarterCells as u,dataFileUrls as y,parseKaggleTaskList as d,parseSubmitResponse as h,validateSubmissionText as b}from"../lib/kaggle.js";function m(){return process.env.ICOA_KAGGLE_SERVER?process.env.ICOA_KAGGLE_SERVER.replace(/\/$/,""):"https://practice.icoa2026.au"}async function p(o){try{const e=await fetch(m()+o,{signal:AbortSignal.timeout(3e4)});return await e.json()}catch{return null}}async function f(o){try{const e=await fetch(o,{signal:AbortSignal.timeout(6e4)});return e.ok?await e.text():null}catch{return null}}function w(){console.log(),console.log(chalk.yellow(" The practice server is not reachable right now.")),console.log(chalk.gray(" Check your connection, or try again later.")),console.log()}function k(o){return s(process.cwd(),"icoa-kaggle",o)}function v(o,e){const n=[];let l="";for(const t of o.split(/\s+/))""!==l&&l.length+1+t.length>e?(n.push(l),l=t):l=""===l?t:`${l} ${t}`;return""!==l&&n.push(l),n}function $(o){return"local-eval"===o?.judge?(console.log(chalk.bold.white(" Scoring (inside the notebook):")),void console.log(chalk.gray(" run the final cell — the ")+chalk.white("FINAL")+chalk.gray(" line is your score. Nothing to upload."))):"icoa-holdout"===o?.judge?(console.log(chalk.bold.white(" Submit to ICOA (scored on the server):")),console.log(chalk.gray(" ")+chalk.bold.cyan(`kaggle submit ${o.comp_id}`)),void console.log(chalk.gray(" scores vs the secret test labels → live rank on ")+chalk.cyan("board"))):"nitro"===o?.judge?(console.log(chalk.bold.white(" 怎么知道做得对不对:")),console.log(chalk.gray(" · 这道题来自 judge.nitro-ai.org,判分在他们服务器上")),console.log(chalk.gray(" · 想要真分数:去 ")+chalk.cyan("judge.nitro-ai.org")+chalk.gray(" 注册后提交")),void console.log(chalk.gray(" · 冲刺期更快的办法:做完对照官方解答,或问 ")+chalk.cyan("ai4ioai"))):(console.log(chalk.bold.white(" Submit on Kaggle (manual, your own account):")),void(o?.kaggle_url?(console.log(chalk.gray(" 1. open ")+chalk.cyan(o.kaggle_url)),o?.needs_gpu?console.log(chalk.gray(" 2. submit the file your notebook produced")+chalk.gray(" — its final cell has the exact steps")):console.log(chalk.gray(" 2. Submit Predictions → upload ")+chalk.white("submission.csv")),console.log(chalk.gray(" 3. read your score, improve the MODEL cell, re-run, repeat."))):(console.log(chalk.gray(" 在 kaggle.com 搜这个比赛名提交,或做完对照官方解答自查。")),console.log(chalk.gray(" 卡住了问 ")+chalk.cyan("ai4ioai")+chalk.gray(" —— 它是弱模型,把问题问准是这次要练的本事。")))))}export async function runKaggle(n){const l=a(),i=async o=>await l.ask(o)??"";try{console.log(),console.log(chalk.bold.cyan(" 📊 KAGGLE PRACTICE")+chalk.gray(" · real ML competitions, a runnable starter notebook")),console.log(chalk.gray(" Small tasks run on your CPU; ")+chalk.magenta("⚡ GPU tasks")+chalk.gray(" run on the ICOA GPU box.")),console.log();const l=await p("/api/icoa/kaggle/tasks");if(!l)return w();const a=d(l);if(0===a.length)return console.log(chalk.yellow(" No practice competitions are live yet — check back soon.")),void console.log();let g=n?a.find(o=>o.comp_id===n):void 0;if(n&&!g&&console.log(chalk.yellow(` No competition called "${n}".`)),!g){console.log(chalk.white(" Live practice competitions:")),a.forEach((o,e)=>{const n=o.needs_gpu?chalk.magenta(" ⚡GPU"):"";console.log(chalk.gray(` ${e+1}. `)+chalk.cyan(o.comp_id)+chalk.gray(` — ${o.title} · ${o.metric}`)+n)});for(let o=0;o<3&&!g;o++){const o=(await i(chalk.cyan(" Pick one (number or id): "))).trim();if(!o)return;const e=Number(o);g=!Number.isNaN(e)&&a[e-1]||a.find(e=>e.comp_id===o.toLowerCase())||void 0,g||console.log(chalk.gray(` Try a number 1-${a.length} or an id like "${a[0].comp_id}".`))}if(!g)return}const h=g.comp_id;if(r(`kaggle: download ${h}`),g.needs_gpu)return void await async function(n,l){const a=k(n);if(console.log(),console.log(chalk.white(` ${l.title}`)+chalk.gray(` · ${l.metric}`)+chalk.bold.magenta(" ⚡ GPU task")),l.description){console.log();for(const o of v(l.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(" Fetching the notebook…")+chalk.gray(" (the dataset stays on the GPU box — no download)"));const r=await p(`/api/icoa/kaggle/${n}/starter`),i=r?.data?.starter??r?.starter;if("string"!=typeof i||0===i.length)return w();const c=s(a,"starter.ipynb");let g=!1;try{e(a,{recursive:!0}),o(c)?g=!0:t(c,i),t(s(a,"meta.json"),`${JSON.stringify(l,null,2)}\n`)}catch{return void console.log(chalk.yellow(" Could not write the notebook here — check directory permissions."))}console.log(chalk.green(" ✓ notebook: ")+chalk.white(c)+chalk.gray(g?" (kept your existing one)":" (the real IOAI task inside)")),console.log(chalk.green(" ✓ dataset: ")+chalk.white("already on the GPU box")+chalk.gray(" — no download needed")),console.log(),console.log(chalk.bold.white(" This is a GPU task — 3 steps:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${c}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.bold.cyan("gpu on")+chalk.gray(" (connects you to the box where the data lives)")),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("run all")+chalk.gray(" → the notebook trains on the GPU.")),console.log(),console.log(chalk.gray(" While you work: ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on, who is waiting")),console.log(),l.kaggle_url&&(console.log(chalk.gray(" Submit on Kaggle: ")+chalk.cyan(l.kaggle_url)),console.log())}(h,g);if(console.log(),console.log(chalk.white(` ${g.title}`)+chalk.gray(` · ${g.metric}`)),g.description){console.log();for(const o of v(g.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(" Downloading data…"));let b=null;const m=y(g);if(m){const[o,e,n]=await Promise.all([f(m.train),f(m.test),f(m.sample_submission)]);o&&e&&n&&(b={train:o,test:e,sample_submission:n})}if(!b){const o=await p(`/api/icoa/kaggle/${h}/data`);b=o?.data??o}if(!b?.train||!b?.test||!b?.sample_submission)return w();const $=k(h),j={...g,...b.meta??{}};try{e($,{recursive:!0}),t(s($,"train.csv"),b.train),t(s($,"test.csv"),b.test),t(s($,"sample_submission.csv"),b.sample_submission),t(s($,"meta.json"),`${JSON.stringify(j,null,2)}\n`)}catch{return void console.log(chalk.yellow(" Could not write the data files here — check directory permissions."))}const S=s($,"starter.ipynb");let x=!1;if(o(S))x=!0;else{const o=await p(`/api/icoa/kaggle/${h}/starter`),e=o?.data?.starter??o?.starter;"string"==typeof e&&e.length>0?t(S,e):t(S,c(u($,j)))}const G="number"==typeof j.n_train?`${j.n_train} rows`:"labelled",N="number"==typeof j.n_test?`${j.n_test} rows`:"predict these";console.log(chalk.green(" ✓ train: ")+chalk.white(s($,"train.csv"))+chalk.gray(` (${G})`)),console.log(chalk.green(" ✓ test: ")+chalk.white(s($,"test.csv"))+chalk.gray(` (${N})`)),console.log(chalk.green(" ✓ format: ")+chalk.white(s($,"sample_submission.csv"))),console.log(chalk.green(" ✓ notebook: ")+chalk.white(S)+chalk.gray(x?" (kept your existing one)":" (runnable baseline inside)")),(j.licence||j.attribution)&&console.log(chalk.gray(` licence: ${j.licence??"—"} · ${j.attribution??""}`)),console.log(),_(h,j,S),console.log()}finally{l.close()}}function _(o,e,n){e?.needs_gpu?(console.log(chalk.bold.white(" Your move — 4 steps (⚡ GPU task):")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${n}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.bold.cyan("gpu on")+chalk.gray(" → ")+chalk.bold.cyan("run all")+chalk.gray(" (trains on the GPU box)")),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("download <file>")+chalk.gray(" → pulls your results (submission.csv / predictions.zip) here")),console.log(chalk.gray(" 4. submit on kaggle.com — the notebook's final cell has the exact steps.")),console.log(),console.log(chalk.gray(" While you work: ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on, who is waiting"))):(console.log(chalk.bold.white(" Your move — 3 steps:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${n}`)+chalk.gray(" → run all (baseline trains)")),console.log(chalk.gray(" 2. it writes ")+chalk.white("submission.csv")+chalk.gray(" → verify with ")+chalk.cyan(`kaggle check ${o}`)),"icoa-holdout"===e?.judge?console.log(chalk.gray(" 3. ")+chalk.bold.cyan(`kaggle submit ${o}`)+chalk.gray(" → scored + ranked live.")):"nitro"===e?.judge?console.log(chalk.gray(" 3. scored at ")+chalk.cyan("judge.nitro-ai.org")+chalk.gray(" (not Kaggle) — or just work the val score. See below.")):console.log(chalk.gray(" 3. upload it on Kaggle yourself — then beat the baseline."))),console.log(),console.log(chalk.bold.white(" 🤝 Want AI help? Set up your cockpit:")),console.log(chalk.gray(" 1. split the screen: ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" (lesson/work left · AI right)")),console.log(chalk.gray(" 2. in the right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" then type ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" → live Gemma 3")),console.log(chalk.gray(" 3. ask it for feature ideas or bug fixes — then ")+chalk.bold.white("VERIFY")+chalk.gray(" with your val score (a tip that lowers it, drop it).")),console.log(),$(e)}export async function runKaggleGuide(e){console.log();const l=j(e,"guide");if(!l)return;const t=k(l);let a=null;try{a=JSON.parse(n(s(t,"meta.json"),"utf-8"))}catch{a=null}r(`kaggle: guide ${l}`);const i=s(t,"starter.ipynb"),c=o(s(t,"submission.csv"));console.log(chalk.bold.white(` ═══ 📖 ${a?.title??l} — walkthrough ═══`)),console.log(),console.log(chalk.gray(" Where you are: data ")+chalk.green("downloaded ✓")+chalk.gray(" · submission.csv: ")+(c?chalk.green("written ✓"):chalk.yellow("not yet — run the notebook"))),console.log(),_(l,a,i),console.log(),console.log(chalk.gray(" Inside the notebook, ")+chalk.cyan("guide")+chalk.gray(" shows the notebook-level guide.")),console.log()}function j(e,n){if(e)return e;const t=s(process.cwd(),"icoa-kaggle"),a=o(t)?l(t,{withFileTypes:!0}).filter(e=>e.isDirectory()&&(o(s(t,e.name,"sample_submission.csv"))||o(s(t,e.name,"meta.json")))).map(o=>o.name):[];if(1===a.length)return a[0];if(0===a.length)return console.log(chalk.yellow(" No downloaded competition found here — run ")+chalk.cyan("kaggle")+chalk.yellow(" first.")),console.log(),null;console.log(chalk.white(" Several competitions downloaded — pick one:"));for(const o of a)console.log(chalk.gray(` kaggle ${n} `)+chalk.cyan(o));return console.log(),null}export async function runKaggleCheck(e){console.log();const l=j(e,"check");if(!l)return;const t=k(l),a=s(t,"submission.csv"),c=s(t,"sample_submission.csv");try{if(JSON.parse(n(s(t,"meta.json"),"utf-8")).needs_gpu&&!o(c))return console.log(chalk.gray(" ⚡ GPU task — results are produced and validated by the notebook itself.")),console.log(chalk.gray(" Pull them with ")+chalk.cyan("download <file>")+chalk.gray(" inside ")+chalk.cyan("icoa ipynb")+chalk.gray(", then submit on kaggle.com (final cell has the steps).")),void console.log()}catch{}if(!o(c))return console.log(chalk.yellow(` No data for "${l}" here — run `)+chalk.cyan(`kaggle ${l}`)+chalk.yellow(" first.")),void console.log();if(!o(a))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(t,"starter.ipynb")}`)),void console.log();const g=b(n(a,"utf-8"),n(c,"utf-8"));r(`kaggle: check ${l} → ${g.ok?"ok":`rejected: ${g.problems[0]??"format"}`}`);let u=null;try{u=JSON.parse(n(s(t,"meta.json"),"utf-8"))}catch{u=null}if(g.ok)console.log(chalk.bold.green(" ✓ submission.csv has the right format")+chalk.gray(" (matches sample_submission.csv)")),console.log(chalk.gray(" ")+chalk.white(a)),console.log(),$(u),i(t);else{console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of g.problems)console.log(chalk.yellow(` · ${o}`));console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it."))}console.log()}export async function runKaggleSubmit(e){console.log();const l=j(e,"submit");if(!l)return;const t=k(l),i=s(t,"submission.csv"),c=s(t,"sample_submission.csv");let u=null;try{u=JSON.parse(n(s(t,"meta.json"),"utf-8"))}catch{u=null}if("local-eval"===u?.judge)return console.log(chalk.yellow(" This task is scored inside the notebook — nothing to upload.")),$(u),void console.log();if(!u||!o(c))return console.log(chalk.yellow(` No data for "${l}" here — run `)+chalk.cyan(`kaggle ${l}`)+chalk.yellow(" first.")),void console.log();if("icoa-holdout"!==u.judge)return console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here.")),console.log(),$(u),void console.log();if(!o(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 y=n(i,"utf-8"),d=b(y,n(c,"utf-8"));if(!d.ok){r(`kaggle: submit ${l} → local-reject: ${d.problems[0]??"format"}`),console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of d.problems)console.log(chalk.yellow(` · ${o}`));return console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it.")),void console.log()}let p=g()?.token??"";if(!p){const o=a();try{p=(await o.ask(chalk.cyan(" Your learn token: "))??"").trim()}finally{o.close()}if(!p)return console.log(chalk.gray(" A learn token identifies you on the board — ask your coach for one.")),void console.log()}console.log(chalk.gray(" Scoring on the server…"));const f=await async function(o,e){try{const n=await fetch(m()+o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(6e4)});return await n.json()}catch{return null}}(`/api/icoa/kaggle/${l}/submit`,{token:p,submission_csv:y}),w=h(f);if(r(`kaggle: submit ${l} → ${w.ok?`${w.metric}=${w.score}${w.deduped?" (deduped)":""} rank=${w.rank??"-"}`:w.reason??"error"}`),console.log(),w.ok){const o=`${w.metric}: ${Number(w.score).toFixed(4).replace(/\.?0+$/,"")}`;w.deduped?(console.log(chalk.bold.white(` ✓ already scored — ${o}`)),console.log(chalk.gray(" These exact predictions were scored before. Improve the MODEL cell and re-run."))):(console.log(chalk.bold.green(` ✓ scored — ${o}`)),"number"==typeof w.rank&&"number"==typeof w.fieldSize&&console.log(chalk.bold.white(` 🏁 board rank #${w.rank}`)+chalk.gray(` of ${w.fieldSize}`))),w.boardEvent&&console.log(chalk.gray(" standings: ")+chalk.cyan(`board ${w.boardEvent} ${l}`))}else switch(w.reason){case"bad_token":console.log(chalk.bold.red(" ✗ that learn token was not accepted")+chalk.gray(" (invalid or expired)")),console.log(chalk.gray(" Check the token with your coach, then try again."));break;case"format":console.log(chalk.bold.red(" ✗ the server rejected submission.csv:"));for(const o of w.problems??[])console.log(chalk.yellow(` · ${o}`));break;case"event_closed":case"outside_window":console.log(chalk.bold.yellow(" ⏱ the submission window for this competition is closed."));break;case"cap_reached":console.log(chalk.bold.yellow(" ⏱ you have used all your submissions for this competition."));break;case"kaggle_judged":console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here."));break;default:console.log(chalk.yellow(" The scoring server is not reachable right now — try again in a minute."))}console.log()}export function registerKaggleCommand(o){o.command("kaggle").argument("[action]",'competition id, or "check" / "submit"').argument("[comp]",'competition id (with "check" / "submit")').description("Kaggle-style ML practice — dataset + starter notebook, check & submit").action(async(o,e)=>{"check"===o?await runKaggleCheck(e):"submit"===o?await runKaggleSubmit(e):"guide"===o?await runKaggleGuide(e):await runKaggle(o)}),o.command("guide").argument("[comp]","competition id").description("Show the competition walkthrough (3 steps + AI cockpit)").action(async o=>{await runKaggleGuide(o)})}
1
+ import{existsSync as o,mkdirSync as e,readFileSync as n,readdirSync as t,writeFileSync as l}from"node:fs";import{join as s}from"node:path";import chalk from"chalk";import{makeReplAsker as a}from"../lib/repl-asker.js";import{getConfig as i}from"../lib/config.js";import{logCommand as r}from"../lib/logger.js";import{openFile as c}from"../lib/open-file.js";import{serializeIpynb as g}from"../lib/notebook-doc.js";import{loadLearnState as u}from"../lib/learn-state.js";import{buildStarterCells as y,dataFileUrls as d,parseKaggleTaskList as h,parseSubmitResponse as b,validateSubmissionText as m}from"../lib/kaggle.js";function p(){return process.env.ICOA_KAGGLE_SERVER?process.env.ICOA_KAGGLE_SERVER.replace(/\/$/,""):"https://practice.icoa2026.au"}async function f(o){try{const e=await fetch(p()+o,{signal:AbortSignal.timeout(3e4)});return await e.json()}catch{return null}}async function k(o){try{const e=await fetch(o,{signal:AbortSignal.timeout(6e4)});return e.ok?await e.text():null}catch{return null}}function w(o,e){return(i().language||"en").toLowerCase().startsWith("zh")?o:e}function v(){console.log(),console.log(chalk.yellow(w(" 练习服务器现在连不上。"," The practice server is not reachable right now."))),console.log(chalk.gray(w(" 检查一下网络,或者过一会儿再试。"," Check your connection, or try again later."))),console.log()}function $(o){return s(process.cwd(),"icoa-kaggle",o)}function _(o,e){const n=[];let t="",l=0;const s=o=>/[ᄀ-ᅟ⺀-꓏가-힣豈-﫿︰-﹏＀-⦆¢-₩]/.test(o);for(const a of o){const o=s(a)?2:1;if(l+o>e){const o=t.lastIndexOf(" ");if(!s(a)&&" "!==a&&o>e/3){const e=t.slice(o+1);n.push(t.slice(0,o)),t=e,l=[...e].reduce((o,e)=>o+(s(e)?2:1),0)}else n.push(t),t="",l=0;if(" "===a&&""===t)continue}t+=a,l+=o}return""!==t.trim()&&n.push(t),n}function j(o){return"local-eval"===o?.judge?(console.log(chalk.bold.white(w(" 出分(就在 notebook 里):"," Scoring (inside the notebook):"))),void console.log(chalk.gray(w(" 跑最后一格 —— "," run the final cell — the "))+chalk.white("FINAL")+chalk.gray(w(" 那一行就是你的分数,没有东西要上传。"," line is your score. Nothing to upload.")))):"icoa-holdout"===o?.judge?(console.log(chalk.bold.white(w(" 交给 ICOA 判分(服务端评分):"," Submit to ICOA (scored on the server):"))),console.log(chalk.gray(" ")+chalk.bold.cyan(`kaggle submit ${o.comp_id}`)),void console.log(chalk.gray(w(" 与秘密测试标签比对 → 实时排名看 "," scores vs the secret test labels → live rank on "))+chalk.cyan("board"))):"nitro"===o?.judge?(console.log(chalk.bold.white(w(" 怎么知道做得对不对:"," How to tell whether you got it right:"))),console.log(chalk.gray(w(" · 这道题来自 judge.nitro-ai.org,判分在他们服务器上"," · this task comes from judge.nitro-ai.org — the judging lives on their server"))),console.log(chalk.gray(w(" · 想要真分数:去 "," · for a real score: register at "))+chalk.cyan("judge.nitro-ai.org")+chalk.gray(w(" 注册后提交"," and submit there"))),void console.log(chalk.gray(w(" · 冲刺期更快的办法:做完对照官方解答,或问 "," · faster right now: compare against the official solution, or ask "))+chalk.cyan("ai4ioai"))):(console.log(chalk.bold.white(w(" 去 Kaggle 提交(手动,用你自己的账号):"," Submit on Kaggle (manual, your own account):"))),void(o?.kaggle_url?(console.log(chalk.gray(w(" 1. 打开 "," 1. open "))+chalk.cyan(o.kaggle_url)),o?.needs_gpu?console.log(chalk.gray(w(" 2. 交 notebook 产出的那个文件 —— 最后一格写了确切步骤"," 2. submit the file your notebook produced — its final cell has the exact steps"))):console.log(chalk.gray(w(" 2. Submit Predictions → 上传 "," 2. Submit Predictions → upload "))+chalk.white("submission.csv")),console.log(chalk.gray(w(" 3. 看分数,改 MODEL 那一格,重跑,再来一轮。"," 3. read your score, improve the MODEL cell, re-run, repeat.")))):(console.log(chalk.gray(w(" 在 kaggle.com 搜这个比赛名提交,或做完对照官方解答自查。"," Search kaggle.com for this competition, or check yourself against the official solution."))),console.log(chalk.gray(w(" 卡住了问 "," Stuck? ask "))+chalk.cyan("ai4ioai")+chalk.gray(w(" —— 它是弱模型,把问题问准是这次要练的本事。"," — a deliberately weak model; asking precisely is the skill you are training."))))))}export async function runKaggle(n){const t=a(),i=async o=>await t.ask(o)??"";try{console.log(),console.log(chalk.bold.cyan(" 📊 KAGGLE PRACTICE")+chalk.gray(w(" · 真实的 ML 比赛,配一本能直接跑的 starter notebook"," · real ML competitions, a runnable starter notebook"))),console.log(chalk.gray(w(" 小题在你自己的 CPU 上跑;"," Small tasks run on your CPU; "))+chalk.magenta(w("⚡ GPU 题","⚡ GPU tasks"))+chalk.gray(w("在 ICOA 的 GPU 箱上跑。"," run on the ICOA GPU box."))),console.log();const t=await f("/api/icoa/kaggle/tasks");if(!t)return v();const a=h(t);if(0===a.length)return console.log(chalk.yellow(w(" 现在还没有上线的练习赛 —— 过一会儿再来。"," No practice competitions are live yet — check back soon."))),void console.log();let c=n?a.find(o=>o.comp_id===n):void 0;if(n&&!c&&console.log(chalk.yellow(w(` 没有叫 "${n}" 的比赛。`,` No competition called "${n}".`))),!c){console.log(chalk.white(w(" 正在开放的练习赛:"," Live practice competitions:"))),a.forEach((o,e)=>{const n=o.needs_gpu?chalk.magenta(" ⚡GPU"):"";console.log(chalk.gray(` ${e+1}. `)+chalk.cyan(o.comp_id)+chalk.gray(` — ${o.title} · ${o.metric}`)+n)});for(let o=0;o<3&&!c;o++){const o=(await i(chalk.cyan(w(" 选一个(序号或 id): "," Pick one (number or id): ")))).trim();if(!o)return;const e=Number(o);c=!Number.isNaN(e)&&a[e-1]||a.find(e=>e.comp_id===o.toLowerCase())||void 0,c||console.log(chalk.gray(w(` 输 1-${a.length} 之间的序号,或者一个 id,比如 "${a[0].comp_id}"。`,` Try a number 1-${a.length} or an id like "${a[0].comp_id}".`)))}if(!c)return}const u=c.comp_id;if(r(`kaggle: download ${u}`),c.needs_gpu)return void await async function(n,t){const a=$(n);if(console.log(),console.log(chalk.white(` ${t.title}`)+chalk.gray(` · ${t.metric}`)+chalk.bold.magenta(" ⚡ GPU task")),t.description){console.log();for(const o of _(t.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(w(" 正在取 notebook…"," Fetching the notebook…"))+chalk.gray(w(" (数据留在 GPU 箱上,不下载)"," (the dataset stays on the GPU box — no download)")));const i=await f(`/api/icoa/kaggle/${n}/starter`),r=i?.data?.starter??i?.starter;if("string"!=typeof r||0===r.length)return v();const c=s(a,"starter.ipynb");let g=!1;try{e(a,{recursive:!0}),o(c)?g=!0:l(c,r),l(s(a,"meta.json"),`${JSON.stringify(t,null,2)}\n`)}catch{return void console.log(chalk.yellow(w(" 写不进 notebook —— 检查一下这个目录的写权限。"," Could not write the notebook here — check directory permissions.")))}console.log(chalk.green(" ✓ notebook: ")+chalk.white(c)+chalk.gray(g?w(" (保留了你原来那本)"," (kept your existing one)"):w(" (里面是真正的 IOAI 题)"," (the real IOAI task inside)"))),console.log(chalk.green(" ✓ dataset: ")+chalk.white(w("已经在 GPU 箱上","already on the GPU box"))+chalk.gray(w(" —— 不用下载"," — no download needed"))),console.log(),console.log(chalk.bold.white(w(" 这是 GPU 题 —— 三步:"," This is a GPU task — 3 steps:"))),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${c}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(w(" 然后 "," then "))+chalk.bold.cyan("gpu on")+chalk.gray(w(" (连到数据所在的那台箱子)"," (connects you to the box where the data lives)"))),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("run all")+chalk.gray(w(" → notebook 在 GPU 上训练。"," → the notebook trains on the GPU."))),console.log(),console.log(chalk.gray(w(" 做题时随时看: "," While you work: "))+chalk.cyan("gpu status")+chalk.gray(w(" 你还剩多少时间 · "," your time left · "))+chalk.cyan("gpu queue")+chalk.gray(w(" 谁在用,谁在等"," who is on, who is waiting"))),console.log(),t.kaggle_url&&(console.log(chalk.gray(w(" 去 Kaggle 提交: "," Submit on Kaggle: "))+chalk.cyan(t.kaggle_url)),console.log())}(u,c);if(console.log(),console.log(chalk.white(` ${c.title}`)+chalk.gray(` · ${c.metric}`)),c.description){console.log();for(const o of _(c.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(w(" 正在下载数据…"," Downloading data…")));let b=null;const m=d(c);if(m){const[o,e,n]=await Promise.all([k(m.train),k(m.test),k(m.sample_submission)]);o&&e&&n&&(b={train:o,test:e,sample_submission:n})}if(!b){const o=await f(`/api/icoa/kaggle/${u}/data`);b=o?.data??o}if(!b?.train||!b?.test||!b?.sample_submission)return v();const p=$(u),j={...c,...b.meta??{}};try{e(p,{recursive:!0}),l(s(p,"train.csv"),b.train),l(s(p,"test.csv"),b.test),l(s(p,"sample_submission.csv"),b.sample_submission),l(s(p,"meta.json"),`${JSON.stringify(j,null,2)}\n`)}catch{return void console.log(chalk.yellow(" Could not write the data files here — check directory permissions."))}const G=s(p,"starter.ipynb");let P=!1;if(o(G))P=!0;else{const o=await f(`/api/icoa/kaggle/${u}/starter`),e=o?.data?.starter??o?.starter;"string"==typeof e&&e.length>0?l(G,e):l(G,g(y(p,j)))}const x="number"==typeof j.n_train?`${j.n_train} rows`:"labelled",C="number"==typeof j.n_test?`${j.n_test} rows`:"predict these";console.log(chalk.green(" ✓ train: ")+chalk.white(s(p,"train.csv"))+chalk.gray(` (${x})`)),console.log(chalk.green(" ✓ test: ")+chalk.white(s(p,"test.csv"))+chalk.gray(` (${C})`)),console.log(chalk.green(" ✓ format: ")+chalk.white(s(p,"sample_submission.csv"))),console.log(chalk.green(" ✓ notebook: ")+chalk.white(G)+chalk.gray(P?" (kept your existing one)":" (runnable baseline inside)")),(j.licence||j.attribution)&&console.log(chalk.gray(` licence: ${j.licence??"—"} · ${j.attribution??""}`)),console.log(),S(u,j,G),console.log()}finally{t.close()}}function S(o,e,n){e?.needs_gpu?(console.log(chalk.bold.white(" Your move — 4 steps (⚡ GPU task):")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${n}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.bold.cyan("gpu on")+chalk.gray(" → ")+chalk.bold.cyan("run all")+chalk.gray(" (trains on the GPU box)")),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("download <file>")+chalk.gray(" → pulls your results (submission.csv / predictions.zip) here")),console.log(chalk.gray(" 4. submit on kaggle.com — the notebook's final cell has the exact steps.")),console.log(),console.log(chalk.gray(" While you work: ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on, who is waiting"))):(console.log(chalk.bold.white(" Your move — 3 steps:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${n}`)+chalk.gray(" → run all (baseline trains)")),console.log(chalk.gray(" 2. it writes ")+chalk.white("submission.csv")+chalk.gray(" → verify with ")+chalk.cyan(`kaggle check ${o}`)),"icoa-holdout"===e?.judge?console.log(chalk.gray(" 3. ")+chalk.bold.cyan(`kaggle submit ${o}`)+chalk.gray(" → scored + ranked live.")):"nitro"===e?.judge?console.log(chalk.gray(" 3. scored at ")+chalk.cyan("judge.nitro-ai.org")+chalk.gray(" (not Kaggle) — or just work the val score. See below.")):console.log(chalk.gray(" 3. upload it on Kaggle yourself — then beat the baseline."))),console.log(),console.log(chalk.bold.white(" 🤝 Want AI help? Set up your cockpit:")),console.log(chalk.gray(" 1. split the screen: ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" (lesson/work left · AI right)")),console.log(chalk.gray(" 2. in the right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" then type ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" → live Gemma 3")),console.log(chalk.gray(" 3. ask it for feature ideas or bug fixes — then ")+chalk.bold.white("VERIFY")+chalk.gray(" with your val score (a tip that lowers it, drop it).")),console.log(),j(e)}export async function runKaggleGuide(e){console.log();const t=G(e,"guide");if(!t)return;const l=$(t);let a=null;try{a=JSON.parse(n(s(l,"meta.json"),"utf-8"))}catch{a=null}r(`kaggle: guide ${t}`);const i=s(l,"starter.ipynb"),c=o(s(l,"submission.csv"));console.log(chalk.bold.white(` ═══ 📖 ${a?.title??t} — walkthrough ═══`)),console.log(),console.log(chalk.gray(" Where you are: data ")+chalk.green("downloaded ✓")+chalk.gray(" · submission.csv: ")+(c?chalk.green("written ✓"):chalk.yellow("not yet — run the notebook"))),console.log(),S(t,a,i),console.log(),console.log(chalk.gray(" Inside the notebook, ")+chalk.cyan("guide")+chalk.gray(" shows the notebook-level guide.")),console.log()}function G(e,n){if(e)return e;const l=s(process.cwd(),"icoa-kaggle"),a=o(l)?t(l,{withFileTypes:!0}).filter(e=>e.isDirectory()&&(o(s(l,e.name,"sample_submission.csv"))||o(s(l,e.name,"meta.json")))).map(o=>o.name):[];if(1===a.length)return a[0];if(0===a.length)return console.log(chalk.yellow(" No downloaded competition found here — run ")+chalk.cyan("kaggle")+chalk.yellow(" first.")),console.log(),null;console.log(chalk.white(" Several competitions downloaded — pick one:"));for(const o of a)console.log(chalk.gray(` kaggle ${n} `)+chalk.cyan(o));return console.log(),null}export async function runKaggleCheck(e){console.log();const t=G(e,"check");if(!t)return;const l=$(t),a=s(l,"submission.csv"),i=s(l,"sample_submission.csv");try{if(JSON.parse(n(s(l,"meta.json"),"utf-8")).needs_gpu&&!o(i))return console.log(chalk.gray(" ⚡ GPU task — results are produced and validated by the notebook itself.")),console.log(chalk.gray(" Pull them with ")+chalk.cyan("download <file>")+chalk.gray(" inside ")+chalk.cyan("icoa ipynb")+chalk.gray(", then submit on kaggle.com (final cell has the steps).")),void console.log()}catch{}if(!o(i))return console.log(chalk.yellow(` No data for "${t}" here — run `)+chalk.cyan(`kaggle ${t}`)+chalk.yellow(" first.")),void console.log();if(!o(a))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(l,"starter.ipynb")}`)),void console.log();const g=m(n(a,"utf-8"),n(i,"utf-8"));r(`kaggle: check ${t} → ${g.ok?"ok":`rejected: ${g.problems[0]??"format"}`}`);let u=null;try{u=JSON.parse(n(s(l,"meta.json"),"utf-8"))}catch{u=null}if(g.ok)console.log(chalk.bold.green(" ✓ submission.csv has the right format")+chalk.gray(" (matches sample_submission.csv)")),console.log(chalk.gray(" ")+chalk.white(a)),console.log(),j(u),c(l);else{console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of g.problems)console.log(chalk.yellow(` · ${o}`));console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it."))}console.log()}export async function runKaggleSubmit(e){console.log();const t=G(e,"submit");if(!t)return;const l=$(t),i=s(l,"submission.csv"),c=s(l,"sample_submission.csv");let g=null;try{g=JSON.parse(n(s(l,"meta.json"),"utf-8"))}catch{g=null}if("local-eval"===g?.judge)return console.log(chalk.yellow(" This task is scored inside the notebook — nothing to upload.")),j(g),void console.log();if(!g||!o(c))return console.log(chalk.yellow(` No data for "${t}" here — run `)+chalk.cyan(`kaggle ${t}`)+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(),j(g),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(l,"starter.ipynb")}`)),void console.log();const y=n(i,"utf-8"),d=m(y,n(c,"utf-8"));if(!d.ok){r(`kaggle: submit ${t} → local-reject: ${d.problems[0]??"format"}`),console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of d.problems)console.log(chalk.yellow(` · ${o}`));return console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it.")),void console.log()}let h=u()?.token??"";if(!h){const o=a();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 f=await async function(o,e){try{const n=await fetch(p()+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/${t}/submit`,{token:h,submission_csv:y}),k=b(f);if(r(`kaggle: submit ${t} → ${k.ok?`${k.metric}=${k.score}${k.deduped?" (deduped)":""} rank=${k.rank??"-"}`:k.reason??"error"}`),console.log(),k.ok){const o=`${k.metric}: ${Number(k.score).toFixed(4).replace(/\.?0+$/,"")}`;k.deduped?(console.log(chalk.bold.white(` ✓ already scored — ${o}`)),console.log(chalk.gray(" These exact predictions were scored before. Improve the MODEL cell and re-run."))):(console.log(chalk.bold.green(` ✓ scored — ${o}`)),"number"==typeof k.rank&&"number"==typeof k.fieldSize&&console.log(chalk.bold.white(` 🏁 board rank #${k.rank}`)+chalk.gray(` of ${k.fieldSize}`))),k.boardEvent&&console.log(chalk.gray(" standings: ")+chalk.cyan(`board ${k.boardEvent} ${t}`))}else switch(k.reason){case"bad_token":console.log(chalk.bold.red(" ✗ that learn token was not accepted")+chalk.gray(" (invalid or expired)")),console.log(chalk.gray(" Check the token with your coach, then try again."));break;case"format":console.log(chalk.bold.red(" ✗ the server rejected submission.csv:"));for(const o of k.problems??[])console.log(chalk.yellow(` · ${o}`));break;case"event_closed":case"outside_window":console.log(chalk.bold.yellow(" ⏱ the submission window for this competition is closed."));break;case"cap_reached":console.log(chalk.bold.yellow(" ⏱ you have used all your submissions for this competition."));break;case"kaggle_judged":console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here."));break;default:console.log(chalk.yellow(" The scoring server is not reachable right now — try again in a minute."))}console.log()}export function registerKaggleCommand(o){o.command("kaggle").argument("[action]",'competition id, or "check" / "submit"').argument("[comp]",'competition id (with "check" / "submit")').description("Kaggle-style ML practice — dataset + starter notebook, check & submit").action(async(o,e)=>{"check"===o?await runKaggleCheck(e):"submit"===o?await runKaggleSubmit(e):"guide"===o?await runKaggleGuide(e):await runKaggle(o)}),o.command("guide").argument("[comp]","competition id").description("Show the competition walkthrough (3 steps + AI cockpit)").action(async o=>{await runKaggleGuide(o)})}