icoa-cli 2.19.481 → 2.19.482

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 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 I}from"../lib/log-sync.js";import{cellPreview as N,parseIpynb as j,parsePercentPy as q,parseRunRange as U,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(e){e.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 e=>{await runIpynb(e)})}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"]}`))}export async function runIpynb(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")?j(e):q(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 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(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"))}})()})():"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>"))},he=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}},pe=(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 me=!1;const fe=(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)),we=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||I(),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(N(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=he(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=he(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=he(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=he(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 ue(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(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=he(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 pe(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=pe(a.cell.source,Math.floor(.6*m)),w=s?(b=s,k=m-f.length,b.length<=k?b:`…(${b.length-k} chars elided)…\n${b.slice(-k)}`):"";var b,k;const v=[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"),$=v.includes("chars elided"),P=y;console.log(),me||(me=!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} · ${v.length}/${u} chars`)+chalk.gray(P?" · 单轮(竞赛档模型)":" · single-turn (contest model)")+(s?chalk.gray(P?" · 含输出":" · output included"):"")+($?chalk.yellow(P?" ⚠ 上下文被裁过,加一句具体问题会更准":" ⚠ context trimmed — a specific question helps"):"")),S(`ipynb: ai ${a.idx}${t?` — ${t}`:""}`);const E=await h(v);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} ${P?"<你的问题>":"<your question>"}`)+chalk.gray(P?" 追问 · ":" follow up · ")+chalk.cyan(`edit ${a.idx}`)+chalk.gray(P?" 改这一格 · ":" edit it · ")+chalk.cyan(`run ${a.idx}`)+chalk.gray(P?" 再跑一次":" run it again")),console.log(chalk.gray(P?" 这是调试助手(超限自动裁剪);想练现场那堵墙用 ":" This is the debugging aid (it trims to fit). To train against the real wall: ")+chalk.cyan("ai4ioai")),console.log()})(d),ce=!1,void ge();if("run"===a)return ce=!0,await(async e=>{const o=U(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(N(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),fe(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=fe(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=>{we(e)}),ne||te.on("close",async()=>{await X.shutdown().catch(()=>{}),process.exit(0)}),ge(),await de}
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 S}from"../lib/kernel.js";import{getMainRl as E,setMainRl as G}from"../lib/main-rl.js";import{logCommand as A}from"../lib/logger.js";import{startLogSync as j,stopLogSync as I}from"../lib/log-sync.js";import{cellPreview as N,parseIpynb as U,parsePercentPy as q,parseRunRange as C,serializeIpynb as O,statusChar as L}from"../lib/notebook-doc.js";import{openFile as T}from"../lib/open-file.js";const _=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");function R(){return(p().language||"en").toLowerCase().startsWith("zh")}export function registerIpynbCommand(e){e.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 e=>{await runIpynb(e)})}function M(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}const K=new Set(["guide","/guide","help","?","quit","exit","back","menu","cells","run all"]);function B(){console.log(chalk.gray(" 🧭 stuck? type ")+chalk.cyan("guide")+chalk.gray(" for the basics · ")+chalk.cyan("help")+chalk.gray(" for every command."))}const D="https://practice.icoa2026.au";function W(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):D}function J(){return g(t(),".icoa","gpu-key")}function Y(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return n(J(),"utf-8").trim()||null}catch{return null}}async function z(e,o,n){try{const l=await fetch(`${W()}/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 V(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let F=0,H=null;function Q(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(_,"")}`))}else"display"===n.kind&&X(n.data,o)}function X(e,n){if(e["image/png"])try{o(n,{recursive:!0}),F+=1;const t=g(n,`figure-${F}.png`);return l(t,Buffer.from(e["image/png"],"base64")),H=t,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(t)),void(T(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"]}`))}export async function runIpynb(p){const b=d(t()),D=g(t(),".icoa","ipynb-out");if(M(),!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 F=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")?U(e):q(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,X=F?F.doc:{cells:[],path:null,dirty:!1};let Z=new P({venvPython:b.python,venvRoot:b.root}),ee=null,oe=V(X.path);process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await Z.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.")),F&&console.log(F.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 ne=E(),le=null!==ne,te=le?ne.listeners("line").slice():[];le&&ne.removeAllListeners("line");const re=le?ne:a({input:process.stdin,output:process.stdout,terminal:!0});le||G(re);const ae=le?re.prompt:null,se=le?re.getPrompt():"";le&&(re.prompt=r.prototype.prompt),le||j();const ce=[];let ie=!1,ge=!1,ye=!1;const de=()=>{const e=ee?"icoa ipynb ⚡gpu":"icoa ipynb";re.setPrompt(chalk.bold.cyan(ce.length?`${e} ...> `:`${e}> `)),re.prompt()};let ue=()=>{};const he=new Promise(e=>{ue=e}),pe=async e=>{const[n,...r]=e.trim().split(/\s+/),a=(n??"").toLowerCase();"on"===a||"connect"===a?await(async()=>{if(ee)return void console.log(chalk.gray(" already on the GPU kernel — ")+chalk.cyan("gpu status")+chalk.gray(" for time left."));const e=Y();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)."));oe||(oe=V(X.path)),process.stdout.write(chalk.gray(" Requesting a GPU box…"));let n=await z("lease",e,oe??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 z("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 z("release",e);const s=oe?`${n.dataRoot}/${oe}`:n.dataRoot,c=S(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 z("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 z("release",e)}await Z.shutdown().catch(()=>{}),Z=y,ee=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.")),oe&&console.log(chalk.gray(` Dataset is already on the box (${oe}) — 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(async()=>{if(!ee)return void console.log(chalk.gray(" not on a GPU kernel."));const e=Y();await Z.shutdown().catch(()=>{}),e&&await z("release",e),ee=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped.")),await(async()=>{Z=new P({venvPython:b.python,venvRoot:b.root}),process.stdout.write(chalk.gray(" Starting local kernel…"));try{await Z.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"))}})()})():"status"===a||""===a?await(async()=>{const e=Y();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const o=await z("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(ee?" (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=Y();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(`${W()}/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(J(),`${n}\n`,{mode:384}),console.log(chalk.green(" ✓ GPU key saved")+chalk.gray(" — ")+chalk.cyan("gpu on")+chalk.gray(" when you need the box."))}catch{console.log(chalk.red(" could not save the key")+chalk.gray(` (${J()})`))}else console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu key <your-key>"))})(r.join(" ")):console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu on")+chalk.yellow(" · ")+chalk.cyan("gpu off")+chalk.yellow(" · ")+chalk.cyan("gpu status")+chalk.yellow(" · ")+chalk.cyan("gpu queue")+chalk.yellow(" · ")+chalk.cyan("gpu key <k>"))},me=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>X.cells.length?(console.log(0===X.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${X.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:X.cells[o-1],idx:o}},fe=(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 we=!1;const 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()&&A(`ipynb: ${t.trim()}`),ge)return void(t.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));let r=t.trim();if(0===ce.length&&/^icoa\s+[a-z/]/i.test(r)&&(r=r.replace(/^icoa\s+/i,"")),0===ce.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&&(ye=!1),"quit"===a||"exit"===a||"back"===a||"q"===a||"menu"===a)return X.dirty&&!ye?(ye=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void de()):void await(async()=>{if(re.removeAllListeners("line"),le||I(),console.log(),ee){const e=Y();e&&await z("release",e),ee=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await Z.shutdown().catch(()=>{}),le){ae&&(re.prompt=ae),re.setPrompt(se);for(const e of te)re.on("line",e);re.prompt(),ue()}else G(null),ue(),re.close()})();if("clear"===a||"cls"===a)return console.clear(),M(),void de();if("restart"===a)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await Z.shutdown().catch(()=>{});try{await Z.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 de();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(R()?" 问 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(" check / submit")+chalk.gray(" verify / score your submission.csv — right here, no quit needed")),console.log(chalk.cyan(" board")+chalk.gray(" live standings for this competition")),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 de();if("guide"===a||"/guide"===a)return(()=>{const o=X.path?c(X.path):process.cwd(),l=V(X.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=X.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(X.path?s(X.path):"new empty notebook")+chalk.gray(` · ${X.cells.length} cells (${a} run) · submission.csv: `)+(i?chalk.green("written ✓"):chalk.yellow("not yet — run all"))),ee?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.bold.cyan("submit")+chalk.gray(" — scored + ranked right here, no need to leave (")+chalk.cyan("board")+chalk.gray(" shows standings)")),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.bold.cyan("check")+chalk.gray(" — verifies the file format, right here")),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(" → ↑↓ pick 🧠 Learn → at ")+chalk.cyan("icoa learn>")+chalk.gray(" type ")+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 de();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 de();if("open"===a)return H&&T(H)?console.log(chalk.gray(" reopening ")+chalk.cyan(H)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void de();if("cells"===a||"ls"===a)return(()=>{if(0===X.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);X.cells.forEach((o,n)=>{const l=L(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(N(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 de();if("show"===a)return(e=>{const o=me(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 ──")),Q(o.cell.result,D)),console.log()}})(d),void de();if("edit"===a)return(e=>{const o=me(e);if(!o)return;re.pause();const n=m(o.cell.source,"markdown"===o.cell.kind?".md":".py");if(re.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,X.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 de();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)"));re.pause();const l=m(n?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",n?".md":".py");re.resume();const t=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");t?(X.cells.push({kind:n?"markdown":"code",source:t,result:null}),X.dirty=!0,console.log(chalk.green(` ✓ added ${n?"markdown ":""}cell ${X.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${X.cells.length}`)+chalk.gray(n?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(d),void de();if("del"===a||"delete"===a)return(e=>{const o=me(e);o&&(X.cells.splice(o.idx-1,1),X.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${X.cells.length} left.`)+(o.idx<=X.cells.length?chalk.yellow(" ⚠ 后面的 cell 号已顺移")+chalk.gray(" — ")+chalk.cyan("cells")+chalk.gray(" 重看一眼"):"")))})(d),void de();if(("md"===a||"py"===a)&&/^\d+$/.test(d))return((e,o)=>{const n=me(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,X.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 de();if("gpu"===a)return ge=!0,await pe(d),ge=!1,void de();if("download"===a||"dl"===a)return ge=!0,await(async e=>{if(!ee)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:`${ee.outDir}/${n}`;let r;try{r=await Z.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=oe?g(process.cwd(),"icoa-kaggle",oe):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)`)),oe&&"submission.csv"===s(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${oe}`)+chalk.gray(" — then upload on Kaggle yourself."))})(d),ge=!1,void de();if("check"===a||"submit"===a||"kaggle"===a){const e=await import("./kaggle.js"),o=d.split(/\s+/).filter(Boolean),n="kaggle"===a?(o[0]||"").toLowerCase():a,l=("kaggle"===a?o[1]:o[0])||V(X.path)||void 0;ge=!0;try{"submit"===n?await e.runKaggleSubmit(l):"check"===n?await e.runKaggleCheck(l):"guide"===n?await e.runKaggleGuide(l):await e.runKaggle("kaggle"===a?o[0]:l)}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return ge=!1,void de()}if("board"===a){const{runBoard:e}=await import("./board.js"),o=d.split(/\s+/).filter(Boolean);ge=!0;try{await e(o[0],o[1])}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return ge=!1,void de()}if("ai"===a||"/ai"===a)return ge=!0,await(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=X.cells.length-1;e>=0;e--)if((X.cells[e].result?.outputs??[]).some(e=>"error"===e.kind))return e+1;return null})()??X.cells.length;if(0===X.cells.length)return void console.log(chalk.yellow(" 还没有 cell —— 先写点代码,或用 ")+chalk.cyan("add"));const a=me(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(_,"")).join("\n")));return o.join("\n").replace(_,"").replace(/\n{3,}/g,"\n\n").trim()})(a.cell),i=(()=>{if(!X.path||!V(X.path))return"";try{const e=JSON.parse(n(g(c(X.path),"meta.json"),"utf-8")),o=[e.title,e.metric?`metric: ${e.metric}`:"",e.description].filter(Boolean).join("\n");return fe(o,350)}catch{return""}})(),y=R(),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=fe(a.cell.source,Math.floor(.6*m)),w=s?(b=s,k=m-f.length,b.length<=k?b:`…(${b.length-k} chars elided)…\n${b.slice(-k)}`):"";var b,k;const v=[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"),$=v.includes("chars elided"),P=y;console.log(),we||(we=!0,console.log(chalk.gray(" ")+chalk.bold.white("IOAI 2026 ")+chalk.white("Gemma 3n E4B")+chalk.gray(" (32k) · ")+chalk.white(R()?"单轮无记忆":"single-turn, no memory")+chalk.gray(" · ")+chalk.white(`${u} ${R()?"字符/条":"chars/message"}`)+chalk.gray(" · ")+chalk.white(R()?"1000 token/回复":"1000 tokens/reply")),console.log(chalk.gray(R()?" —— 现场就是这个模型和这几条上限,在这里练的手感能原样带过去。":" — the onsite model and the onsite limits, so the habit transfers as-is."))),console.log(chalk.gray(` → cell ${a.idx} · ${v.length}/${u} chars`)+chalk.gray(P?" · 单轮(竞赛档模型)":" · single-turn (contest model)")+(s?chalk.gray(P?" · 含输出":" · output included"):"")+($?chalk.yellow(P?" ⚠ 上下文被裁过,加一句具体问题会更准":" ⚠ context trimmed — a specific question helps"):"")),A(`ipynb: ai ${a.idx}${t?` — ${t}`:""}`);const S=await h(v);if(console.log(),!S.ok)return console.log(chalk.yellow(" AI 现在连不上 —— ")+chalk.gray(S.text)),console.log(chalk.gray(" 过一会儿再试,或用 ")+chalk.cyan("ai4ioai")+chalk.gray(" 单开一个会话。")),void console.log();for(const e of x(S.text))console.log(e);console.log(),console.log(chalk.gray(" ")+chalk.cyan(`ai ${a.idx} ${P?"<你的问题>":"<your question>"}`)+chalk.gray(P?" 追问 · ":" follow up · ")+chalk.cyan(`edit ${a.idx}`)+chalk.gray(P?" 改这一格 · ":" edit it · ")+chalk.cyan(`run ${a.idx}`)+chalk.gray(P?" 再跑一次":" run it again")),console.log(chalk.gray(P?" 这是调试助手(超限自动裁剪);想练现场那堵墙用 ":" This is the debugging aid (it trims to fit). To train against the real wall: ")+chalk.cyan("ai4ioai")),console.log()})(d),ge=!1,void de();if("run"===a)return ge=!0,await(async e=>{const o=C(e,X.cells.length);if(o)for(const e of o){const n=X.cells[e-1];if("markdown"!==n.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(N(n,50))+chalk.gray(" ──"));try{n.result=await Z.execute(n.source)}catch(e){return console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),void B()}if(X.dirty=!0,Q(n.result,D),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(R()?" 卡住了? ":" Stuck? ")+chalk.bold.cyan(`ai ${e}`)+chalk.gray(R()?" 把这一格的代码和报错一起问 AI(不用离开 notebook)":" sends this cell and its traceback to the AI — without leaving the notebook")),void B()}}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of x(n.source))console.log(e);console.log()}}else console.log(0===X.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),ge=!1,void de();if("save"===a)return(e=>{if(0===X.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()):X.path?X.path.endsWith(".ipynb")?X.path:`${X.path.replace(/\.[^./]+$/,"")}.ipynb`:y(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");try{l(o,O(X.cells)),X.path=o,X.dirty=!1,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${X.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(d),void de();if(""===r)return void de()}if(ce.length>0&&K.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 de();if(ce.push(t),!v(ce))return 1!==ce.length||ie||(ie=!0,console.log(chalk.gray(" (multi-line block started — keep typing; an empty line runs it)"))),void de();const a=ce.join("\n").replace(/\s+$/,"");if(ce.length=0,""!==a.trim()){ge=!0;try{const e=await Z.execute(a);X.cells.push({kind:"code",source:a,result:e}),X.dirty=!0,Q(e,D);const o=be(X.cells[X.cells.length-1],X.cells.length);e.ok||o||B()}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),B()}ge=!1,de()}else de()};re.on("line",e=>{ke(e)}),le||re.on("close",async()=>{await Z.shutdown().catch(()=>{}),process.exit(0)}),de(),await he}
@@ -1 +1 @@
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 d,dataFileUrls as y,parseKaggleTaskList as h,parseSubmitResponse as m,validateSubmissionText as b}from"../lib/kaggle.js";import{mediaHelpLines as p,sprintTaskForComp as f}from"../lib/sprint-meta.js";function k(){return process.env.ICOA_KAGGLE_SERVER?process.env.ICOA_KAGGLE_SERVER.replace(/\/$/,""):"https://practice.icoa2026.au"}async function w(o){try{const e=await fetch(k()+o,{signal:AbortSignal.timeout(3e4)});return await e.json()}catch{return null}}async function v(o){try{const e=await fetch(o,{signal:AbortSignal.timeout(6e4)});return e.ok?await e.text():null}catch{return null}}function $(){return(i().language||"en").toLowerCase().startsWith("zh")}function j(o,e){return $()?o:e}function _(){console.log(),console.log(chalk.yellow(j(" 练习服务器现在连不上。"," The practice server is not reachable right now."))),console.log(chalk.gray(j(" 检查一下网络,或者过一会儿再试。"," Check your connection, or try again later."))),console.log()}function S(o){return s(process.cwd(),"icoa-kaggle",o)}function G(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 P(o){return"local-eval"===o?.judge?(console.log(chalk.bold.white(j(" 出分(就在 notebook 里):"," Scoring (inside the notebook):"))),void console.log(chalk.gray(j(" 跑最后一格 —— "," run the final cell — the "))+chalk.white("FINAL")+chalk.gray(j(" 那一行就是你的分数,没有东西要上传。"," line is your score. Nothing to upload.")))):"icoa-holdout"===o?.judge?(console.log(chalk.bold.white(j(" 交给 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(j(" 与秘密测试标签比对 → 实时排名看 "," scores vs the secret test labels → live rank on "))+chalk.cyan("board"))):"nitro"===o?.judge?(console.log(chalk.bold.white(j(" 怎么知道做得对不对:"," How to tell whether you got it right:"))),console.log(chalk.gray(j(" · 这道题来自 judge.nitro-ai.org,判分在他们服务器上"," · this task comes from judge.nitro-ai.org — the judging lives on their server"))),console.log(chalk.gray(j(" · 想要真分数:去 "," · for a real score: register at "))+chalk.cyan("judge.nitro-ai.org")+chalk.gray(j(" 注册后提交"," and submit there"))),void console.log(chalk.gray(j(" · 冲刺期更快的办法:做完对照官方解答,或问 "," · faster right now: compare against the official solution, or ask "))+chalk.cyan("ai4ioai"))):(console.log(chalk.bold.white(j(" 去 Kaggle 提交(手动,用你自己的账号):"," Submit on Kaggle (manual, your own account):"))),void(o?.kaggle_url?(console.log(chalk.gray(j(" 1. 打开 "," 1. open "))+chalk.cyan(o.kaggle_url)),o?.needs_gpu?console.log(chalk.gray(j(" 2. 交 notebook 产出的那个文件 —— 最后一格写了确切步骤"," 2. submit the file your notebook produced — its final cell has the exact steps"))):console.log(chalk.gray(j(" 2. Submit Predictions → 上传 "," 2. Submit Predictions → upload "))+chalk.white("submission.csv")),console.log(chalk.gray(j(" 3. 看分数,改 MODEL 那一格,重跑,再来一轮。"," 3. read your score, improve the MODEL cell, re-run, repeat.")))):(console.log(chalk.gray(j(" 在 kaggle.com 搜这个比赛名提交,或做完对照官方解答自查。"," Search kaggle.com for this competition, or check yourself against the official solution."))),console.log(chalk.gray(j(" 卡住了问 "," Stuck? ask "))+chalk.cyan("ai4ioai")+chalk.gray(j(" —— 它是弱模型,把问题问准是这次要练的本事。"," — 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(j(" · 真实的 ML 比赛,配一本能直接跑的 starter notebook"," · real ML competitions, a runnable starter notebook"))),console.log(chalk.gray(j(" 小题在你自己的 CPU 上跑;"," Small tasks run on your CPU; "))+chalk.magenta(j("⚡ GPU 题","⚡ GPU tasks"))+chalk.gray(j("在 ICOA 的 GPU 箱上跑。"," run on the ICOA GPU box."))),console.log();const t=await w("/api/icoa/kaggle/tasks");if(!t)return _();const a=h(t);if(0===a.length)return console.log(chalk.yellow(j(" 现在还没有上线的练习赛 —— 过一会儿再来。"," 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(j(` 没有叫 "${n}" 的比赛。`,` No competition called "${n}".`))),!c){console.log(chalk.white(j(" 正在开放的练习赛:"," 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(j(" 选一个(序号或 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(j(` 输 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=S(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 G(t.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(j(" 正在取 notebook…"," Fetching the notebook…"))+chalk.gray(j(" (数据留在 GPU 箱上,不下载)"," (the dataset stays on the GPU box — no download)")));const i=await w(`/api/icoa/kaggle/${n}/starter`),r=i?.data?.starter??i?.starter;if("string"!=typeof r||0===r.length)return _();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(j(" 写不进 notebook —— 检查一下这个目录的写权限。"," Could not write the notebook here — check directory permissions.")))}console.log(chalk.green(" ✓ notebook: ")+chalk.white(c)+chalk.gray(g?j(" (保留了你原来那本)"," (kept your existing one)"):j(" (里面是真正的 IOAI 题)"," (the real IOAI task inside)"))),console.log(chalk.green(" ✓ dataset: ")+chalk.white(j("已经在 GPU 箱上","already on the GPU box"))+chalk.gray(j(" —— 不用下载"," — no download needed"))),console.log(),console.log(chalk.bold.white(j(" 这是 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(j(" 然后 "," then "))+chalk.bold.cyan("gpu on")+chalk.gray(j(" (连到数据所在的那台箱子)"," (connects you to the box where the data lives)"))),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("run all")+chalk.gray(j(" → notebook 在 GPU 上训练。"," → the notebook trains on the GPU."))),console.log(),console.log(chalk.gray(j(" 做题时随时看: "," While you work: "))+chalk.cyan("gpu status")+chalk.gray(j(" 你还剩多少时间 · "," your time left · "))+chalk.cyan("gpu queue")+chalk.gray(j(" 谁在用,谁在等"," who is on, who is waiting"))),console.log(),t.kaggle_url&&(console.log(chalk.gray(j(" 去 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 G(c.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(j(" 正在下载数据…"," Downloading data…")));let m=null;const b=y(c);if(b){const[o,e,n]=await Promise.all([v(b.train),v(b.test),v(b.sample_submission)]);o&&e&&n&&(m={train:o,test:e,sample_submission:n})}if(!m){const o=await w(`/api/icoa/kaggle/${u}/data`);m=o?.data??o}if(!m?.train||!m?.test||!m?.sample_submission)return _();const p=S(u),k={...c,...m.meta??{}};try{e(p,{recursive:!0}),l(s(p,"train.csv"),m.train),l(s(p,"test.csv"),m.test),l(s(p,"sample_submission.csv"),m.sample_submission),l(s(p,"meta.json"),`${JSON.stringify(k,null,2)}\n`)}catch{return void console.log(chalk.yellow(" Could not write the data files here — check directory permissions."))}const $=s(p,"starter.ipynb");let P=!1;if(o($))P=!0;else{const o=await w(`/api/icoa/kaggle/${u}/starter`),e=o?.data?.starter??o?.starter;"string"==typeof e&&e.length>0?l($,e):l($,g(d(p,k)))}const A="number"==typeof k.n_train?`${k.n_train} rows`:"labelled",C="number"==typeof k.n_test?`${k.n_test} rows`:"predict these";console.log(chalk.green(" ✓ train: ")+chalk.white(s(p,"train.csv"))+chalk.gray(` (${A})`)),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")));const E=f(u),U="none"===(E?.baseline||"").trim();console.log(chalk.green(" ✓ notebook: ")+chalk.white($)+chalk.gray(P?" (kept your existing one)":U?j(" (starter 在里面,FEATURES 那一格要你自己写)"," (starter inside — the FEATURES cell is yours to write)"):" (runnable baseline inside)")),(k.licence||k.attribution)&&console.log(chalk.gray(` licence: ${k.licence??"—"} · ${k.attribution??""}`)),console.log(),x(u,k,$),console.log()}finally{t.close()}}function A(o){const e=$();switch(o){case"audio":return e?"音频":"audio";case"image":return e?"图片":"images";case"weights":return e?"模型权重":"model weights";default:return e?"附件":"the extra files"}}function x(o,e,n){const t=f(o),l=t?p(t,$()):[];if(l.length>0){for(const o of l)for(const e of G(o,74))console.log(chalk.yellow(` ${e}`));console.log()}if(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"));else{const l=t?.media?.pack,s="none"===(t?.baseline||"").trim();console.log(chalk.bold.white(l?j(" 接下来 4 步:"," Your move — 4 steps:"):j(" 接下来 3 步:"," Your move — 3 steps:")));let a=1;l&&console.log(chalk.gray(` ${a++}. `)+chalk.bold.cyan(`teleload ${l}`)+chalk.gray(j(` → 把${A(t?.media?.kind)}拉下来(CSV 里没有)`,` → fetch the ${A(t?.media?.kind)} (the CSVs do not carry it)`))),console.log(chalk.gray(` ${a++}. `)+chalk.bold.cyan(`icoa ipynb ${n}`)+chalk.gray(s?j(" → run all 到 FEATURES 那格会停,那格是你的活"," → run all stops at FEATURES — that cell is your job"):" → run all (baseline trains)")),console.log(chalk.gray(` ${a++}. it writes `)+chalk.white("submission.csv")+chalk.gray(" → verify with ")+chalk.cyan(`kaggle check ${o}`)),"icoa-holdout"===e?.judge?console.log(chalk.gray(` ${a}. `)+chalk.bold.cyan(`kaggle submit ${o}`)+chalk.gray(" → scored + ranked live.")):"nitro"===e?.judge?console.log(chalk.gray(` ${a}. scored at `)+chalk.cyan("judge.nitro-ai.org")+chalk.gray(" (not Kaggle) — or just work the val score. See below.")):console.log(chalk.gray(` ${a}. 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(),P(e)}export async function runKaggleGuide(e){console.log();const t=C(e,"guide");if(!t)return;const l=S(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(),x(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 C(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=C(e,"check");if(!t)return;const l=S(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=b(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(),P(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=C(e,"submit");if(!t)return;const l=S(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.")),P(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(),P(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 d=n(i,"utf-8"),y=b(d,n(c,"utf-8"));if(!y.ok){r(`kaggle: submit ${t} → local-reject: ${y.problems[0]??"format"}`),console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of y.problems)console.log(chalk.yellow(` · ${o}`));return console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it.")),void console.log()}let 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 p=await async function(o,e){try{const n=await fetch(k()+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:d}),f=m(p);if(r(`kaggle: submit ${t} → ${f.ok?`${f.metric}=${f.score}${f.deduped?" (deduped)":""} rank=${f.rank??"-"}`:f.reason??"error"}`),console.log(),f.ok){const o=`${f.metric}: ${Number(f.score).toFixed(4).replace(/\.?0+$/,"")}`;f.deduped?(console.log(chalk.bold.white(` ✓ already scored — ${o}`)),console.log(chalk.gray(" These exact predictions were scored before. Improve the MODEL cell and re-run."))):(console.log(chalk.bold.green(` ✓ scored — ${o}`)),"number"==typeof f.rank&&"number"==typeof f.fieldSize&&console.log(chalk.bold.white(` 🏁 board rank #${f.rank}`)+chalk.gray(` of ${f.fieldSize}`))),f.boardEvent&&console.log(chalk.gray(" standings: ")+chalk.cyan(`board ${f.boardEvent} ${t}`))}else switch(f.reason){case"bad_token":console.log(chalk.bold.red(" ✗ that learn token was not accepted")+chalk.gray(" (invalid or expired)")),console.log(chalk.gray(" Check the token with your coach, then try again."));break;case"format":console.log(chalk.bold.red(" ✗ the server rejected submission.csv:"));for(const o of f.problems??[])console.log(chalk.yellow(` · ${o}`));break;case"event_closed":case"outside_window":console.log(chalk.bold.yellow(" ⏱ the submission window for this competition is closed."));break;case"cap_reached":console.log(chalk.bold.yellow(" ⏱ you have used all your submissions for this competition."));break;case"kaggle_judged":console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here."));break;default:console.log(chalk.yellow(" The scoring server is not reachable right now — try again in a minute."))}console.log()}export function registerKaggleCommand(o){o.command("kaggle").argument("[action]",'competition id, or "check" / "submit"').argument("[comp]",'competition id (with "check" / "submit")').description("Kaggle-style ML practice — dataset + starter notebook, check & submit").action(async(o,e)=>{"check"===o?await runKaggleCheck(e):"submit"===o?await runKaggleSubmit(e):"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 t,readdirSync as n,writeFileSync as l}from"node:fs";import{join as s}from"node:path";import chalk from"chalk";import{makeReplAsker as r}from"../lib/repl-asker.js";import{getConfig as a}from"../lib/config.js";import{logCommand as i}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 d,dataFileUrls as y,parseKaggleTaskList as h,parseSubmitResponse as m,validateSubmissionText as b}from"../lib/kaggle.js";import{mediaHelpLines as p,sprintTaskForComp as f}from"../lib/sprint-meta.js";function k(){return process.env.ICOA_KAGGLE_SERVER?process.env.ICOA_KAGGLE_SERVER.replace(/\/$/,""):"https://practice.icoa2026.au"}async function w(o){try{const e=await fetch(k()+o,{signal:AbortSignal.timeout(3e4)});return await e.json()}catch{return null}}async function v(o){try{const e=await fetch(o,{signal:AbortSignal.timeout(6e4)});return e.ok?await e.text():null}catch{return null}}function $(){return(a().language||"en").toLowerCase().startsWith("zh")}function j(o,e){return $()?o:e}function _(){console.log(),console.log(chalk.yellow(j(" 练习服务器现在连不上。"," The practice server is not reachable right now."))),console.log(chalk.gray(j(" 检查一下网络,或者过一会儿再试。"," Check your connection, or try again later."))),console.log()}function S(o){return s(process.cwd(),"icoa-kaggle",o)}function G(o,e){const t=[];let n="",l=0;const s=o=>/[ᄀ-ᅟ⺀-꓏가-힣豈-﫿︰-﹏＀-⦆¢-₩]/.test(o);for(const r of o){const o=s(r)?2:1;if(l+o>e){const o=n.lastIndexOf(" ");if(!s(r)&&" "!==r&&o>e/3){const e=n.slice(o+1);t.push(n.slice(0,o)),n=e,l=[...e].reduce((o,e)=>o+(s(e)?2:1),0)}else t.push(n),n="",l=0;if(" "===r&&""===n)continue}n+=r,l+=o}return""!==n.trim()&&t.push(n),t}function P(o){return"local-eval"===o?.judge?(console.log(chalk.bold.white(j(" 出分(就在 notebook 里):"," Scoring (inside the notebook):"))),void console.log(chalk.gray(j(" 跑最后一格 —— "," run the final cell — the "))+chalk.white("FINAL")+chalk.gray(j(" 那一行就是你的分数,没有东西要上传。"," line is your score. Nothing to upload.")))):"icoa-holdout"===o?.judge?(console.log(chalk.bold.white(j(" 交给 ICOA 判分(服务端评分):"," Submit to ICOA (scored on the server):"))),console.log(chalk.gray(" ")+chalk.bold.cyan(`kaggle submit ${o.comp_id}`)),console.log(chalk.gray(j(" 与秘密测试标签比对 → 实时排名看 "," scores vs the secret test labels → live rank on "))+chalk.cyan("board")),void console.log(chalk.gray(j(" 在 notebook 里可直接敲 "," inside the notebook just type "))+chalk.cyan("submit")+chalk.gray(j(" —— 不用退出来"," — no need to leave")))):"nitro"===o?.judge?(console.log(chalk.bold.white(j(" 怎么知道做得对不对:"," How to tell whether you got it right:"))),console.log(chalk.gray(j(" · 这道题来自 judge.nitro-ai.org,判分在他们服务器上"," · this task comes from judge.nitro-ai.org — the judging lives on their server"))),console.log(chalk.gray(j(" · 想要真分数:去 "," · for a real score: register at "))+chalk.cyan("judge.nitro-ai.org")+chalk.gray(j(" 注册后提交"," and submit there"))),void console.log(chalk.gray(j(" · 冲刺期更快的办法:做完对照官方解答,或问 "," · faster right now: compare against the official solution, or ask "))+chalk.cyan("ai4ioai"))):(console.log(chalk.bold.white(j(" 去 Kaggle 提交(手动,用你自己的账号):"," Submit on Kaggle (manual, your own account):"))),void(o?.kaggle_url?(console.log(chalk.gray(j(" 1. 打开 "," 1. open "))+chalk.cyan(o.kaggle_url)),o?.needs_gpu?console.log(chalk.gray(j(" 2. 交 notebook 产出的那个文件 —— 最后一格写了确切步骤"," 2. submit the file your notebook produced — its final cell has the exact steps"))):console.log(chalk.gray(j(" 2. Submit Predictions → 上传 "," 2. Submit Predictions → upload "))+chalk.white("submission.csv")),console.log(chalk.gray(j(" 3. 看分数,改 MODEL 那一格,重跑,再来一轮。"," 3. read your score, improve the MODEL cell, re-run, repeat.")))):(console.log(chalk.gray(j(" 在 kaggle.com 搜这个比赛名提交,或做完对照官方解答自查。"," Search kaggle.com for this competition, or check yourself against the official solution."))),console.log(chalk.gray(j(" 卡住了问 "," Stuck? ask "))+chalk.cyan("ai4ioai")+chalk.gray(j(" —— 它是弱模型,把问题问准是这次要练的本事。"," — a deliberately weak model; asking precisely is the skill you are training."))))))}export async function runKaggle(t){const n=r(),a=async o=>await n.ask(o)??"";try{console.log(),console.log(chalk.bold.cyan(" 📊 KAGGLE PRACTICE")+chalk.gray(j(" · 真实的 ML 比赛,配一本能直接跑的 starter notebook"," · real ML competitions, a runnable starter notebook"))),console.log(chalk.gray(j(" 小题在你自己的 CPU 上跑;"," Small tasks run on your CPU; "))+chalk.magenta(j("⚡ GPU 题","⚡ GPU tasks"))+chalk.gray(j("在 ICOA 的 GPU 箱上跑。"," run on the ICOA GPU box."))),console.log();const n=await w("/api/icoa/kaggle/tasks");if(!n)return _();const r=h(n);if(0===r.length)return console.log(chalk.yellow(j(" 现在还没有上线的练习赛 —— 过一会儿再来。"," No practice competitions are live yet — check back soon."))),void console.log();let c=t?r.find(o=>o.comp_id===t):void 0;if(t&&!c&&console.log(chalk.yellow(j(` 没有叫 "${t}" 的比赛。`,` No competition called "${t}".`))),!c){console.log(chalk.white(j(" 正在开放的练习赛:"," Live practice competitions:"))),r.forEach((o,e)=>{const t=o.needs_gpu?chalk.magenta(" ⚡GPU"):"";console.log(chalk.gray(` ${e+1}. `)+chalk.cyan(o.comp_id)+chalk.gray(` — ${o.title} · ${o.metric}`)+t)});for(let o=0;o<3&&!c;o++){const o=(await a(chalk.cyan(j(" 选一个(序号或 id): "," Pick one (number or id): ")))).trim();if(!o)return;const e=Number(o);c=!Number.isNaN(e)&&r[e-1]||r.find(e=>e.comp_id===o.toLowerCase())||void 0,c||console.log(chalk.gray(j(` 输 1-${r.length} 之间的序号,或者一个 id,比如 "${r[0].comp_id}"。`,` Try a number 1-${r.length} or an id like "${r[0].comp_id}".`)))}if(!c)return}const u=c.comp_id;if(i(`kaggle: download ${u}`),c.needs_gpu)return void await async function(t,n){const r=S(t);if(console.log(),console.log(chalk.white(` ${n.title}`)+chalk.gray(` · ${n.metric}`)+chalk.bold.magenta(" ⚡ GPU task")),n.description){console.log();for(const o of G(n.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(j(" 正在取 notebook…"," Fetching the notebook…"))+chalk.gray(j(" (数据留在 GPU 箱上,不下载)"," (the dataset stays on the GPU box — no download)")));const a=await w(`/api/icoa/kaggle/${t}/starter`),i=a?.data?.starter??a?.starter;if("string"!=typeof i||0===i.length)return _();const c=s(r,"starter.ipynb");let g=!1;try{e(r,{recursive:!0}),o(c)?g=!0:l(c,i),l(s(r,"meta.json"),`${JSON.stringify(n,null,2)}\n`)}catch{return void console.log(chalk.yellow(j(" 写不进 notebook —— 检查一下这个目录的写权限。"," Could not write the notebook here — check directory permissions.")))}console.log(chalk.green(" ✓ notebook: ")+chalk.white(c)+chalk.gray(g?j(" (保留了你原来那本)"," (kept your existing one)"):j(" (里面是真正的 IOAI 题)"," (the real IOAI task inside)"))),console.log(chalk.green(" ✓ dataset: ")+chalk.white(j("已经在 GPU 箱上","already on the GPU box"))+chalk.gray(j(" —— 不用下载"," — no download needed"))),console.log(),console.log(chalk.bold.white(j(" 这是 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(j(" 然后 "," then "))+chalk.bold.cyan("gpu on")+chalk.gray(j(" (连到数据所在的那台箱子)"," (connects you to the box where the data lives)"))),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("run all")+chalk.gray(j(" → notebook 在 GPU 上训练。"," → the notebook trains on the GPU."))),console.log(),console.log(chalk.gray(j(" 做题时随时看: "," While you work: "))+chalk.cyan("gpu status")+chalk.gray(j(" 你还剩多少时间 · "," your time left · "))+chalk.cyan("gpu queue")+chalk.gray(j(" 谁在用,谁在等"," who is on, who is waiting"))),console.log(),n.kaggle_url&&(console.log(chalk.gray(j(" 去 Kaggle 提交: "," Submit on Kaggle: "))+chalk.cyan(n.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 G(c.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(j(" 正在下载数据…"," Downloading data…")));let m=null;const b=y(c);if(b){const[o,e,t]=await Promise.all([v(b.train),v(b.test),v(b.sample_submission)]);o&&e&&t&&(m={train:o,test:e,sample_submission:t})}if(!m){const o=await w(`/api/icoa/kaggle/${u}/data`);m=o?.data??o}if(!m?.train||!m?.test||!m?.sample_submission)return _();const p=S(u),k={...c,...m.meta??{}};try{e(p,{recursive:!0}),l(s(p,"train.csv"),m.train),l(s(p,"test.csv"),m.test),l(s(p,"sample_submission.csv"),m.sample_submission),l(s(p,"meta.json"),`${JSON.stringify(k,null,2)}\n`)}catch{return void console.log(chalk.yellow(" Could not write the data files here — check directory permissions."))}const $=s(p,"starter.ipynb");let P=!1;if(o($))P=!0;else{const o=await w(`/api/icoa/kaggle/${u}/starter`),e=o?.data?.starter??o?.starter;"string"==typeof e&&e.length>0?l($,e):l($,g(d(p,k)))}const x="number"==typeof k.n_train?`${k.n_train} rows`:"labelled",C="number"==typeof k.n_test?`${k.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")));const E=f(u),U="none"===(E?.baseline||"").trim();console.log(chalk.green(" ✓ notebook: ")+chalk.white($)+chalk.gray(P?" (kept your existing one)":U?j(" (starter 在里面,FEATURES 那一格要你自己写)"," (starter inside — the FEATURES cell is yours to write)"):" (runnable baseline inside)")),(k.licence||k.attribution)&&console.log(chalk.gray(` licence: ${k.licence??"—"} · ${k.attribution??""}`)),console.log(),A(u,k,$),console.log()}finally{n.close()}}function x(o){const e=$();switch(o){case"audio":return e?"音频":"audio";case"image":return e?"图片":"images";case"weights":return e?"模型权重":"model weights";default:return e?"附件":"the extra files"}}function A(o,e,t){const n=f(o),l=n?p(n,$()):[];if(l.length>0){for(const o of l)for(const e of G(o,74))console.log(chalk.yellow(` ${e}`));console.log()}if(e?.needs_gpu)console.log(chalk.bold.white(" Your move — 4 steps (⚡ GPU task):")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${t}`)),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"));else{const l=n?.media?.pack,s="none"===(n?.baseline||"").trim();console.log(chalk.bold.white(l?j(" 接下来 4 步:"," Your move — 4 steps:"):j(" 接下来 3 步:"," Your move — 3 steps:")));let r=1;l&&console.log(chalk.gray(` ${r++}. `)+chalk.bold.cyan(`teleload ${l}`)+chalk.gray(j(` → 把${x(n?.media?.kind)}拉下来(CSV 里没有)`,` → fetch the ${x(n?.media?.kind)} (the CSVs do not carry it)`))),console.log(chalk.gray(` ${r++}. `)+chalk.bold.cyan(`icoa ipynb ${t}`)+chalk.gray(s?j(" → run all 到 FEATURES 那格会停,那格是你的活"," → run all stops at FEATURES — that cell is your job"):" → run all (baseline trains)")),console.log(chalk.gray(` ${r++}. it writes `)+chalk.white("submission.csv")+chalk.gray(" → verify with ")+chalk.cyan(`kaggle check ${o}`)),"icoa-holdout"===e?.judge?console.log(chalk.gray(` ${r}. `)+chalk.bold.cyan(`kaggle submit ${o}`)+chalk.gray(" → scored + ranked live.")):"nitro"===e?.judge?console.log(chalk.gray(` ${r}. scored at `)+chalk.cyan("judge.nitro-ai.org")+chalk.gray(" (not Kaggle) — or just work the val score. See below.")):console.log(chalk.gray(` ${r}. 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(" → ↑↓ pick ")+chalk.bold.white("🧠 Learn")+chalk.gray(" → at ")+chalk.cyan("icoa learn>")+chalk.gray(" 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(),P(e)}export async function runKaggleGuide(e){console.log();const n=C(e,"guide");if(!n)return;const l=S(n);let r=null;try{r=JSON.parse(t(s(l,"meta.json"),"utf-8"))}catch{r=null}i(`kaggle: guide ${n}`);const a=s(l,"starter.ipynb"),c=o(s(l,"submission.csv"));console.log(chalk.bold.white(` ═══ 📖 ${r?.title??n} — 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(),A(n,r,a),console.log(),console.log(chalk.gray(" Inside the notebook, ")+chalk.cyan("guide")+chalk.gray(" shows the notebook-level guide.")),console.log()}function C(e,t){if(e)return e;const l=s(process.cwd(),"icoa-kaggle"),r=o(l)?n(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===r.length)return r[0];if(0===r.length)return console.log(chalk.yellow(" No downloaded competition found here — run ")+chalk.cyan("kaggle")+chalk.yellow(" first.")),console.log(),null;console.log(chalk.white(" Several competitions downloaded — pick one:"));for(const o of r)console.log(chalk.gray(` kaggle ${t} `)+chalk.cyan(o));return console.log(),null}export async function runKaggleCheck(e){console.log();const n=C(e,"check");if(!n)return;const l=S(n),r=s(l,"submission.csv"),a=s(l,"sample_submission.csv");try{if(JSON.parse(t(s(l,"meta.json"),"utf-8")).needs_gpu&&!o(a))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(a))return console.log(chalk.yellow(` No data for "${n}" here — run `)+chalk.cyan(`kaggle ${n}`)+chalk.yellow(" first.")),void console.log();if(!o(r))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(l,"starter.ipynb")}`)),void console.log();const g=b(t(r,"utf-8"),t(a,"utf-8"));i(`kaggle: check ${n} → ${g.ok?"ok":`rejected: ${g.problems[0]??"format"}`}`);let u=null;try{u=JSON.parse(t(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(r)),console.log(),P(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 n=C(e,"submit");if(!n)return;const l=S(n),a=s(l,"submission.csv"),c=s(l,"sample_submission.csv");let g=null;try{g=JSON.parse(t(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.")),P(g),void console.log();if(!g||!o(c))return console.log(chalk.yellow(` No data for "${n}" here — run `)+chalk.cyan(`kaggle ${n}`)+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(),P(g),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 d=t(a,"utf-8"),y=b(d,t(c,"utf-8"));if(!y.ok){i(`kaggle: submit ${n} → local-reject: ${y.problems[0]??"format"}`),console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of y.problems)console.log(chalk.yellow(` · ${o}`));return console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it.")),void console.log()}let h=u()?.token??"";if(!h){const o=r();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()}const p=Date.now();let f,w=null;process.stdout.isTTY?(process.stdout.write(chalk.gray(" ⚖ scoring on the server… 0.0s")),w=setInterval(()=>{process.stdout.write(chalk.gray(`\r ⚖ scoring on the server… ${((Date.now()-p)/1e3).toFixed(1)}s `))},200)):console.log(chalk.gray(" Scoring on the server…"));try{f=await async function(o,e){try{const t=await fetch(k()+o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(6e4)});return await t.json()}catch{return null}}(`/api/icoa/kaggle/${n}/submit`,{token:h,submission_csv:d})}finally{w&&(clearInterval(w),process.stdout.write(`\r ${chalk.gray(`⚖ scored in ${((Date.now()-p)/1e3).toFixed(1)}s`)}${" ".repeat(12)}\n`))}const v=m(f);if(i(`kaggle: submit ${n} → ${v.ok?`${v.metric}=${v.score}${v.deduped?" (deduped)":""} rank=${v.rank??"-"}`:v.reason??"error"}`),console.log(),v.ok){const o=`${v.metric}: ${Number(v.score).toFixed(4).replace(/\.?0+$/,"")}`;v.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 v.rank&&"number"==typeof v.fieldSize&&console.log(chalk.bold.white(` 🏁 board rank #${v.rank}`)+chalk.gray(` of ${v.fieldSize}`))),"number"==typeof v.used&&"number"==typeof v.cap&&console.log(chalk.gray(` ⚖ submissions used ${v.used}/${v.cap}`)),v.boardEvent&&console.log(chalk.gray(" standings: ")+chalk.cyan(`board ${v.boardEvent} ${n}`))}else switch(v.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 v.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)})}